1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
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 "clang/Format/Format.h"
10 
11 #include "../Tooling/ReplacementTest.h"
12 #include "FormatTestUtils.h"
13 
14 #include "llvm/Support/Debug.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "gtest/gtest.h"
17 
18 #define DEBUG_TYPE "format-test"
19 
20 using clang::tooling::ReplacementTest;
21 using clang::tooling::toReplacements;
22 using testing::ScopedTrace;
23 
24 namespace clang {
25 namespace format {
26 namespace {
27 
28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
29 
30 class FormatTest : public ::testing::Test {
31 protected:
32   enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck };
33 
34   std::string format(llvm::StringRef Code,
35                      const FormatStyle &Style = getLLVMStyle(),
36                      StatusCheck CheckComplete = SC_ExpectComplete) {
37     LLVM_DEBUG(llvm::errs() << "---\n");
38     LLVM_DEBUG(llvm::errs() << Code << "\n\n");
39     std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
40     FormattingAttemptStatus Status;
41     tooling::Replacements Replaces =
42         reformat(Style, Code, Ranges, "<stdin>", &Status);
43     if (CheckComplete != SC_DoNotCheck) {
44       bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete;
45       EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete)
46           << Code << "\n\n";
47     }
48     ReplacementCount = Replaces.size();
49     auto Result = applyAllReplacements(Code, Replaces);
50     EXPECT_TRUE(static_cast<bool>(Result));
51     LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
52     return *Result;
53   }
54 
55   FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) {
56     Style.ColumnLimit = ColumnLimit;
57     return Style;
58   }
59 
60   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
61     return getStyleWithColumns(getLLVMStyle(), ColumnLimit);
62   }
63 
64   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
65     return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
66   }
67 
68   void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
69                      llvm::StringRef Code,
70                      const FormatStyle &Style = getLLVMStyle()) {
71     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
72     EXPECT_EQ(Expected.str(), format(Expected, Style))
73         << "Expected code is not stable";
74     EXPECT_EQ(Expected.str(), format(Code, Style));
75     if (Style.Language == FormatStyle::LK_Cpp) {
76       // Objective-C++ is a superset of C++, so everything checked for C++
77       // needs to be checked for Objective-C++ as well.
78       FormatStyle ObjCStyle = Style;
79       ObjCStyle.Language = FormatStyle::LK_ObjC;
80       EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle));
81     }
82   }
83 
84   void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
85                      const FormatStyle &Style = getLLVMStyle()) {
86     _verifyFormat(File, Line, Code, test::messUp(Code), Style);
87   }
88 
89   void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code,
90                                const FormatStyle &Style = getLLVMStyle()) {
91     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
92     EXPECT_EQ(Code.str(),
93               format(test::messUp(Code), Style, SC_ExpectIncomplete));
94   }
95 
96   void _verifyIndependentOfContext(const char *File, int Line,
97                                    llvm::StringRef Text,
98                                    const FormatStyle &Style = getLLVMStyle()) {
99     _verifyFormat(File, Line, Text, Style);
100     _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(),
101                   Style);
102   }
103 
104   /// \brief Verify that clang-format does not crash on the given input.
105   void verifyNoCrash(llvm::StringRef Code,
106                      const FormatStyle &Style = getLLVMStyle()) {
107     format(Code, Style, SC_DoNotCheck);
108   }
109 
110   int ReplacementCount;
111 };
112 
113 #define verifyIndependentOfContext(...)                                        \
114   _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__)
115 #define verifyIncompleteFormat(...)                                            \
116   _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle())
119 
120 TEST_F(FormatTest, MessUp) {
121   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
122   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
123   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
124   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
125   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
126 }
127 
128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
129   EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
130 }
131 
132 TEST_F(FormatTest, LLVMStyleOverride) {
133   EXPECT_EQ(FormatStyle::LK_Proto,
134             getLLVMStyle(FormatStyle::LK_Proto).Language);
135 }
136 
137 //===----------------------------------------------------------------------===//
138 // Basic function tests.
139 //===----------------------------------------------------------------------===//
140 
141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
142   EXPECT_EQ(";", format(";"));
143 }
144 
145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
146   EXPECT_EQ("int i;", format("  int i;"));
147   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
148   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
149   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
150 }
151 
152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
153   EXPECT_EQ("int i;", format("int\ni;"));
154 }
155 
156 TEST_F(FormatTest, FormatsNestedBlockStatements) {
157   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
158 }
159 
160 TEST_F(FormatTest, FormatsNestedCall) {
161   verifyFormat("Method(f1, f2(f3));");
162   verifyFormat("Method(f1(f2, f3()));");
163   verifyFormat("Method(f1(f2, (f3())));");
164 }
165 
166 TEST_F(FormatTest, NestedNameSpecifiers) {
167   verifyFormat("vector<::Type> v;");
168   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
169   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
170   verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
171   verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
172   verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
173   verifyFormat("bool a = 2 < ::SomeFunction();");
174   verifyFormat("ALWAYS_INLINE ::std::string getName();");
175   verifyFormat("some::string getName();");
176 }
177 
178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
179   EXPECT_EQ("if (a) {\n"
180             "  f();\n"
181             "}",
182             format("if(a){f();}"));
183   EXPECT_EQ(4, ReplacementCount);
184   EXPECT_EQ("if (a) {\n"
185             "  f();\n"
186             "}",
187             format("if (a) {\n"
188                    "  f();\n"
189                    "}"));
190   EXPECT_EQ(0, ReplacementCount);
191   EXPECT_EQ("/*\r\n"
192             "\r\n"
193             "*/\r\n",
194             format("/*\r\n"
195                    "\r\n"
196                    "*/\r\n"));
197   EXPECT_EQ(0, ReplacementCount);
198 }
199 
200 TEST_F(FormatTest, RemovesEmptyLines) {
201   EXPECT_EQ("class C {\n"
202             "  int i;\n"
203             "};",
204             format("class C {\n"
205                    " int i;\n"
206                    "\n"
207                    "};"));
208 
209   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
210   EXPECT_EQ("namespace N {\n"
211             "\n"
212             "int i;\n"
213             "}",
214             format("namespace N {\n"
215                    "\n"
216                    "int    i;\n"
217                    "}",
218                    getGoogleStyle()));
219   EXPECT_EQ("/* something */ namespace N {\n"
220             "\n"
221             "int i;\n"
222             "}",
223             format("/* something */ namespace N {\n"
224                    "\n"
225                    "int    i;\n"
226                    "}",
227                    getGoogleStyle()));
228   EXPECT_EQ("inline namespace N {\n"
229             "\n"
230             "int i;\n"
231             "}",
232             format("inline namespace N {\n"
233                    "\n"
234                    "int    i;\n"
235                    "}",
236                    getGoogleStyle()));
237   EXPECT_EQ("/* something */ inline namespace N {\n"
238             "\n"
239             "int i;\n"
240             "}",
241             format("/* something */ inline namespace N {\n"
242                    "\n"
243                    "int    i;\n"
244                    "}",
245                    getGoogleStyle()));
246   EXPECT_EQ("export namespace N {\n"
247             "\n"
248             "int i;\n"
249             "}",
250             format("export namespace N {\n"
251                    "\n"
252                    "int    i;\n"
253                    "}",
254                    getGoogleStyle()));
255   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
256             "\n"
257             "int i;\n"
258             "}",
259             format("extern /**/ \"C\" /**/ {\n"
260                    "\n"
261                    "int    i;\n"
262                    "}",
263                    getGoogleStyle()));
264 
265   auto CustomStyle = getLLVMStyle();
266   CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom;
267   CustomStyle.BraceWrapping.AfterNamespace = true;
268   CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
269   EXPECT_EQ("namespace N\n"
270             "{\n"
271             "\n"
272             "int i;\n"
273             "}",
274             format("namespace N\n"
275                    "{\n"
276                    "\n"
277                    "\n"
278                    "int    i;\n"
279                    "}",
280                    CustomStyle));
281   EXPECT_EQ("/* something */ namespace N\n"
282             "{\n"
283             "\n"
284             "int i;\n"
285             "}",
286             format("/* something */ namespace N {\n"
287                    "\n"
288                    "\n"
289                    "int    i;\n"
290                    "}",
291                    CustomStyle));
292   EXPECT_EQ("inline namespace N\n"
293             "{\n"
294             "\n"
295             "int i;\n"
296             "}",
297             format("inline namespace N\n"
298                    "{\n"
299                    "\n"
300                    "\n"
301                    "int    i;\n"
302                    "}",
303                    CustomStyle));
304   EXPECT_EQ("/* something */ inline namespace N\n"
305             "{\n"
306             "\n"
307             "int i;\n"
308             "}",
309             format("/* something */ inline namespace N\n"
310                    "{\n"
311                    "\n"
312                    "int    i;\n"
313                    "}",
314                    CustomStyle));
315   EXPECT_EQ("export namespace N\n"
316             "{\n"
317             "\n"
318             "int i;\n"
319             "}",
320             format("export namespace N\n"
321                    "{\n"
322                    "\n"
323                    "int    i;\n"
324                    "}",
325                    CustomStyle));
326   EXPECT_EQ("namespace a\n"
327             "{\n"
328             "namespace b\n"
329             "{\n"
330             "\n"
331             "class AA {};\n"
332             "\n"
333             "} // namespace b\n"
334             "} // namespace a\n",
335             format("namespace a\n"
336                    "{\n"
337                    "namespace b\n"
338                    "{\n"
339                    "\n"
340                    "\n"
341                    "class AA {};\n"
342                    "\n"
343                    "\n"
344                    "}\n"
345                    "}\n",
346                    CustomStyle));
347   EXPECT_EQ("namespace A /* comment */\n"
348             "{\n"
349             "class B {}\n"
350             "} // namespace A",
351             format("namespace A /* comment */ { class B {} }", CustomStyle));
352   EXPECT_EQ("namespace A\n"
353             "{ /* comment */\n"
354             "class B {}\n"
355             "} // namespace A",
356             format("namespace A {/* comment */ class B {} }", CustomStyle));
357   EXPECT_EQ("namespace A\n"
358             "{ /* comment */\n"
359             "\n"
360             "class B {}\n"
361             "\n"
362             ""
363             "} // namespace A",
364             format("namespace A { /* comment */\n"
365                    "\n"
366                    "\n"
367                    "class B {}\n"
368                    "\n"
369                    "\n"
370                    "}",
371                    CustomStyle));
372   EXPECT_EQ("namespace A /* comment */\n"
373             "{\n"
374             "\n"
375             "class B {}\n"
376             "\n"
377             "} // namespace A",
378             format("namespace A/* comment */ {\n"
379                    "\n"
380                    "\n"
381                    "class B {}\n"
382                    "\n"
383                    "\n"
384                    "}",
385                    CustomStyle));
386 
387   // ...but do keep inlining and removing empty lines for non-block extern "C"
388   // functions.
389   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
390   EXPECT_EQ("extern \"C\" int f() {\n"
391             "  int i = 42;\n"
392             "  return i;\n"
393             "}",
394             format("extern \"C\" int f() {\n"
395                    "\n"
396                    "  int i = 42;\n"
397                    "  return i;\n"
398                    "}",
399                    getGoogleStyle()));
400 
401   // Remove empty lines at the beginning and end of blocks.
402   EXPECT_EQ("void f() {\n"
403             "\n"
404             "  if (a) {\n"
405             "\n"
406             "    f();\n"
407             "  }\n"
408             "}",
409             format("void f() {\n"
410                    "\n"
411                    "  if (a) {\n"
412                    "\n"
413                    "    f();\n"
414                    "\n"
415                    "  }\n"
416                    "\n"
417                    "}",
418                    getLLVMStyle()));
419   EXPECT_EQ("void f() {\n"
420             "  if (a) {\n"
421             "    f();\n"
422             "  }\n"
423             "}",
424             format("void f() {\n"
425                    "\n"
426                    "  if (a) {\n"
427                    "\n"
428                    "    f();\n"
429                    "\n"
430                    "  }\n"
431                    "\n"
432                    "}",
433                    getGoogleStyle()));
434 
435   // Don't remove empty lines in more complex control statements.
436   EXPECT_EQ("void f() {\n"
437             "  if (a) {\n"
438             "    f();\n"
439             "\n"
440             "  } else if (b) {\n"
441             "    f();\n"
442             "  }\n"
443             "}",
444             format("void f() {\n"
445                    "  if (a) {\n"
446                    "    f();\n"
447                    "\n"
448                    "  } else if (b) {\n"
449                    "    f();\n"
450                    "\n"
451                    "  }\n"
452                    "\n"
453                    "}"));
454 
455   // Don't remove empty lines before namespace endings.
456   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
457   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
458   EXPECT_EQ("namespace {\n"
459             "int i;\n"
460             "\n"
461             "}",
462             format("namespace {\n"
463                    "int i;\n"
464                    "\n"
465                    "}",
466                    LLVMWithNoNamespaceFix));
467   EXPECT_EQ("namespace {\n"
468             "int i;\n"
469             "}",
470             format("namespace {\n"
471                    "int i;\n"
472                    "}",
473                    LLVMWithNoNamespaceFix));
474   EXPECT_EQ("namespace {\n"
475             "int i;\n"
476             "\n"
477             "};",
478             format("namespace {\n"
479                    "int i;\n"
480                    "\n"
481                    "};",
482                    LLVMWithNoNamespaceFix));
483   EXPECT_EQ("namespace {\n"
484             "int i;\n"
485             "};",
486             format("namespace {\n"
487                    "int i;\n"
488                    "};",
489                    LLVMWithNoNamespaceFix));
490   EXPECT_EQ("namespace {\n"
491             "int i;\n"
492             "\n"
493             "}",
494             format("namespace {\n"
495                    "int i;\n"
496                    "\n"
497                    "}"));
498   EXPECT_EQ("namespace {\n"
499             "int i;\n"
500             "\n"
501             "} // namespace",
502             format("namespace {\n"
503                    "int i;\n"
504                    "\n"
505                    "}  // namespace"));
506 
507   FormatStyle Style = getLLVMStyle();
508   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
509   Style.MaxEmptyLinesToKeep = 2;
510   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
511   Style.BraceWrapping.AfterClass = true;
512   Style.BraceWrapping.AfterFunction = true;
513   Style.KeepEmptyLinesAtTheStartOfBlocks = false;
514 
515   EXPECT_EQ("class Foo\n"
516             "{\n"
517             "  Foo() {}\n"
518             "\n"
519             "  void funk() {}\n"
520             "};",
521             format("class Foo\n"
522                    "{\n"
523                    "  Foo()\n"
524                    "  {\n"
525                    "  }\n"
526                    "\n"
527                    "  void funk() {}\n"
528                    "};",
529                    Style));
530 }
531 
532 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
533   verifyFormat("x = (a) and (b);");
534   verifyFormat("x = (a) or (b);");
535   verifyFormat("x = (a) bitand (b);");
536   verifyFormat("x = (a) bitor (b);");
537   verifyFormat("x = (a) not_eq (b);");
538   verifyFormat("x = (a) and_eq (b);");
539   verifyFormat("x = (a) or_eq (b);");
540   verifyFormat("x = (a) xor (b);");
541 }
542 
543 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
544   verifyFormat("x = compl(a);");
545   verifyFormat("x = not(a);");
546   verifyFormat("x = bitand(a);");
547   // Unary operator must not be merged with the next identifier
548   verifyFormat("x = compl a;");
549   verifyFormat("x = not a;");
550   verifyFormat("x = bitand a;");
551 }
552 
553 //===----------------------------------------------------------------------===//
554 // Tests for control statements.
555 //===----------------------------------------------------------------------===//
556 
557 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
558   verifyFormat("if (true)\n  f();\ng();");
559   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
560   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
561   verifyFormat("if constexpr (true)\n"
562                "  f();\ng();");
563   verifyFormat("if CONSTEXPR (true)\n"
564                "  f();\ng();");
565   verifyFormat("if constexpr (a)\n"
566                "  if constexpr (b)\n"
567                "    if constexpr (c)\n"
568                "      g();\n"
569                "h();");
570   verifyFormat("if CONSTEXPR (a)\n"
571                "  if CONSTEXPR (b)\n"
572                "    if CONSTEXPR (c)\n"
573                "      g();\n"
574                "h();");
575   verifyFormat("if constexpr (a)\n"
576                "  if constexpr (b) {\n"
577                "    f();\n"
578                "  }\n"
579                "g();");
580   verifyFormat("if CONSTEXPR (a)\n"
581                "  if CONSTEXPR (b) {\n"
582                "    f();\n"
583                "  }\n"
584                "g();");
585 
586   verifyFormat("if (a)\n"
587                "  g();");
588   verifyFormat("if (a) {\n"
589                "  g()\n"
590                "};");
591   verifyFormat("if (a)\n"
592                "  g();\n"
593                "else\n"
594                "  g();");
595   verifyFormat("if (a) {\n"
596                "  g();\n"
597                "} else\n"
598                "  g();");
599   verifyFormat("if (a)\n"
600                "  g();\n"
601                "else {\n"
602                "  g();\n"
603                "}");
604   verifyFormat("if (a) {\n"
605                "  g();\n"
606                "} else {\n"
607                "  g();\n"
608                "}");
609   verifyFormat("if (a)\n"
610                "  g();\n"
611                "else if (b)\n"
612                "  g();\n"
613                "else\n"
614                "  g();");
615   verifyFormat("if (a) {\n"
616                "  g();\n"
617                "} else if (b)\n"
618                "  g();\n"
619                "else\n"
620                "  g();");
621   verifyFormat("if (a)\n"
622                "  g();\n"
623                "else if (b) {\n"
624                "  g();\n"
625                "} else\n"
626                "  g();");
627   verifyFormat("if (a)\n"
628                "  g();\n"
629                "else if (b)\n"
630                "  g();\n"
631                "else {\n"
632                "  g();\n"
633                "}");
634   verifyFormat("if (a)\n"
635                "  g();\n"
636                "else if (b) {\n"
637                "  g();\n"
638                "} else {\n"
639                "  g();\n"
640                "}");
641   verifyFormat("if (a) {\n"
642                "  g();\n"
643                "} else if (b) {\n"
644                "  g();\n"
645                "} else {\n"
646                "  g();\n"
647                "}");
648 
649   FormatStyle AllowsMergedIf = getLLVMStyle();
650   AllowsMergedIf.IfMacros.push_back("MYIF");
651   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
652   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
653       FormatStyle::SIS_WithoutElse;
654   verifyFormat("if (a)\n"
655                "  // comment\n"
656                "  f();",
657                AllowsMergedIf);
658   verifyFormat("{\n"
659                "  if (a)\n"
660                "  label:\n"
661                "    f();\n"
662                "}",
663                AllowsMergedIf);
664   verifyFormat("#define A \\\n"
665                "  if (a)  \\\n"
666                "  label:  \\\n"
667                "    f()",
668                AllowsMergedIf);
669   verifyFormat("if (a)\n"
670                "  ;",
671                AllowsMergedIf);
672   verifyFormat("if (a)\n"
673                "  if (b) return;",
674                AllowsMergedIf);
675 
676   verifyFormat("if (a) // Can't merge this\n"
677                "  f();\n",
678                AllowsMergedIf);
679   verifyFormat("if (a) /* still don't merge */\n"
680                "  f();",
681                AllowsMergedIf);
682   verifyFormat("if (a) { // Never merge this\n"
683                "  f();\n"
684                "}",
685                AllowsMergedIf);
686   verifyFormat("if (a) { /* Never merge this */\n"
687                "  f();\n"
688                "}",
689                AllowsMergedIf);
690   verifyFormat("MYIF (a)\n"
691                "  // comment\n"
692                "  f();",
693                AllowsMergedIf);
694   verifyFormat("{\n"
695                "  MYIF (a)\n"
696                "  label:\n"
697                "    f();\n"
698                "}",
699                AllowsMergedIf);
700   verifyFormat("#define A  \\\n"
701                "  MYIF (a) \\\n"
702                "  label:   \\\n"
703                "    f()",
704                AllowsMergedIf);
705   verifyFormat("MYIF (a)\n"
706                "  ;",
707                AllowsMergedIf);
708   verifyFormat("MYIF (a)\n"
709                "  MYIF (b) return;",
710                AllowsMergedIf);
711 
712   verifyFormat("MYIF (a) // Can't merge this\n"
713                "  f();\n",
714                AllowsMergedIf);
715   verifyFormat("MYIF (a) /* still don't merge */\n"
716                "  f();",
717                AllowsMergedIf);
718   verifyFormat("MYIF (a) { // Never merge this\n"
719                "  f();\n"
720                "}",
721                AllowsMergedIf);
722   verifyFormat("MYIF (a) { /* Never merge this */\n"
723                "  f();\n"
724                "}",
725                AllowsMergedIf);
726 
727   AllowsMergedIf.ColumnLimit = 14;
728   // Where line-lengths matter, a 2-letter synonym that maintains line length.
729   // Not IF to avoid any confusion that IF is somehow special.
730   AllowsMergedIf.IfMacros.push_back("FI");
731   verifyFormat("if (a) return;", AllowsMergedIf);
732   verifyFormat("if (aaaaaaaaa)\n"
733                "  return;",
734                AllowsMergedIf);
735   verifyFormat("FI (a) return;", AllowsMergedIf);
736   verifyFormat("FI (aaaaaaaaa)\n"
737                "  return;",
738                AllowsMergedIf);
739 
740   AllowsMergedIf.ColumnLimit = 13;
741   verifyFormat("if (a)\n  return;", AllowsMergedIf);
742   verifyFormat("FI (a)\n  return;", AllowsMergedIf);
743 
744   FormatStyle AllowsMergedIfElse = getLLVMStyle();
745   AllowsMergedIfElse.IfMacros.push_back("MYIF");
746   AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine =
747       FormatStyle::SIS_AllIfsAndElse;
748   verifyFormat("if (a)\n"
749                "  // comment\n"
750                "  f();\n"
751                "else\n"
752                "  // comment\n"
753                "  f();",
754                AllowsMergedIfElse);
755   verifyFormat("{\n"
756                "  if (a)\n"
757                "  label:\n"
758                "    f();\n"
759                "  else\n"
760                "  label:\n"
761                "    f();\n"
762                "}",
763                AllowsMergedIfElse);
764   verifyFormat("if (a)\n"
765                "  ;\n"
766                "else\n"
767                "  ;",
768                AllowsMergedIfElse);
769   verifyFormat("if (a) {\n"
770                "} else {\n"
771                "}",
772                AllowsMergedIfElse);
773   verifyFormat("if (a) return;\n"
774                "else if (b) return;\n"
775                "else return;",
776                AllowsMergedIfElse);
777   verifyFormat("if (a) {\n"
778                "} else return;",
779                AllowsMergedIfElse);
780   verifyFormat("if (a) {\n"
781                "} else if (b) return;\n"
782                "else return;",
783                AllowsMergedIfElse);
784   verifyFormat("if (a) return;\n"
785                "else if (b) {\n"
786                "} else return;",
787                AllowsMergedIfElse);
788   verifyFormat("if (a)\n"
789                "  if (b) return;\n"
790                "  else return;",
791                AllowsMergedIfElse);
792   verifyFormat("if constexpr (a)\n"
793                "  if constexpr (b) return;\n"
794                "  else if constexpr (c) return;\n"
795                "  else return;",
796                AllowsMergedIfElse);
797   verifyFormat("MYIF (a)\n"
798                "  // comment\n"
799                "  f();\n"
800                "else\n"
801                "  // comment\n"
802                "  f();",
803                AllowsMergedIfElse);
804   verifyFormat("{\n"
805                "  MYIF (a)\n"
806                "  label:\n"
807                "    f();\n"
808                "  else\n"
809                "  label:\n"
810                "    f();\n"
811                "}",
812                AllowsMergedIfElse);
813   verifyFormat("MYIF (a)\n"
814                "  ;\n"
815                "else\n"
816                "  ;",
817                AllowsMergedIfElse);
818   verifyFormat("MYIF (a) {\n"
819                "} else {\n"
820                "}",
821                AllowsMergedIfElse);
822   verifyFormat("MYIF (a) return;\n"
823                "else MYIF (b) return;\n"
824                "else return;",
825                AllowsMergedIfElse);
826   verifyFormat("MYIF (a) {\n"
827                "} else return;",
828                AllowsMergedIfElse);
829   verifyFormat("MYIF (a) {\n"
830                "} else MYIF (b) return;\n"
831                "else return;",
832                AllowsMergedIfElse);
833   verifyFormat("MYIF (a) return;\n"
834                "else MYIF (b) {\n"
835                "} else return;",
836                AllowsMergedIfElse);
837   verifyFormat("MYIF (a)\n"
838                "  MYIF (b) return;\n"
839                "  else return;",
840                AllowsMergedIfElse);
841   verifyFormat("MYIF constexpr (a)\n"
842                "  MYIF constexpr (b) return;\n"
843                "  else MYIF constexpr (c) return;\n"
844                "  else return;",
845                AllowsMergedIfElse);
846 }
847 
848 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
849   FormatStyle AllowsMergedIf = getLLVMStyle();
850   AllowsMergedIf.IfMacros.push_back("MYIF");
851   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
852   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
853       FormatStyle::SIS_WithoutElse;
854   verifyFormat("if (a)\n"
855                "  f();\n"
856                "else {\n"
857                "  g();\n"
858                "}",
859                AllowsMergedIf);
860   verifyFormat("if (a)\n"
861                "  f();\n"
862                "else\n"
863                "  g();\n",
864                AllowsMergedIf);
865 
866   verifyFormat("if (a) g();", AllowsMergedIf);
867   verifyFormat("if (a) {\n"
868                "  g()\n"
869                "};",
870                AllowsMergedIf);
871   verifyFormat("if (a)\n"
872                "  g();\n"
873                "else\n"
874                "  g();",
875                AllowsMergedIf);
876   verifyFormat("if (a) {\n"
877                "  g();\n"
878                "} else\n"
879                "  g();",
880                AllowsMergedIf);
881   verifyFormat("if (a)\n"
882                "  g();\n"
883                "else {\n"
884                "  g();\n"
885                "}",
886                AllowsMergedIf);
887   verifyFormat("if (a) {\n"
888                "  g();\n"
889                "} else {\n"
890                "  g();\n"
891                "}",
892                AllowsMergedIf);
893   verifyFormat("if (a)\n"
894                "  g();\n"
895                "else if (b)\n"
896                "  g();\n"
897                "else\n"
898                "  g();",
899                AllowsMergedIf);
900   verifyFormat("if (a) {\n"
901                "  g();\n"
902                "} else if (b)\n"
903                "  g();\n"
904                "else\n"
905                "  g();",
906                AllowsMergedIf);
907   verifyFormat("if (a)\n"
908                "  g();\n"
909                "else if (b) {\n"
910                "  g();\n"
911                "} else\n"
912                "  g();",
913                AllowsMergedIf);
914   verifyFormat("if (a)\n"
915                "  g();\n"
916                "else if (b)\n"
917                "  g();\n"
918                "else {\n"
919                "  g();\n"
920                "}",
921                AllowsMergedIf);
922   verifyFormat("if (a)\n"
923                "  g();\n"
924                "else if (b) {\n"
925                "  g();\n"
926                "} else {\n"
927                "  g();\n"
928                "}",
929                AllowsMergedIf);
930   verifyFormat("if (a) {\n"
931                "  g();\n"
932                "} else if (b) {\n"
933                "  g();\n"
934                "} else {\n"
935                "  g();\n"
936                "}",
937                AllowsMergedIf);
938   verifyFormat("MYIF (a)\n"
939                "  f();\n"
940                "else {\n"
941                "  g();\n"
942                "}",
943                AllowsMergedIf);
944   verifyFormat("MYIF (a)\n"
945                "  f();\n"
946                "else\n"
947                "  g();\n",
948                AllowsMergedIf);
949 
950   verifyFormat("MYIF (a) g();", AllowsMergedIf);
951   verifyFormat("MYIF (a) {\n"
952                "  g()\n"
953                "};",
954                AllowsMergedIf);
955   verifyFormat("MYIF (a)\n"
956                "  g();\n"
957                "else\n"
958                "  g();",
959                AllowsMergedIf);
960   verifyFormat("MYIF (a) {\n"
961                "  g();\n"
962                "} else\n"
963                "  g();",
964                AllowsMergedIf);
965   verifyFormat("MYIF (a)\n"
966                "  g();\n"
967                "else {\n"
968                "  g();\n"
969                "}",
970                AllowsMergedIf);
971   verifyFormat("MYIF (a) {\n"
972                "  g();\n"
973                "} else {\n"
974                "  g();\n"
975                "}",
976                AllowsMergedIf);
977   verifyFormat("MYIF (a)\n"
978                "  g();\n"
979                "else MYIF (b)\n"
980                "  g();\n"
981                "else\n"
982                "  g();",
983                AllowsMergedIf);
984   verifyFormat("MYIF (a)\n"
985                "  g();\n"
986                "else if (b)\n"
987                "  g();\n"
988                "else\n"
989                "  g();",
990                AllowsMergedIf);
991   verifyFormat("MYIF (a) {\n"
992                "  g();\n"
993                "} else MYIF (b)\n"
994                "  g();\n"
995                "else\n"
996                "  g();",
997                AllowsMergedIf);
998   verifyFormat("MYIF (a) {\n"
999                "  g();\n"
1000                "} else if (b)\n"
1001                "  g();\n"
1002                "else\n"
1003                "  g();",
1004                AllowsMergedIf);
1005   verifyFormat("MYIF (a)\n"
1006                "  g();\n"
1007                "else MYIF (b) {\n"
1008                "  g();\n"
1009                "} else\n"
1010                "  g();",
1011                AllowsMergedIf);
1012   verifyFormat("MYIF (a)\n"
1013                "  g();\n"
1014                "else if (b) {\n"
1015                "  g();\n"
1016                "} else\n"
1017                "  g();",
1018                AllowsMergedIf);
1019   verifyFormat("MYIF (a)\n"
1020                "  g();\n"
1021                "else MYIF (b)\n"
1022                "  g();\n"
1023                "else {\n"
1024                "  g();\n"
1025                "}",
1026                AllowsMergedIf);
1027   verifyFormat("MYIF (a)\n"
1028                "  g();\n"
1029                "else if (b)\n"
1030                "  g();\n"
1031                "else {\n"
1032                "  g();\n"
1033                "}",
1034                AllowsMergedIf);
1035   verifyFormat("MYIF (a)\n"
1036                "  g();\n"
1037                "else MYIF (b) {\n"
1038                "  g();\n"
1039                "} else {\n"
1040                "  g();\n"
1041                "}",
1042                AllowsMergedIf);
1043   verifyFormat("MYIF (a)\n"
1044                "  g();\n"
1045                "else if (b) {\n"
1046                "  g();\n"
1047                "} else {\n"
1048                "  g();\n"
1049                "}",
1050                AllowsMergedIf);
1051   verifyFormat("MYIF (a) {\n"
1052                "  g();\n"
1053                "} else MYIF (b) {\n"
1054                "  g();\n"
1055                "} else {\n"
1056                "  g();\n"
1057                "}",
1058                AllowsMergedIf);
1059   verifyFormat("MYIF (a) {\n"
1060                "  g();\n"
1061                "} else if (b) {\n"
1062                "  g();\n"
1063                "} else {\n"
1064                "  g();\n"
1065                "}",
1066                AllowsMergedIf);
1067 
1068   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1069       FormatStyle::SIS_OnlyFirstIf;
1070 
1071   verifyFormat("if (a) f();\n"
1072                "else {\n"
1073                "  g();\n"
1074                "}",
1075                AllowsMergedIf);
1076   verifyFormat("if (a) f();\n"
1077                "else {\n"
1078                "  if (a) f();\n"
1079                "  else {\n"
1080                "    g();\n"
1081                "  }\n"
1082                "  g();\n"
1083                "}",
1084                AllowsMergedIf);
1085 
1086   verifyFormat("if (a) g();", AllowsMergedIf);
1087   verifyFormat("if (a) {\n"
1088                "  g()\n"
1089                "};",
1090                AllowsMergedIf);
1091   verifyFormat("if (a) g();\n"
1092                "else\n"
1093                "  g();",
1094                AllowsMergedIf);
1095   verifyFormat("if (a) {\n"
1096                "  g();\n"
1097                "} else\n"
1098                "  g();",
1099                AllowsMergedIf);
1100   verifyFormat("if (a) g();\n"
1101                "else {\n"
1102                "  g();\n"
1103                "}",
1104                AllowsMergedIf);
1105   verifyFormat("if (a) {\n"
1106                "  g();\n"
1107                "} else {\n"
1108                "  g();\n"
1109                "}",
1110                AllowsMergedIf);
1111   verifyFormat("if (a) g();\n"
1112                "else if (b)\n"
1113                "  g();\n"
1114                "else\n"
1115                "  g();",
1116                AllowsMergedIf);
1117   verifyFormat("if (a) {\n"
1118                "  g();\n"
1119                "} else if (b)\n"
1120                "  g();\n"
1121                "else\n"
1122                "  g();",
1123                AllowsMergedIf);
1124   verifyFormat("if (a) g();\n"
1125                "else if (b) {\n"
1126                "  g();\n"
1127                "} else\n"
1128                "  g();",
1129                AllowsMergedIf);
1130   verifyFormat("if (a) g();\n"
1131                "else if (b)\n"
1132                "  g();\n"
1133                "else {\n"
1134                "  g();\n"
1135                "}",
1136                AllowsMergedIf);
1137   verifyFormat("if (a) g();\n"
1138                "else if (b) {\n"
1139                "  g();\n"
1140                "} else {\n"
1141                "  g();\n"
1142                "}",
1143                AllowsMergedIf);
1144   verifyFormat("if (a) {\n"
1145                "  g();\n"
1146                "} else if (b) {\n"
1147                "  g();\n"
1148                "} else {\n"
1149                "  g();\n"
1150                "}",
1151                AllowsMergedIf);
1152   verifyFormat("MYIF (a) f();\n"
1153                "else {\n"
1154                "  g();\n"
1155                "}",
1156                AllowsMergedIf);
1157   verifyFormat("MYIF (a) f();\n"
1158                "else {\n"
1159                "  if (a) f();\n"
1160                "  else {\n"
1161                "    g();\n"
1162                "  }\n"
1163                "  g();\n"
1164                "}",
1165                AllowsMergedIf);
1166 
1167   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1168   verifyFormat("MYIF (a) {\n"
1169                "  g()\n"
1170                "};",
1171                AllowsMergedIf);
1172   verifyFormat("MYIF (a) g();\n"
1173                "else\n"
1174                "  g();",
1175                AllowsMergedIf);
1176   verifyFormat("MYIF (a) {\n"
1177                "  g();\n"
1178                "} else\n"
1179                "  g();",
1180                AllowsMergedIf);
1181   verifyFormat("MYIF (a) g();\n"
1182                "else {\n"
1183                "  g();\n"
1184                "}",
1185                AllowsMergedIf);
1186   verifyFormat("MYIF (a) {\n"
1187                "  g();\n"
1188                "} else {\n"
1189                "  g();\n"
1190                "}",
1191                AllowsMergedIf);
1192   verifyFormat("MYIF (a) g();\n"
1193                "else MYIF (b)\n"
1194                "  g();\n"
1195                "else\n"
1196                "  g();",
1197                AllowsMergedIf);
1198   verifyFormat("MYIF (a) g();\n"
1199                "else if (b)\n"
1200                "  g();\n"
1201                "else\n"
1202                "  g();",
1203                AllowsMergedIf);
1204   verifyFormat("MYIF (a) {\n"
1205                "  g();\n"
1206                "} else MYIF (b)\n"
1207                "  g();\n"
1208                "else\n"
1209                "  g();",
1210                AllowsMergedIf);
1211   verifyFormat("MYIF (a) {\n"
1212                "  g();\n"
1213                "} else if (b)\n"
1214                "  g();\n"
1215                "else\n"
1216                "  g();",
1217                AllowsMergedIf);
1218   verifyFormat("MYIF (a) g();\n"
1219                "else MYIF (b) {\n"
1220                "  g();\n"
1221                "} else\n"
1222                "  g();",
1223                AllowsMergedIf);
1224   verifyFormat("MYIF (a) g();\n"
1225                "else if (b) {\n"
1226                "  g();\n"
1227                "} else\n"
1228                "  g();",
1229                AllowsMergedIf);
1230   verifyFormat("MYIF (a) g();\n"
1231                "else MYIF (b)\n"
1232                "  g();\n"
1233                "else {\n"
1234                "  g();\n"
1235                "}",
1236                AllowsMergedIf);
1237   verifyFormat("MYIF (a) g();\n"
1238                "else if (b)\n"
1239                "  g();\n"
1240                "else {\n"
1241                "  g();\n"
1242                "}",
1243                AllowsMergedIf);
1244   verifyFormat("MYIF (a) g();\n"
1245                "else MYIF (b) {\n"
1246                "  g();\n"
1247                "} else {\n"
1248                "  g();\n"
1249                "}",
1250                AllowsMergedIf);
1251   verifyFormat("MYIF (a) g();\n"
1252                "else if (b) {\n"
1253                "  g();\n"
1254                "} else {\n"
1255                "  g();\n"
1256                "}",
1257                AllowsMergedIf);
1258   verifyFormat("MYIF (a) {\n"
1259                "  g();\n"
1260                "} else MYIF (b) {\n"
1261                "  g();\n"
1262                "} else {\n"
1263                "  g();\n"
1264                "}",
1265                AllowsMergedIf);
1266   verifyFormat("MYIF (a) {\n"
1267                "  g();\n"
1268                "} else if (b) {\n"
1269                "  g();\n"
1270                "} else {\n"
1271                "  g();\n"
1272                "}",
1273                AllowsMergedIf);
1274 
1275   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1276       FormatStyle::SIS_AllIfsAndElse;
1277 
1278   verifyFormat("if (a) f();\n"
1279                "else {\n"
1280                "  g();\n"
1281                "}",
1282                AllowsMergedIf);
1283   verifyFormat("if (a) f();\n"
1284                "else {\n"
1285                "  if (a) f();\n"
1286                "  else {\n"
1287                "    g();\n"
1288                "  }\n"
1289                "  g();\n"
1290                "}",
1291                AllowsMergedIf);
1292 
1293   verifyFormat("if (a) g();", AllowsMergedIf);
1294   verifyFormat("if (a) {\n"
1295                "  g()\n"
1296                "};",
1297                AllowsMergedIf);
1298   verifyFormat("if (a) g();\n"
1299                "else g();",
1300                AllowsMergedIf);
1301   verifyFormat("if (a) {\n"
1302                "  g();\n"
1303                "} else g();",
1304                AllowsMergedIf);
1305   verifyFormat("if (a) g();\n"
1306                "else {\n"
1307                "  g();\n"
1308                "}",
1309                AllowsMergedIf);
1310   verifyFormat("if (a) {\n"
1311                "  g();\n"
1312                "} else {\n"
1313                "  g();\n"
1314                "}",
1315                AllowsMergedIf);
1316   verifyFormat("if (a) g();\n"
1317                "else if (b) g();\n"
1318                "else g();",
1319                AllowsMergedIf);
1320   verifyFormat("if (a) {\n"
1321                "  g();\n"
1322                "} else if (b) g();\n"
1323                "else g();",
1324                AllowsMergedIf);
1325   verifyFormat("if (a) g();\n"
1326                "else if (b) {\n"
1327                "  g();\n"
1328                "} else g();",
1329                AllowsMergedIf);
1330   verifyFormat("if (a) g();\n"
1331                "else if (b) g();\n"
1332                "else {\n"
1333                "  g();\n"
1334                "}",
1335                AllowsMergedIf);
1336   verifyFormat("if (a) g();\n"
1337                "else if (b) {\n"
1338                "  g();\n"
1339                "} else {\n"
1340                "  g();\n"
1341                "}",
1342                AllowsMergedIf);
1343   verifyFormat("if (a) {\n"
1344                "  g();\n"
1345                "} else if (b) {\n"
1346                "  g();\n"
1347                "} else {\n"
1348                "  g();\n"
1349                "}",
1350                AllowsMergedIf);
1351   verifyFormat("MYIF (a) f();\n"
1352                "else {\n"
1353                "  g();\n"
1354                "}",
1355                AllowsMergedIf);
1356   verifyFormat("MYIF (a) f();\n"
1357                "else {\n"
1358                "  if (a) f();\n"
1359                "  else {\n"
1360                "    g();\n"
1361                "  }\n"
1362                "  g();\n"
1363                "}",
1364                AllowsMergedIf);
1365 
1366   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1367   verifyFormat("MYIF (a) {\n"
1368                "  g()\n"
1369                "};",
1370                AllowsMergedIf);
1371   verifyFormat("MYIF (a) g();\n"
1372                "else g();",
1373                AllowsMergedIf);
1374   verifyFormat("MYIF (a) {\n"
1375                "  g();\n"
1376                "} else g();",
1377                AllowsMergedIf);
1378   verifyFormat("MYIF (a) g();\n"
1379                "else {\n"
1380                "  g();\n"
1381                "}",
1382                AllowsMergedIf);
1383   verifyFormat("MYIF (a) {\n"
1384                "  g();\n"
1385                "} else {\n"
1386                "  g();\n"
1387                "}",
1388                AllowsMergedIf);
1389   verifyFormat("MYIF (a) g();\n"
1390                "else MYIF (b) g();\n"
1391                "else g();",
1392                AllowsMergedIf);
1393   verifyFormat("MYIF (a) g();\n"
1394                "else if (b) g();\n"
1395                "else g();",
1396                AllowsMergedIf);
1397   verifyFormat("MYIF (a) {\n"
1398                "  g();\n"
1399                "} else MYIF (b) g();\n"
1400                "else g();",
1401                AllowsMergedIf);
1402   verifyFormat("MYIF (a) {\n"
1403                "  g();\n"
1404                "} else if (b) g();\n"
1405                "else g();",
1406                AllowsMergedIf);
1407   verifyFormat("MYIF (a) g();\n"
1408                "else MYIF (b) {\n"
1409                "  g();\n"
1410                "} else g();",
1411                AllowsMergedIf);
1412   verifyFormat("MYIF (a) g();\n"
1413                "else if (b) {\n"
1414                "  g();\n"
1415                "} else g();",
1416                AllowsMergedIf);
1417   verifyFormat("MYIF (a) g();\n"
1418                "else MYIF (b) g();\n"
1419                "else {\n"
1420                "  g();\n"
1421                "}",
1422                AllowsMergedIf);
1423   verifyFormat("MYIF (a) g();\n"
1424                "else if (b) g();\n"
1425                "else {\n"
1426                "  g();\n"
1427                "}",
1428                AllowsMergedIf);
1429   verifyFormat("MYIF (a) g();\n"
1430                "else MYIF (b) {\n"
1431                "  g();\n"
1432                "} else {\n"
1433                "  g();\n"
1434                "}",
1435                AllowsMergedIf);
1436   verifyFormat("MYIF (a) g();\n"
1437                "else if (b) {\n"
1438                "  g();\n"
1439                "} else {\n"
1440                "  g();\n"
1441                "}",
1442                AllowsMergedIf);
1443   verifyFormat("MYIF (a) {\n"
1444                "  g();\n"
1445                "} else MYIF (b) {\n"
1446                "  g();\n"
1447                "} else {\n"
1448                "  g();\n"
1449                "}",
1450                AllowsMergedIf);
1451   verifyFormat("MYIF (a) {\n"
1452                "  g();\n"
1453                "} else if (b) {\n"
1454                "  g();\n"
1455                "} else {\n"
1456                "  g();\n"
1457                "}",
1458                AllowsMergedIf);
1459 }
1460 
1461 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
1462   FormatStyle AllowsMergedLoops = getLLVMStyle();
1463   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
1464   verifyFormat("while (true) continue;", AllowsMergedLoops);
1465   verifyFormat("for (;;) continue;", AllowsMergedLoops);
1466   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
1467   verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
1468   verifyFormat("while (true)\n"
1469                "  ;",
1470                AllowsMergedLoops);
1471   verifyFormat("for (;;)\n"
1472                "  ;",
1473                AllowsMergedLoops);
1474   verifyFormat("for (;;)\n"
1475                "  for (;;) continue;",
1476                AllowsMergedLoops);
1477   verifyFormat("for (;;)\n"
1478                "  while (true) continue;",
1479                AllowsMergedLoops);
1480   verifyFormat("while (true)\n"
1481                "  for (;;) continue;",
1482                AllowsMergedLoops);
1483   verifyFormat("BOOST_FOREACH (int &v, vec)\n"
1484                "  for (;;) continue;",
1485                AllowsMergedLoops);
1486   verifyFormat("for (;;)\n"
1487                "  BOOST_FOREACH (int &v, vec) continue;",
1488                AllowsMergedLoops);
1489   verifyFormat("for (;;) // Can't merge this\n"
1490                "  continue;",
1491                AllowsMergedLoops);
1492   verifyFormat("for (;;) /* still don't merge */\n"
1493                "  continue;",
1494                AllowsMergedLoops);
1495   verifyFormat("do a++;\n"
1496                "while (true);",
1497                AllowsMergedLoops);
1498   verifyFormat("do /* Don't merge */\n"
1499                "  a++;\n"
1500                "while (true);",
1501                AllowsMergedLoops);
1502   verifyFormat("do // Don't merge\n"
1503                "  a++;\n"
1504                "while (true);",
1505                AllowsMergedLoops);
1506   verifyFormat("do\n"
1507                "  // Don't merge\n"
1508                "  a++;\n"
1509                "while (true);",
1510                AllowsMergedLoops);
1511   // Without braces labels are interpreted differently.
1512   verifyFormat("{\n"
1513                "  do\n"
1514                "  label:\n"
1515                "    a++;\n"
1516                "  while (true);\n"
1517                "}",
1518                AllowsMergedLoops);
1519 }
1520 
1521 TEST_F(FormatTest, FormatShortBracedStatements) {
1522   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
1523   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false);
1524   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine,
1525             FormatStyle::SIS_Never);
1526   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false);
1527   EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false);
1528   verifyFormat("for (;;) {\n"
1529                "  f();\n"
1530                "}");
1531   verifyFormat("/*comment*/ for (;;) {\n"
1532                "  f();\n"
1533                "}");
1534   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1535                "  f();\n"
1536                "}");
1537   verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n"
1538                "  f();\n"
1539                "}");
1540   verifyFormat("while (true) {\n"
1541                "  f();\n"
1542                "}");
1543   verifyFormat("/*comment*/ while (true) {\n"
1544                "  f();\n"
1545                "}");
1546   verifyFormat("if (true) {\n"
1547                "  f();\n"
1548                "}");
1549   verifyFormat("/*comment*/ if (true) {\n"
1550                "  f();\n"
1551                "}");
1552 
1553   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
1554   // Where line-lengths matter, a 2-letter synonym that maintains line length.
1555   // Not IF to avoid any confusion that IF is somehow special.
1556   AllowSimpleBracedStatements.IfMacros.push_back("FI");
1557   AllowSimpleBracedStatements.ColumnLimit = 40;
1558   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1559       FormatStyle::SBS_Always;
1560 
1561   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1562       FormatStyle::SIS_WithoutElse;
1563   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1564 
1565   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1566   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1567   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1568 
1569   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1570   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1571   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1572   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1573   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1574   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1575   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1576   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1577   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1578   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1579   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1580   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1581   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1582   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1583   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1584   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1585   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1586                AllowSimpleBracedStatements);
1587   verifyFormat("if (true) {\n"
1588                "  ffffffffffffffffffffffff();\n"
1589                "}",
1590                AllowSimpleBracedStatements);
1591   verifyFormat("if (true) {\n"
1592                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1593                "}",
1594                AllowSimpleBracedStatements);
1595   verifyFormat("if (true) { //\n"
1596                "  f();\n"
1597                "}",
1598                AllowSimpleBracedStatements);
1599   verifyFormat("if (true) {\n"
1600                "  f();\n"
1601                "  f();\n"
1602                "}",
1603                AllowSimpleBracedStatements);
1604   verifyFormat("if (true) {\n"
1605                "  f();\n"
1606                "} else {\n"
1607                "  f();\n"
1608                "}",
1609                AllowSimpleBracedStatements);
1610   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1611                AllowSimpleBracedStatements);
1612   verifyFormat("MYIF (true) {\n"
1613                "  ffffffffffffffffffffffff();\n"
1614                "}",
1615                AllowSimpleBracedStatements);
1616   verifyFormat("MYIF (true) {\n"
1617                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1618                "}",
1619                AllowSimpleBracedStatements);
1620   verifyFormat("MYIF (true) { //\n"
1621                "  f();\n"
1622                "}",
1623                AllowSimpleBracedStatements);
1624   verifyFormat("MYIF (true) {\n"
1625                "  f();\n"
1626                "  f();\n"
1627                "}",
1628                AllowSimpleBracedStatements);
1629   verifyFormat("MYIF (true) {\n"
1630                "  f();\n"
1631                "} else {\n"
1632                "  f();\n"
1633                "}",
1634                AllowSimpleBracedStatements);
1635 
1636   verifyFormat("struct A2 {\n"
1637                "  int X;\n"
1638                "};",
1639                AllowSimpleBracedStatements);
1640   verifyFormat("typedef struct A2 {\n"
1641                "  int X;\n"
1642                "} A2_t;",
1643                AllowSimpleBracedStatements);
1644   verifyFormat("template <int> struct A2 {\n"
1645                "  struct B {};\n"
1646                "};",
1647                AllowSimpleBracedStatements);
1648 
1649   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1650       FormatStyle::SIS_Never;
1651   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1652   verifyFormat("if (true) {\n"
1653                "  f();\n"
1654                "}",
1655                AllowSimpleBracedStatements);
1656   verifyFormat("if (true) {\n"
1657                "  f();\n"
1658                "} else {\n"
1659                "  f();\n"
1660                "}",
1661                AllowSimpleBracedStatements);
1662   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1663   verifyFormat("MYIF (true) {\n"
1664                "  f();\n"
1665                "}",
1666                AllowSimpleBracedStatements);
1667   verifyFormat("MYIF (true) {\n"
1668                "  f();\n"
1669                "} else {\n"
1670                "  f();\n"
1671                "}",
1672                AllowSimpleBracedStatements);
1673 
1674   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1675   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1676   verifyFormat("while (true) {\n"
1677                "  f();\n"
1678                "}",
1679                AllowSimpleBracedStatements);
1680   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1681   verifyFormat("for (;;) {\n"
1682                "  f();\n"
1683                "}",
1684                AllowSimpleBracedStatements);
1685   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1686   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1687                "  f();\n"
1688                "}",
1689                AllowSimpleBracedStatements);
1690 
1691   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1692       FormatStyle::SIS_WithoutElse;
1693   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1694   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1695       FormatStyle::BWACS_Always;
1696 
1697   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1698   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1699   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1700   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1701   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1702   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1703   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1704   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1705   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1706   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1707   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1708   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1709   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1710   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1711   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1712   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1713   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1714                AllowSimpleBracedStatements);
1715   verifyFormat("if (true)\n"
1716                "{\n"
1717                "  ffffffffffffffffffffffff();\n"
1718                "}",
1719                AllowSimpleBracedStatements);
1720   verifyFormat("if (true)\n"
1721                "{\n"
1722                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1723                "}",
1724                AllowSimpleBracedStatements);
1725   verifyFormat("if (true)\n"
1726                "{ //\n"
1727                "  f();\n"
1728                "}",
1729                AllowSimpleBracedStatements);
1730   verifyFormat("if (true)\n"
1731                "{\n"
1732                "  f();\n"
1733                "  f();\n"
1734                "}",
1735                AllowSimpleBracedStatements);
1736   verifyFormat("if (true)\n"
1737                "{\n"
1738                "  f();\n"
1739                "} else\n"
1740                "{\n"
1741                "  f();\n"
1742                "}",
1743                AllowSimpleBracedStatements);
1744   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1745                AllowSimpleBracedStatements);
1746   verifyFormat("MYIF (true)\n"
1747                "{\n"
1748                "  ffffffffffffffffffffffff();\n"
1749                "}",
1750                AllowSimpleBracedStatements);
1751   verifyFormat("MYIF (true)\n"
1752                "{\n"
1753                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1754                "}",
1755                AllowSimpleBracedStatements);
1756   verifyFormat("MYIF (true)\n"
1757                "{ //\n"
1758                "  f();\n"
1759                "}",
1760                AllowSimpleBracedStatements);
1761   verifyFormat("MYIF (true)\n"
1762                "{\n"
1763                "  f();\n"
1764                "  f();\n"
1765                "}",
1766                AllowSimpleBracedStatements);
1767   verifyFormat("MYIF (true)\n"
1768                "{\n"
1769                "  f();\n"
1770                "} else\n"
1771                "{\n"
1772                "  f();\n"
1773                "}",
1774                AllowSimpleBracedStatements);
1775 
1776   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1777       FormatStyle::SIS_Never;
1778   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1779   verifyFormat("if (true)\n"
1780                "{\n"
1781                "  f();\n"
1782                "}",
1783                AllowSimpleBracedStatements);
1784   verifyFormat("if (true)\n"
1785                "{\n"
1786                "  f();\n"
1787                "} else\n"
1788                "{\n"
1789                "  f();\n"
1790                "}",
1791                AllowSimpleBracedStatements);
1792   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1793   verifyFormat("MYIF (true)\n"
1794                "{\n"
1795                "  f();\n"
1796                "}",
1797                AllowSimpleBracedStatements);
1798   verifyFormat("MYIF (true)\n"
1799                "{\n"
1800                "  f();\n"
1801                "} else\n"
1802                "{\n"
1803                "  f();\n"
1804                "}",
1805                AllowSimpleBracedStatements);
1806 
1807   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1808   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1809   verifyFormat("while (true)\n"
1810                "{\n"
1811                "  f();\n"
1812                "}",
1813                AllowSimpleBracedStatements);
1814   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1815   verifyFormat("for (;;)\n"
1816                "{\n"
1817                "  f();\n"
1818                "}",
1819                AllowSimpleBracedStatements);
1820   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1821   verifyFormat("BOOST_FOREACH (int v, vec)\n"
1822                "{\n"
1823                "  f();\n"
1824                "}",
1825                AllowSimpleBracedStatements);
1826 }
1827 
1828 TEST_F(FormatTest, UnderstandsMacros) {
1829   verifyFormat("#define A (parentheses)");
1830   verifyFormat("/* comment */ #define A (parentheses)");
1831   verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
1832   // Even the partial code should never be merged.
1833   EXPECT_EQ("/* comment */ #define A (parentheses)\n"
1834             "#",
1835             format("/* comment */ #define A (parentheses)\n"
1836                    "#"));
1837   verifyFormat("/* comment */ #define A (parentheses)\n"
1838                "#\n");
1839   verifyFormat("/* comment */ #define A (parentheses)\n"
1840                "#define B (parentheses)");
1841   verifyFormat("#define true ((int)1)");
1842   verifyFormat("#define and(x)");
1843   verifyFormat("#define if(x) x");
1844   verifyFormat("#define return(x) (x)");
1845   verifyFormat("#define while(x) for (; x;)");
1846   verifyFormat("#define xor(x) (^(x))");
1847   verifyFormat("#define __except(x)");
1848   verifyFormat("#define __try(x)");
1849 
1850   FormatStyle Style = getLLVMStyle();
1851   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1852   Style.BraceWrapping.AfterFunction = true;
1853   // Test that a macro definition never gets merged with the following
1854   // definition.
1855   // FIXME: The AAA macro definition probably should not be split into 3 lines.
1856   verifyFormat("#define AAA                                                    "
1857                "                \\\n"
1858                "  N                                                            "
1859                "                \\\n"
1860                "  {\n"
1861                "#define BBB }\n",
1862                Style);
1863   // verifyFormat("#define AAA N { //\n", Style);
1864 
1865   verifyFormat("MACRO(return)");
1866   verifyFormat("MACRO(co_await)");
1867   verifyFormat("MACRO(co_return)");
1868   verifyFormat("MACRO(co_yield)");
1869   verifyFormat("MACRO(return, something)");
1870   verifyFormat("MACRO(co_return, something)");
1871   verifyFormat("MACRO(something##something)");
1872   verifyFormat("MACRO(return##something)");
1873   verifyFormat("MACRO(co_return##something)");
1874 }
1875 
1876 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1877   FormatStyle Style = getLLVMStyleWithColumns(60);
1878   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1879   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1880   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1881   EXPECT_EQ("#define A                                                  \\\n"
1882             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1883             "  {                                                        \\\n"
1884             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1885             "  }\n"
1886             "X;",
1887             format("#define A \\\n"
1888                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1889                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1890                    "   }\n"
1891                    "X;",
1892                    Style));
1893 }
1894 
1895 TEST_F(FormatTest, ParseIfElse) {
1896   verifyFormat("if (true)\n"
1897                "  if (true)\n"
1898                "    if (true)\n"
1899                "      f();\n"
1900                "    else\n"
1901                "      g();\n"
1902                "  else\n"
1903                "    h();\n"
1904                "else\n"
1905                "  i();");
1906   verifyFormat("if (true)\n"
1907                "  if (true)\n"
1908                "    if (true) {\n"
1909                "      if (true)\n"
1910                "        f();\n"
1911                "    } else {\n"
1912                "      g();\n"
1913                "    }\n"
1914                "  else\n"
1915                "    h();\n"
1916                "else {\n"
1917                "  i();\n"
1918                "}");
1919   verifyFormat("if (true)\n"
1920                "  if constexpr (true)\n"
1921                "    if (true) {\n"
1922                "      if constexpr (true)\n"
1923                "        f();\n"
1924                "    } else {\n"
1925                "      g();\n"
1926                "    }\n"
1927                "  else\n"
1928                "    h();\n"
1929                "else {\n"
1930                "  i();\n"
1931                "}");
1932   verifyFormat("if (true)\n"
1933                "  if CONSTEXPR (true)\n"
1934                "    if (true) {\n"
1935                "      if CONSTEXPR (true)\n"
1936                "        f();\n"
1937                "    } else {\n"
1938                "      g();\n"
1939                "    }\n"
1940                "  else\n"
1941                "    h();\n"
1942                "else {\n"
1943                "  i();\n"
1944                "}");
1945   verifyFormat("void f() {\n"
1946                "  if (a) {\n"
1947                "  } else {\n"
1948                "  }\n"
1949                "}");
1950 }
1951 
1952 TEST_F(FormatTest, ElseIf) {
1953   verifyFormat("if (a) {\n} else if (b) {\n}");
1954   verifyFormat("if (a)\n"
1955                "  f();\n"
1956                "else if (b)\n"
1957                "  g();\n"
1958                "else\n"
1959                "  h();");
1960   verifyFormat("if (a)\n"
1961                "  f();\n"
1962                "else // comment\n"
1963                "  if (b) {\n"
1964                "    g();\n"
1965                "    h();\n"
1966                "  }");
1967   verifyFormat("if constexpr (a)\n"
1968                "  f();\n"
1969                "else if constexpr (b)\n"
1970                "  g();\n"
1971                "else\n"
1972                "  h();");
1973   verifyFormat("if CONSTEXPR (a)\n"
1974                "  f();\n"
1975                "else if CONSTEXPR (b)\n"
1976                "  g();\n"
1977                "else\n"
1978                "  h();");
1979   verifyFormat("if (a) {\n"
1980                "  f();\n"
1981                "}\n"
1982                "// or else ..\n"
1983                "else {\n"
1984                "  g()\n"
1985                "}");
1986 
1987   verifyFormat("if (a) {\n"
1988                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1989                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1990                "}");
1991   verifyFormat("if (a) {\n"
1992                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1993                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1994                "}");
1995   verifyFormat("if (a) {\n"
1996                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1997                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1998                "}");
1999   verifyFormat("if (a) {\n"
2000                "} else if (\n"
2001                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2002                "}",
2003                getLLVMStyleWithColumns(62));
2004   verifyFormat("if (a) {\n"
2005                "} else if constexpr (\n"
2006                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2007                "}",
2008                getLLVMStyleWithColumns(62));
2009   verifyFormat("if (a) {\n"
2010                "} else if CONSTEXPR (\n"
2011                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2012                "}",
2013                getLLVMStyleWithColumns(62));
2014 }
2015 
2016 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
2017   FormatStyle Style = getLLVMStyle();
2018   EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
2019   EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer);
2020   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
2021   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
2022   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
2023   verifyFormat("int *f1(int &a) const &;", Style);
2024   verifyFormat("int *f1(int &a) const & = 0;", Style);
2025   verifyFormat("int *a = f1();", Style);
2026   verifyFormat("int &b = f2();", Style);
2027   verifyFormat("int &&c = f3();", Style);
2028   verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
2029   verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2030   verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
2031   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2032   verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
2033   verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2034   verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
2035   verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
2036   verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
2037   verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
2038   verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
2039   verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
2040   verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
2041   verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
2042   verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
2043   verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
2044   verifyFormat(
2045       "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n"
2046       "                     res2 = [](int &a) { return 0000000000000; };",
2047       Style);
2048 
2049   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2050   verifyFormat("Const unsigned int *c;\n"
2051                "const unsigned int *d;\n"
2052                "Const unsigned int &e;\n"
2053                "const unsigned int &f;\n"
2054                "const unsigned    &&g;\n"
2055                "Const unsigned      h;",
2056                Style);
2057 
2058   Style.PointerAlignment = FormatStyle::PAS_Left;
2059   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
2060   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
2061   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
2062   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
2063   verifyFormat("int* f1(int& a) const& = 0;", Style);
2064   verifyFormat("int* a = f1();", Style);
2065   verifyFormat("int& b = f2();", Style);
2066   verifyFormat("int&& c = f3();", Style);
2067   verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2068   verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2069   verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2070   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2071   verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2072   verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2073   verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2074   verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2075   verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
2076   verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
2077   verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
2078   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2079   verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
2080   verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
2081   verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
2082   verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
2083   verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
2084   verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
2085   verifyFormat(
2086       "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n"
2087       "                    res2 = [](int& a) { return 0000000000000; };",
2088       Style);
2089 
2090   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2091   verifyFormat("Const unsigned int* c;\n"
2092                "const unsigned int* d;\n"
2093                "Const unsigned int& e;\n"
2094                "const unsigned int& f;\n"
2095                "const unsigned&&    g;\n"
2096                "Const unsigned      h;",
2097                Style);
2098 
2099   Style.PointerAlignment = FormatStyle::PAS_Right;
2100   Style.ReferenceAlignment = FormatStyle::RAS_Left;
2101   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
2102   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
2103   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
2104   verifyFormat("int *a = f1();", Style);
2105   verifyFormat("int& b = f2();", Style);
2106   verifyFormat("int&& c = f3();", Style);
2107   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2108   verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2109   verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
2110 
2111   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2112   verifyFormat("Const unsigned int *c;\n"
2113                "const unsigned int *d;\n"
2114                "Const unsigned int& e;\n"
2115                "const unsigned int& f;\n"
2116                "const unsigned      g;\n"
2117                "Const unsigned      h;",
2118                Style);
2119 
2120   Style.PointerAlignment = FormatStyle::PAS_Left;
2121   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
2122   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
2123   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
2124   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
2125   verifyFormat("int* a = f1();", Style);
2126   verifyFormat("int & b = f2();", Style);
2127   verifyFormat("int && c = f3();", Style);
2128   verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
2129   verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
2130   verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
2131   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2132   verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
2133   verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
2134   verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
2135   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2136   verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
2137   verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
2138   verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
2139   verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
2140   verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
2141   verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
2142   verifyFormat(
2143       "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n"
2144       "                     res2 = [](int & a) { return 0000000000000; };",
2145       Style);
2146 
2147   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2148   verifyFormat("Const unsigned int*  c;\n"
2149                "const unsigned int*  d;\n"
2150                "Const unsigned int & e;\n"
2151                "const unsigned int & f;\n"
2152                "const unsigned &&    g;\n"
2153                "Const unsigned       h;",
2154                Style);
2155 
2156   Style.PointerAlignment = FormatStyle::PAS_Middle;
2157   Style.ReferenceAlignment = FormatStyle::RAS_Right;
2158   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
2159   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
2160   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
2161   verifyFormat("int * a = f1();", Style);
2162   verifyFormat("int &b = f2();", Style);
2163   verifyFormat("int &&c = f3();", Style);
2164   verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2165   verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2166   verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
2167 
2168   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2169   // specifically handled
2170   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2171 }
2172 
2173 TEST_F(FormatTest, FormatsForLoop) {
2174   verifyFormat(
2175       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2176       "     ++VeryVeryLongLoopVariable)\n"
2177       "  ;");
2178   verifyFormat("for (;;)\n"
2179                "  f();");
2180   verifyFormat("for (;;) {\n}");
2181   verifyFormat("for (;;) {\n"
2182                "  f();\n"
2183                "}");
2184   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2185 
2186   verifyFormat(
2187       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2188       "                                          E = UnwrappedLines.end();\n"
2189       "     I != E; ++I) {\n}");
2190 
2191   verifyFormat(
2192       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2193       "     ++IIIII) {\n}");
2194   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2195                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2196                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2197   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2198                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2199                "         E = FD->getDeclsInPrototypeScope().end();\n"
2200                "     I != E; ++I) {\n}");
2201   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2202                "         I = Container.begin(),\n"
2203                "         E = Container.end();\n"
2204                "     I != E; ++I) {\n}",
2205                getLLVMStyleWithColumns(76));
2206 
2207   verifyFormat(
2208       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2209       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2210       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2211       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2212       "     ++aaaaaaaaaaa) {\n}");
2213   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2214                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2215                "     ++i) {\n}");
2216   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2217                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2218                "}");
2219   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2220                "         aaaaaaaaaa);\n"
2221                "     iter; ++iter) {\n"
2222                "}");
2223   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2224                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2225                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2226                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2227 
2228   // These should not be formatted as Objective-C for-in loops.
2229   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2230   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2231   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2232   verifyFormat(
2233       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2234 
2235   FormatStyle NoBinPacking = getLLVMStyle();
2236   NoBinPacking.BinPackParameters = false;
2237   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2238                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2239                "                                           aaaaaaaaaaaaaaaa,\n"
2240                "                                           aaaaaaaaaaaaaaaa,\n"
2241                "                                           aaaaaaaaaaaaaaaa);\n"
2242                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2243                "}",
2244                NoBinPacking);
2245   verifyFormat(
2246       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2247       "                                          E = UnwrappedLines.end();\n"
2248       "     I != E;\n"
2249       "     ++I) {\n}",
2250       NoBinPacking);
2251 
2252   FormatStyle AlignLeft = getLLVMStyle();
2253   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2254   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2255 }
2256 
2257 TEST_F(FormatTest, RangeBasedForLoops) {
2258   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2259                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2260   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2261                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2262   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2263                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2264   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2265                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2266 }
2267 
2268 TEST_F(FormatTest, ForEachLoops) {
2269   FormatStyle Style = getLLVMStyle();
2270   EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2271   EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
2272   verifyFormat("void f() {\n"
2273                "  for (;;) {\n"
2274                "  }\n"
2275                "  foreach (Item *item, itemlist) {\n"
2276                "  }\n"
2277                "  Q_FOREACH (Item *item, itemlist) {\n"
2278                "  }\n"
2279                "  BOOST_FOREACH (Item *item, itemlist) {\n"
2280                "  }\n"
2281                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2282                "}",
2283                Style);
2284   verifyFormat("void f() {\n"
2285                "  for (;;)\n"
2286                "    int j = 1;\n"
2287                "  Q_FOREACH (int v, vec)\n"
2288                "    v *= 2;\n"
2289                "  for (;;) {\n"
2290                "    int j = 1;\n"
2291                "  }\n"
2292                "  Q_FOREACH (int v, vec) {\n"
2293                "    v *= 2;\n"
2294                "  }\n"
2295                "}",
2296                Style);
2297 
2298   FormatStyle ShortBlocks = getLLVMStyle();
2299   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2300   EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
2301   verifyFormat("void f() {\n"
2302                "  for (;;)\n"
2303                "    int j = 1;\n"
2304                "  Q_FOREACH (int &v, vec)\n"
2305                "    v *= 2;\n"
2306                "  for (;;) {\n"
2307                "    int j = 1;\n"
2308                "  }\n"
2309                "  Q_FOREACH (int &v, vec) {\n"
2310                "    int j = 1;\n"
2311                "  }\n"
2312                "}",
2313                ShortBlocks);
2314 
2315   FormatStyle ShortLoops = getLLVMStyle();
2316   ShortLoops.AllowShortLoopsOnASingleLine = true;
2317   EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2318   verifyFormat("void f() {\n"
2319                "  for (;;) int j = 1;\n"
2320                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2321                "  for (;;) {\n"
2322                "    int j = 1;\n"
2323                "  }\n"
2324                "  Q_FOREACH (int &v, vec) {\n"
2325                "    int j = 1;\n"
2326                "  }\n"
2327                "}",
2328                ShortLoops);
2329 
2330   FormatStyle ShortBlocksAndLoops = getLLVMStyle();
2331   ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2332   ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true;
2333   verifyFormat("void f() {\n"
2334                "  for (;;) int j = 1;\n"
2335                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2336                "  for (;;) { int j = 1; }\n"
2337                "  Q_FOREACH (int &v, vec) { int j = 1; }\n"
2338                "}",
2339                ShortBlocksAndLoops);
2340 
2341   Style.SpaceBeforeParens =
2342       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2343   verifyFormat("void f() {\n"
2344                "  for (;;) {\n"
2345                "  }\n"
2346                "  foreach(Item *item, itemlist) {\n"
2347                "  }\n"
2348                "  Q_FOREACH(Item *item, itemlist) {\n"
2349                "  }\n"
2350                "  BOOST_FOREACH(Item *item, itemlist) {\n"
2351                "  }\n"
2352                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2353                "}",
2354                Style);
2355 
2356   // As function-like macros.
2357   verifyFormat("#define foreach(x, y)\n"
2358                "#define Q_FOREACH(x, y)\n"
2359                "#define BOOST_FOREACH(x, y)\n"
2360                "#define UNKNOWN_FOREACH(x, y)\n");
2361 
2362   // Not as function-like macros.
2363   verifyFormat("#define foreach (x, y)\n"
2364                "#define Q_FOREACH (x, y)\n"
2365                "#define BOOST_FOREACH (x, y)\n"
2366                "#define UNKNOWN_FOREACH (x, y)\n");
2367 
2368   // handle microsoft non standard extension
2369   verifyFormat("for each (char c in x->MyStringProperty)");
2370 }
2371 
2372 TEST_F(FormatTest, FormatsWhileLoop) {
2373   verifyFormat("while (true) {\n}");
2374   verifyFormat("while (true)\n"
2375                "  f();");
2376   verifyFormat("while () {\n}");
2377   verifyFormat("while () {\n"
2378                "  f();\n"
2379                "}");
2380 }
2381 
2382 TEST_F(FormatTest, FormatsDoWhile) {
2383   verifyFormat("do {\n"
2384                "  do_something();\n"
2385                "} while (something());");
2386   verifyFormat("do\n"
2387                "  do_something();\n"
2388                "while (something());");
2389 }
2390 
2391 TEST_F(FormatTest, FormatsSwitchStatement) {
2392   verifyFormat("switch (x) {\n"
2393                "case 1:\n"
2394                "  f();\n"
2395                "  break;\n"
2396                "case kFoo:\n"
2397                "case ns::kBar:\n"
2398                "case kBaz:\n"
2399                "  break;\n"
2400                "default:\n"
2401                "  g();\n"
2402                "  break;\n"
2403                "}");
2404   verifyFormat("switch (x) {\n"
2405                "case 1: {\n"
2406                "  f();\n"
2407                "  break;\n"
2408                "}\n"
2409                "case 2: {\n"
2410                "  break;\n"
2411                "}\n"
2412                "}");
2413   verifyFormat("switch (x) {\n"
2414                "case 1: {\n"
2415                "  f();\n"
2416                "  {\n"
2417                "    g();\n"
2418                "    h();\n"
2419                "  }\n"
2420                "  break;\n"
2421                "}\n"
2422                "}");
2423   verifyFormat("switch (x) {\n"
2424                "case 1: {\n"
2425                "  f();\n"
2426                "  if (foo) {\n"
2427                "    g();\n"
2428                "    h();\n"
2429                "  }\n"
2430                "  break;\n"
2431                "}\n"
2432                "}");
2433   verifyFormat("switch (x) {\n"
2434                "case 1: {\n"
2435                "  f();\n"
2436                "  g();\n"
2437                "} break;\n"
2438                "}");
2439   verifyFormat("switch (test)\n"
2440                "  ;");
2441   verifyFormat("switch (x) {\n"
2442                "default: {\n"
2443                "  // Do nothing.\n"
2444                "}\n"
2445                "}");
2446   verifyFormat("switch (x) {\n"
2447                "// comment\n"
2448                "// if 1, do f()\n"
2449                "case 1:\n"
2450                "  f();\n"
2451                "}");
2452   verifyFormat("switch (x) {\n"
2453                "case 1:\n"
2454                "  // Do amazing stuff\n"
2455                "  {\n"
2456                "    f();\n"
2457                "    g();\n"
2458                "  }\n"
2459                "  break;\n"
2460                "}");
2461   verifyFormat("#define A          \\\n"
2462                "  switch (x) {     \\\n"
2463                "  case a:          \\\n"
2464                "    foo = b;       \\\n"
2465                "  }",
2466                getLLVMStyleWithColumns(20));
2467   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2468                "  case OP_name:                        \\\n"
2469                "    return operations::Operation##name\n",
2470                getLLVMStyleWithColumns(40));
2471   verifyFormat("switch (x) {\n"
2472                "case 1:;\n"
2473                "default:;\n"
2474                "  int i;\n"
2475                "}");
2476 
2477   verifyGoogleFormat("switch (x) {\n"
2478                      "  case 1:\n"
2479                      "    f();\n"
2480                      "    break;\n"
2481                      "  case kFoo:\n"
2482                      "  case ns::kBar:\n"
2483                      "  case kBaz:\n"
2484                      "    break;\n"
2485                      "  default:\n"
2486                      "    g();\n"
2487                      "    break;\n"
2488                      "}");
2489   verifyGoogleFormat("switch (x) {\n"
2490                      "  case 1: {\n"
2491                      "    f();\n"
2492                      "    break;\n"
2493                      "  }\n"
2494                      "}");
2495   verifyGoogleFormat("switch (test)\n"
2496                      "  ;");
2497 
2498   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2499                      "  case OP_name:              \\\n"
2500                      "    return operations::Operation##name\n");
2501   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2502                      "  // Get the correction operation class.\n"
2503                      "  switch (OpCode) {\n"
2504                      "    CASE(Add);\n"
2505                      "    CASE(Subtract);\n"
2506                      "    default:\n"
2507                      "      return operations::Unknown;\n"
2508                      "  }\n"
2509                      "#undef OPERATION_CASE\n"
2510                      "}");
2511   verifyFormat("DEBUG({\n"
2512                "  switch (x) {\n"
2513                "  case A:\n"
2514                "    f();\n"
2515                "    break;\n"
2516                "    // fallthrough\n"
2517                "  case B:\n"
2518                "    g();\n"
2519                "    break;\n"
2520                "  }\n"
2521                "});");
2522   EXPECT_EQ("DEBUG({\n"
2523             "  switch (x) {\n"
2524             "  case A:\n"
2525             "    f();\n"
2526             "    break;\n"
2527             "  // On B:\n"
2528             "  case B:\n"
2529             "    g();\n"
2530             "    break;\n"
2531             "  }\n"
2532             "});",
2533             format("DEBUG({\n"
2534                    "  switch (x) {\n"
2535                    "  case A:\n"
2536                    "    f();\n"
2537                    "    break;\n"
2538                    "  // On B:\n"
2539                    "  case B:\n"
2540                    "    g();\n"
2541                    "    break;\n"
2542                    "  }\n"
2543                    "});",
2544                    getLLVMStyle()));
2545   EXPECT_EQ("switch (n) {\n"
2546             "case 0: {\n"
2547             "  return false;\n"
2548             "}\n"
2549             "default: {\n"
2550             "  return true;\n"
2551             "}\n"
2552             "}",
2553             format("switch (n)\n"
2554                    "{\n"
2555                    "case 0: {\n"
2556                    "  return false;\n"
2557                    "}\n"
2558                    "default: {\n"
2559                    "  return true;\n"
2560                    "}\n"
2561                    "}",
2562                    getLLVMStyle()));
2563   verifyFormat("switch (a) {\n"
2564                "case (b):\n"
2565                "  return;\n"
2566                "}");
2567 
2568   verifyFormat("switch (a) {\n"
2569                "case some_namespace::\n"
2570                "    some_constant:\n"
2571                "  return;\n"
2572                "}",
2573                getLLVMStyleWithColumns(34));
2574 
2575   FormatStyle Style = getLLVMStyle();
2576   Style.IndentCaseLabels = true;
2577   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2578   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2579   Style.BraceWrapping.AfterCaseLabel = true;
2580   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2581   EXPECT_EQ("switch (n)\n"
2582             "{\n"
2583             "  case 0:\n"
2584             "  {\n"
2585             "    return false;\n"
2586             "  }\n"
2587             "  default:\n"
2588             "  {\n"
2589             "    return true;\n"
2590             "  }\n"
2591             "}",
2592             format("switch (n) {\n"
2593                    "  case 0: {\n"
2594                    "    return false;\n"
2595                    "  }\n"
2596                    "  default: {\n"
2597                    "    return true;\n"
2598                    "  }\n"
2599                    "}",
2600                    Style));
2601   Style.BraceWrapping.AfterCaseLabel = false;
2602   EXPECT_EQ("switch (n)\n"
2603             "{\n"
2604             "  case 0: {\n"
2605             "    return false;\n"
2606             "  }\n"
2607             "  default: {\n"
2608             "    return true;\n"
2609             "  }\n"
2610             "}",
2611             format("switch (n) {\n"
2612                    "  case 0:\n"
2613                    "  {\n"
2614                    "    return false;\n"
2615                    "  }\n"
2616                    "  default:\n"
2617                    "  {\n"
2618                    "    return true;\n"
2619                    "  }\n"
2620                    "}",
2621                    Style));
2622   Style.IndentCaseLabels = false;
2623   Style.IndentCaseBlocks = true;
2624   EXPECT_EQ("switch (n)\n"
2625             "{\n"
2626             "case 0:\n"
2627             "  {\n"
2628             "    return false;\n"
2629             "  }\n"
2630             "case 1:\n"
2631             "  break;\n"
2632             "default:\n"
2633             "  {\n"
2634             "    return true;\n"
2635             "  }\n"
2636             "}",
2637             format("switch (n) {\n"
2638                    "case 0: {\n"
2639                    "  return false;\n"
2640                    "}\n"
2641                    "case 1:\n"
2642                    "  break;\n"
2643                    "default: {\n"
2644                    "  return true;\n"
2645                    "}\n"
2646                    "}",
2647                    Style));
2648   Style.IndentCaseLabels = true;
2649   Style.IndentCaseBlocks = true;
2650   EXPECT_EQ("switch (n)\n"
2651             "{\n"
2652             "  case 0:\n"
2653             "    {\n"
2654             "      return false;\n"
2655             "    }\n"
2656             "  case 1:\n"
2657             "    break;\n"
2658             "  default:\n"
2659             "    {\n"
2660             "      return true;\n"
2661             "    }\n"
2662             "}",
2663             format("switch (n) {\n"
2664                    "case 0: {\n"
2665                    "  return false;\n"
2666                    "}\n"
2667                    "case 1:\n"
2668                    "  break;\n"
2669                    "default: {\n"
2670                    "  return true;\n"
2671                    "}\n"
2672                    "}",
2673                    Style));
2674 }
2675 
2676 TEST_F(FormatTest, CaseRanges) {
2677   verifyFormat("switch (x) {\n"
2678                "case 'A' ... 'Z':\n"
2679                "case 1 ... 5:\n"
2680                "case a ... b:\n"
2681                "  break;\n"
2682                "}");
2683 }
2684 
2685 TEST_F(FormatTest, ShortEnums) {
2686   FormatStyle Style = getLLVMStyle();
2687   Style.AllowShortEnumsOnASingleLine = true;
2688   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2689   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2690   Style.AllowShortEnumsOnASingleLine = false;
2691   verifyFormat("enum {\n"
2692                "  A,\n"
2693                "  B,\n"
2694                "  C\n"
2695                "} ShortEnum1, ShortEnum2;",
2696                Style);
2697   verifyFormat("typedef enum {\n"
2698                "  A,\n"
2699                "  B,\n"
2700                "  C\n"
2701                "} ShortEnum1, ShortEnum2;",
2702                Style);
2703   verifyFormat("enum {\n"
2704                "  A,\n"
2705                "} ShortEnum1, ShortEnum2;",
2706                Style);
2707   verifyFormat("typedef enum {\n"
2708                "  A,\n"
2709                "} ShortEnum1, ShortEnum2;",
2710                Style);
2711   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2712   Style.BraceWrapping.AfterEnum = true;
2713   verifyFormat("enum\n"
2714                "{\n"
2715                "  A,\n"
2716                "  B,\n"
2717                "  C\n"
2718                "} ShortEnum1, ShortEnum2;",
2719                Style);
2720   verifyFormat("typedef enum\n"
2721                "{\n"
2722                "  A,\n"
2723                "  B,\n"
2724                "  C\n"
2725                "} ShortEnum1, ShortEnum2;",
2726                Style);
2727 }
2728 
2729 TEST_F(FormatTest, ShortCaseLabels) {
2730   FormatStyle Style = getLLVMStyle();
2731   Style.AllowShortCaseLabelsOnASingleLine = true;
2732   verifyFormat("switch (a) {\n"
2733                "case 1: x = 1; break;\n"
2734                "case 2: return;\n"
2735                "case 3:\n"
2736                "case 4:\n"
2737                "case 5: return;\n"
2738                "case 6: // comment\n"
2739                "  return;\n"
2740                "case 7:\n"
2741                "  // comment\n"
2742                "  return;\n"
2743                "case 8:\n"
2744                "  x = 8; // comment\n"
2745                "  break;\n"
2746                "default: y = 1; break;\n"
2747                "}",
2748                Style);
2749   verifyFormat("switch (a) {\n"
2750                "case 0: return; // comment\n"
2751                "case 1: break;  // comment\n"
2752                "case 2: return;\n"
2753                "// comment\n"
2754                "case 3: return;\n"
2755                "// comment 1\n"
2756                "// comment 2\n"
2757                "// comment 3\n"
2758                "case 4: break; /* comment */\n"
2759                "case 5:\n"
2760                "  // comment\n"
2761                "  break;\n"
2762                "case 6: /* comment */ x = 1; break;\n"
2763                "case 7: x = /* comment */ 1; break;\n"
2764                "case 8:\n"
2765                "  x = 1; /* comment */\n"
2766                "  break;\n"
2767                "case 9:\n"
2768                "  break; // comment line 1\n"
2769                "         // comment line 2\n"
2770                "}",
2771                Style);
2772   EXPECT_EQ("switch (a) {\n"
2773             "case 1:\n"
2774             "  x = 8;\n"
2775             "  // fall through\n"
2776             "case 2: x = 8;\n"
2777             "// comment\n"
2778             "case 3:\n"
2779             "  return; /* comment line 1\n"
2780             "           * comment line 2 */\n"
2781             "case 4: i = 8;\n"
2782             "// something else\n"
2783             "#if FOO\n"
2784             "case 5: break;\n"
2785             "#endif\n"
2786             "}",
2787             format("switch (a) {\n"
2788                    "case 1: x = 8;\n"
2789                    "  // fall through\n"
2790                    "case 2:\n"
2791                    "  x = 8;\n"
2792                    "// comment\n"
2793                    "case 3:\n"
2794                    "  return; /* comment line 1\n"
2795                    "           * comment line 2 */\n"
2796                    "case 4:\n"
2797                    "  i = 8;\n"
2798                    "// something else\n"
2799                    "#if FOO\n"
2800                    "case 5: break;\n"
2801                    "#endif\n"
2802                    "}",
2803                    Style));
2804   EXPECT_EQ("switch (a) {\n"
2805             "case 0:\n"
2806             "  return; // long long long long long long long long long long "
2807             "long long comment\n"
2808             "          // line\n"
2809             "}",
2810             format("switch (a) {\n"
2811                    "case 0: return; // long long long long long long long long "
2812                    "long long long long comment line\n"
2813                    "}",
2814                    Style));
2815   EXPECT_EQ("switch (a) {\n"
2816             "case 0:\n"
2817             "  return; /* long long long long long long long long long long "
2818             "long long comment\n"
2819             "             line */\n"
2820             "}",
2821             format("switch (a) {\n"
2822                    "case 0: return; /* long long long long long long long long "
2823                    "long long long long comment line */\n"
2824                    "}",
2825                    Style));
2826   verifyFormat("switch (a) {\n"
2827                "#if FOO\n"
2828                "case 0: return 0;\n"
2829                "#endif\n"
2830                "}",
2831                Style);
2832   verifyFormat("switch (a) {\n"
2833                "case 1: {\n"
2834                "}\n"
2835                "case 2: {\n"
2836                "  return;\n"
2837                "}\n"
2838                "case 3: {\n"
2839                "  x = 1;\n"
2840                "  return;\n"
2841                "}\n"
2842                "case 4:\n"
2843                "  if (x)\n"
2844                "    return;\n"
2845                "}",
2846                Style);
2847   Style.ColumnLimit = 21;
2848   verifyFormat("switch (a) {\n"
2849                "case 1: x = 1; break;\n"
2850                "case 2: return;\n"
2851                "case 3:\n"
2852                "case 4:\n"
2853                "case 5: return;\n"
2854                "default:\n"
2855                "  y = 1;\n"
2856                "  break;\n"
2857                "}",
2858                Style);
2859   Style.ColumnLimit = 80;
2860   Style.AllowShortCaseLabelsOnASingleLine = false;
2861   Style.IndentCaseLabels = true;
2862   EXPECT_EQ("switch (n) {\n"
2863             "  default /*comments*/:\n"
2864             "    return true;\n"
2865             "  case 0:\n"
2866             "    return false;\n"
2867             "}",
2868             format("switch (n) {\n"
2869                    "default/*comments*/:\n"
2870                    "  return true;\n"
2871                    "case 0:\n"
2872                    "  return false;\n"
2873                    "}",
2874                    Style));
2875   Style.AllowShortCaseLabelsOnASingleLine = true;
2876   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2877   Style.BraceWrapping.AfterCaseLabel = true;
2878   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2879   EXPECT_EQ("switch (n)\n"
2880             "{\n"
2881             "  case 0:\n"
2882             "  {\n"
2883             "    return false;\n"
2884             "  }\n"
2885             "  default:\n"
2886             "  {\n"
2887             "    return true;\n"
2888             "  }\n"
2889             "}",
2890             format("switch (n) {\n"
2891                    "  case 0: {\n"
2892                    "    return false;\n"
2893                    "  }\n"
2894                    "  default:\n"
2895                    "  {\n"
2896                    "    return true;\n"
2897                    "  }\n"
2898                    "}",
2899                    Style));
2900 }
2901 
2902 TEST_F(FormatTest, FormatsLabels) {
2903   verifyFormat("void f() {\n"
2904                "  some_code();\n"
2905                "test_label:\n"
2906                "  some_other_code();\n"
2907                "  {\n"
2908                "    some_more_code();\n"
2909                "  another_label:\n"
2910                "    some_more_code();\n"
2911                "  }\n"
2912                "}");
2913   verifyFormat("{\n"
2914                "  some_code();\n"
2915                "test_label:\n"
2916                "  some_other_code();\n"
2917                "}");
2918   verifyFormat("{\n"
2919                "  some_code();\n"
2920                "test_label:;\n"
2921                "  int i = 0;\n"
2922                "}");
2923   FormatStyle Style = getLLVMStyle();
2924   Style.IndentGotoLabels = false;
2925   verifyFormat("void f() {\n"
2926                "  some_code();\n"
2927                "test_label:\n"
2928                "  some_other_code();\n"
2929                "  {\n"
2930                "    some_more_code();\n"
2931                "another_label:\n"
2932                "    some_more_code();\n"
2933                "  }\n"
2934                "}",
2935                Style);
2936   verifyFormat("{\n"
2937                "  some_code();\n"
2938                "test_label:\n"
2939                "  some_other_code();\n"
2940                "}",
2941                Style);
2942   verifyFormat("{\n"
2943                "  some_code();\n"
2944                "test_label:;\n"
2945                "  int i = 0;\n"
2946                "}");
2947 }
2948 
2949 TEST_F(FormatTest, MultiLineControlStatements) {
2950   FormatStyle Style = getLLVMStyleWithColumns(20);
2951   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2952   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2953   // Short lines should keep opening brace on same line.
2954   EXPECT_EQ("if (foo) {\n"
2955             "  bar();\n"
2956             "}",
2957             format("if(foo){bar();}", Style));
2958   EXPECT_EQ("if (foo) {\n"
2959             "  bar();\n"
2960             "} else {\n"
2961             "  baz();\n"
2962             "}",
2963             format("if(foo){bar();}else{baz();}", Style));
2964   EXPECT_EQ("if (foo && bar) {\n"
2965             "  baz();\n"
2966             "}",
2967             format("if(foo&&bar){baz();}", Style));
2968   EXPECT_EQ("if (foo) {\n"
2969             "  bar();\n"
2970             "} else if (baz) {\n"
2971             "  quux();\n"
2972             "}",
2973             format("if(foo){bar();}else if(baz){quux();}", Style));
2974   EXPECT_EQ(
2975       "if (foo) {\n"
2976       "  bar();\n"
2977       "} else if (baz) {\n"
2978       "  quux();\n"
2979       "} else {\n"
2980       "  foobar();\n"
2981       "}",
2982       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
2983   EXPECT_EQ("for (;;) {\n"
2984             "  foo();\n"
2985             "}",
2986             format("for(;;){foo();}"));
2987   EXPECT_EQ("while (1) {\n"
2988             "  foo();\n"
2989             "}",
2990             format("while(1){foo();}", Style));
2991   EXPECT_EQ("switch (foo) {\n"
2992             "case bar:\n"
2993             "  return;\n"
2994             "}",
2995             format("switch(foo){case bar:return;}", Style));
2996   EXPECT_EQ("try {\n"
2997             "  foo();\n"
2998             "} catch (...) {\n"
2999             "  bar();\n"
3000             "}",
3001             format("try{foo();}catch(...){bar();}", Style));
3002   EXPECT_EQ("do {\n"
3003             "  foo();\n"
3004             "} while (bar &&\n"
3005             "         baz);",
3006             format("do{foo();}while(bar&&baz);", Style));
3007   // Long lines should put opening brace on new line.
3008   EXPECT_EQ("if (foo && bar &&\n"
3009             "    baz)\n"
3010             "{\n"
3011             "  quux();\n"
3012             "}",
3013             format("if(foo&&bar&&baz){quux();}", Style));
3014   EXPECT_EQ("if (foo && bar &&\n"
3015             "    baz)\n"
3016             "{\n"
3017             "  quux();\n"
3018             "}",
3019             format("if (foo && bar &&\n"
3020                    "    baz) {\n"
3021                    "  quux();\n"
3022                    "}",
3023                    Style));
3024   EXPECT_EQ("if (foo) {\n"
3025             "  bar();\n"
3026             "} else if (baz ||\n"
3027             "           quux)\n"
3028             "{\n"
3029             "  foobar();\n"
3030             "}",
3031             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
3032   EXPECT_EQ(
3033       "if (foo) {\n"
3034       "  bar();\n"
3035       "} else if (baz ||\n"
3036       "           quux)\n"
3037       "{\n"
3038       "  foobar();\n"
3039       "} else {\n"
3040       "  barbaz();\n"
3041       "}",
3042       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3043              Style));
3044   EXPECT_EQ("for (int i = 0;\n"
3045             "     i < 10; ++i)\n"
3046             "{\n"
3047             "  foo();\n"
3048             "}",
3049             format("for(int i=0;i<10;++i){foo();}", Style));
3050   EXPECT_EQ("foreach (int i,\n"
3051             "         list)\n"
3052             "{\n"
3053             "  foo();\n"
3054             "}",
3055             format("foreach(int i, list){foo();}", Style));
3056   Style.ColumnLimit =
3057       40; // to concentrate at brace wrapping, not line wrap due to column limit
3058   EXPECT_EQ("foreach (int i, list) {\n"
3059             "  foo();\n"
3060             "}",
3061             format("foreach(int i, list){foo();}", Style));
3062   Style.ColumnLimit =
3063       20; // to concentrate at brace wrapping, not line wrap due to column limit
3064   EXPECT_EQ("while (foo || bar ||\n"
3065             "       baz)\n"
3066             "{\n"
3067             "  quux();\n"
3068             "}",
3069             format("while(foo||bar||baz){quux();}", Style));
3070   EXPECT_EQ("switch (\n"
3071             "    foo = barbaz)\n"
3072             "{\n"
3073             "case quux:\n"
3074             "  return;\n"
3075             "}",
3076             format("switch(foo=barbaz){case quux:return;}", Style));
3077   EXPECT_EQ("try {\n"
3078             "  foo();\n"
3079             "} catch (\n"
3080             "    Exception &bar)\n"
3081             "{\n"
3082             "  baz();\n"
3083             "}",
3084             format("try{foo();}catch(Exception&bar){baz();}", Style));
3085   Style.ColumnLimit =
3086       40; // to concentrate at brace wrapping, not line wrap due to column limit
3087   EXPECT_EQ("try {\n"
3088             "  foo();\n"
3089             "} catch (Exception &bar) {\n"
3090             "  baz();\n"
3091             "}",
3092             format("try{foo();}catch(Exception&bar){baz();}", Style));
3093   Style.ColumnLimit =
3094       20; // to concentrate at brace wrapping, not line wrap due to column limit
3095 
3096   Style.BraceWrapping.BeforeElse = true;
3097   EXPECT_EQ(
3098       "if (foo) {\n"
3099       "  bar();\n"
3100       "}\n"
3101       "else if (baz ||\n"
3102       "         quux)\n"
3103       "{\n"
3104       "  foobar();\n"
3105       "}\n"
3106       "else {\n"
3107       "  barbaz();\n"
3108       "}",
3109       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3110              Style));
3111 
3112   Style.BraceWrapping.BeforeCatch = true;
3113   EXPECT_EQ("try {\n"
3114             "  foo();\n"
3115             "}\n"
3116             "catch (...) {\n"
3117             "  baz();\n"
3118             "}",
3119             format("try{foo();}catch(...){baz();}", Style));
3120 
3121   Style.BraceWrapping.AfterFunction = true;
3122   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3123   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
3124   Style.ColumnLimit = 80;
3125   verifyFormat("void shortfunction() { bar(); }", Style);
3126 
3127   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
3128   verifyFormat("void shortfunction()\n"
3129                "{\n"
3130                "  bar();\n"
3131                "}",
3132                Style);
3133 }
3134 
3135 TEST_F(FormatTest, BeforeWhile) {
3136   FormatStyle Style = getLLVMStyle();
3137   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3138 
3139   verifyFormat("do {\n"
3140                "  foo();\n"
3141                "} while (1);",
3142                Style);
3143   Style.BraceWrapping.BeforeWhile = true;
3144   verifyFormat("do {\n"
3145                "  foo();\n"
3146                "}\n"
3147                "while (1);",
3148                Style);
3149 }
3150 
3151 //===----------------------------------------------------------------------===//
3152 // Tests for classes, namespaces, etc.
3153 //===----------------------------------------------------------------------===//
3154 
3155 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
3156   verifyFormat("class A {};");
3157 }
3158 
3159 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
3160   verifyFormat("class A {\n"
3161                "public:\n"
3162                "public: // comment\n"
3163                "protected:\n"
3164                "private:\n"
3165                "  void f() {}\n"
3166                "};");
3167   verifyFormat("export class A {\n"
3168                "public:\n"
3169                "public: // comment\n"
3170                "protected:\n"
3171                "private:\n"
3172                "  void f() {}\n"
3173                "};");
3174   verifyGoogleFormat("class A {\n"
3175                      " public:\n"
3176                      " protected:\n"
3177                      " private:\n"
3178                      "  void f() {}\n"
3179                      "};");
3180   verifyGoogleFormat("export class A {\n"
3181                      " public:\n"
3182                      " protected:\n"
3183                      " private:\n"
3184                      "  void f() {}\n"
3185                      "};");
3186   verifyFormat("class A {\n"
3187                "public slots:\n"
3188                "  void f1() {}\n"
3189                "public Q_SLOTS:\n"
3190                "  void f2() {}\n"
3191                "protected slots:\n"
3192                "  void f3() {}\n"
3193                "protected Q_SLOTS:\n"
3194                "  void f4() {}\n"
3195                "private slots:\n"
3196                "  void f5() {}\n"
3197                "private Q_SLOTS:\n"
3198                "  void f6() {}\n"
3199                "signals:\n"
3200                "  void g1();\n"
3201                "Q_SIGNALS:\n"
3202                "  void g2();\n"
3203                "};");
3204 
3205   // Don't interpret 'signals' the wrong way.
3206   verifyFormat("signals.set();");
3207   verifyFormat("for (Signals signals : f()) {\n}");
3208   verifyFormat("{\n"
3209                "  signals.set(); // This needs indentation.\n"
3210                "}");
3211   verifyFormat("void f() {\n"
3212                "label:\n"
3213                "  signals.baz();\n"
3214                "}");
3215   verifyFormat("private[1];");
3216   verifyFormat("testArray[public] = 1;");
3217   verifyFormat("public();");
3218   verifyFormat("myFunc(public);");
3219   verifyFormat("std::vector<int> testVec = {private};");
3220   verifyFormat("private.p = 1;");
3221   verifyFormat("void function(private...){};");
3222   verifyFormat("if (private && public)\n");
3223   verifyFormat("private &= true;");
3224   verifyFormat("int x = private * public;");
3225   verifyFormat("public *= private;");
3226   verifyFormat("int x = public + private;");
3227   verifyFormat("private++;");
3228   verifyFormat("++private;");
3229   verifyFormat("public += private;");
3230   verifyFormat("public = public - private;");
3231   verifyFormat("public->foo();");
3232   verifyFormat("private--;");
3233   verifyFormat("--private;");
3234   verifyFormat("public -= 1;");
3235   verifyFormat("if (!private && !public)\n");
3236   verifyFormat("public != private;");
3237   verifyFormat("int x = public / private;");
3238   verifyFormat("public /= 2;");
3239   verifyFormat("public = public % 2;");
3240   verifyFormat("public %= 2;");
3241   verifyFormat("if (public < private)\n");
3242   verifyFormat("public << private;");
3243   verifyFormat("public <<= private;");
3244   verifyFormat("if (public > private)\n");
3245   verifyFormat("public >> private;");
3246   verifyFormat("public >>= private;");
3247   verifyFormat("public ^ private;");
3248   verifyFormat("public ^= private;");
3249   verifyFormat("public | private;");
3250   verifyFormat("public |= private;");
3251   verifyFormat("auto x = private ? 1 : 2;");
3252   verifyFormat("if (public == private)\n");
3253   verifyFormat("void foo(public, private)");
3254   verifyFormat("public::foo();");
3255 }
3256 
3257 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3258   EXPECT_EQ("class A {\n"
3259             "public:\n"
3260             "  void f();\n"
3261             "\n"
3262             "private:\n"
3263             "  void g() {}\n"
3264             "  // test\n"
3265             "protected:\n"
3266             "  int h;\n"
3267             "};",
3268             format("class A {\n"
3269                    "public:\n"
3270                    "void f();\n"
3271                    "private:\n"
3272                    "void g() {}\n"
3273                    "// test\n"
3274                    "protected:\n"
3275                    "int h;\n"
3276                    "};"));
3277   EXPECT_EQ("class A {\n"
3278             "protected:\n"
3279             "public:\n"
3280             "  void f();\n"
3281             "};",
3282             format("class A {\n"
3283                    "protected:\n"
3284                    "\n"
3285                    "public:\n"
3286                    "\n"
3287                    "  void f();\n"
3288                    "};"));
3289 
3290   // Even ensure proper spacing inside macros.
3291   EXPECT_EQ("#define B     \\\n"
3292             "  class A {   \\\n"
3293             "   protected: \\\n"
3294             "   public:    \\\n"
3295             "    void f(); \\\n"
3296             "  };",
3297             format("#define B     \\\n"
3298                    "  class A {   \\\n"
3299                    "   protected: \\\n"
3300                    "              \\\n"
3301                    "   public:    \\\n"
3302                    "              \\\n"
3303                    "    void f(); \\\n"
3304                    "  };",
3305                    getGoogleStyle()));
3306   // But don't remove empty lines after macros ending in access specifiers.
3307   EXPECT_EQ("#define A private:\n"
3308             "\n"
3309             "int i;",
3310             format("#define A         private:\n"
3311                    "\n"
3312                    "int              i;"));
3313 }
3314 
3315 TEST_F(FormatTest, FormatsClasses) {
3316   verifyFormat("class A : public B {};");
3317   verifyFormat("class A : public ::B {};");
3318 
3319   verifyFormat(
3320       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3321       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3322   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3323                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3324                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3325   verifyFormat(
3326       "class A : public B, public C, public D, public E, public F {};");
3327   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3328                "                     public C,\n"
3329                "                     public D,\n"
3330                "                     public E,\n"
3331                "                     public F,\n"
3332                "                     public G {};");
3333 
3334   verifyFormat("class\n"
3335                "    ReallyReallyLongClassName {\n"
3336                "  int i;\n"
3337                "};",
3338                getLLVMStyleWithColumns(32));
3339   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3340                "                           aaaaaaaaaaaaaaaa> {};");
3341   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3342                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3343                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3344   verifyFormat("template <class R, class C>\n"
3345                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3346                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3347   verifyFormat("class ::A::B {};");
3348 }
3349 
3350 TEST_F(FormatTest, BreakInheritanceStyle) {
3351   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3352   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3353       FormatStyle::BILS_BeforeComma;
3354   verifyFormat("class MyClass : public X {};",
3355                StyleWithInheritanceBreakBeforeComma);
3356   verifyFormat("class MyClass\n"
3357                "    : public X\n"
3358                "    , public Y {};",
3359                StyleWithInheritanceBreakBeforeComma);
3360   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3361                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3362                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3363                StyleWithInheritanceBreakBeforeComma);
3364   verifyFormat("struct aaaaaaaaaaaaa\n"
3365                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3366                "          aaaaaaaaaaaaaaaa> {};",
3367                StyleWithInheritanceBreakBeforeComma);
3368 
3369   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3370   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3371       FormatStyle::BILS_AfterColon;
3372   verifyFormat("class MyClass : public X {};",
3373                StyleWithInheritanceBreakAfterColon);
3374   verifyFormat("class MyClass : public X, public Y {};",
3375                StyleWithInheritanceBreakAfterColon);
3376   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3377                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3378                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3379                StyleWithInheritanceBreakAfterColon);
3380   verifyFormat("struct aaaaaaaaaaaaa :\n"
3381                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3382                "        aaaaaaaaaaaaaaaa> {};",
3383                StyleWithInheritanceBreakAfterColon);
3384 
3385   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3386   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3387       FormatStyle::BILS_AfterComma;
3388   verifyFormat("class MyClass : public X {};",
3389                StyleWithInheritanceBreakAfterComma);
3390   verifyFormat("class MyClass : public X,\n"
3391                "                public Y {};",
3392                StyleWithInheritanceBreakAfterComma);
3393   verifyFormat(
3394       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3395       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3396       "{};",
3397       StyleWithInheritanceBreakAfterComma);
3398   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3399                "                           aaaaaaaaaaaaaaaa> {};",
3400                StyleWithInheritanceBreakAfterComma);
3401   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3402                "    : public OnceBreak,\n"
3403                "      public AlwaysBreak,\n"
3404                "      EvenBasesFitInOneLine {};",
3405                StyleWithInheritanceBreakAfterComma);
3406 }
3407 
3408 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) {
3409   verifyFormat("class A {\n} a, b;");
3410   verifyFormat("struct A {\n} a, b;");
3411   verifyFormat("union A {\n} a, b;");
3412 
3413   verifyFormat("constexpr class A {\n} a, b;");
3414   verifyFormat("constexpr struct A {\n} a, b;");
3415   verifyFormat("constexpr union A {\n} a, b;");
3416 
3417   verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace");
3418   verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace");
3419   verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace");
3420 
3421   verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace");
3422   verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace");
3423   verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace");
3424 
3425   verifyFormat("namespace ns {\n"
3426                "class {\n"
3427                "} a, b;\n"
3428                "} // namespace ns");
3429   verifyFormat("namespace ns {\n"
3430                "const class {\n"
3431                "} a, b;\n"
3432                "} // namespace ns");
3433   verifyFormat("namespace ns {\n"
3434                "constexpr class C {\n"
3435                "} a, b;\n"
3436                "} // namespace ns");
3437   verifyFormat("namespace ns {\n"
3438                "class { /* comment */\n"
3439                "} a, b;\n"
3440                "} // namespace ns");
3441   verifyFormat("namespace ns {\n"
3442                "const class { /* comment */\n"
3443                "} a, b;\n"
3444                "} // namespace ns");
3445 }
3446 
3447 TEST_F(FormatTest, FormatsEnum) {
3448   verifyFormat("enum {\n"
3449                "  Zero,\n"
3450                "  One = 1,\n"
3451                "  Two = One + 1,\n"
3452                "  Three = (One + Two),\n"
3453                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3454                "  Five = (One, Two, Three, Four, 5)\n"
3455                "};");
3456   verifyGoogleFormat("enum {\n"
3457                      "  Zero,\n"
3458                      "  One = 1,\n"
3459                      "  Two = One + 1,\n"
3460                      "  Three = (One + Two),\n"
3461                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3462                      "  Five = (One, Two, Three, Four, 5)\n"
3463                      "};");
3464   verifyFormat("enum Enum {};");
3465   verifyFormat("enum {};");
3466   verifyFormat("enum X E {} d;");
3467   verifyFormat("enum __attribute__((...)) E {} d;");
3468   verifyFormat("enum __declspec__((...)) E {} d;");
3469   verifyFormat("enum {\n"
3470                "  Bar = Foo<int, int>::value\n"
3471                "};",
3472                getLLVMStyleWithColumns(30));
3473 
3474   verifyFormat("enum ShortEnum { A, B, C };");
3475   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3476 
3477   EXPECT_EQ("enum KeepEmptyLines {\n"
3478             "  ONE,\n"
3479             "\n"
3480             "  TWO,\n"
3481             "\n"
3482             "  THREE\n"
3483             "}",
3484             format("enum KeepEmptyLines {\n"
3485                    "  ONE,\n"
3486                    "\n"
3487                    "  TWO,\n"
3488                    "\n"
3489                    "\n"
3490                    "  THREE\n"
3491                    "}"));
3492   verifyFormat("enum E { // comment\n"
3493                "  ONE,\n"
3494                "  TWO\n"
3495                "};\n"
3496                "int i;");
3497 
3498   FormatStyle EightIndent = getLLVMStyle();
3499   EightIndent.IndentWidth = 8;
3500   verifyFormat("enum {\n"
3501                "        VOID,\n"
3502                "        CHAR,\n"
3503                "        SHORT,\n"
3504                "        INT,\n"
3505                "        LONG,\n"
3506                "        SIGNED,\n"
3507                "        UNSIGNED,\n"
3508                "        BOOL,\n"
3509                "        FLOAT,\n"
3510                "        DOUBLE,\n"
3511                "        COMPLEX\n"
3512                "};",
3513                EightIndent);
3514 
3515   // Not enums.
3516   verifyFormat("enum X f() {\n"
3517                "  a();\n"
3518                "  return 42;\n"
3519                "}");
3520   verifyFormat("enum X Type::f() {\n"
3521                "  a();\n"
3522                "  return 42;\n"
3523                "}");
3524   verifyFormat("enum ::X f() {\n"
3525                "  a();\n"
3526                "  return 42;\n"
3527                "}");
3528   verifyFormat("enum ns::X f() {\n"
3529                "  a();\n"
3530                "  return 42;\n"
3531                "}");
3532 }
3533 
3534 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3535   verifyFormat("enum Type {\n"
3536                "  One = 0; // These semicolons should be commas.\n"
3537                "  Two = 1;\n"
3538                "};");
3539   verifyFormat("namespace n {\n"
3540                "enum Type {\n"
3541                "  One,\n"
3542                "  Two, // missing };\n"
3543                "  int i;\n"
3544                "}\n"
3545                "void g() {}");
3546 }
3547 
3548 TEST_F(FormatTest, FormatsEnumStruct) {
3549   verifyFormat("enum struct {\n"
3550                "  Zero,\n"
3551                "  One = 1,\n"
3552                "  Two = One + 1,\n"
3553                "  Three = (One + Two),\n"
3554                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3555                "  Five = (One, Two, Three, Four, 5)\n"
3556                "};");
3557   verifyFormat("enum struct Enum {};");
3558   verifyFormat("enum struct {};");
3559   verifyFormat("enum struct X E {} d;");
3560   verifyFormat("enum struct __attribute__((...)) E {} d;");
3561   verifyFormat("enum struct __declspec__((...)) E {} d;");
3562   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3563 }
3564 
3565 TEST_F(FormatTest, FormatsEnumClass) {
3566   verifyFormat("enum class {\n"
3567                "  Zero,\n"
3568                "  One = 1,\n"
3569                "  Two = One + 1,\n"
3570                "  Three = (One + Two),\n"
3571                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3572                "  Five = (One, Two, Three, Four, 5)\n"
3573                "};");
3574   verifyFormat("enum class Enum {};");
3575   verifyFormat("enum class {};");
3576   verifyFormat("enum class X E {} d;");
3577   verifyFormat("enum class __attribute__((...)) E {} d;");
3578   verifyFormat("enum class __declspec__((...)) E {} d;");
3579   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3580 }
3581 
3582 TEST_F(FormatTest, FormatsEnumTypes) {
3583   verifyFormat("enum X : int {\n"
3584                "  A, // Force multiple lines.\n"
3585                "  B\n"
3586                "};");
3587   verifyFormat("enum X : int { A, B };");
3588   verifyFormat("enum X : std::uint32_t { A, B };");
3589 }
3590 
3591 TEST_F(FormatTest, FormatsTypedefEnum) {
3592   FormatStyle Style = getLLVMStyleWithColumns(40);
3593   verifyFormat("typedef enum {} EmptyEnum;");
3594   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3595   verifyFormat("typedef enum {\n"
3596                "  ZERO = 0,\n"
3597                "  ONE = 1,\n"
3598                "  TWO = 2,\n"
3599                "  THREE = 3\n"
3600                "} LongEnum;",
3601                Style);
3602   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3603   Style.BraceWrapping.AfterEnum = true;
3604   verifyFormat("typedef enum {} EmptyEnum;");
3605   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3606   verifyFormat("typedef enum\n"
3607                "{\n"
3608                "  ZERO = 0,\n"
3609                "  ONE = 1,\n"
3610                "  TWO = 2,\n"
3611                "  THREE = 3\n"
3612                "} LongEnum;",
3613                Style);
3614 }
3615 
3616 TEST_F(FormatTest, FormatsNSEnums) {
3617   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3618   verifyGoogleFormat(
3619       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3620   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3621                      "  // Information about someDecentlyLongValue.\n"
3622                      "  someDecentlyLongValue,\n"
3623                      "  // Information about anotherDecentlyLongValue.\n"
3624                      "  anotherDecentlyLongValue,\n"
3625                      "  // Information about aThirdDecentlyLongValue.\n"
3626                      "  aThirdDecentlyLongValue\n"
3627                      "};");
3628   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3629                      "  // Information about someDecentlyLongValue.\n"
3630                      "  someDecentlyLongValue,\n"
3631                      "  // Information about anotherDecentlyLongValue.\n"
3632                      "  anotherDecentlyLongValue,\n"
3633                      "  // Information about aThirdDecentlyLongValue.\n"
3634                      "  aThirdDecentlyLongValue\n"
3635                      "};");
3636   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3637                      "  a = 1,\n"
3638                      "  b = 2,\n"
3639                      "  c = 3,\n"
3640                      "};");
3641   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3642                      "  a = 1,\n"
3643                      "  b = 2,\n"
3644                      "  c = 3,\n"
3645                      "};");
3646   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3647                      "  a = 1,\n"
3648                      "  b = 2,\n"
3649                      "  c = 3,\n"
3650                      "};");
3651   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3652                      "  a = 1,\n"
3653                      "  b = 2,\n"
3654                      "  c = 3,\n"
3655                      "};");
3656 }
3657 
3658 TEST_F(FormatTest, FormatsBitfields) {
3659   verifyFormat("struct Bitfields {\n"
3660                "  unsigned sClass : 8;\n"
3661                "  unsigned ValueKind : 2;\n"
3662                "};");
3663   verifyFormat("struct A {\n"
3664                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3665                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3666                "};");
3667   verifyFormat("struct MyStruct {\n"
3668                "  uchar data;\n"
3669                "  uchar : 8;\n"
3670                "  uchar : 8;\n"
3671                "  uchar other;\n"
3672                "};");
3673   FormatStyle Style = getLLVMStyle();
3674   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3675   verifyFormat("struct Bitfields {\n"
3676                "  unsigned sClass:8;\n"
3677                "  unsigned ValueKind:2;\n"
3678                "  uchar other;\n"
3679                "};",
3680                Style);
3681   verifyFormat("struct A {\n"
3682                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3683                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3684                "};",
3685                Style);
3686   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3687   verifyFormat("struct Bitfields {\n"
3688                "  unsigned sClass :8;\n"
3689                "  unsigned ValueKind :2;\n"
3690                "  uchar other;\n"
3691                "};",
3692                Style);
3693   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3694   verifyFormat("struct Bitfields {\n"
3695                "  unsigned sClass: 8;\n"
3696                "  unsigned ValueKind: 2;\n"
3697                "  uchar other;\n"
3698                "};",
3699                Style);
3700 }
3701 
3702 TEST_F(FormatTest, FormatsNamespaces) {
3703   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3704   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3705 
3706   verifyFormat("namespace some_namespace {\n"
3707                "class A {};\n"
3708                "void f() { f(); }\n"
3709                "}",
3710                LLVMWithNoNamespaceFix);
3711   verifyFormat("namespace N::inline D {\n"
3712                "class A {};\n"
3713                "void f() { f(); }\n"
3714                "}",
3715                LLVMWithNoNamespaceFix);
3716   verifyFormat("namespace N::inline D::E {\n"
3717                "class A {};\n"
3718                "void f() { f(); }\n"
3719                "}",
3720                LLVMWithNoNamespaceFix);
3721   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3722                "class A {};\n"
3723                "void f() { f(); }\n"
3724                "}",
3725                LLVMWithNoNamespaceFix);
3726   verifyFormat("/* something */ namespace some_namespace {\n"
3727                "class A {};\n"
3728                "void f() { f(); }\n"
3729                "}",
3730                LLVMWithNoNamespaceFix);
3731   verifyFormat("namespace {\n"
3732                "class A {};\n"
3733                "void f() { f(); }\n"
3734                "}",
3735                LLVMWithNoNamespaceFix);
3736   verifyFormat("/* something */ namespace {\n"
3737                "class A {};\n"
3738                "void f() { f(); }\n"
3739                "}",
3740                LLVMWithNoNamespaceFix);
3741   verifyFormat("inline namespace X {\n"
3742                "class A {};\n"
3743                "void f() { f(); }\n"
3744                "}",
3745                LLVMWithNoNamespaceFix);
3746   verifyFormat("/* something */ inline namespace X {\n"
3747                "class A {};\n"
3748                "void f() { f(); }\n"
3749                "}",
3750                LLVMWithNoNamespaceFix);
3751   verifyFormat("export namespace X {\n"
3752                "class A {};\n"
3753                "void f() { f(); }\n"
3754                "}",
3755                LLVMWithNoNamespaceFix);
3756   verifyFormat("using namespace some_namespace;\n"
3757                "class A {};\n"
3758                "void f() { f(); }",
3759                LLVMWithNoNamespaceFix);
3760 
3761   // This code is more common than we thought; if we
3762   // layout this correctly the semicolon will go into
3763   // its own line, which is undesirable.
3764   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3765   verifyFormat("namespace {\n"
3766                "class A {};\n"
3767                "};",
3768                LLVMWithNoNamespaceFix);
3769 
3770   verifyFormat("namespace {\n"
3771                "int SomeVariable = 0; // comment\n"
3772                "} // namespace",
3773                LLVMWithNoNamespaceFix);
3774   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3775             "#define HEADER_GUARD\n"
3776             "namespace my_namespace {\n"
3777             "int i;\n"
3778             "} // my_namespace\n"
3779             "#endif // HEADER_GUARD",
3780             format("#ifndef HEADER_GUARD\n"
3781                    " #define HEADER_GUARD\n"
3782                    "   namespace my_namespace {\n"
3783                    "int i;\n"
3784                    "}    // my_namespace\n"
3785                    "#endif    // HEADER_GUARD",
3786                    LLVMWithNoNamespaceFix));
3787 
3788   EXPECT_EQ("namespace A::B {\n"
3789             "class C {};\n"
3790             "}",
3791             format("namespace A::B {\n"
3792                    "class C {};\n"
3793                    "}",
3794                    LLVMWithNoNamespaceFix));
3795 
3796   FormatStyle Style = getLLVMStyle();
3797   Style.NamespaceIndentation = FormatStyle::NI_All;
3798   EXPECT_EQ("namespace out {\n"
3799             "  int i;\n"
3800             "  namespace in {\n"
3801             "    int i;\n"
3802             "  } // namespace in\n"
3803             "} // namespace out",
3804             format("namespace out {\n"
3805                    "int i;\n"
3806                    "namespace in {\n"
3807                    "int i;\n"
3808                    "} // namespace in\n"
3809                    "} // namespace out",
3810                    Style));
3811 
3812   FormatStyle ShortInlineFunctions = getLLVMStyle();
3813   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3814   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3815       FormatStyle::SFS_Inline;
3816   verifyFormat("namespace {\n"
3817                "  void f() {\n"
3818                "    return;\n"
3819                "  }\n"
3820                "} // namespace\n",
3821                ShortInlineFunctions);
3822   verifyFormat("namespace { /* comment */\n"
3823                "  void f() {\n"
3824                "    return;\n"
3825                "  }\n"
3826                "} // namespace\n",
3827                ShortInlineFunctions);
3828   verifyFormat("namespace { // comment\n"
3829                "  void f() {\n"
3830                "    return;\n"
3831                "  }\n"
3832                "} // namespace\n",
3833                ShortInlineFunctions);
3834   verifyFormat("namespace {\n"
3835                "  int some_int;\n"
3836                "  void f() {\n"
3837                "    return;\n"
3838                "  }\n"
3839                "} // namespace\n",
3840                ShortInlineFunctions);
3841   verifyFormat("namespace interface {\n"
3842                "  void f() {\n"
3843                "    return;\n"
3844                "  }\n"
3845                "} // namespace interface\n",
3846                ShortInlineFunctions);
3847   verifyFormat("namespace {\n"
3848                "  class X {\n"
3849                "    void f() { return; }\n"
3850                "  };\n"
3851                "} // namespace\n",
3852                ShortInlineFunctions);
3853   verifyFormat("namespace {\n"
3854                "  class X { /* comment */\n"
3855                "    void f() { return; }\n"
3856                "  };\n"
3857                "} // namespace\n",
3858                ShortInlineFunctions);
3859   verifyFormat("namespace {\n"
3860                "  class X { // comment\n"
3861                "    void f() { return; }\n"
3862                "  };\n"
3863                "} // namespace\n",
3864                ShortInlineFunctions);
3865   verifyFormat("namespace {\n"
3866                "  struct X {\n"
3867                "    void f() { return; }\n"
3868                "  };\n"
3869                "} // namespace\n",
3870                ShortInlineFunctions);
3871   verifyFormat("namespace {\n"
3872                "  union X {\n"
3873                "    void f() { return; }\n"
3874                "  };\n"
3875                "} // namespace\n",
3876                ShortInlineFunctions);
3877   verifyFormat("extern \"C\" {\n"
3878                "void f() {\n"
3879                "  return;\n"
3880                "}\n"
3881                "} // namespace\n",
3882                ShortInlineFunctions);
3883   verifyFormat("namespace {\n"
3884                "  class X {\n"
3885                "    void f() { return; }\n"
3886                "  } x;\n"
3887                "} // namespace\n",
3888                ShortInlineFunctions);
3889   verifyFormat("namespace {\n"
3890                "  [[nodiscard]] class X {\n"
3891                "    void f() { return; }\n"
3892                "  };\n"
3893                "} // namespace\n",
3894                ShortInlineFunctions);
3895   verifyFormat("namespace {\n"
3896                "  static class X {\n"
3897                "    void f() { return; }\n"
3898                "  } x;\n"
3899                "} // namespace\n",
3900                ShortInlineFunctions);
3901   verifyFormat("namespace {\n"
3902                "  constexpr class X {\n"
3903                "    void f() { return; }\n"
3904                "  } x;\n"
3905                "} // namespace\n",
3906                ShortInlineFunctions);
3907 
3908   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
3909   verifyFormat("extern \"C\" {\n"
3910                "  void f() {\n"
3911                "    return;\n"
3912                "  }\n"
3913                "} // namespace\n",
3914                ShortInlineFunctions);
3915 
3916   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3917   EXPECT_EQ("namespace out {\n"
3918             "int i;\n"
3919             "namespace in {\n"
3920             "  int i;\n"
3921             "} // namespace in\n"
3922             "} // namespace out",
3923             format("namespace out {\n"
3924                    "int i;\n"
3925                    "namespace in {\n"
3926                    "int i;\n"
3927                    "} // namespace in\n"
3928                    "} // namespace out",
3929                    Style));
3930 
3931   Style.NamespaceIndentation = FormatStyle::NI_None;
3932   verifyFormat("template <class T>\n"
3933                "concept a_concept = X<>;\n"
3934                "namespace B {\n"
3935                "struct b_struct {};\n"
3936                "} // namespace B\n",
3937                Style);
3938   verifyFormat("template <int I>\n"
3939                "constexpr void foo()\n"
3940                "  requires(I == 42)\n"
3941                "{}\n"
3942                "namespace ns {\n"
3943                "void foo() {}\n"
3944                "} // namespace ns\n",
3945                Style);
3946 }
3947 
3948 TEST_F(FormatTest, NamespaceMacros) {
3949   FormatStyle Style = getLLVMStyle();
3950   Style.NamespaceMacros.push_back("TESTSUITE");
3951 
3952   verifyFormat("TESTSUITE(A) {\n"
3953                "int foo();\n"
3954                "} // TESTSUITE(A)",
3955                Style);
3956 
3957   verifyFormat("TESTSUITE(A, B) {\n"
3958                "int foo();\n"
3959                "} // TESTSUITE(A)",
3960                Style);
3961 
3962   // Properly indent according to NamespaceIndentation style
3963   Style.NamespaceIndentation = FormatStyle::NI_All;
3964   verifyFormat("TESTSUITE(A) {\n"
3965                "  int foo();\n"
3966                "} // TESTSUITE(A)",
3967                Style);
3968   verifyFormat("TESTSUITE(A) {\n"
3969                "  namespace B {\n"
3970                "    int foo();\n"
3971                "  } // namespace B\n"
3972                "} // TESTSUITE(A)",
3973                Style);
3974   verifyFormat("namespace A {\n"
3975                "  TESTSUITE(B) {\n"
3976                "    int foo();\n"
3977                "  } // TESTSUITE(B)\n"
3978                "} // namespace A",
3979                Style);
3980 
3981   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3982   verifyFormat("TESTSUITE(A) {\n"
3983                "TESTSUITE(B) {\n"
3984                "  int foo();\n"
3985                "} // TESTSUITE(B)\n"
3986                "} // TESTSUITE(A)",
3987                Style);
3988   verifyFormat("TESTSUITE(A) {\n"
3989                "namespace B {\n"
3990                "  int foo();\n"
3991                "} // namespace B\n"
3992                "} // TESTSUITE(A)",
3993                Style);
3994   verifyFormat("namespace A {\n"
3995                "TESTSUITE(B) {\n"
3996                "  int foo();\n"
3997                "} // TESTSUITE(B)\n"
3998                "} // namespace A",
3999                Style);
4000 
4001   // Properly merge namespace-macros blocks in CompactNamespaces mode
4002   Style.NamespaceIndentation = FormatStyle::NI_None;
4003   Style.CompactNamespaces = true;
4004   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
4005                "}} // TESTSUITE(A::B)",
4006                Style);
4007 
4008   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4009             "}} // TESTSUITE(out::in)",
4010             format("TESTSUITE(out) {\n"
4011                    "TESTSUITE(in) {\n"
4012                    "} // TESTSUITE(in)\n"
4013                    "} // TESTSUITE(out)",
4014                    Style));
4015 
4016   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4017             "}} // TESTSUITE(out::in)",
4018             format("TESTSUITE(out) {\n"
4019                    "TESTSUITE(in) {\n"
4020                    "} // TESTSUITE(in)\n"
4021                    "} // TESTSUITE(out)",
4022                    Style));
4023 
4024   // Do not merge different namespaces/macros
4025   EXPECT_EQ("namespace out {\n"
4026             "TESTSUITE(in) {\n"
4027             "} // TESTSUITE(in)\n"
4028             "} // namespace out",
4029             format("namespace out {\n"
4030                    "TESTSUITE(in) {\n"
4031                    "} // TESTSUITE(in)\n"
4032                    "} // namespace out",
4033                    Style));
4034   EXPECT_EQ("TESTSUITE(out) {\n"
4035             "namespace in {\n"
4036             "} // namespace in\n"
4037             "} // TESTSUITE(out)",
4038             format("TESTSUITE(out) {\n"
4039                    "namespace in {\n"
4040                    "} // namespace in\n"
4041                    "} // TESTSUITE(out)",
4042                    Style));
4043   Style.NamespaceMacros.push_back("FOOBAR");
4044   EXPECT_EQ("TESTSUITE(out) {\n"
4045             "FOOBAR(in) {\n"
4046             "} // FOOBAR(in)\n"
4047             "} // TESTSUITE(out)",
4048             format("TESTSUITE(out) {\n"
4049                    "FOOBAR(in) {\n"
4050                    "} // FOOBAR(in)\n"
4051                    "} // TESTSUITE(out)",
4052                    Style));
4053 }
4054 
4055 TEST_F(FormatTest, FormatsCompactNamespaces) {
4056   FormatStyle Style = getLLVMStyle();
4057   Style.CompactNamespaces = true;
4058   Style.NamespaceMacros.push_back("TESTSUITE");
4059 
4060   verifyFormat("namespace A { namespace B {\n"
4061                "}} // namespace A::B",
4062                Style);
4063 
4064   EXPECT_EQ("namespace out { namespace in {\n"
4065             "}} // namespace out::in",
4066             format("namespace out {\n"
4067                    "namespace in {\n"
4068                    "} // namespace in\n"
4069                    "} // namespace out",
4070                    Style));
4071 
4072   // Only namespaces which have both consecutive opening and end get compacted
4073   EXPECT_EQ("namespace out {\n"
4074             "namespace in1 {\n"
4075             "} // namespace in1\n"
4076             "namespace in2 {\n"
4077             "} // namespace in2\n"
4078             "} // namespace out",
4079             format("namespace out {\n"
4080                    "namespace in1 {\n"
4081                    "} // namespace in1\n"
4082                    "namespace in2 {\n"
4083                    "} // namespace in2\n"
4084                    "} // namespace out",
4085                    Style));
4086 
4087   EXPECT_EQ("namespace out {\n"
4088             "int i;\n"
4089             "namespace in {\n"
4090             "int j;\n"
4091             "} // namespace in\n"
4092             "int k;\n"
4093             "} // namespace out",
4094             format("namespace out { int i;\n"
4095                    "namespace in { int j; } // namespace in\n"
4096                    "int k; } // namespace out",
4097                    Style));
4098 
4099   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
4100             "}}} // namespace A::B::C\n",
4101             format("namespace A { namespace B {\n"
4102                    "namespace C {\n"
4103                    "}} // namespace B::C\n"
4104                    "} // namespace A\n",
4105                    Style));
4106 
4107   Style.ColumnLimit = 40;
4108   EXPECT_EQ("namespace aaaaaaaaaa {\n"
4109             "namespace bbbbbbbbbb {\n"
4110             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
4111             format("namespace aaaaaaaaaa {\n"
4112                    "namespace bbbbbbbbbb {\n"
4113                    "} // namespace bbbbbbbbbb\n"
4114                    "} // namespace aaaaaaaaaa",
4115                    Style));
4116 
4117   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
4118             "namespace cccccc {\n"
4119             "}}} // namespace aaaaaa::bbbbbb::cccccc",
4120             format("namespace aaaaaa {\n"
4121                    "namespace bbbbbb {\n"
4122                    "namespace cccccc {\n"
4123                    "} // namespace cccccc\n"
4124                    "} // namespace bbbbbb\n"
4125                    "} // namespace aaaaaa",
4126                    Style));
4127   Style.ColumnLimit = 80;
4128 
4129   // Extra semicolon after 'inner' closing brace prevents merging
4130   EXPECT_EQ("namespace out { namespace in {\n"
4131             "}; } // namespace out::in",
4132             format("namespace out {\n"
4133                    "namespace in {\n"
4134                    "}; // namespace in\n"
4135                    "} // namespace out",
4136                    Style));
4137 
4138   // Extra semicolon after 'outer' closing brace is conserved
4139   EXPECT_EQ("namespace out { namespace in {\n"
4140             "}}; // namespace out::in",
4141             format("namespace out {\n"
4142                    "namespace in {\n"
4143                    "} // namespace in\n"
4144                    "}; // namespace out",
4145                    Style));
4146 
4147   Style.NamespaceIndentation = FormatStyle::NI_All;
4148   EXPECT_EQ("namespace out { namespace in {\n"
4149             "  int i;\n"
4150             "}} // namespace out::in",
4151             format("namespace out {\n"
4152                    "namespace in {\n"
4153                    "int i;\n"
4154                    "} // namespace in\n"
4155                    "} // namespace out",
4156                    Style));
4157   EXPECT_EQ("namespace out { namespace mid {\n"
4158             "  namespace in {\n"
4159             "    int j;\n"
4160             "  } // namespace in\n"
4161             "  int k;\n"
4162             "}} // namespace out::mid",
4163             format("namespace out { namespace mid {\n"
4164                    "namespace in { int j; } // namespace in\n"
4165                    "int k; }} // namespace out::mid",
4166                    Style));
4167 
4168   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4169   EXPECT_EQ("namespace out { namespace in {\n"
4170             "  int i;\n"
4171             "}} // namespace out::in",
4172             format("namespace out {\n"
4173                    "namespace in {\n"
4174                    "int i;\n"
4175                    "} // namespace in\n"
4176                    "} // namespace out",
4177                    Style));
4178   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
4179             "  int i;\n"
4180             "}}} // namespace out::mid::in",
4181             format("namespace out {\n"
4182                    "namespace mid {\n"
4183                    "namespace in {\n"
4184                    "int i;\n"
4185                    "} // namespace in\n"
4186                    "} // namespace mid\n"
4187                    "} // namespace out",
4188                    Style));
4189 
4190   Style.CompactNamespaces = true;
4191   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
4192   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4193   Style.BraceWrapping.BeforeLambdaBody = true;
4194   verifyFormat("namespace out { namespace in {\n"
4195                "}} // namespace out::in",
4196                Style);
4197   EXPECT_EQ("namespace out { namespace in {\n"
4198             "}} // namespace out::in",
4199             format("namespace out {\n"
4200                    "namespace in {\n"
4201                    "} // namespace in\n"
4202                    "} // namespace out",
4203                    Style));
4204 }
4205 
4206 TEST_F(FormatTest, FormatsExternC) {
4207   verifyFormat("extern \"C\" {\nint a;");
4208   verifyFormat("extern \"C\" {}");
4209   verifyFormat("extern \"C\" {\n"
4210                "int foo();\n"
4211                "}");
4212   verifyFormat("extern \"C\" int foo() {}");
4213   verifyFormat("extern \"C\" int foo();");
4214   verifyFormat("extern \"C\" int foo() {\n"
4215                "  int i = 42;\n"
4216                "  return i;\n"
4217                "}");
4218 
4219   FormatStyle Style = getLLVMStyle();
4220   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4221   Style.BraceWrapping.AfterFunction = true;
4222   verifyFormat("extern \"C\" int foo() {}", Style);
4223   verifyFormat("extern \"C\" int foo();", Style);
4224   verifyFormat("extern \"C\" int foo()\n"
4225                "{\n"
4226                "  int i = 42;\n"
4227                "  return i;\n"
4228                "}",
4229                Style);
4230 
4231   Style.BraceWrapping.AfterExternBlock = true;
4232   Style.BraceWrapping.SplitEmptyRecord = false;
4233   verifyFormat("extern \"C\"\n"
4234                "{}",
4235                Style);
4236   verifyFormat("extern \"C\"\n"
4237                "{\n"
4238                "  int foo();\n"
4239                "}",
4240                Style);
4241 }
4242 
4243 TEST_F(FormatTest, IndentExternBlockStyle) {
4244   FormatStyle Style = getLLVMStyle();
4245   Style.IndentWidth = 2;
4246 
4247   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4248   verifyFormat("extern \"C\" { /*9*/\n"
4249                "}",
4250                Style);
4251   verifyFormat("extern \"C\" {\n"
4252                "  int foo10();\n"
4253                "}",
4254                Style);
4255 
4256   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4257   verifyFormat("extern \"C\" { /*11*/\n"
4258                "}",
4259                Style);
4260   verifyFormat("extern \"C\" {\n"
4261                "int foo12();\n"
4262                "}",
4263                Style);
4264 
4265   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4266   Style.BraceWrapping.AfterExternBlock = true;
4267   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4268   verifyFormat("extern \"C\"\n"
4269                "{ /*13*/\n"
4270                "}",
4271                Style);
4272   verifyFormat("extern \"C\"\n{\n"
4273                "  int foo14();\n"
4274                "}",
4275                Style);
4276 
4277   Style.BraceWrapping.AfterExternBlock = false;
4278   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4279   verifyFormat("extern \"C\" { /*15*/\n"
4280                "}",
4281                Style);
4282   verifyFormat("extern \"C\" {\n"
4283                "int foo16();\n"
4284                "}",
4285                Style);
4286 
4287   Style.BraceWrapping.AfterExternBlock = true;
4288   verifyFormat("extern \"C\"\n"
4289                "{ /*13*/\n"
4290                "}",
4291                Style);
4292   verifyFormat("extern \"C\"\n"
4293                "{\n"
4294                "int foo14();\n"
4295                "}",
4296                Style);
4297 
4298   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4299   verifyFormat("extern \"C\"\n"
4300                "{ /*13*/\n"
4301                "}",
4302                Style);
4303   verifyFormat("extern \"C\"\n"
4304                "{\n"
4305                "  int foo14();\n"
4306                "}",
4307                Style);
4308 }
4309 
4310 TEST_F(FormatTest, FormatsInlineASM) {
4311   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4312   verifyFormat("asm(\"nop\" ::: \"memory\");");
4313   verifyFormat(
4314       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4315       "    \"cpuid\\n\\t\"\n"
4316       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4317       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4318       "    : \"a\"(value));");
4319   EXPECT_EQ(
4320       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4321       "  __asm {\n"
4322       "        mov     edx,[that] // vtable in edx\n"
4323       "        mov     eax,methodIndex\n"
4324       "        call    [edx][eax*4] // stdcall\n"
4325       "  }\n"
4326       "}",
4327       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4328              "    __asm {\n"
4329              "        mov     edx,[that] // vtable in edx\n"
4330              "        mov     eax,methodIndex\n"
4331              "        call    [edx][eax*4] // stdcall\n"
4332              "    }\n"
4333              "}"));
4334   EXPECT_EQ("_asm {\n"
4335             "  xor eax, eax;\n"
4336             "  cpuid;\n"
4337             "}",
4338             format("_asm {\n"
4339                    "  xor eax, eax;\n"
4340                    "  cpuid;\n"
4341                    "}"));
4342   verifyFormat("void function() {\n"
4343                "  // comment\n"
4344                "  asm(\"\");\n"
4345                "}");
4346   EXPECT_EQ("__asm {\n"
4347             "}\n"
4348             "int i;",
4349             format("__asm   {\n"
4350                    "}\n"
4351                    "int   i;"));
4352 }
4353 
4354 TEST_F(FormatTest, FormatTryCatch) {
4355   verifyFormat("try {\n"
4356                "  throw a * b;\n"
4357                "} catch (int a) {\n"
4358                "  // Do nothing.\n"
4359                "} catch (...) {\n"
4360                "  exit(42);\n"
4361                "}");
4362 
4363   // Function-level try statements.
4364   verifyFormat("int f() try { return 4; } catch (...) {\n"
4365                "  return 5;\n"
4366                "}");
4367   verifyFormat("class A {\n"
4368                "  int a;\n"
4369                "  A() try : a(0) {\n"
4370                "  } catch (...) {\n"
4371                "    throw;\n"
4372                "  }\n"
4373                "};\n");
4374   verifyFormat("class A {\n"
4375                "  int a;\n"
4376                "  A() try : a(0), b{1} {\n"
4377                "  } catch (...) {\n"
4378                "    throw;\n"
4379                "  }\n"
4380                "};\n");
4381   verifyFormat("class A {\n"
4382                "  int a;\n"
4383                "  A() try : a(0), b{1}, c{2} {\n"
4384                "  } catch (...) {\n"
4385                "    throw;\n"
4386                "  }\n"
4387                "};\n");
4388   verifyFormat("class A {\n"
4389                "  int a;\n"
4390                "  A() try : a(0), b{1}, c{2} {\n"
4391                "    { // New scope.\n"
4392                "    }\n"
4393                "  } catch (...) {\n"
4394                "    throw;\n"
4395                "  }\n"
4396                "};\n");
4397 
4398   // Incomplete try-catch blocks.
4399   verifyIncompleteFormat("try {} catch (");
4400 }
4401 
4402 TEST_F(FormatTest, FormatTryAsAVariable) {
4403   verifyFormat("int try;");
4404   verifyFormat("int try, size;");
4405   verifyFormat("try = foo();");
4406   verifyFormat("if (try < size) {\n  return true;\n}");
4407 
4408   verifyFormat("int catch;");
4409   verifyFormat("int catch, size;");
4410   verifyFormat("catch = foo();");
4411   verifyFormat("if (catch < size) {\n  return true;\n}");
4412 
4413   FormatStyle Style = getLLVMStyle();
4414   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4415   Style.BraceWrapping.AfterFunction = true;
4416   Style.BraceWrapping.BeforeCatch = true;
4417   verifyFormat("try {\n"
4418                "  int bar = 1;\n"
4419                "}\n"
4420                "catch (...) {\n"
4421                "  int bar = 1;\n"
4422                "}",
4423                Style);
4424   verifyFormat("#if NO_EX\n"
4425                "try\n"
4426                "#endif\n"
4427                "{\n"
4428                "}\n"
4429                "#if NO_EX\n"
4430                "catch (...) {\n"
4431                "}",
4432                Style);
4433   verifyFormat("try /* abc */ {\n"
4434                "  int bar = 1;\n"
4435                "}\n"
4436                "catch (...) {\n"
4437                "  int bar = 1;\n"
4438                "}",
4439                Style);
4440   verifyFormat("try\n"
4441                "// abc\n"
4442                "{\n"
4443                "  int bar = 1;\n"
4444                "}\n"
4445                "catch (...) {\n"
4446                "  int bar = 1;\n"
4447                "}",
4448                Style);
4449 }
4450 
4451 TEST_F(FormatTest, FormatSEHTryCatch) {
4452   verifyFormat("__try {\n"
4453                "  int a = b * c;\n"
4454                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4455                "  // Do nothing.\n"
4456                "}");
4457 
4458   verifyFormat("__try {\n"
4459                "  int a = b * c;\n"
4460                "} __finally {\n"
4461                "  // Do nothing.\n"
4462                "}");
4463 
4464   verifyFormat("DEBUG({\n"
4465                "  __try {\n"
4466                "  } __finally {\n"
4467                "  }\n"
4468                "});\n");
4469 }
4470 
4471 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4472   verifyFormat("try {\n"
4473                "  f();\n"
4474                "} catch {\n"
4475                "  g();\n"
4476                "}");
4477   verifyFormat("try {\n"
4478                "  f();\n"
4479                "} catch (A a) MACRO(x) {\n"
4480                "  g();\n"
4481                "} catch (B b) MACRO(x) {\n"
4482                "  g();\n"
4483                "}");
4484 }
4485 
4486 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4487   FormatStyle Style = getLLVMStyle();
4488   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4489                           FormatStyle::BS_WebKit}) {
4490     Style.BreakBeforeBraces = BraceStyle;
4491     verifyFormat("try {\n"
4492                  "  // something\n"
4493                  "} catch (...) {\n"
4494                  "  // something\n"
4495                  "}",
4496                  Style);
4497   }
4498   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4499   verifyFormat("try {\n"
4500                "  // something\n"
4501                "}\n"
4502                "catch (...) {\n"
4503                "  // something\n"
4504                "}",
4505                Style);
4506   verifyFormat("__try {\n"
4507                "  // something\n"
4508                "}\n"
4509                "__finally {\n"
4510                "  // something\n"
4511                "}",
4512                Style);
4513   verifyFormat("@try {\n"
4514                "  // something\n"
4515                "}\n"
4516                "@finally {\n"
4517                "  // something\n"
4518                "}",
4519                Style);
4520   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4521   verifyFormat("try\n"
4522                "{\n"
4523                "  // something\n"
4524                "}\n"
4525                "catch (...)\n"
4526                "{\n"
4527                "  // something\n"
4528                "}",
4529                Style);
4530   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4531   verifyFormat("try\n"
4532                "  {\n"
4533                "  // something white\n"
4534                "  }\n"
4535                "catch (...)\n"
4536                "  {\n"
4537                "  // something white\n"
4538                "  }",
4539                Style);
4540   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4541   verifyFormat("try\n"
4542                "  {\n"
4543                "    // something\n"
4544                "  }\n"
4545                "catch (...)\n"
4546                "  {\n"
4547                "    // something\n"
4548                "  }",
4549                Style);
4550   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4551   Style.BraceWrapping.BeforeCatch = true;
4552   verifyFormat("try {\n"
4553                "  // something\n"
4554                "}\n"
4555                "catch (...) {\n"
4556                "  // something\n"
4557                "}",
4558                Style);
4559 }
4560 
4561 TEST_F(FormatTest, StaticInitializers) {
4562   verifyFormat("static SomeClass SC = {1, 'a'};");
4563 
4564   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4565                "    100000000, "
4566                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4567 
4568   // Here, everything other than the "}" would fit on a line.
4569   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4570                "    10000000000000000000000000};");
4571   EXPECT_EQ("S s = {a,\n"
4572             "\n"
4573             "       b};",
4574             format("S s = {\n"
4575                    "  a,\n"
4576                    "\n"
4577                    "  b\n"
4578                    "};"));
4579 
4580   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4581   // line. However, the formatting looks a bit off and this probably doesn't
4582   // happen often in practice.
4583   verifyFormat("static int Variable[1] = {\n"
4584                "    {1000000000000000000000000000000000000}};",
4585                getLLVMStyleWithColumns(40));
4586 }
4587 
4588 TEST_F(FormatTest, DesignatedInitializers) {
4589   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4590   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4591                "                    .bbbbbbbbbb = 2,\n"
4592                "                    .cccccccccc = 3,\n"
4593                "                    .dddddddddd = 4,\n"
4594                "                    .eeeeeeeeee = 5};");
4595   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4596                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4597                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4598                "    .ccccccccccccccccccccccccccc = 3,\n"
4599                "    .ddddddddddddddddddddddddddd = 4,\n"
4600                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4601 
4602   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4603 
4604   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4605   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4606                "                    [2] = bbbbbbbbbb,\n"
4607                "                    [3] = cccccccccc,\n"
4608                "                    [4] = dddddddddd,\n"
4609                "                    [5] = eeeeeeeeee};");
4610   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4611                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4612                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4613                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4614                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4615                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4616 }
4617 
4618 TEST_F(FormatTest, NestedStaticInitializers) {
4619   verifyFormat("static A x = {{{}}};\n");
4620   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4621                "               {init1, init2, init3, init4}}};",
4622                getLLVMStyleWithColumns(50));
4623 
4624   verifyFormat("somes Status::global_reps[3] = {\n"
4625                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4626                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4627                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4628                getLLVMStyleWithColumns(60));
4629   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4630                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4631                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4632                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4633   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4634                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4635                "rect.fTop}};");
4636 
4637   verifyFormat(
4638       "SomeArrayOfSomeType a = {\n"
4639       "    {{1, 2, 3},\n"
4640       "     {1, 2, 3},\n"
4641       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4642       "      333333333333333333333333333333},\n"
4643       "     {1, 2, 3},\n"
4644       "     {1, 2, 3}}};");
4645   verifyFormat(
4646       "SomeArrayOfSomeType a = {\n"
4647       "    {{1, 2, 3}},\n"
4648       "    {{1, 2, 3}},\n"
4649       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4650       "      333333333333333333333333333333}},\n"
4651       "    {{1, 2, 3}},\n"
4652       "    {{1, 2, 3}}};");
4653 
4654   verifyFormat("struct {\n"
4655                "  unsigned bit;\n"
4656                "  const char *const name;\n"
4657                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4658                "                 {kOsWin, \"Windows\"},\n"
4659                "                 {kOsLinux, \"Linux\"},\n"
4660                "                 {kOsCrOS, \"Chrome OS\"}};");
4661   verifyFormat("struct {\n"
4662                "  unsigned bit;\n"
4663                "  const char *const name;\n"
4664                "} kBitsToOs[] = {\n"
4665                "    {kOsMac, \"Mac\"},\n"
4666                "    {kOsWin, \"Windows\"},\n"
4667                "    {kOsLinux, \"Linux\"},\n"
4668                "    {kOsCrOS, \"Chrome OS\"},\n"
4669                "};");
4670 }
4671 
4672 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4673   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4674                "                      \\\n"
4675                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4676 }
4677 
4678 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4679   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4680                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4681 
4682   // Do break defaulted and deleted functions.
4683   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4684                "    default;",
4685                getLLVMStyleWithColumns(40));
4686   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4687                "    delete;",
4688                getLLVMStyleWithColumns(40));
4689 }
4690 
4691 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4692   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4693                getLLVMStyleWithColumns(40));
4694   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4695                getLLVMStyleWithColumns(40));
4696   EXPECT_EQ("#define Q                              \\\n"
4697             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4698             "  \"aaaaaaaa.cpp\"",
4699             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4700                    getLLVMStyleWithColumns(40)));
4701 }
4702 
4703 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4704   EXPECT_EQ("# 123 \"A string literal\"",
4705             format("   #     123    \"A string literal\""));
4706 }
4707 
4708 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4709   EXPECT_EQ("#;", format("#;"));
4710   verifyFormat("#\n;\n;\n;");
4711 }
4712 
4713 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4714   EXPECT_EQ("#line 42 \"test\"\n",
4715             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4716   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4717                                     getLLVMStyleWithColumns(12)));
4718 }
4719 
4720 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4721   EXPECT_EQ("#line 42 \"test\"",
4722             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4723   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4724 }
4725 
4726 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4727   verifyFormat("#define A \\x20");
4728   verifyFormat("#define A \\ x20");
4729   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4730   verifyFormat("#define A ''");
4731   verifyFormat("#define A ''qqq");
4732   verifyFormat("#define A `qqq");
4733   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4734   EXPECT_EQ("const char *c = STRINGIFY(\n"
4735             "\\na : b);",
4736             format("const char * c = STRINGIFY(\n"
4737                    "\\na : b);"));
4738 
4739   verifyFormat("a\r\\");
4740   verifyFormat("a\v\\");
4741   verifyFormat("a\f\\");
4742 }
4743 
4744 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4745   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4746   style.IndentWidth = 4;
4747   style.PPIndentWidth = 1;
4748 
4749   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4750   verifyFormat("#ifdef __linux__\n"
4751                "void foo() {\n"
4752                "    int x = 0;\n"
4753                "}\n"
4754                "#define FOO\n"
4755                "#endif\n"
4756                "void bar() {\n"
4757                "    int y = 0;\n"
4758                "}\n",
4759                style);
4760 
4761   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4762   verifyFormat("#ifdef __linux__\n"
4763                "void foo() {\n"
4764                "    int x = 0;\n"
4765                "}\n"
4766                "# define FOO foo\n"
4767                "#endif\n"
4768                "void bar() {\n"
4769                "    int y = 0;\n"
4770                "}\n",
4771                style);
4772 
4773   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4774   verifyFormat("#ifdef __linux__\n"
4775                "void foo() {\n"
4776                "    int x = 0;\n"
4777                "}\n"
4778                " #define FOO foo\n"
4779                "#endif\n"
4780                "void bar() {\n"
4781                "    int y = 0;\n"
4782                "}\n",
4783                style);
4784 }
4785 
4786 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4787   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4788   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4789   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4790   // FIXME: We never break before the macro name.
4791   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4792 
4793   verifyFormat("#define A A\n#define A A");
4794   verifyFormat("#define A(X) A\n#define A A");
4795 
4796   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4797   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4798 }
4799 
4800 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4801   EXPECT_EQ("// somecomment\n"
4802             "#include \"a.h\"\n"
4803             "#define A(  \\\n"
4804             "    A, B)\n"
4805             "#include \"b.h\"\n"
4806             "// somecomment\n",
4807             format("  // somecomment\n"
4808                    "  #include \"a.h\"\n"
4809                    "#define A(A,\\\n"
4810                    "    B)\n"
4811                    "    #include \"b.h\"\n"
4812                    " // somecomment\n",
4813                    getLLVMStyleWithColumns(13)));
4814 }
4815 
4816 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4817 
4818 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4819   EXPECT_EQ("#define A    \\\n"
4820             "  c;         \\\n"
4821             "  e;\n"
4822             "f;",
4823             format("#define A c; e;\n"
4824                    "f;",
4825                    getLLVMStyleWithColumns(14)));
4826 }
4827 
4828 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4829 
4830 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4831   EXPECT_EQ("int x,\n"
4832             "#define A\n"
4833             "    y;",
4834             format("int x,\n#define A\ny;"));
4835 }
4836 
4837 TEST_F(FormatTest, HashInMacroDefinition) {
4838   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4839   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4840   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4841   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4842   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4843   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4844   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4845   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4846   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4847   verifyFormat("#define A  \\\n"
4848                "  {        \\\n"
4849                "    f(#c); \\\n"
4850                "  }",
4851                getLLVMStyleWithColumns(11));
4852 
4853   verifyFormat("#define A(X)         \\\n"
4854                "  void function##X()",
4855                getLLVMStyleWithColumns(22));
4856 
4857   verifyFormat("#define A(a, b, c)   \\\n"
4858                "  void a##b##c()",
4859                getLLVMStyleWithColumns(22));
4860 
4861   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4862 }
4863 
4864 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4865   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4866   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4867 
4868   FormatStyle Style = getLLVMStyle();
4869   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4870   verifyFormat("#define true ((foo)1)", Style);
4871   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4872   verifyFormat("#define false((foo)0)", Style);
4873 }
4874 
4875 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4876   EXPECT_EQ("#define A b;", format("#define A \\\n"
4877                                    "          \\\n"
4878                                    "  b;",
4879                                    getLLVMStyleWithColumns(25)));
4880   EXPECT_EQ("#define A \\\n"
4881             "          \\\n"
4882             "  a;      \\\n"
4883             "  b;",
4884             format("#define A \\\n"
4885                    "          \\\n"
4886                    "  a;      \\\n"
4887                    "  b;",
4888                    getLLVMStyleWithColumns(11)));
4889   EXPECT_EQ("#define A \\\n"
4890             "  a;      \\\n"
4891             "          \\\n"
4892             "  b;",
4893             format("#define A \\\n"
4894                    "  a;      \\\n"
4895                    "          \\\n"
4896                    "  b;",
4897                    getLLVMStyleWithColumns(11)));
4898 }
4899 
4900 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
4901   verifyIncompleteFormat("#define A :");
4902   verifyFormat("#define SOMECASES  \\\n"
4903                "  case 1:          \\\n"
4904                "  case 2\n",
4905                getLLVMStyleWithColumns(20));
4906   verifyFormat("#define MACRO(a) \\\n"
4907                "  if (a)         \\\n"
4908                "    f();         \\\n"
4909                "  else           \\\n"
4910                "    g()",
4911                getLLVMStyleWithColumns(18));
4912   verifyFormat("#define A template <typename T>");
4913   verifyIncompleteFormat("#define STR(x) #x\n"
4914                          "f(STR(this_is_a_string_literal{));");
4915   verifyFormat("#pragma omp threadprivate( \\\n"
4916                "    y)), // expected-warning",
4917                getLLVMStyleWithColumns(28));
4918   verifyFormat("#d, = };");
4919   verifyFormat("#if \"a");
4920   verifyIncompleteFormat("({\n"
4921                          "#define b     \\\n"
4922                          "  }           \\\n"
4923                          "  a\n"
4924                          "a",
4925                          getLLVMStyleWithColumns(15));
4926   verifyFormat("#define A     \\\n"
4927                "  {           \\\n"
4928                "    {\n"
4929                "#define B     \\\n"
4930                "  }           \\\n"
4931                "  }",
4932                getLLVMStyleWithColumns(15));
4933   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
4934   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
4935   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
4936   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
4937 }
4938 
4939 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
4940   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
4941   EXPECT_EQ("class A : public QObject {\n"
4942             "  Q_OBJECT\n"
4943             "\n"
4944             "  A() {}\n"
4945             "};",
4946             format("class A  :  public QObject {\n"
4947                    "     Q_OBJECT\n"
4948                    "\n"
4949                    "  A() {\n}\n"
4950                    "}  ;"));
4951   EXPECT_EQ("MACRO\n"
4952             "/*static*/ int i;",
4953             format("MACRO\n"
4954                    " /*static*/ int   i;"));
4955   EXPECT_EQ("SOME_MACRO\n"
4956             "namespace {\n"
4957             "void f();\n"
4958             "} // namespace",
4959             format("SOME_MACRO\n"
4960                    "  namespace    {\n"
4961                    "void   f(  );\n"
4962                    "} // namespace"));
4963   // Only if the identifier contains at least 5 characters.
4964   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
4965   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
4966   // Only if everything is upper case.
4967   EXPECT_EQ("class A : public QObject {\n"
4968             "  Q_Object A() {}\n"
4969             "};",
4970             format("class A  :  public QObject {\n"
4971                    "     Q_Object\n"
4972                    "  A() {\n}\n"
4973                    "}  ;"));
4974 
4975   // Only if the next line can actually start an unwrapped line.
4976   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
4977             format("SOME_WEIRD_LOG_MACRO\n"
4978                    "<< SomeThing;"));
4979 
4980   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
4981                "(n, buffers))\n",
4982                getChromiumStyle(FormatStyle::LK_Cpp));
4983 
4984   // See PR41483
4985   EXPECT_EQ("/**/ FOO(a)\n"
4986             "FOO(b)",
4987             format("/**/ FOO(a)\n"
4988                    "FOO(b)"));
4989 }
4990 
4991 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
4992   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4993             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4994             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4995             "class X {};\n"
4996             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4997             "int *createScopDetectionPass() { return 0; }",
4998             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4999                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5000                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5001                    "  class X {};\n"
5002                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5003                    "  int *createScopDetectionPass() { return 0; }"));
5004   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
5005   // braces, so that inner block is indented one level more.
5006   EXPECT_EQ("int q() {\n"
5007             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5008             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5009             "  IPC_END_MESSAGE_MAP()\n"
5010             "}",
5011             format("int q() {\n"
5012                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5013                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5014                    "  IPC_END_MESSAGE_MAP()\n"
5015                    "}"));
5016 
5017   // Same inside macros.
5018   EXPECT_EQ("#define LIST(L) \\\n"
5019             "  L(A)          \\\n"
5020             "  L(B)          \\\n"
5021             "  L(C)",
5022             format("#define LIST(L) \\\n"
5023                    "  L(A) \\\n"
5024                    "  L(B) \\\n"
5025                    "  L(C)",
5026                    getGoogleStyle()));
5027 
5028   // These must not be recognized as macros.
5029   EXPECT_EQ("int q() {\n"
5030             "  f(x);\n"
5031             "  f(x) {}\n"
5032             "  f(x)->g();\n"
5033             "  f(x)->*g();\n"
5034             "  f(x).g();\n"
5035             "  f(x) = x;\n"
5036             "  f(x) += x;\n"
5037             "  f(x) -= x;\n"
5038             "  f(x) *= x;\n"
5039             "  f(x) /= x;\n"
5040             "  f(x) %= x;\n"
5041             "  f(x) &= x;\n"
5042             "  f(x) |= x;\n"
5043             "  f(x) ^= x;\n"
5044             "  f(x) >>= x;\n"
5045             "  f(x) <<= x;\n"
5046             "  f(x)[y].z();\n"
5047             "  LOG(INFO) << x;\n"
5048             "  ifstream(x) >> x;\n"
5049             "}\n",
5050             format("int q() {\n"
5051                    "  f(x)\n;\n"
5052                    "  f(x)\n {}\n"
5053                    "  f(x)\n->g();\n"
5054                    "  f(x)\n->*g();\n"
5055                    "  f(x)\n.g();\n"
5056                    "  f(x)\n = x;\n"
5057                    "  f(x)\n += x;\n"
5058                    "  f(x)\n -= x;\n"
5059                    "  f(x)\n *= x;\n"
5060                    "  f(x)\n /= x;\n"
5061                    "  f(x)\n %= x;\n"
5062                    "  f(x)\n &= x;\n"
5063                    "  f(x)\n |= x;\n"
5064                    "  f(x)\n ^= x;\n"
5065                    "  f(x)\n >>= x;\n"
5066                    "  f(x)\n <<= x;\n"
5067                    "  f(x)\n[y].z();\n"
5068                    "  LOG(INFO)\n << x;\n"
5069                    "  ifstream(x)\n >> x;\n"
5070                    "}\n"));
5071   EXPECT_EQ("int q() {\n"
5072             "  F(x)\n"
5073             "  if (1) {\n"
5074             "  }\n"
5075             "  F(x)\n"
5076             "  while (1) {\n"
5077             "  }\n"
5078             "  F(x)\n"
5079             "  G(x);\n"
5080             "  F(x)\n"
5081             "  try {\n"
5082             "    Q();\n"
5083             "  } catch (...) {\n"
5084             "  }\n"
5085             "}\n",
5086             format("int q() {\n"
5087                    "F(x)\n"
5088                    "if (1) {}\n"
5089                    "F(x)\n"
5090                    "while (1) {}\n"
5091                    "F(x)\n"
5092                    "G(x);\n"
5093                    "F(x)\n"
5094                    "try { Q(); } catch (...) {}\n"
5095                    "}\n"));
5096   EXPECT_EQ("class A {\n"
5097             "  A() : t(0) {}\n"
5098             "  A(int i) noexcept() : {}\n"
5099             "  A(X x)\n" // FIXME: function-level try blocks are broken.
5100             "  try : t(0) {\n"
5101             "  } catch (...) {\n"
5102             "  }\n"
5103             "};",
5104             format("class A {\n"
5105                    "  A()\n : t(0) {}\n"
5106                    "  A(int i)\n noexcept() : {}\n"
5107                    "  A(X x)\n"
5108                    "  try : t(0) {} catch (...) {}\n"
5109                    "};"));
5110   FormatStyle Style = getLLVMStyle();
5111   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5112   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5113   Style.BraceWrapping.AfterFunction = true;
5114   EXPECT_EQ("void f()\n"
5115             "try\n"
5116             "{\n"
5117             "}",
5118             format("void f() try {\n"
5119                    "}",
5120                    Style));
5121   EXPECT_EQ("class SomeClass {\n"
5122             "public:\n"
5123             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5124             "};",
5125             format("class SomeClass {\n"
5126                    "public:\n"
5127                    "  SomeClass()\n"
5128                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5129                    "};"));
5130   EXPECT_EQ("class SomeClass {\n"
5131             "public:\n"
5132             "  SomeClass()\n"
5133             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5134             "};",
5135             format("class SomeClass {\n"
5136                    "public:\n"
5137                    "  SomeClass()\n"
5138                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5139                    "};",
5140                    getLLVMStyleWithColumns(40)));
5141 
5142   verifyFormat("MACRO(>)");
5143 
5144   // Some macros contain an implicit semicolon.
5145   Style = getLLVMStyle();
5146   Style.StatementMacros.push_back("FOO");
5147   verifyFormat("FOO(a) int b = 0;");
5148   verifyFormat("FOO(a)\n"
5149                "int b = 0;",
5150                Style);
5151   verifyFormat("FOO(a);\n"
5152                "int b = 0;",
5153                Style);
5154   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
5155                "int b = 0;",
5156                Style);
5157   verifyFormat("FOO()\n"
5158                "int b = 0;",
5159                Style);
5160   verifyFormat("FOO\n"
5161                "int b = 0;",
5162                Style);
5163   verifyFormat("void f() {\n"
5164                "  FOO(a)\n"
5165                "  return a;\n"
5166                "}",
5167                Style);
5168   verifyFormat("FOO(a)\n"
5169                "FOO(b)",
5170                Style);
5171   verifyFormat("int a = 0;\n"
5172                "FOO(b)\n"
5173                "int c = 0;",
5174                Style);
5175   verifyFormat("int a = 0;\n"
5176                "int x = FOO(a)\n"
5177                "int b = 0;",
5178                Style);
5179   verifyFormat("void foo(int a) { FOO(a) }\n"
5180                "uint32_t bar() {}",
5181                Style);
5182 }
5183 
5184 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
5185   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
5186 
5187   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
5188                ZeroColumn);
5189 }
5190 
5191 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5192   verifyFormat("#define A \\\n"
5193                "  f({     \\\n"
5194                "    g();  \\\n"
5195                "  });",
5196                getLLVMStyleWithColumns(11));
5197 }
5198 
5199 TEST_F(FormatTest, IndentPreprocessorDirectives) {
5200   FormatStyle Style = getLLVMStyleWithColumns(40);
5201   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
5202   verifyFormat("#ifdef _WIN32\n"
5203                "#define A 0\n"
5204                "#ifdef VAR2\n"
5205                "#define B 1\n"
5206                "#include <someheader.h>\n"
5207                "#define MACRO                          \\\n"
5208                "  some_very_long_func_aaaaaaaaaa();\n"
5209                "#endif\n"
5210                "#else\n"
5211                "#define A 1\n"
5212                "#endif",
5213                Style);
5214   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
5215   verifyFormat("#ifdef _WIN32\n"
5216                "#  define A 0\n"
5217                "#  ifdef VAR2\n"
5218                "#    define B 1\n"
5219                "#    include <someheader.h>\n"
5220                "#    define MACRO                      \\\n"
5221                "      some_very_long_func_aaaaaaaaaa();\n"
5222                "#  endif\n"
5223                "#else\n"
5224                "#  define A 1\n"
5225                "#endif",
5226                Style);
5227   verifyFormat("#if A\n"
5228                "#  define MACRO                        \\\n"
5229                "    void a(int x) {                    \\\n"
5230                "      b();                             \\\n"
5231                "      c();                             \\\n"
5232                "      d();                             \\\n"
5233                "      e();                             \\\n"
5234                "      f();                             \\\n"
5235                "    }\n"
5236                "#endif",
5237                Style);
5238   // Comments before include guard.
5239   verifyFormat("// file comment\n"
5240                "// file comment\n"
5241                "#ifndef HEADER_H\n"
5242                "#define HEADER_H\n"
5243                "code();\n"
5244                "#endif",
5245                Style);
5246   // Test with include guards.
5247   verifyFormat("#ifndef HEADER_H\n"
5248                "#define HEADER_H\n"
5249                "code();\n"
5250                "#endif",
5251                Style);
5252   // Include guards must have a #define with the same variable immediately
5253   // after #ifndef.
5254   verifyFormat("#ifndef NOT_GUARD\n"
5255                "#  define FOO\n"
5256                "code();\n"
5257                "#endif",
5258                Style);
5259 
5260   // Include guards must cover the entire file.
5261   verifyFormat("code();\n"
5262                "code();\n"
5263                "#ifndef NOT_GUARD\n"
5264                "#  define NOT_GUARD\n"
5265                "code();\n"
5266                "#endif",
5267                Style);
5268   verifyFormat("#ifndef NOT_GUARD\n"
5269                "#  define NOT_GUARD\n"
5270                "code();\n"
5271                "#endif\n"
5272                "code();",
5273                Style);
5274   // Test with trailing blank lines.
5275   verifyFormat("#ifndef HEADER_H\n"
5276                "#define HEADER_H\n"
5277                "code();\n"
5278                "#endif\n",
5279                Style);
5280   // Include guards don't have #else.
5281   verifyFormat("#ifndef NOT_GUARD\n"
5282                "#  define NOT_GUARD\n"
5283                "code();\n"
5284                "#else\n"
5285                "#endif",
5286                Style);
5287   verifyFormat("#ifndef NOT_GUARD\n"
5288                "#  define NOT_GUARD\n"
5289                "code();\n"
5290                "#elif FOO\n"
5291                "#endif",
5292                Style);
5293   // Non-identifier #define after potential include guard.
5294   verifyFormat("#ifndef FOO\n"
5295                "#  define 1\n"
5296                "#endif\n",
5297                Style);
5298   // #if closes past last non-preprocessor line.
5299   verifyFormat("#ifndef FOO\n"
5300                "#define FOO\n"
5301                "#if 1\n"
5302                "int i;\n"
5303                "#  define A 0\n"
5304                "#endif\n"
5305                "#endif\n",
5306                Style);
5307   // Don't crash if there is an #elif directive without a condition.
5308   verifyFormat("#if 1\n"
5309                "int x;\n"
5310                "#elif\n"
5311                "int y;\n"
5312                "#else\n"
5313                "int z;\n"
5314                "#endif",
5315                Style);
5316   // FIXME: This doesn't handle the case where there's code between the
5317   // #ifndef and #define but all other conditions hold. This is because when
5318   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5319   // previous code line yet, so we can't detect it.
5320   EXPECT_EQ("#ifndef NOT_GUARD\n"
5321             "code();\n"
5322             "#define NOT_GUARD\n"
5323             "code();\n"
5324             "#endif",
5325             format("#ifndef NOT_GUARD\n"
5326                    "code();\n"
5327                    "#  define NOT_GUARD\n"
5328                    "code();\n"
5329                    "#endif",
5330                    Style));
5331   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5332   // be outside an include guard. Examples are #pragma once and
5333   // #pragma GCC diagnostic, or anything else that does not change the meaning
5334   // of the file if it's included multiple times.
5335   EXPECT_EQ("#ifdef WIN32\n"
5336             "#  pragma once\n"
5337             "#endif\n"
5338             "#ifndef HEADER_H\n"
5339             "#  define HEADER_H\n"
5340             "code();\n"
5341             "#endif",
5342             format("#ifdef WIN32\n"
5343                    "#  pragma once\n"
5344                    "#endif\n"
5345                    "#ifndef HEADER_H\n"
5346                    "#define HEADER_H\n"
5347                    "code();\n"
5348                    "#endif",
5349                    Style));
5350   // FIXME: This does not detect when there is a single non-preprocessor line
5351   // in front of an include-guard-like structure where other conditions hold
5352   // because ScopedLineState hides the line.
5353   EXPECT_EQ("code();\n"
5354             "#ifndef HEADER_H\n"
5355             "#define HEADER_H\n"
5356             "code();\n"
5357             "#endif",
5358             format("code();\n"
5359                    "#ifndef HEADER_H\n"
5360                    "#  define HEADER_H\n"
5361                    "code();\n"
5362                    "#endif",
5363                    Style));
5364   // Keep comments aligned with #, otherwise indent comments normally. These
5365   // tests cannot use verifyFormat because messUp manipulates leading
5366   // whitespace.
5367   {
5368     const char *Expected = ""
5369                            "void f() {\n"
5370                            "#if 1\n"
5371                            "// Preprocessor aligned.\n"
5372                            "#  define A 0\n"
5373                            "  // Code. Separated by blank line.\n"
5374                            "\n"
5375                            "#  define B 0\n"
5376                            "  // Code. Not aligned with #\n"
5377                            "#  define C 0\n"
5378                            "#endif";
5379     const char *ToFormat = ""
5380                            "void f() {\n"
5381                            "#if 1\n"
5382                            "// Preprocessor aligned.\n"
5383                            "#  define A 0\n"
5384                            "// Code. Separated by blank line.\n"
5385                            "\n"
5386                            "#  define B 0\n"
5387                            "   // Code. Not aligned with #\n"
5388                            "#  define C 0\n"
5389                            "#endif";
5390     EXPECT_EQ(Expected, format(ToFormat, Style));
5391     EXPECT_EQ(Expected, format(Expected, Style));
5392   }
5393   // Keep block quotes aligned.
5394   {
5395     const char *Expected = ""
5396                            "void f() {\n"
5397                            "#if 1\n"
5398                            "/* Preprocessor aligned. */\n"
5399                            "#  define A 0\n"
5400                            "  /* Code. Separated by blank line. */\n"
5401                            "\n"
5402                            "#  define B 0\n"
5403                            "  /* Code. Not aligned with # */\n"
5404                            "#  define C 0\n"
5405                            "#endif";
5406     const char *ToFormat = ""
5407                            "void f() {\n"
5408                            "#if 1\n"
5409                            "/* Preprocessor aligned. */\n"
5410                            "#  define A 0\n"
5411                            "/* Code. Separated by blank line. */\n"
5412                            "\n"
5413                            "#  define B 0\n"
5414                            "   /* Code. Not aligned with # */\n"
5415                            "#  define C 0\n"
5416                            "#endif";
5417     EXPECT_EQ(Expected, format(ToFormat, Style));
5418     EXPECT_EQ(Expected, format(Expected, Style));
5419   }
5420   // Keep comments aligned with un-indented directives.
5421   {
5422     const char *Expected = ""
5423                            "void f() {\n"
5424                            "// Preprocessor aligned.\n"
5425                            "#define A 0\n"
5426                            "  // Code. Separated by blank line.\n"
5427                            "\n"
5428                            "#define B 0\n"
5429                            "  // Code. Not aligned with #\n"
5430                            "#define C 0\n";
5431     const char *ToFormat = ""
5432                            "void f() {\n"
5433                            "// Preprocessor aligned.\n"
5434                            "#define A 0\n"
5435                            "// Code. Separated by blank line.\n"
5436                            "\n"
5437                            "#define B 0\n"
5438                            "   // Code. Not aligned with #\n"
5439                            "#define C 0\n";
5440     EXPECT_EQ(Expected, format(ToFormat, Style));
5441     EXPECT_EQ(Expected, format(Expected, Style));
5442   }
5443   // Test AfterHash with tabs.
5444   {
5445     FormatStyle Tabbed = Style;
5446     Tabbed.UseTab = FormatStyle::UT_Always;
5447     Tabbed.IndentWidth = 8;
5448     Tabbed.TabWidth = 8;
5449     verifyFormat("#ifdef _WIN32\n"
5450                  "#\tdefine A 0\n"
5451                  "#\tifdef VAR2\n"
5452                  "#\t\tdefine B 1\n"
5453                  "#\t\tinclude <someheader.h>\n"
5454                  "#\t\tdefine MACRO          \\\n"
5455                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5456                  "#\tendif\n"
5457                  "#else\n"
5458                  "#\tdefine A 1\n"
5459                  "#endif",
5460                  Tabbed);
5461   }
5462 
5463   // Regression test: Multiline-macro inside include guards.
5464   verifyFormat("#ifndef HEADER_H\n"
5465                "#define HEADER_H\n"
5466                "#define A()        \\\n"
5467                "  int i;           \\\n"
5468                "  int j;\n"
5469                "#endif // HEADER_H",
5470                getLLVMStyleWithColumns(20));
5471 
5472   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5473   // Basic before hash indent tests
5474   verifyFormat("#ifdef _WIN32\n"
5475                "  #define A 0\n"
5476                "  #ifdef VAR2\n"
5477                "    #define B 1\n"
5478                "    #include <someheader.h>\n"
5479                "    #define MACRO                      \\\n"
5480                "      some_very_long_func_aaaaaaaaaa();\n"
5481                "  #endif\n"
5482                "#else\n"
5483                "  #define A 1\n"
5484                "#endif",
5485                Style);
5486   verifyFormat("#if A\n"
5487                "  #define MACRO                        \\\n"
5488                "    void a(int x) {                    \\\n"
5489                "      b();                             \\\n"
5490                "      c();                             \\\n"
5491                "      d();                             \\\n"
5492                "      e();                             \\\n"
5493                "      f();                             \\\n"
5494                "    }\n"
5495                "#endif",
5496                Style);
5497   // Keep comments aligned with indented directives. These
5498   // tests cannot use verifyFormat because messUp manipulates leading
5499   // whitespace.
5500   {
5501     const char *Expected = "void f() {\n"
5502                            "// Aligned to preprocessor.\n"
5503                            "#if 1\n"
5504                            "  // Aligned to code.\n"
5505                            "  int a;\n"
5506                            "  #if 1\n"
5507                            "    // Aligned to preprocessor.\n"
5508                            "    #define A 0\n"
5509                            "  // Aligned to code.\n"
5510                            "  int b;\n"
5511                            "  #endif\n"
5512                            "#endif\n"
5513                            "}";
5514     const char *ToFormat = "void f() {\n"
5515                            "// Aligned to preprocessor.\n"
5516                            "#if 1\n"
5517                            "// Aligned to code.\n"
5518                            "int a;\n"
5519                            "#if 1\n"
5520                            "// Aligned to preprocessor.\n"
5521                            "#define A 0\n"
5522                            "// Aligned to code.\n"
5523                            "int b;\n"
5524                            "#endif\n"
5525                            "#endif\n"
5526                            "}";
5527     EXPECT_EQ(Expected, format(ToFormat, Style));
5528     EXPECT_EQ(Expected, format(Expected, Style));
5529   }
5530   {
5531     const char *Expected = "void f() {\n"
5532                            "/* Aligned to preprocessor. */\n"
5533                            "#if 1\n"
5534                            "  /* Aligned to code. */\n"
5535                            "  int a;\n"
5536                            "  #if 1\n"
5537                            "    /* Aligned to preprocessor. */\n"
5538                            "    #define A 0\n"
5539                            "  /* Aligned to code. */\n"
5540                            "  int b;\n"
5541                            "  #endif\n"
5542                            "#endif\n"
5543                            "}";
5544     const char *ToFormat = "void f() {\n"
5545                            "/* Aligned to preprocessor. */\n"
5546                            "#if 1\n"
5547                            "/* Aligned to code. */\n"
5548                            "int a;\n"
5549                            "#if 1\n"
5550                            "/* Aligned to preprocessor. */\n"
5551                            "#define A 0\n"
5552                            "/* Aligned to code. */\n"
5553                            "int b;\n"
5554                            "#endif\n"
5555                            "#endif\n"
5556                            "}";
5557     EXPECT_EQ(Expected, format(ToFormat, Style));
5558     EXPECT_EQ(Expected, format(Expected, Style));
5559   }
5560 
5561   // Test single comment before preprocessor
5562   verifyFormat("// Comment\n"
5563                "\n"
5564                "#if 1\n"
5565                "#endif",
5566                Style);
5567 }
5568 
5569 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5570   verifyFormat("{\n  { a #c; }\n}");
5571 }
5572 
5573 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5574   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5575             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5576   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5577             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5578 }
5579 
5580 TEST_F(FormatTest, EscapedNewlines) {
5581   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5582   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5583             format("#define A \\\nint i;\\\n  int j;", Narrow));
5584   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5585   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5586   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5587   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5588 
5589   FormatStyle AlignLeft = getLLVMStyle();
5590   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5591   EXPECT_EQ("#define MACRO(x) \\\n"
5592             "private:         \\\n"
5593             "  int x(int a);\n",
5594             format("#define MACRO(x) \\\n"
5595                    "private:         \\\n"
5596                    "  int x(int a);\n",
5597                    AlignLeft));
5598 
5599   // CRLF line endings
5600   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5601             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5602   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5603   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5604   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5605   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5606   EXPECT_EQ("#define MACRO(x) \\\r\n"
5607             "private:         \\\r\n"
5608             "  int x(int a);\r\n",
5609             format("#define MACRO(x) \\\r\n"
5610                    "private:         \\\r\n"
5611                    "  int x(int a);\r\n",
5612                    AlignLeft));
5613 
5614   FormatStyle DontAlign = getLLVMStyle();
5615   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5616   DontAlign.MaxEmptyLinesToKeep = 3;
5617   // FIXME: can't use verifyFormat here because the newline before
5618   // "public:" is not inserted the first time it's reformatted
5619   EXPECT_EQ("#define A \\\n"
5620             "  class Foo { \\\n"
5621             "    void bar(); \\\n"
5622             "\\\n"
5623             "\\\n"
5624             "\\\n"
5625             "  public: \\\n"
5626             "    void baz(); \\\n"
5627             "  };",
5628             format("#define A \\\n"
5629                    "  class Foo { \\\n"
5630                    "    void bar(); \\\n"
5631                    "\\\n"
5632                    "\\\n"
5633                    "\\\n"
5634                    "  public: \\\n"
5635                    "    void baz(); \\\n"
5636                    "  };",
5637                    DontAlign));
5638 }
5639 
5640 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5641   verifyFormat("#define A \\\n"
5642                "  int v(  \\\n"
5643                "      a); \\\n"
5644                "  int i;",
5645                getLLVMStyleWithColumns(11));
5646 }
5647 
5648 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5649   EXPECT_EQ(
5650       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5651       "                      \\\n"
5652       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5653       "\n"
5654       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5655       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5656       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5657              "\\\n"
5658              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5659              "  \n"
5660              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5661              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5662 }
5663 
5664 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5665   EXPECT_EQ("int\n"
5666             "#define A\n"
5667             "    a;",
5668             format("int\n#define A\na;"));
5669   verifyFormat("functionCallTo(\n"
5670                "    someOtherFunction(\n"
5671                "        withSomeParameters, whichInSequence,\n"
5672                "        areLongerThanALine(andAnotherCall,\n"
5673                "#define A B\n"
5674                "                           withMoreParamters,\n"
5675                "                           whichStronglyInfluenceTheLayout),\n"
5676                "        andMoreParameters),\n"
5677                "    trailing);",
5678                getLLVMStyleWithColumns(69));
5679   verifyFormat("Foo::Foo()\n"
5680                "#ifdef BAR\n"
5681                "    : baz(0)\n"
5682                "#endif\n"
5683                "{\n"
5684                "}");
5685   verifyFormat("void f() {\n"
5686                "  if (true)\n"
5687                "#ifdef A\n"
5688                "    f(42);\n"
5689                "  x();\n"
5690                "#else\n"
5691                "    g();\n"
5692                "  x();\n"
5693                "#endif\n"
5694                "}");
5695   verifyFormat("void f(param1, param2,\n"
5696                "       param3,\n"
5697                "#ifdef A\n"
5698                "       param4(param5,\n"
5699                "#ifdef A1\n"
5700                "              param6,\n"
5701                "#ifdef A2\n"
5702                "              param7),\n"
5703                "#else\n"
5704                "              param8),\n"
5705                "       param9,\n"
5706                "#endif\n"
5707                "       param10,\n"
5708                "#endif\n"
5709                "       param11)\n"
5710                "#else\n"
5711                "       param12)\n"
5712                "#endif\n"
5713                "{\n"
5714                "  x();\n"
5715                "}",
5716                getLLVMStyleWithColumns(28));
5717   verifyFormat("#if 1\n"
5718                "int i;");
5719   verifyFormat("#if 1\n"
5720                "#endif\n"
5721                "#if 1\n"
5722                "#else\n"
5723                "#endif\n");
5724   verifyFormat("DEBUG({\n"
5725                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5726                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5727                "});\n"
5728                "#if a\n"
5729                "#else\n"
5730                "#endif");
5731 
5732   verifyIncompleteFormat("void f(\n"
5733                          "#if A\n"
5734                          ");\n"
5735                          "#else\n"
5736                          "#endif");
5737 }
5738 
5739 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5740   verifyFormat("#endif\n"
5741                "#if B");
5742 }
5743 
5744 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5745   FormatStyle SingleLine = getLLVMStyle();
5746   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5747   verifyFormat("#if 0\n"
5748                "#elif 1\n"
5749                "#endif\n"
5750                "void foo() {\n"
5751                "  if (test) foo2();\n"
5752                "}",
5753                SingleLine);
5754 }
5755 
5756 TEST_F(FormatTest, LayoutBlockInsideParens) {
5757   verifyFormat("functionCall({ int i; });");
5758   verifyFormat("functionCall({\n"
5759                "  int i;\n"
5760                "  int j;\n"
5761                "});");
5762   verifyFormat("functionCall(\n"
5763                "    {\n"
5764                "      int i;\n"
5765                "      int j;\n"
5766                "    },\n"
5767                "    aaaa, bbbb, cccc);");
5768   verifyFormat("functionA(functionB({\n"
5769                "            int i;\n"
5770                "            int j;\n"
5771                "          }),\n"
5772                "          aaaa, bbbb, cccc);");
5773   verifyFormat("functionCall(\n"
5774                "    {\n"
5775                "      int i;\n"
5776                "      int j;\n"
5777                "    },\n"
5778                "    aaaa, bbbb, // comment\n"
5779                "    cccc);");
5780   verifyFormat("functionA(functionB({\n"
5781                "            int i;\n"
5782                "            int j;\n"
5783                "          }),\n"
5784                "          aaaa, bbbb, // comment\n"
5785                "          cccc);");
5786   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5787   verifyFormat("functionCall(aaaa, bbbb, {\n"
5788                "  int i;\n"
5789                "  int j;\n"
5790                "});");
5791   verifyFormat(
5792       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5793       "    {\n"
5794       "      int i; // break\n"
5795       "    },\n"
5796       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5797       "                                     ccccccccccccccccc));");
5798   verifyFormat("DEBUG({\n"
5799                "  if (a)\n"
5800                "    f();\n"
5801                "});");
5802 }
5803 
5804 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5805   EXPECT_EQ("SOME_MACRO { int i; }\n"
5806             "int i;",
5807             format("  SOME_MACRO  {int i;}  int i;"));
5808 }
5809 
5810 TEST_F(FormatTest, LayoutNestedBlocks) {
5811   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5812                "  struct s {\n"
5813                "    int i;\n"
5814                "  };\n"
5815                "  s kBitsToOs[] = {{10}};\n"
5816                "  for (int i = 0; i < 10; ++i)\n"
5817                "    return;\n"
5818                "}");
5819   verifyFormat("call(parameter, {\n"
5820                "  something();\n"
5821                "  // Comment using all columns.\n"
5822                "  somethingelse();\n"
5823                "});",
5824                getLLVMStyleWithColumns(40));
5825   verifyFormat("DEBUG( //\n"
5826                "    { f(); }, a);");
5827   verifyFormat("DEBUG( //\n"
5828                "    {\n"
5829                "      f(); //\n"
5830                "    },\n"
5831                "    a);");
5832 
5833   EXPECT_EQ("call(parameter, {\n"
5834             "  something();\n"
5835             "  // Comment too\n"
5836             "  // looooooooooong.\n"
5837             "  somethingElse();\n"
5838             "});",
5839             format("call(parameter, {\n"
5840                    "  something();\n"
5841                    "  // Comment too looooooooooong.\n"
5842                    "  somethingElse();\n"
5843                    "});",
5844                    getLLVMStyleWithColumns(29)));
5845   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5846   EXPECT_EQ("DEBUG({ // comment\n"
5847             "  int i;\n"
5848             "});",
5849             format("DEBUG({ // comment\n"
5850                    "int  i;\n"
5851                    "});"));
5852   EXPECT_EQ("DEBUG({\n"
5853             "  int i;\n"
5854             "\n"
5855             "  // comment\n"
5856             "  int j;\n"
5857             "});",
5858             format("DEBUG({\n"
5859                    "  int  i;\n"
5860                    "\n"
5861                    "  // comment\n"
5862                    "  int  j;\n"
5863                    "});"));
5864 
5865   verifyFormat("DEBUG({\n"
5866                "  if (a)\n"
5867                "    return;\n"
5868                "});");
5869   verifyGoogleFormat("DEBUG({\n"
5870                      "  if (a) return;\n"
5871                      "});");
5872   FormatStyle Style = getGoogleStyle();
5873   Style.ColumnLimit = 45;
5874   verifyFormat("Debug(\n"
5875                "    aaaaa,\n"
5876                "    {\n"
5877                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5878                "    },\n"
5879                "    a);",
5880                Style);
5881 
5882   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5883 
5884   verifyNoCrash("^{v^{a}}");
5885 }
5886 
5887 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
5888   EXPECT_EQ("#define MACRO()                     \\\n"
5889             "  Debug(aaa, /* force line break */ \\\n"
5890             "        {                           \\\n"
5891             "          int i;                    \\\n"
5892             "          int j;                    \\\n"
5893             "        })",
5894             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
5895                    "          {  int   i;  int  j;   })",
5896                    getGoogleStyle()));
5897 
5898   EXPECT_EQ("#define A                                       \\\n"
5899             "  [] {                                          \\\n"
5900             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
5901             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
5902             "  }",
5903             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
5904                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
5905                    getGoogleStyle()));
5906 }
5907 
5908 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
5909   EXPECT_EQ("{}", format("{}"));
5910   verifyFormat("enum E {};");
5911   verifyFormat("enum E {}");
5912   FormatStyle Style = getLLVMStyle();
5913   Style.SpaceInEmptyBlock = true;
5914   EXPECT_EQ("void f() { }", format("void f() {}", Style));
5915   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
5916   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
5917   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5918   Style.BraceWrapping.BeforeElse = false;
5919   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5920   verifyFormat("if (a)\n"
5921                "{\n"
5922                "} else if (b)\n"
5923                "{\n"
5924                "} else\n"
5925                "{ }",
5926                Style);
5927   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
5928   verifyFormat("if (a) {\n"
5929                "} else if (b) {\n"
5930                "} else {\n"
5931                "}",
5932                Style);
5933   Style.BraceWrapping.BeforeElse = true;
5934   verifyFormat("if (a) { }\n"
5935                "else if (b) { }\n"
5936                "else { }",
5937                Style);
5938 }
5939 
5940 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
5941   FormatStyle Style = getLLVMStyle();
5942   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
5943   Style.MacroBlockEnd = "^[A-Z_]+_END$";
5944   verifyFormat("FOO_BEGIN\n"
5945                "  FOO_ENTRY\n"
5946                "FOO_END",
5947                Style);
5948   verifyFormat("FOO_BEGIN\n"
5949                "  NESTED_FOO_BEGIN\n"
5950                "    NESTED_FOO_ENTRY\n"
5951                "  NESTED_FOO_END\n"
5952                "FOO_END",
5953                Style);
5954   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
5955                "  int x;\n"
5956                "  x = 1;\n"
5957                "FOO_END(Baz)",
5958                Style);
5959 }
5960 
5961 //===----------------------------------------------------------------------===//
5962 // Line break tests.
5963 //===----------------------------------------------------------------------===//
5964 
5965 TEST_F(FormatTest, PreventConfusingIndents) {
5966   verifyFormat(
5967       "void f() {\n"
5968       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
5969       "                         parameter, parameter, parameter)),\n"
5970       "                     SecondLongCall(parameter));\n"
5971       "}");
5972   verifyFormat(
5973       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5974       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5975       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5976       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
5977   verifyFormat(
5978       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5979       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
5980       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5981       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
5982   verifyFormat(
5983       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5984       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
5985       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
5986       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
5987   verifyFormat("int a = bbbb && ccc &&\n"
5988                "        fffff(\n"
5989                "#define A Just forcing a new line\n"
5990                "            ddd);");
5991 }
5992 
5993 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
5994   verifyFormat(
5995       "bool aaaaaaa =\n"
5996       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
5997       "    bbbbbbbb();");
5998   verifyFormat(
5999       "bool aaaaaaa =\n"
6000       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
6001       "    bbbbbbbb();");
6002 
6003   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6004                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
6005                "    ccccccccc == ddddddddddd;");
6006   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6007                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
6008                "    ccccccccc == ddddddddddd;");
6009   verifyFormat(
6010       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6011       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
6012       "    ccccccccc == ddddddddddd;");
6013 
6014   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6015                "                 aaaaaa) &&\n"
6016                "         bbbbbb && cccccc;");
6017   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6018                "                 aaaaaa) >>\n"
6019                "         bbbbbb;");
6020   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
6021                "    SourceMgr.getSpellingColumnNumber(\n"
6022                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
6023                "    1);");
6024 
6025   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6026                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
6027                "    cccccc) {\n}");
6028   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6029                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6030                "              cccccc) {\n}");
6031   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6032                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6033                "              cccccc) {\n}");
6034   verifyFormat("b = a &&\n"
6035                "    // Comment\n"
6036                "    b.c && d;");
6037 
6038   // If the LHS of a comparison is not a binary expression itself, the
6039   // additional linebreak confuses many people.
6040   verifyFormat(
6041       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6042       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
6043       "}");
6044   verifyFormat(
6045       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6046       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6047       "}");
6048   verifyFormat(
6049       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
6050       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6051       "}");
6052   verifyFormat(
6053       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6054       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
6055       "}");
6056   // Even explicit parentheses stress the precedence enough to make the
6057   // additional break unnecessary.
6058   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6059                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6060                "}");
6061   // This cases is borderline, but with the indentation it is still readable.
6062   verifyFormat(
6063       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6064       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6065       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
6066       "}",
6067       getLLVMStyleWithColumns(75));
6068 
6069   // If the LHS is a binary expression, we should still use the additional break
6070   // as otherwise the formatting hides the operator precedence.
6071   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6072                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6073                "    5) {\n"
6074                "}");
6075   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6076                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
6077                "    5) {\n"
6078                "}");
6079 
6080   FormatStyle OnePerLine = getLLVMStyle();
6081   OnePerLine.BinPackParameters = false;
6082   verifyFormat(
6083       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6084       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6085       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
6086       OnePerLine);
6087 
6088   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
6089                "                .aaa(aaaaaaaaaaaaa) *\n"
6090                "            aaaaaaa +\n"
6091                "        aaaaaaa;",
6092                getLLVMStyleWithColumns(40));
6093 }
6094 
6095 TEST_F(FormatTest, ExpressionIndentation) {
6096   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6097                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6098                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6099                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6100                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6101                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
6102                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6103                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
6104                "                 ccccccccccccccccccccccccccccccccccccccccc;");
6105   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6106                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6107                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6108                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6109   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6110                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6111                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6112                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6113   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6114                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6115                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6116                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6117   verifyFormat("if () {\n"
6118                "} else if (aaaaa && bbbbb > // break\n"
6119                "                        ccccc) {\n"
6120                "}");
6121   verifyFormat("if () {\n"
6122                "} else if constexpr (aaaaa && bbbbb > // break\n"
6123                "                                  ccccc) {\n"
6124                "}");
6125   verifyFormat("if () {\n"
6126                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
6127                "                                  ccccc) {\n"
6128                "}");
6129   verifyFormat("if () {\n"
6130                "} else if (aaaaa &&\n"
6131                "           bbbbb > // break\n"
6132                "               ccccc &&\n"
6133                "           ddddd) {\n"
6134                "}");
6135 
6136   // Presence of a trailing comment used to change indentation of b.
6137   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
6138                "       b;\n"
6139                "return aaaaaaaaaaaaaaaaaaa +\n"
6140                "       b; //",
6141                getLLVMStyleWithColumns(30));
6142 }
6143 
6144 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
6145   // Not sure what the best system is here. Like this, the LHS can be found
6146   // immediately above an operator (everything with the same or a higher
6147   // indent). The RHS is aligned right of the operator and so compasses
6148   // everything until something with the same indent as the operator is found.
6149   // FIXME: Is this a good system?
6150   FormatStyle Style = getLLVMStyle();
6151   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6152   verifyFormat(
6153       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6154       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6155       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6156       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6157       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6158       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6159       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6160       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6161       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
6162       Style);
6163   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6164                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6165                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6166                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6167                Style);
6168   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6169                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6170                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6171                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6172                Style);
6173   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6174                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6175                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6176                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6177                Style);
6178   verifyFormat("if () {\n"
6179                "} else if (aaaaa\n"
6180                "           && bbbbb // break\n"
6181                "                  > ccccc) {\n"
6182                "}",
6183                Style);
6184   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6185                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6186                Style);
6187   verifyFormat("return (a)\n"
6188                "       // comment\n"
6189                "       + b;",
6190                Style);
6191   verifyFormat(
6192       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6193       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6194       "             + cc;",
6195       Style);
6196 
6197   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6198                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6199                Style);
6200 
6201   // Forced by comments.
6202   verifyFormat(
6203       "unsigned ContentSize =\n"
6204       "    sizeof(int16_t)   // DWARF ARange version number\n"
6205       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6206       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6207       "    + sizeof(int8_t); // Segment Size (in bytes)");
6208 
6209   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6210                "       == boost::fusion::at_c<1>(iiii).second;",
6211                Style);
6212 
6213   Style.ColumnLimit = 60;
6214   verifyFormat("zzzzzzzzzz\n"
6215                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6216                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6217                Style);
6218 
6219   Style.ColumnLimit = 80;
6220   Style.IndentWidth = 4;
6221   Style.TabWidth = 4;
6222   Style.UseTab = FormatStyle::UT_Always;
6223   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6224   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6225   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
6226             "\t&& (someOtherLongishConditionPart1\n"
6227             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
6228             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
6229                    "(someOtherLongishConditionPart1 || "
6230                    "someOtherEvenLongerNestedConditionPart2);",
6231                    Style));
6232 }
6233 
6234 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
6235   FormatStyle Style = getLLVMStyle();
6236   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6237   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
6238 
6239   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6240                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6241                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6242                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6243                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6244                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6245                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6246                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6247                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
6248                Style);
6249   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6250                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6251                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6252                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6253                Style);
6254   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6255                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6256                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6257                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6258                Style);
6259   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6260                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6261                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6262                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6263                Style);
6264   verifyFormat("if () {\n"
6265                "} else if (aaaaa\n"
6266                "           && bbbbb // break\n"
6267                "                  > ccccc) {\n"
6268                "}",
6269                Style);
6270   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6271                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6272                Style);
6273   verifyFormat("return (a)\n"
6274                "     // comment\n"
6275                "     + b;",
6276                Style);
6277   verifyFormat(
6278       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6279       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6280       "           + cc;",
6281       Style);
6282   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6283                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6284                "                        : 3333333333333333;",
6285                Style);
6286   verifyFormat(
6287       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6288       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6289       "                                             : eeeeeeeeeeeeeeeeee)\n"
6290       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6291       "                        : 3333333333333333;",
6292       Style);
6293   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6294                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6295                Style);
6296 
6297   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6298                "    == boost::fusion::at_c<1>(iiii).second;",
6299                Style);
6300 
6301   Style.ColumnLimit = 60;
6302   verifyFormat("zzzzzzzzzzzzz\n"
6303                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6304                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6305                Style);
6306 
6307   // Forced by comments.
6308   Style.ColumnLimit = 80;
6309   verifyFormat(
6310       "unsigned ContentSize\n"
6311       "    = sizeof(int16_t) // DWARF ARange version number\n"
6312       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6313       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6314       "    + sizeof(int8_t); // Segment Size (in bytes)",
6315       Style);
6316 
6317   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6318   verifyFormat(
6319       "unsigned ContentSize =\n"
6320       "    sizeof(int16_t)   // DWARF ARange version number\n"
6321       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6322       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6323       "    + sizeof(int8_t); // Segment Size (in bytes)",
6324       Style);
6325 
6326   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6327   verifyFormat(
6328       "unsigned ContentSize =\n"
6329       "    sizeof(int16_t)   // DWARF ARange version number\n"
6330       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6331       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6332       "    + sizeof(int8_t); // Segment Size (in bytes)",
6333       Style);
6334 }
6335 
6336 TEST_F(FormatTest, EnforcedOperatorWraps) {
6337   // Here we'd like to wrap after the || operators, but a comment is forcing an
6338   // earlier wrap.
6339   verifyFormat("bool x = aaaaa //\n"
6340                "         || bbbbb\n"
6341                "         //\n"
6342                "         || cccc;");
6343 }
6344 
6345 TEST_F(FormatTest, NoOperandAlignment) {
6346   FormatStyle Style = getLLVMStyle();
6347   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6348   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6349                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6350                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6351                Style);
6352   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6353   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6354                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6355                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6356                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6357                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6358                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6359                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6360                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6361                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6362                Style);
6363 
6364   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6365                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6366                "    + cc;",
6367                Style);
6368   verifyFormat("int a = aa\n"
6369                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6370                "        * cccccccccccccccccccccccccccccccccccc;\n",
6371                Style);
6372 
6373   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6374   verifyFormat("return (a > b\n"
6375                "    // comment1\n"
6376                "    // comment2\n"
6377                "    || c);",
6378                Style);
6379 }
6380 
6381 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6382   FormatStyle Style = getLLVMStyle();
6383   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6384   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6385                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6386                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6387                Style);
6388 }
6389 
6390 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6391   FormatStyle Style = getLLVMStyleWithColumns(40);
6392   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6393   Style.BinPackArguments = false;
6394   verifyFormat("void test() {\n"
6395                "  someFunction(\n"
6396                "      this + argument + is + quite\n"
6397                "      + long + so + it + gets + wrapped\n"
6398                "      + but + remains + bin - packed);\n"
6399                "}",
6400                Style);
6401   verifyFormat("void test() {\n"
6402                "  someFunction(arg1,\n"
6403                "               this + argument + is\n"
6404                "                   + quite + long + so\n"
6405                "                   + it + gets + wrapped\n"
6406                "                   + but + remains + bin\n"
6407                "                   - packed,\n"
6408                "               arg3);\n"
6409                "}",
6410                Style);
6411   verifyFormat("void test() {\n"
6412                "  someFunction(\n"
6413                "      arg1,\n"
6414                "      this + argument + has\n"
6415                "          + anotherFunc(nested,\n"
6416                "                        calls + whose\n"
6417                "                            + arguments\n"
6418                "                            + are + also\n"
6419                "                            + wrapped,\n"
6420                "                        in + addition)\n"
6421                "          + to + being + bin - packed,\n"
6422                "      arg3);\n"
6423                "}",
6424                Style);
6425 
6426   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6427   verifyFormat("void test() {\n"
6428                "  someFunction(\n"
6429                "      arg1,\n"
6430                "      this + argument + has +\n"
6431                "          anotherFunc(nested,\n"
6432                "                      calls + whose +\n"
6433                "                          arguments +\n"
6434                "                          are + also +\n"
6435                "                          wrapped,\n"
6436                "                      in + addition) +\n"
6437                "          to + being + bin - packed,\n"
6438                "      arg3);\n"
6439                "}",
6440                Style);
6441 }
6442 
6443 TEST_F(FormatTest, ConstructorInitializers) {
6444   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6445   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6446                getLLVMStyleWithColumns(45));
6447   verifyFormat("Constructor()\n"
6448                "    : Inttializer(FitsOnTheLine) {}",
6449                getLLVMStyleWithColumns(44));
6450   verifyFormat("Constructor()\n"
6451                "    : Inttializer(FitsOnTheLine) {}",
6452                getLLVMStyleWithColumns(43));
6453 
6454   verifyFormat("template <typename T>\n"
6455                "Constructor() : Initializer(FitsOnTheLine) {}",
6456                getLLVMStyleWithColumns(45));
6457 
6458   verifyFormat(
6459       "SomeClass::Constructor()\n"
6460       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6461 
6462   verifyFormat(
6463       "SomeClass::Constructor()\n"
6464       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6465       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6466   verifyFormat(
6467       "SomeClass::Constructor()\n"
6468       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6469       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6470   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6471                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6472                "    : aaaaaaaaaa(aaaaaa) {}");
6473 
6474   verifyFormat("Constructor()\n"
6475                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6476                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6477                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6478                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6479 
6480   verifyFormat("Constructor()\n"
6481                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6482                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6483 
6484   verifyFormat("Constructor(int Parameter = 0)\n"
6485                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6486                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6487   verifyFormat("Constructor()\n"
6488                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6489                "}",
6490                getLLVMStyleWithColumns(60));
6491   verifyFormat("Constructor()\n"
6492                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6493                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6494 
6495   // Here a line could be saved by splitting the second initializer onto two
6496   // lines, but that is not desirable.
6497   verifyFormat("Constructor()\n"
6498                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6499                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6500                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6501 
6502   FormatStyle OnePerLine = getLLVMStyle();
6503   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6504   verifyFormat("MyClass::MyClass()\n"
6505                "    : a(a),\n"
6506                "      b(b),\n"
6507                "      c(c) {}",
6508                OnePerLine);
6509   verifyFormat("MyClass::MyClass()\n"
6510                "    : a(a), // comment\n"
6511                "      b(b),\n"
6512                "      c(c) {}",
6513                OnePerLine);
6514   verifyFormat("MyClass::MyClass(int a)\n"
6515                "    : b(a),      // comment\n"
6516                "      c(a + 1) { // lined up\n"
6517                "}",
6518                OnePerLine);
6519   verifyFormat("Constructor()\n"
6520                "    : a(b, b, b) {}",
6521                OnePerLine);
6522   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6523   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6524   verifyFormat("SomeClass::Constructor()\n"
6525                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6526                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6527                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6528                OnePerLine);
6529   verifyFormat("SomeClass::Constructor()\n"
6530                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6531                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6532                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6533                OnePerLine);
6534   verifyFormat("MyClass::MyClass(int var)\n"
6535                "    : some_var_(var),            // 4 space indent\n"
6536                "      some_other_var_(var + 1) { // lined up\n"
6537                "}",
6538                OnePerLine);
6539   verifyFormat("Constructor()\n"
6540                "    : aaaaa(aaaaaa),\n"
6541                "      aaaaa(aaaaaa),\n"
6542                "      aaaaa(aaaaaa),\n"
6543                "      aaaaa(aaaaaa),\n"
6544                "      aaaaa(aaaaaa) {}",
6545                OnePerLine);
6546   verifyFormat("Constructor()\n"
6547                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6548                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6549                OnePerLine);
6550   OnePerLine.BinPackParameters = false;
6551   verifyFormat(
6552       "Constructor()\n"
6553       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6554       "          aaaaaaaaaaa().aaa(),\n"
6555       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6556       OnePerLine);
6557   OnePerLine.ColumnLimit = 60;
6558   verifyFormat("Constructor()\n"
6559                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6560                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6561                OnePerLine);
6562 
6563   EXPECT_EQ("Constructor()\n"
6564             "    : // Comment forcing unwanted break.\n"
6565             "      aaaa(aaaa) {}",
6566             format("Constructor() :\n"
6567                    "    // Comment forcing unwanted break.\n"
6568                    "    aaaa(aaaa) {}"));
6569 }
6570 
6571 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6572   FormatStyle Style = getLLVMStyleWithColumns(60);
6573   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6574   Style.BinPackParameters = false;
6575 
6576   for (int i = 0; i < 4; ++i) {
6577     // Test all combinations of parameters that should not have an effect.
6578     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6579     Style.AllowAllArgumentsOnNextLine = i & 2;
6580 
6581     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6582     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6583     verifyFormat("Constructor()\n"
6584                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6585                  Style);
6586     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6587 
6588     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6589     verifyFormat("Constructor()\n"
6590                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6591                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6592                  Style);
6593     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6594 
6595     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6596     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6597     verifyFormat("Constructor()\n"
6598                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6599                  Style);
6600 
6601     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6602     verifyFormat("Constructor()\n"
6603                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6604                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6605                  Style);
6606 
6607     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6608     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6609     verifyFormat("Constructor() :\n"
6610                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6611                  Style);
6612 
6613     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6614     verifyFormat("Constructor() :\n"
6615                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6616                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6617                  Style);
6618   }
6619 
6620   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6621   // AllowAllConstructorInitializersOnNextLine in all
6622   // BreakConstructorInitializers modes
6623   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6624   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6625   verifyFormat("SomeClassWithALongName::Constructor(\n"
6626                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6627                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6628                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6629                Style);
6630 
6631   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6632   verifyFormat("SomeClassWithALongName::Constructor(\n"
6633                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6634                "    int bbbbbbbbbbbbb,\n"
6635                "    int cccccccccccccccc)\n"
6636                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6637                Style);
6638 
6639   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6640   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6641   verifyFormat("SomeClassWithALongName::Constructor(\n"
6642                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6643                "    int bbbbbbbbbbbbb)\n"
6644                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6645                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6646                Style);
6647 
6648   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6649 
6650   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6651   verifyFormat("SomeClassWithALongName::Constructor(\n"
6652                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6653                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6654                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6655                Style);
6656 
6657   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6658   verifyFormat("SomeClassWithALongName::Constructor(\n"
6659                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6660                "    int bbbbbbbbbbbbb,\n"
6661                "    int cccccccccccccccc)\n"
6662                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6663                Style);
6664 
6665   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6666   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6667   verifyFormat("SomeClassWithALongName::Constructor(\n"
6668                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6669                "    int bbbbbbbbbbbbb)\n"
6670                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6671                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6672                Style);
6673 
6674   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6675   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6676   verifyFormat("SomeClassWithALongName::Constructor(\n"
6677                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6678                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6679                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6680                Style);
6681 
6682   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6683   verifyFormat("SomeClassWithALongName::Constructor(\n"
6684                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6685                "    int bbbbbbbbbbbbb,\n"
6686                "    int cccccccccccccccc) :\n"
6687                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6688                Style);
6689 
6690   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6691   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6692   verifyFormat("SomeClassWithALongName::Constructor(\n"
6693                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6694                "    int bbbbbbbbbbbbb) :\n"
6695                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6696                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6697                Style);
6698 }
6699 
6700 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6701   FormatStyle Style = getLLVMStyleWithColumns(60);
6702   Style.BinPackArguments = false;
6703   for (int i = 0; i < 4; ++i) {
6704     // Test all combinations of parameters that should not have an effect.
6705     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6706     Style.PackConstructorInitializers =
6707         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6708 
6709     Style.AllowAllArgumentsOnNextLine = true;
6710     verifyFormat("void foo() {\n"
6711                  "  FunctionCallWithReallyLongName(\n"
6712                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6713                  "}",
6714                  Style);
6715     Style.AllowAllArgumentsOnNextLine = false;
6716     verifyFormat("void foo() {\n"
6717                  "  FunctionCallWithReallyLongName(\n"
6718                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6719                  "      bbbbbbbbbbbb);\n"
6720                  "}",
6721                  Style);
6722 
6723     Style.AllowAllArgumentsOnNextLine = true;
6724     verifyFormat("void foo() {\n"
6725                  "  auto VariableWithReallyLongName = {\n"
6726                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6727                  "}",
6728                  Style);
6729     Style.AllowAllArgumentsOnNextLine = false;
6730     verifyFormat("void foo() {\n"
6731                  "  auto VariableWithReallyLongName = {\n"
6732                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6733                  "      bbbbbbbbbbbb};\n"
6734                  "}",
6735                  Style);
6736   }
6737 
6738   // This parameter should not affect declarations.
6739   Style.BinPackParameters = false;
6740   Style.AllowAllArgumentsOnNextLine = false;
6741   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6742   verifyFormat("void FunctionCallWithReallyLongName(\n"
6743                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6744                Style);
6745   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6746   verifyFormat("void FunctionCallWithReallyLongName(\n"
6747                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6748                "    int bbbbbbbbbbbb);",
6749                Style);
6750 }
6751 
6752 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6753   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6754   // and BAS_Align.
6755   FormatStyle Style = getLLVMStyleWithColumns(35);
6756   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6757                     "void functionDecl(int A, int B, int C);";
6758   Style.AllowAllArgumentsOnNextLine = false;
6759   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6760   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6761                       "    paramC);\n"
6762                       "void functionDecl(int A, int B,\n"
6763                       "    int C);"),
6764             format(Input, Style));
6765   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6766   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6767                       "             paramC);\n"
6768                       "void functionDecl(int A, int B,\n"
6769                       "                  int C);"),
6770             format(Input, Style));
6771   // However, BAS_AlwaysBreak should take precedence over
6772   // AllowAllArgumentsOnNextLine.
6773   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6774   EXPECT_EQ(StringRef("functionCall(\n"
6775                       "    paramA, paramB, paramC);\n"
6776                       "void functionDecl(\n"
6777                       "    int A, int B, int C);"),
6778             format(Input, Style));
6779 
6780   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6781   // first argument.
6782   Style.AllowAllArgumentsOnNextLine = true;
6783   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6784   EXPECT_EQ(StringRef("functionCall(\n"
6785                       "    paramA, paramB, paramC);\n"
6786                       "void functionDecl(\n"
6787                       "    int A, int B, int C);"),
6788             format(Input, Style));
6789   // It wouldn't fit on one line with aligned parameters so this setting
6790   // doesn't change anything for BAS_Align.
6791   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6792   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6793                       "             paramC);\n"
6794                       "void functionDecl(int A, int B,\n"
6795                       "                  int C);"),
6796             format(Input, Style));
6797   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6798   EXPECT_EQ(StringRef("functionCall(\n"
6799                       "    paramA, paramB, paramC);\n"
6800                       "void functionDecl(\n"
6801                       "    int A, int B, int C);"),
6802             format(Input, Style));
6803 }
6804 
6805 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6806   FormatStyle Style = getLLVMStyle();
6807   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6808 
6809   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6810   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6811                getStyleWithColumns(Style, 45));
6812   verifyFormat("Constructor() :\n"
6813                "    Initializer(FitsOnTheLine) {}",
6814                getStyleWithColumns(Style, 44));
6815   verifyFormat("Constructor() :\n"
6816                "    Initializer(FitsOnTheLine) {}",
6817                getStyleWithColumns(Style, 43));
6818 
6819   verifyFormat("template <typename T>\n"
6820                "Constructor() : Initializer(FitsOnTheLine) {}",
6821                getStyleWithColumns(Style, 50));
6822   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6823   verifyFormat(
6824       "SomeClass::Constructor() :\n"
6825       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6826       Style);
6827 
6828   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6829   verifyFormat(
6830       "SomeClass::Constructor() :\n"
6831       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6832       Style);
6833 
6834   verifyFormat(
6835       "SomeClass::Constructor() :\n"
6836       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6837       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6838       Style);
6839   verifyFormat(
6840       "SomeClass::Constructor() :\n"
6841       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6842       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6843       Style);
6844   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6845                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6846                "    aaaaaaaaaa(aaaaaa) {}",
6847                Style);
6848 
6849   verifyFormat("Constructor() :\n"
6850                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6851                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6852                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6853                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
6854                Style);
6855 
6856   verifyFormat("Constructor() :\n"
6857                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6858                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6859                Style);
6860 
6861   verifyFormat("Constructor(int Parameter = 0) :\n"
6862                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6863                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
6864                Style);
6865   verifyFormat("Constructor() :\n"
6866                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6867                "}",
6868                getStyleWithColumns(Style, 60));
6869   verifyFormat("Constructor() :\n"
6870                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6871                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
6872                Style);
6873 
6874   // Here a line could be saved by splitting the second initializer onto two
6875   // lines, but that is not desirable.
6876   verifyFormat("Constructor() :\n"
6877                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6878                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
6879                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6880                Style);
6881 
6882   FormatStyle OnePerLine = Style;
6883   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6884   verifyFormat("SomeClass::Constructor() :\n"
6885                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6886                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6887                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6888                OnePerLine);
6889   verifyFormat("SomeClass::Constructor() :\n"
6890                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6891                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6892                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6893                OnePerLine);
6894   verifyFormat("MyClass::MyClass(int var) :\n"
6895                "    some_var_(var),            // 4 space indent\n"
6896                "    some_other_var_(var + 1) { // lined up\n"
6897                "}",
6898                OnePerLine);
6899   verifyFormat("Constructor() :\n"
6900                "    aaaaa(aaaaaa),\n"
6901                "    aaaaa(aaaaaa),\n"
6902                "    aaaaa(aaaaaa),\n"
6903                "    aaaaa(aaaaaa),\n"
6904                "    aaaaa(aaaaaa) {}",
6905                OnePerLine);
6906   verifyFormat("Constructor() :\n"
6907                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6908                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
6909                OnePerLine);
6910   OnePerLine.BinPackParameters = false;
6911   verifyFormat("Constructor() :\n"
6912                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6913                "        aaaaaaaaaaa().aaa(),\n"
6914                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6915                OnePerLine);
6916   OnePerLine.ColumnLimit = 60;
6917   verifyFormat("Constructor() :\n"
6918                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6919                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6920                OnePerLine);
6921 
6922   EXPECT_EQ("Constructor() :\n"
6923             "    // Comment forcing unwanted break.\n"
6924             "    aaaa(aaaa) {}",
6925             format("Constructor() :\n"
6926                    "    // Comment forcing unwanted break.\n"
6927                    "    aaaa(aaaa) {}",
6928                    Style));
6929 
6930   Style.ColumnLimit = 0;
6931   verifyFormat("SomeClass::Constructor() :\n"
6932                "    a(a) {}",
6933                Style);
6934   verifyFormat("SomeClass::Constructor() noexcept :\n"
6935                "    a(a) {}",
6936                Style);
6937   verifyFormat("SomeClass::Constructor() :\n"
6938                "    a(a), b(b), c(c) {}",
6939                Style);
6940   verifyFormat("SomeClass::Constructor() :\n"
6941                "    a(a) {\n"
6942                "  foo();\n"
6943                "  bar();\n"
6944                "}",
6945                Style);
6946 
6947   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6948   verifyFormat("SomeClass::Constructor() :\n"
6949                "    a(a), b(b), c(c) {\n"
6950                "}",
6951                Style);
6952   verifyFormat("SomeClass::Constructor() :\n"
6953                "    a(a) {\n"
6954                "}",
6955                Style);
6956 
6957   Style.ColumnLimit = 80;
6958   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
6959   Style.ConstructorInitializerIndentWidth = 2;
6960   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
6961   verifyFormat("SomeClass::Constructor() :\n"
6962                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6963                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
6964                Style);
6965 
6966   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
6967   // well
6968   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
6969   verifyFormat(
6970       "class SomeClass\n"
6971       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6972       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6973       Style);
6974   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
6975   verifyFormat(
6976       "class SomeClass\n"
6977       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6978       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6979       Style);
6980   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
6981   verifyFormat(
6982       "class SomeClass :\n"
6983       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6984       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6985       Style);
6986   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
6987   verifyFormat(
6988       "class SomeClass\n"
6989       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6990       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6991       Style);
6992 }
6993 
6994 #ifndef EXPENSIVE_CHECKS
6995 // Expensive checks enables libstdc++ checking which includes validating the
6996 // state of ranges used in std::priority_queue - this blows out the
6997 // runtime/scalability of the function and makes this test unacceptably slow.
6998 TEST_F(FormatTest, MemoizationTests) {
6999   // This breaks if the memoization lookup does not take \c Indent and
7000   // \c LastSpace into account.
7001   verifyFormat(
7002       "extern CFRunLoopTimerRef\n"
7003       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
7004       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
7005       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
7006       "                     CFRunLoopTimerContext *context) {}");
7007 
7008   // Deep nesting somewhat works around our memoization.
7009   verifyFormat(
7010       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7011       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7012       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7013       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7014       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
7015       getLLVMStyleWithColumns(65));
7016   verifyFormat(
7017       "aaaaa(\n"
7018       "    aaaaa,\n"
7019       "    aaaaa(\n"
7020       "        aaaaa,\n"
7021       "        aaaaa(\n"
7022       "            aaaaa,\n"
7023       "            aaaaa(\n"
7024       "                aaaaa,\n"
7025       "                aaaaa(\n"
7026       "                    aaaaa,\n"
7027       "                    aaaaa(\n"
7028       "                        aaaaa,\n"
7029       "                        aaaaa(\n"
7030       "                            aaaaa,\n"
7031       "                            aaaaa(\n"
7032       "                                aaaaa,\n"
7033       "                                aaaaa(\n"
7034       "                                    aaaaa,\n"
7035       "                                    aaaaa(\n"
7036       "                                        aaaaa,\n"
7037       "                                        aaaaa(\n"
7038       "                                            aaaaa,\n"
7039       "                                            aaaaa(\n"
7040       "                                                aaaaa,\n"
7041       "                                                aaaaa))))))))))));",
7042       getLLVMStyleWithColumns(65));
7043   verifyFormat(
7044       "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n"
7045       "                                  a),\n"
7046       "                                a),\n"
7047       "                              a),\n"
7048       "                            a),\n"
7049       "                          a),\n"
7050       "                        a),\n"
7051       "                      a),\n"
7052       "                    a),\n"
7053       "                  a),\n"
7054       "                a),\n"
7055       "              a),\n"
7056       "            a),\n"
7057       "          a),\n"
7058       "        a),\n"
7059       "      a),\n"
7060       "    a),\n"
7061       "  a)",
7062       getLLVMStyleWithColumns(65));
7063 
7064   // This test takes VERY long when memoization is broken.
7065   FormatStyle OnePerLine = getLLVMStyle();
7066   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
7067   OnePerLine.BinPackParameters = false;
7068   std::string input = "Constructor()\n"
7069                       "    : aaaa(a,\n";
7070   for (unsigned i = 0, e = 80; i != e; ++i) {
7071     input += "           a,\n";
7072   }
7073   input += "           a) {}";
7074   verifyFormat(input, OnePerLine);
7075 }
7076 #endif
7077 
7078 TEST_F(FormatTest, BreaksAsHighAsPossible) {
7079   verifyFormat(
7080       "void f() {\n"
7081       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
7082       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
7083       "    f();\n"
7084       "}");
7085   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
7086                "    Intervals[i - 1].getRange().getLast()) {\n}");
7087 }
7088 
7089 TEST_F(FormatTest, BreaksFunctionDeclarations) {
7090   // Principially, we break function declarations in a certain order:
7091   // 1) break amongst arguments.
7092   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
7093                "                              Cccccccccccccc cccccccccccccc);");
7094   verifyFormat("template <class TemplateIt>\n"
7095                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
7096                "                            TemplateIt *stop) {}");
7097 
7098   // 2) break after return type.
7099   verifyFormat(
7100       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7101       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
7102       getGoogleStyle());
7103 
7104   // 3) break after (.
7105   verifyFormat(
7106       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
7107       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
7108       getGoogleStyle());
7109 
7110   // 4) break before after nested name specifiers.
7111   verifyFormat(
7112       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7113       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
7114       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
7115       getGoogleStyle());
7116 
7117   // However, there are exceptions, if a sufficient amount of lines can be
7118   // saved.
7119   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
7120   // more adjusting.
7121   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7122                "                                  Cccccccccccccc cccccccccc,\n"
7123                "                                  Cccccccccccccc cccccccccc,\n"
7124                "                                  Cccccccccccccc cccccccccc,\n"
7125                "                                  Cccccccccccccc cccccccccc);");
7126   verifyFormat(
7127       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7128       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7129       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7130       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
7131       getGoogleStyle());
7132   verifyFormat(
7133       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7134       "                                          Cccccccccccccc cccccccccc,\n"
7135       "                                          Cccccccccccccc cccccccccc,\n"
7136       "                                          Cccccccccccccc cccccccccc,\n"
7137       "                                          Cccccccccccccc cccccccccc,\n"
7138       "                                          Cccccccccccccc cccccccccc,\n"
7139       "                                          Cccccccccccccc cccccccccc);");
7140   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7141                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7142                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7143                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7144                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
7145 
7146   // Break after multi-line parameters.
7147   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7148                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7149                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7150                "    bbbb bbbb);");
7151   verifyFormat("void SomeLoooooooooooongFunction(\n"
7152                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
7153                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7154                "    int bbbbbbbbbbbbb);");
7155 
7156   // Treat overloaded operators like other functions.
7157   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7158                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
7159   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7160                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
7161   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7162                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
7163   verifyGoogleFormat(
7164       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
7165       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7166   verifyGoogleFormat(
7167       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
7168       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7169   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7170                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7171   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
7172                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7173   verifyGoogleFormat(
7174       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
7175       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7176       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
7177   verifyGoogleFormat("template <typename T>\n"
7178                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7179                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
7180                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
7181 
7182   FormatStyle Style = getLLVMStyle();
7183   Style.PointerAlignment = FormatStyle::PAS_Left;
7184   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7185                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
7186                Style);
7187   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
7188                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7189                Style);
7190 }
7191 
7192 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
7193   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
7194   // Prefer keeping `::` followed by `operator` together.
7195   EXPECT_EQ("const aaaa::bbbbbbb &\n"
7196             "ccccccccc::operator++() {\n"
7197             "  stuff();\n"
7198             "}",
7199             format("const aaaa::bbbbbbb\n"
7200                    "&ccccccccc::operator++() { stuff(); }",
7201                    getLLVMStyleWithColumns(40)));
7202 }
7203 
7204 TEST_F(FormatTest, TrailingReturnType) {
7205   verifyFormat("auto foo() -> int;\n");
7206   // correct trailing return type spacing
7207   verifyFormat("auto operator->() -> int;\n");
7208   verifyFormat("auto operator++(int) -> int;\n");
7209 
7210   verifyFormat("struct S {\n"
7211                "  auto bar() const -> int;\n"
7212                "};");
7213   verifyFormat("template <size_t Order, typename T>\n"
7214                "auto load_img(const std::string &filename)\n"
7215                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
7216   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
7217                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
7218   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
7219   verifyFormat("template <typename T>\n"
7220                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
7221                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
7222 
7223   // Not trailing return types.
7224   verifyFormat("void f() { auto a = b->c(); }");
7225   verifyFormat("auto a = p->foo();");
7226   verifyFormat("int a = p->foo();");
7227   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
7228 }
7229 
7230 TEST_F(FormatTest, DeductionGuides) {
7231   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
7232   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
7233   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
7234   verifyFormat(
7235       "template <class... T>\n"
7236       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
7237   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
7238   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
7239   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
7240   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
7241   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
7242   verifyFormat("template <class T> x() -> x<1>;");
7243   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
7244 
7245   // Ensure not deduction guides.
7246   verifyFormat("c()->f<int>();");
7247   verifyFormat("x()->foo<1>;");
7248   verifyFormat("x = p->foo<3>();");
7249   verifyFormat("x()->x<1>();");
7250   verifyFormat("x()->x<1>;");
7251 }
7252 
7253 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
7254   // Avoid breaking before trailing 'const' or other trailing annotations, if
7255   // they are not function-like.
7256   FormatStyle Style = getGoogleStyleWithColumns(47);
7257   verifyFormat("void someLongFunction(\n"
7258                "    int someLoooooooooooooongParameter) const {\n}",
7259                getLLVMStyleWithColumns(47));
7260   verifyFormat("LoooooongReturnType\n"
7261                "someLoooooooongFunction() const {}",
7262                getLLVMStyleWithColumns(47));
7263   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
7264                "    const {}",
7265                Style);
7266   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7267                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
7268   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7269                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
7270   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7271                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
7272   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
7273                "                   aaaaaaaaaaa aaaaa) const override;");
7274   verifyGoogleFormat(
7275       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7276       "    const override;");
7277 
7278   // Even if the first parameter has to be wrapped.
7279   verifyFormat("void someLongFunction(\n"
7280                "    int someLongParameter) const {}",
7281                getLLVMStyleWithColumns(46));
7282   verifyFormat("void someLongFunction(\n"
7283                "    int someLongParameter) const {}",
7284                Style);
7285   verifyFormat("void someLongFunction(\n"
7286                "    int someLongParameter) override {}",
7287                Style);
7288   verifyFormat("void someLongFunction(\n"
7289                "    int someLongParameter) OVERRIDE {}",
7290                Style);
7291   verifyFormat("void someLongFunction(\n"
7292                "    int someLongParameter) final {}",
7293                Style);
7294   verifyFormat("void someLongFunction(\n"
7295                "    int someLongParameter) FINAL {}",
7296                Style);
7297   verifyFormat("void someLongFunction(\n"
7298                "    int parameter) const override {}",
7299                Style);
7300 
7301   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
7302   verifyFormat("void someLongFunction(\n"
7303                "    int someLongParameter) const\n"
7304                "{\n"
7305                "}",
7306                Style);
7307 
7308   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
7309   verifyFormat("void someLongFunction(\n"
7310                "    int someLongParameter) const\n"
7311                "  {\n"
7312                "  }",
7313                Style);
7314 
7315   // Unless these are unknown annotations.
7316   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
7317                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7318                "    LONG_AND_UGLY_ANNOTATION;");
7319 
7320   // Breaking before function-like trailing annotations is fine to keep them
7321   // close to their arguments.
7322   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7323                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7324   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7325                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7326   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7327                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
7328   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
7329                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
7330   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
7331 
7332   verifyFormat(
7333       "void aaaaaaaaaaaaaaaaaa()\n"
7334       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
7335       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
7336   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7337                "    __attribute__((unused));");
7338   verifyGoogleFormat(
7339       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7340       "    GUARDED_BY(aaaaaaaaaaaa);");
7341   verifyGoogleFormat(
7342       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7343       "    GUARDED_BY(aaaaaaaaaaaa);");
7344   verifyGoogleFormat(
7345       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7346       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7347   verifyGoogleFormat(
7348       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7349       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
7350 }
7351 
7352 TEST_F(FormatTest, FunctionAnnotations) {
7353   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7354                "int OldFunction(const string &parameter) {}");
7355   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7356                "string OldFunction(const string &parameter) {}");
7357   verifyFormat("template <typename T>\n"
7358                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7359                "string OldFunction(const string &parameter) {}");
7360 
7361   // Not function annotations.
7362   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7363                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
7364   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
7365                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
7366   verifyFormat("MACRO(abc).function() // wrap\n"
7367                "    << abc;");
7368   verifyFormat("MACRO(abc)->function() // wrap\n"
7369                "    << abc;");
7370   verifyFormat("MACRO(abc)::function() // wrap\n"
7371                "    << abc;");
7372 }
7373 
7374 TEST_F(FormatTest, BreaksDesireably) {
7375   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7376                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7377                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
7378   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7379                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
7380                "}");
7381 
7382   verifyFormat(
7383       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7384       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7385 
7386   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7387                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7388                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7389 
7390   verifyFormat(
7391       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7392       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7393       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7394       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7395       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7396 
7397   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7398                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7399 
7400   verifyFormat(
7401       "void f() {\n"
7402       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7403       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7404       "}");
7405   verifyFormat(
7406       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7407       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7408   verifyFormat(
7409       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7410       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7411   verifyFormat(
7412       "aaaaaa(aaa,\n"
7413       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7414       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7415       "       aaaa);");
7416   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7417                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7418                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7419 
7420   // Indent consistently independent of call expression and unary operator.
7421   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7422                "    dddddddddddddddddddddddddddddd));");
7423   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7424                "    dddddddddddddddddddddddddddddd));");
7425   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7426                "    dddddddddddddddddddddddddddddd));");
7427 
7428   // This test case breaks on an incorrect memoization, i.e. an optimization not
7429   // taking into account the StopAt value.
7430   verifyFormat(
7431       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7432       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7433       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7434       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7435 
7436   verifyFormat("{\n  {\n    {\n"
7437                "      Annotation.SpaceRequiredBefore =\n"
7438                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7439                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7440                "    }\n  }\n}");
7441 
7442   // Break on an outer level if there was a break on an inner level.
7443   EXPECT_EQ("f(g(h(a, // comment\n"
7444             "      b, c),\n"
7445             "    d, e),\n"
7446             "  x, y);",
7447             format("f(g(h(a, // comment\n"
7448                    "    b, c), d, e), x, y);"));
7449 
7450   // Prefer breaking similar line breaks.
7451   verifyFormat(
7452       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7453       "                             NSTrackingMouseEnteredAndExited |\n"
7454       "                             NSTrackingActiveAlways;");
7455 }
7456 
7457 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7458   FormatStyle NoBinPacking = getGoogleStyle();
7459   NoBinPacking.BinPackParameters = false;
7460   NoBinPacking.BinPackArguments = true;
7461   verifyFormat("void f() {\n"
7462                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7463                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7464                "}",
7465                NoBinPacking);
7466   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7467                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7468                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7469                NoBinPacking);
7470 
7471   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7472   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7473                "                        vector<int> bbbbbbbbbbbbbbb);",
7474                NoBinPacking);
7475   // FIXME: This behavior difference is probably not wanted. However, currently
7476   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7477   // template arguments from BreakBeforeParameter being set because of the
7478   // one-per-line formatting.
7479   verifyFormat(
7480       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7481       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7482       NoBinPacking);
7483   verifyFormat(
7484       "void fffffffffff(\n"
7485       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7486       "        aaaaaaaaaa);");
7487 }
7488 
7489 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7490   FormatStyle NoBinPacking = getGoogleStyle();
7491   NoBinPacking.BinPackParameters = false;
7492   NoBinPacking.BinPackArguments = false;
7493   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7494                "  aaaaaaaaaaaaaaaaaaaa,\n"
7495                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7496                NoBinPacking);
7497   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7498                "        aaaaaaaaaaaaa,\n"
7499                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7500                NoBinPacking);
7501   verifyFormat(
7502       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7503       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7504       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7505       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7506       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7507       NoBinPacking);
7508   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7509                "    .aaaaaaaaaaaaaaaaaa();",
7510                NoBinPacking);
7511   verifyFormat("void f() {\n"
7512                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7513                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7514                "}",
7515                NoBinPacking);
7516 
7517   verifyFormat(
7518       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7519       "             aaaaaaaaaaaa,\n"
7520       "             aaaaaaaaaaaa);",
7521       NoBinPacking);
7522   verifyFormat(
7523       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7524       "                               ddddddddddddddddddddddddddddd),\n"
7525       "             test);",
7526       NoBinPacking);
7527 
7528   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7529                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7530                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7531                "    aaaaaaaaaaaaaaaaaa;",
7532                NoBinPacking);
7533   verifyFormat("a(\"a\"\n"
7534                "  \"a\",\n"
7535                "  a);");
7536 
7537   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7538   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7539                "                aaaaaaaaa,\n"
7540                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7541                NoBinPacking);
7542   verifyFormat(
7543       "void f() {\n"
7544       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7545       "      .aaaaaaa();\n"
7546       "}",
7547       NoBinPacking);
7548   verifyFormat(
7549       "template <class SomeType, class SomeOtherType>\n"
7550       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7551       NoBinPacking);
7552 }
7553 
7554 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7555   FormatStyle Style = getLLVMStyleWithColumns(15);
7556   Style.ExperimentalAutoDetectBinPacking = true;
7557   EXPECT_EQ("aaa(aaaa,\n"
7558             "    aaaa,\n"
7559             "    aaaa);\n"
7560             "aaa(aaaa,\n"
7561             "    aaaa,\n"
7562             "    aaaa);",
7563             format("aaa(aaaa,\n" // one-per-line
7564                    "  aaaa,\n"
7565                    "    aaaa  );\n"
7566                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7567                    Style));
7568   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7569             "    aaaa);\n"
7570             "aaa(aaaa, aaaa,\n"
7571             "    aaaa);",
7572             format("aaa(aaaa,  aaaa,\n" // bin-packed
7573                    "    aaaa  );\n"
7574                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7575                    Style));
7576 }
7577 
7578 TEST_F(FormatTest, FormatsBuilderPattern) {
7579   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7580                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7581                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7582                "    .StartsWith(\".init\", ORDER_INIT)\n"
7583                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7584                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7585                "    .Default(ORDER_TEXT);\n");
7586 
7587   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7588                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7589   verifyFormat("aaaaaaa->aaaaaaa\n"
7590                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7591                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7592                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7593   verifyFormat(
7594       "aaaaaaa->aaaaaaa\n"
7595       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7596       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7597   verifyFormat(
7598       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7599       "    aaaaaaaaaaaaaa);");
7600   verifyFormat(
7601       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7602       "    aaaaaa->aaaaaaaaaaaa()\n"
7603       "        ->aaaaaaaaaaaaaaaa(\n"
7604       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7605       "        ->aaaaaaaaaaaaaaaaa();");
7606   verifyGoogleFormat(
7607       "void f() {\n"
7608       "  someo->Add((new util::filetools::Handler(dir))\n"
7609       "                 ->OnEvent1(NewPermanentCallback(\n"
7610       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7611       "                 ->OnEvent2(NewPermanentCallback(\n"
7612       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7613       "                 ->OnEvent3(NewPermanentCallback(\n"
7614       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7615       "                 ->OnEvent5(NewPermanentCallback(\n"
7616       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7617       "                 ->OnEvent6(NewPermanentCallback(\n"
7618       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7619       "}");
7620 
7621   verifyFormat(
7622       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7623   verifyFormat("aaaaaaaaaaaaaaa()\n"
7624                "    .aaaaaaaaaaaaaaa()\n"
7625                "    .aaaaaaaaaaaaaaa()\n"
7626                "    .aaaaaaaaaaaaaaa()\n"
7627                "    .aaaaaaaaaaaaaaa();");
7628   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7629                "    .aaaaaaaaaaaaaaa()\n"
7630                "    .aaaaaaaaaaaaaaa()\n"
7631                "    .aaaaaaaaaaaaaaa();");
7632   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7633                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7634                "    .aaaaaaaaaaaaaaa();");
7635   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7636                "    ->aaaaaaaaaaaaaae(0)\n"
7637                "    ->aaaaaaaaaaaaaaa();");
7638 
7639   // Don't linewrap after very short segments.
7640   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7641                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7642                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7643   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7644                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7645                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7646   verifyFormat("aaa()\n"
7647                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7648                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7649                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7650 
7651   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7652                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7653                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7654   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7655                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7656                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7657 
7658   // Prefer not to break after empty parentheses.
7659   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7660                "    First->LastNewlineOffset);");
7661 
7662   // Prefer not to create "hanging" indents.
7663   verifyFormat(
7664       "return !soooooooooooooome_map\n"
7665       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7666       "            .second;");
7667   verifyFormat(
7668       "return aaaaaaaaaaaaaaaa\n"
7669       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7670       "    .aaaa(aaaaaaaaaaaaaa);");
7671   // No hanging indent here.
7672   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7673                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7674   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7675                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7676   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7677                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7678                getLLVMStyleWithColumns(60));
7679   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7680                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7681                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7682                getLLVMStyleWithColumns(59));
7683   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7684                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7685                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7686 
7687   // Dont break if only closing statements before member call
7688   verifyFormat("test() {\n"
7689                "  ([]() -> {\n"
7690                "    int b = 32;\n"
7691                "    return 3;\n"
7692                "  }).foo();\n"
7693                "}");
7694   verifyFormat("test() {\n"
7695                "  (\n"
7696                "      []() -> {\n"
7697                "        int b = 32;\n"
7698                "        return 3;\n"
7699                "      },\n"
7700                "      foo, bar)\n"
7701                "      .foo();\n"
7702                "}");
7703   verifyFormat("test() {\n"
7704                "  ([]() -> {\n"
7705                "    int b = 32;\n"
7706                "    return 3;\n"
7707                "  })\n"
7708                "      .foo()\n"
7709                "      .bar();\n"
7710                "}");
7711   verifyFormat("test() {\n"
7712                "  ([]() -> {\n"
7713                "    int b = 32;\n"
7714                "    return 3;\n"
7715                "  })\n"
7716                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7717                "           \"bbbb\");\n"
7718                "}",
7719                getLLVMStyleWithColumns(30));
7720 }
7721 
7722 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7723   verifyFormat(
7724       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7725       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7726   verifyFormat(
7727       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7728       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7729 
7730   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7731                "    ccccccccccccccccccccccccc) {\n}");
7732   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7733                "    ccccccccccccccccccccccccc) {\n}");
7734 
7735   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7736                "    ccccccccccccccccccccccccc) {\n}");
7737   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7738                "    ccccccccccccccccccccccccc) {\n}");
7739 
7740   verifyFormat(
7741       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7742       "    ccccccccccccccccccccccccc) {\n}");
7743   verifyFormat(
7744       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7745       "    ccccccccccccccccccccccccc) {\n}");
7746 
7747   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7748                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7749                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7750                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7751   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7752                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7753                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7754                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7755 
7756   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7757                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7758                "    aaaaaaaaaaaaaaa != aa) {\n}");
7759   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7760                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7761                "    aaaaaaaaaaaaaaa != aa) {\n}");
7762 }
7763 
7764 TEST_F(FormatTest, BreaksAfterAssignments) {
7765   verifyFormat(
7766       "unsigned Cost =\n"
7767       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7768       "                        SI->getPointerAddressSpaceee());\n");
7769   verifyFormat(
7770       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7771       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7772 
7773   verifyFormat(
7774       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7775       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7776   verifyFormat("unsigned OriginalStartColumn =\n"
7777                "    SourceMgr.getSpellingColumnNumber(\n"
7778                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7779                "    1;");
7780 }
7781 
7782 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7783   FormatStyle Style = getLLVMStyle();
7784   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7785                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7786                Style);
7787 
7788   Style.PenaltyBreakAssignment = 20;
7789   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7790                "                                 cccccccccccccccccccccccccc;",
7791                Style);
7792 }
7793 
7794 TEST_F(FormatTest, AlignsAfterAssignments) {
7795   verifyFormat(
7796       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7797       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7798   verifyFormat(
7799       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7800       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7801   verifyFormat(
7802       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7803       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7804   verifyFormat(
7805       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7806       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7807   verifyFormat(
7808       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7809       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7810       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7811 }
7812 
7813 TEST_F(FormatTest, AlignsAfterReturn) {
7814   verifyFormat(
7815       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7816       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7817   verifyFormat(
7818       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7819       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7820   verifyFormat(
7821       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7822       "       aaaaaaaaaaaaaaaaaaaaaa();");
7823   verifyFormat(
7824       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7825       "        aaaaaaaaaaaaaaaaaaaaaa());");
7826   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7827                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7828   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7829                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7830                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7831   verifyFormat("return\n"
7832                "    // true if code is one of a or b.\n"
7833                "    code == a || code == b;");
7834 }
7835 
7836 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7837   verifyFormat(
7838       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7839       "                                                aaaaaaaaa aaaaaaa) {}");
7840   verifyFormat(
7841       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7842       "                                               aaaaaaaaaaa aaaaaaaaa);");
7843   verifyFormat(
7844       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7845       "                                             aaaaaaaaaaaaaaaaaaaaa));");
7846   FormatStyle Style = getLLVMStyle();
7847   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7848   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7849                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
7850                Style);
7851   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7852                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
7853                Style);
7854   verifyFormat("SomeLongVariableName->someFunction(\n"
7855                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
7856                Style);
7857   verifyFormat(
7858       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7859       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7860       Style);
7861   verifyFormat(
7862       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7863       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7864       Style);
7865   verifyFormat(
7866       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7867       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7868       Style);
7869 
7870   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
7871                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
7872                "        b));",
7873                Style);
7874 
7875   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7876   Style.BinPackArguments = false;
7877   Style.BinPackParameters = false;
7878   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7879                "    aaaaaaaaaaa aaaaaaaa,\n"
7880                "    aaaaaaaaa aaaaaaa,\n"
7881                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7882                Style);
7883   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7884                "    aaaaaaaaaaa aaaaaaaaa,\n"
7885                "    aaaaaaaaaaa aaaaaaaaa,\n"
7886                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7887                Style);
7888   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
7889                "    aaaaaaaaaaaaaaa,\n"
7890                "    aaaaaaaaaaaaaaaaaaaaa,\n"
7891                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7892                Style);
7893   verifyFormat(
7894       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
7895       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7896       Style);
7897   verifyFormat(
7898       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
7899       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7900       Style);
7901   verifyFormat(
7902       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7903       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7904       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
7905       "    aaaaaaaaaaaaaaaa);",
7906       Style);
7907   verifyFormat(
7908       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7909       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7910       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
7911       "    aaaaaaaaaaaaaaaa);",
7912       Style);
7913 }
7914 
7915 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
7916   FormatStyle Style = getLLVMStyleWithColumns(40);
7917   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7918                "          bbbbbbbbbbbbbbbbbbbbbb);",
7919                Style);
7920   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7921   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7922   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7923                "          bbbbbbbbbbbbbbbbbbbbbb);",
7924                Style);
7925   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7926   Style.AlignOperands = FormatStyle::OAS_Align;
7927   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7928                "          bbbbbbbbbbbbbbbbbbbbbb);",
7929                Style);
7930   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7931   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7932   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7933                "    bbbbbbbbbbbbbbbbbbbbbb);",
7934                Style);
7935 }
7936 
7937 TEST_F(FormatTest, BreaksConditionalExpressions) {
7938   verifyFormat(
7939       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7940       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7941       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7942   verifyFormat(
7943       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7944       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7945       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7946   verifyFormat(
7947       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7948       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7949   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
7950                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7951                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7952   verifyFormat(
7953       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
7954       "                                                    : aaaaaaaaaaaaa);");
7955   verifyFormat(
7956       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7957       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7958       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7959       "                   aaaaaaaaaaaaa);");
7960   verifyFormat(
7961       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7962       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7963       "                   aaaaaaaaaaaaa);");
7964   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7965                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7966                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7967                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7968                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7969   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7970                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7971                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7972                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7973                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7974                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7975                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7976   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7977                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7978                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7979                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7980                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7981   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7982                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7983                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7984   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7985                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7986                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7987                "        : aaaaaaaaaaaaaaaa;");
7988   verifyFormat(
7989       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7990       "    ? aaaaaaaaaaaaaaa\n"
7991       "    : aaaaaaaaaaaaaaa;");
7992   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7993                "          aaaaaaaaa\n"
7994                "      ? b\n"
7995                "      : c);");
7996   verifyFormat("return aaaa == bbbb\n"
7997                "           // comment\n"
7998                "           ? aaaa\n"
7999                "           : bbbb;");
8000   verifyFormat("unsigned Indent =\n"
8001                "    format(TheLine.First,\n"
8002                "           IndentForLevel[TheLine.Level] >= 0\n"
8003                "               ? IndentForLevel[TheLine.Level]\n"
8004                "               : TheLine * 2,\n"
8005                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8006                getLLVMStyleWithColumns(60));
8007   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8008                "                  ? aaaaaaaaaaaaaaa\n"
8009                "                  : bbbbbbbbbbbbbbb //\n"
8010                "                        ? ccccccccccccccc\n"
8011                "                        : ddddddddddddddd;");
8012   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8013                "                  ? aaaaaaaaaaaaaaa\n"
8014                "                  : (bbbbbbbbbbbbbbb //\n"
8015                "                         ? ccccccccccccccc\n"
8016                "                         : ddddddddddddddd);");
8017   verifyFormat(
8018       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8019       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8020       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
8021       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
8022       "                                      : aaaaaaaaaa;");
8023   verifyFormat(
8024       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8025       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
8026       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8027 
8028   FormatStyle NoBinPacking = getLLVMStyle();
8029   NoBinPacking.BinPackArguments = false;
8030   verifyFormat(
8031       "void f() {\n"
8032       "  g(aaa,\n"
8033       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8034       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8035       "        ? aaaaaaaaaaaaaaa\n"
8036       "        : aaaaaaaaaaaaaaa);\n"
8037       "}",
8038       NoBinPacking);
8039   verifyFormat(
8040       "void f() {\n"
8041       "  g(aaa,\n"
8042       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8043       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8044       "        ?: aaaaaaaaaaaaaaa);\n"
8045       "}",
8046       NoBinPacking);
8047 
8048   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
8049                "             // comment.\n"
8050                "             ccccccccccccccccccccccccccccccccccccccc\n"
8051                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8052                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
8053 
8054   // Assignments in conditional expressions. Apparently not uncommon :-(.
8055   verifyFormat("return a != b\n"
8056                "           // comment\n"
8057                "           ? a = b\n"
8058                "           : a = b;");
8059   verifyFormat("return a != b\n"
8060                "           // comment\n"
8061                "           ? a = a != b\n"
8062                "                     // comment\n"
8063                "                     ? a = b\n"
8064                "                     : a\n"
8065                "           : a;\n");
8066   verifyFormat("return a != b\n"
8067                "           // comment\n"
8068                "           ? a\n"
8069                "           : a = a != b\n"
8070                "                     // comment\n"
8071                "                     ? a = b\n"
8072                "                     : a;");
8073 
8074   // Chained conditionals
8075   FormatStyle Style = getLLVMStyleWithColumns(70);
8076   Style.AlignOperands = FormatStyle::OAS_Align;
8077   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8078                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8079                "                        : 3333333333333333;",
8080                Style);
8081   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8082                "       : bbbbbbbbbb     ? 2222222222222222\n"
8083                "                        : 3333333333333333;",
8084                Style);
8085   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
8086                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
8087                "                          : 3333333333333333;",
8088                Style);
8089   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8090                "       : bbbbbbbbbbbbbb ? 222222\n"
8091                "                        : 333333;",
8092                Style);
8093   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8094                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8095                "       : cccccccccccccc ? 3333333333333333\n"
8096                "                        : 4444444444444444;",
8097                Style);
8098   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
8099                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8100                "                        : 3333333333333333;",
8101                Style);
8102   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8103                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8104                "                        : (aaa ? bbb : ccc);",
8105                Style);
8106   verifyFormat(
8107       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8108       "                                             : cccccccccccccccccc)\n"
8109       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8110       "                        : 3333333333333333;",
8111       Style);
8112   verifyFormat(
8113       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8114       "                                             : cccccccccccccccccc)\n"
8115       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8116       "                        : 3333333333333333;",
8117       Style);
8118   verifyFormat(
8119       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8120       "                                             : dddddddddddddddddd)\n"
8121       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8122       "                        : 3333333333333333;",
8123       Style);
8124   verifyFormat(
8125       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8126       "                                             : dddddddddddddddddd)\n"
8127       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8128       "                        : 3333333333333333;",
8129       Style);
8130   verifyFormat(
8131       "return aaaaaaaaa        ? 1111111111111111\n"
8132       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8133       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8134       "                                             : dddddddddddddddddd)\n",
8135       Style);
8136   verifyFormat(
8137       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8138       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8139       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8140       "                                             : cccccccccccccccccc);",
8141       Style);
8142   verifyFormat(
8143       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8144       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8145       "                                             : eeeeeeeeeeeeeeeeee)\n"
8146       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8147       "                        : 3333333333333333;",
8148       Style);
8149   verifyFormat(
8150       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
8151       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8152       "                                             : eeeeeeeeeeeeeeeeee)\n"
8153       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8154       "                        : 3333333333333333;",
8155       Style);
8156   verifyFormat(
8157       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8158       "                           : cccccccccccc    ? dddddddddddddddddd\n"
8159       "                                             : eeeeeeeeeeeeeeeeee)\n"
8160       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8161       "                        : 3333333333333333;",
8162       Style);
8163   verifyFormat(
8164       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8165       "                                             : cccccccccccccccccc\n"
8166       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8167       "                        : 3333333333333333;",
8168       Style);
8169   verifyFormat(
8170       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8171       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
8172       "                                             : eeeeeeeeeeeeeeeeee\n"
8173       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8174       "                        : 3333333333333333;",
8175       Style);
8176   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
8177                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
8178                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
8179                "                                   : eeeeeeeeeeeeeeeeee)\n"
8180                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8181                "                             : 3333333333333333;",
8182                Style);
8183   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
8184                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8185                "             : cccccccccccccccc ? dddddddddddddddddd\n"
8186                "                                : eeeeeeeeeeeeeeeeee\n"
8187                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8188                "                                 : 3333333333333333;",
8189                Style);
8190 
8191   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8192   Style.BreakBeforeTernaryOperators = false;
8193   // FIXME: Aligning the question marks is weird given DontAlign.
8194   // Consider disabling this alignment in this case. Also check whether this
8195   // will render the adjustment from https://reviews.llvm.org/D82199
8196   // unnecessary.
8197   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
8198                "    bbbb                ? cccccccccccccccccc :\n"
8199                "                          ddddd;\n",
8200                Style);
8201 
8202   EXPECT_EQ(
8203       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8204       "    /*\n"
8205       "     */\n"
8206       "    function() {\n"
8207       "      try {\n"
8208       "        return JJJJJJJJJJJJJJ(\n"
8209       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8210       "      }\n"
8211       "    } :\n"
8212       "    function() {};",
8213       format(
8214           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8215           "     /*\n"
8216           "      */\n"
8217           "     function() {\n"
8218           "      try {\n"
8219           "        return JJJJJJJJJJJJJJ(\n"
8220           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8221           "      }\n"
8222           "    } :\n"
8223           "    function() {};",
8224           getGoogleStyle(FormatStyle::LK_JavaScript)));
8225 }
8226 
8227 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
8228   FormatStyle Style = getLLVMStyleWithColumns(70);
8229   Style.BreakBeforeTernaryOperators = false;
8230   verifyFormat(
8231       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8232       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8233       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8234       Style);
8235   verifyFormat(
8236       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8237       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8238       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8239       Style);
8240   verifyFormat(
8241       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8242       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8243       Style);
8244   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
8245                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8246                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8247                Style);
8248   verifyFormat(
8249       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
8250       "                                                      aaaaaaaaaaaaa);",
8251       Style);
8252   verifyFormat(
8253       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8254       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8255       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8256       "                   aaaaaaaaaaaaa);",
8257       Style);
8258   verifyFormat(
8259       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8260       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8261       "                   aaaaaaaaaaaaa);",
8262       Style);
8263   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8264                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8265                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8266                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8267                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8268                Style);
8269   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8270                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8271                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8272                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8273                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8274                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8275                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8276                Style);
8277   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8278                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
8279                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8280                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8281                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8282                Style);
8283   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8284                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8285                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8286                Style);
8287   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8288                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8289                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8290                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8291                Style);
8292   verifyFormat(
8293       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8294       "    aaaaaaaaaaaaaaa :\n"
8295       "    aaaaaaaaaaaaaaa;",
8296       Style);
8297   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8298                "          aaaaaaaaa ?\n"
8299                "      b :\n"
8300                "      c);",
8301                Style);
8302   verifyFormat("unsigned Indent =\n"
8303                "    format(TheLine.First,\n"
8304                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
8305                "               IndentForLevel[TheLine.Level] :\n"
8306                "               TheLine * 2,\n"
8307                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8308                Style);
8309   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8310                "                  aaaaaaaaaaaaaaa :\n"
8311                "                  bbbbbbbbbbbbbbb ? //\n"
8312                "                      ccccccccccccccc :\n"
8313                "                      ddddddddddddddd;",
8314                Style);
8315   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8316                "                  aaaaaaaaaaaaaaa :\n"
8317                "                  (bbbbbbbbbbbbbbb ? //\n"
8318                "                       ccccccccccccccc :\n"
8319                "                       ddddddddddddddd);",
8320                Style);
8321   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8322                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
8323                "            ccccccccccccccccccccccccccc;",
8324                Style);
8325   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8326                "           aaaaa :\n"
8327                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
8328                Style);
8329 
8330   // Chained conditionals
8331   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8332                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8333                "                          3333333333333333;",
8334                Style);
8335   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8336                "       bbbbbbbbbb       ? 2222222222222222 :\n"
8337                "                          3333333333333333;",
8338                Style);
8339   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
8340                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8341                "                          3333333333333333;",
8342                Style);
8343   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8344                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
8345                "                          333333;",
8346                Style);
8347   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8348                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8349                "       cccccccccccccccc ? 3333333333333333 :\n"
8350                "                          4444444444444444;",
8351                Style);
8352   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
8353                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8354                "                          3333333333333333;",
8355                Style);
8356   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8357                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8358                "                          (aaa ? bbb : ccc);",
8359                Style);
8360   verifyFormat(
8361       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8362       "                                               cccccccccccccccccc) :\n"
8363       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8364       "                          3333333333333333;",
8365       Style);
8366   verifyFormat(
8367       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8368       "                                               cccccccccccccccccc) :\n"
8369       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8370       "                          3333333333333333;",
8371       Style);
8372   verifyFormat(
8373       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8374       "                                               dddddddddddddddddd) :\n"
8375       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8376       "                          3333333333333333;",
8377       Style);
8378   verifyFormat(
8379       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8380       "                                               dddddddddddddddddd) :\n"
8381       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8382       "                          3333333333333333;",
8383       Style);
8384   verifyFormat(
8385       "return aaaaaaaaa        ? 1111111111111111 :\n"
8386       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8387       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8388       "                                               dddddddddddddddddd)\n",
8389       Style);
8390   verifyFormat(
8391       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8392       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8393       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8394       "                                               cccccccccccccccccc);",
8395       Style);
8396   verifyFormat(
8397       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8398       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8399       "                                               eeeeeeeeeeeeeeeeee) :\n"
8400       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8401       "                          3333333333333333;",
8402       Style);
8403   verifyFormat(
8404       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8405       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8406       "                                               eeeeeeeeeeeeeeeeee) :\n"
8407       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8408       "                          3333333333333333;",
8409       Style);
8410   verifyFormat(
8411       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8412       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8413       "                                               eeeeeeeeeeeeeeeeee) :\n"
8414       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8415       "                          3333333333333333;",
8416       Style);
8417   verifyFormat(
8418       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8419       "                                               cccccccccccccccccc :\n"
8420       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8421       "                          3333333333333333;",
8422       Style);
8423   verifyFormat(
8424       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8425       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8426       "                                               eeeeeeeeeeeeeeeeee :\n"
8427       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8428       "                          3333333333333333;",
8429       Style);
8430   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8431                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8432                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8433                "                                 eeeeeeeeeeeeeeeeee) :\n"
8434                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8435                "                               3333333333333333;",
8436                Style);
8437   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8438                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8439                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8440                "                                  eeeeeeeeeeeeeeeeee :\n"
8441                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8442                "                               3333333333333333;",
8443                Style);
8444 }
8445 
8446 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8447   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8448                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8449   verifyFormat("bool a = true, b = false;");
8450 
8451   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8452                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8453                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8454                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8455   verifyFormat(
8456       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8457       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8458       "     d = e && f;");
8459   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8460                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8461   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8462                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8463   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8464                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8465 
8466   FormatStyle Style = getGoogleStyle();
8467   Style.PointerAlignment = FormatStyle::PAS_Left;
8468   Style.DerivePointerAlignment = false;
8469   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8470                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8471                "    *b = bbbbbbbbbbbbbbbbbbb;",
8472                Style);
8473   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8474                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8475                Style);
8476   verifyFormat("vector<int*> a, b;", Style);
8477   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8478   verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style);
8479   verifyFormat("if (int *p, *q; p != q) {\n  p = p->next;\n}", Style);
8480   verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n  p = p->next;\n}",
8481                Style);
8482   verifyFormat("switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8483                Style);
8484   verifyFormat(
8485       "/*comment*/ switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8486       Style);
8487 
8488   verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style);
8489   verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style);
8490   verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style);
8491   verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style);
8492   verifyFormat("switch ([](int* p, int* q) {}()) {\n  default:\n    break;\n}",
8493                Style);
8494 }
8495 
8496 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8497   verifyFormat("arr[foo ? bar : baz];");
8498   verifyFormat("f()[foo ? bar : baz];");
8499   verifyFormat("(a + b)[foo ? bar : baz];");
8500   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8501 }
8502 
8503 TEST_F(FormatTest, AlignsStringLiterals) {
8504   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8505                "                                      \"short literal\");");
8506   verifyFormat(
8507       "looooooooooooooooooooooooongFunction(\n"
8508       "    \"short literal\"\n"
8509       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8510   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8511                "             \" string literals\",\n"
8512                "             and, other, parameters);");
8513   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8514             "      \"5678\";",
8515             format("fun + \"1243\" /* comment */\n"
8516                    "    \"5678\";",
8517                    getLLVMStyleWithColumns(28)));
8518   EXPECT_EQ(
8519       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8520       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8521       "         \"aaaaaaaaaaaaaaaa\";",
8522       format("aaaaaa ="
8523              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8524              "aaaaaaaaaaaaaaaaaaaaa\" "
8525              "\"aaaaaaaaaaaaaaaa\";"));
8526   verifyFormat("a = a + \"a\"\n"
8527                "        \"a\"\n"
8528                "        \"a\";");
8529   verifyFormat("f(\"a\", \"b\"\n"
8530                "       \"c\");");
8531 
8532   verifyFormat(
8533       "#define LL_FORMAT \"ll\"\n"
8534       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8535       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8536 
8537   verifyFormat("#define A(X)          \\\n"
8538                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8539                "  \"ccccc\"",
8540                getLLVMStyleWithColumns(23));
8541   verifyFormat("#define A \"def\"\n"
8542                "f(\"abc\" A \"ghi\"\n"
8543                "  \"jkl\");");
8544 
8545   verifyFormat("f(L\"a\"\n"
8546                "  L\"b\");");
8547   verifyFormat("#define A(X)            \\\n"
8548                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8549                "  L\"ccccc\"",
8550                getLLVMStyleWithColumns(25));
8551 
8552   verifyFormat("f(@\"a\"\n"
8553                "  @\"b\");");
8554   verifyFormat("NSString s = @\"a\"\n"
8555                "             @\"b\"\n"
8556                "             @\"c\";");
8557   verifyFormat("NSString s = @\"a\"\n"
8558                "              \"b\"\n"
8559                "              \"c\";");
8560 }
8561 
8562 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8563   FormatStyle Style = getLLVMStyle();
8564   // No declarations or definitions should be moved to own line.
8565   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8566   verifyFormat("class A {\n"
8567                "  int f() { return 1; }\n"
8568                "  int g();\n"
8569                "};\n"
8570                "int f() { return 1; }\n"
8571                "int g();\n",
8572                Style);
8573 
8574   // All declarations and definitions should have the return type moved to its
8575   // own line.
8576   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8577   Style.TypenameMacros = {"LIST"};
8578   verifyFormat("SomeType\n"
8579                "funcdecl(LIST(uint64_t));",
8580                Style);
8581   verifyFormat("class E {\n"
8582                "  int\n"
8583                "  f() {\n"
8584                "    return 1;\n"
8585                "  }\n"
8586                "  int\n"
8587                "  g();\n"
8588                "};\n"
8589                "int\n"
8590                "f() {\n"
8591                "  return 1;\n"
8592                "}\n"
8593                "int\n"
8594                "g();\n",
8595                Style);
8596 
8597   // Top-level definitions, and no kinds of declarations should have the
8598   // return type moved to its own line.
8599   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8600   verifyFormat("class B {\n"
8601                "  int f() { return 1; }\n"
8602                "  int g();\n"
8603                "};\n"
8604                "int\n"
8605                "f() {\n"
8606                "  return 1;\n"
8607                "}\n"
8608                "int g();\n",
8609                Style);
8610 
8611   // Top-level definitions and declarations should have the return type moved
8612   // to its own line.
8613   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8614   verifyFormat("class C {\n"
8615                "  int f() { return 1; }\n"
8616                "  int g();\n"
8617                "};\n"
8618                "int\n"
8619                "f() {\n"
8620                "  return 1;\n"
8621                "}\n"
8622                "int\n"
8623                "g();\n",
8624                Style);
8625 
8626   // All definitions should have the return type moved to its own line, but no
8627   // kinds of declarations.
8628   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8629   verifyFormat("class D {\n"
8630                "  int\n"
8631                "  f() {\n"
8632                "    return 1;\n"
8633                "  }\n"
8634                "  int g();\n"
8635                "};\n"
8636                "int\n"
8637                "f() {\n"
8638                "  return 1;\n"
8639                "}\n"
8640                "int g();\n",
8641                Style);
8642   verifyFormat("const char *\n"
8643                "f(void) {\n" // Break here.
8644                "  return \"\";\n"
8645                "}\n"
8646                "const char *bar(void);\n", // No break here.
8647                Style);
8648   verifyFormat("template <class T>\n"
8649                "T *\n"
8650                "f(T &c) {\n" // Break here.
8651                "  return NULL;\n"
8652                "}\n"
8653                "template <class T> T *f(T &c);\n", // No break here.
8654                Style);
8655   verifyFormat("class C {\n"
8656                "  int\n"
8657                "  operator+() {\n"
8658                "    return 1;\n"
8659                "  }\n"
8660                "  int\n"
8661                "  operator()() {\n"
8662                "    return 1;\n"
8663                "  }\n"
8664                "};\n",
8665                Style);
8666   verifyFormat("void\n"
8667                "A::operator()() {}\n"
8668                "void\n"
8669                "A::operator>>() {}\n"
8670                "void\n"
8671                "A::operator+() {}\n"
8672                "void\n"
8673                "A::operator*() {}\n"
8674                "void\n"
8675                "A::operator->() {}\n"
8676                "void\n"
8677                "A::operator void *() {}\n"
8678                "void\n"
8679                "A::operator void &() {}\n"
8680                "void\n"
8681                "A::operator void &&() {}\n"
8682                "void\n"
8683                "A::operator char *() {}\n"
8684                "void\n"
8685                "A::operator[]() {}\n"
8686                "void\n"
8687                "A::operator!() {}\n"
8688                "void\n"
8689                "A::operator**() {}\n"
8690                "void\n"
8691                "A::operator<Foo> *() {}\n"
8692                "void\n"
8693                "A::operator<Foo> **() {}\n"
8694                "void\n"
8695                "A::operator<Foo> &() {}\n"
8696                "void\n"
8697                "A::operator void **() {}\n",
8698                Style);
8699   verifyFormat("constexpr auto\n"
8700                "operator()() const -> reference {}\n"
8701                "constexpr auto\n"
8702                "operator>>() const -> reference {}\n"
8703                "constexpr auto\n"
8704                "operator+() const -> reference {}\n"
8705                "constexpr auto\n"
8706                "operator*() const -> reference {}\n"
8707                "constexpr auto\n"
8708                "operator->() const -> reference {}\n"
8709                "constexpr auto\n"
8710                "operator++() const -> reference {}\n"
8711                "constexpr auto\n"
8712                "operator void *() const -> reference {}\n"
8713                "constexpr auto\n"
8714                "operator void **() const -> reference {}\n"
8715                "constexpr auto\n"
8716                "operator void *() const -> reference {}\n"
8717                "constexpr auto\n"
8718                "operator void &() const -> reference {}\n"
8719                "constexpr auto\n"
8720                "operator void &&() const -> reference {}\n"
8721                "constexpr auto\n"
8722                "operator char *() const -> reference {}\n"
8723                "constexpr auto\n"
8724                "operator!() const -> reference {}\n"
8725                "constexpr auto\n"
8726                "operator[]() const -> reference {}\n",
8727                Style);
8728   verifyFormat("void *operator new(std::size_t s);", // No break here.
8729                Style);
8730   verifyFormat("void *\n"
8731                "operator new(std::size_t s) {}",
8732                Style);
8733   verifyFormat("void *\n"
8734                "operator delete[](void *ptr) {}",
8735                Style);
8736   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8737   verifyFormat("const char *\n"
8738                "f(void)\n" // Break here.
8739                "{\n"
8740                "  return \"\";\n"
8741                "}\n"
8742                "const char *bar(void);\n", // No break here.
8743                Style);
8744   verifyFormat("template <class T>\n"
8745                "T *\n"     // Problem here: no line break
8746                "f(T &c)\n" // Break here.
8747                "{\n"
8748                "  return NULL;\n"
8749                "}\n"
8750                "template <class T> T *f(T &c);\n", // No break here.
8751                Style);
8752   verifyFormat("int\n"
8753                "foo(A<bool> a)\n"
8754                "{\n"
8755                "  return a;\n"
8756                "}\n",
8757                Style);
8758   verifyFormat("int\n"
8759                "foo(A<8> a)\n"
8760                "{\n"
8761                "  return a;\n"
8762                "}\n",
8763                Style);
8764   verifyFormat("int\n"
8765                "foo(A<B<bool>, 8> a)\n"
8766                "{\n"
8767                "  return a;\n"
8768                "}\n",
8769                Style);
8770   verifyFormat("int\n"
8771                "foo(A<B<8>, bool> a)\n"
8772                "{\n"
8773                "  return a;\n"
8774                "}\n",
8775                Style);
8776   verifyFormat("int\n"
8777                "foo(A<B<bool>, bool> a)\n"
8778                "{\n"
8779                "  return a;\n"
8780                "}\n",
8781                Style);
8782   verifyFormat("int\n"
8783                "foo(A<B<8>, 8> a)\n"
8784                "{\n"
8785                "  return a;\n"
8786                "}\n",
8787                Style);
8788 
8789   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8790   Style.BraceWrapping.AfterFunction = true;
8791   verifyFormat("int f(i);\n" // No break here.
8792                "int\n"       // Break here.
8793                "f(i)\n"
8794                "{\n"
8795                "  return i + 1;\n"
8796                "}\n"
8797                "int\n" // Break here.
8798                "f(i)\n"
8799                "{\n"
8800                "  return i + 1;\n"
8801                "};",
8802                Style);
8803   verifyFormat("int f(a, b, c);\n" // No break here.
8804                "int\n"             // Break here.
8805                "f(a, b, c)\n"      // Break here.
8806                "short a, b;\n"
8807                "float c;\n"
8808                "{\n"
8809                "  return a + b < c;\n"
8810                "}\n"
8811                "int\n"        // Break here.
8812                "f(a, b, c)\n" // Break here.
8813                "short a, b;\n"
8814                "float c;\n"
8815                "{\n"
8816                "  return a + b < c;\n"
8817                "};",
8818                Style);
8819   verifyFormat("byte *\n" // Break here.
8820                "f(a)\n"   // Break here.
8821                "byte a[];\n"
8822                "{\n"
8823                "  return a;\n"
8824                "}",
8825                Style);
8826   verifyFormat("bool f(int a, int) override;\n"
8827                "Bar g(int a, Bar) final;\n"
8828                "Bar h(a, Bar) final;",
8829                Style);
8830   verifyFormat("int\n"
8831                "f(a)",
8832                Style);
8833   verifyFormat("bool\n"
8834                "f(size_t = 0, bool b = false)\n"
8835                "{\n"
8836                "  return !b;\n"
8837                "}",
8838                Style);
8839 
8840   // The return breaking style doesn't affect:
8841   // * function and object definitions with attribute-like macros
8842   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8843                "    ABSL_GUARDED_BY(mutex) = {};",
8844                getGoogleStyleWithColumns(40));
8845   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8846                "    ABSL_GUARDED_BY(mutex);  // comment",
8847                getGoogleStyleWithColumns(40));
8848   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8849                "    ABSL_GUARDED_BY(mutex1)\n"
8850                "        ABSL_GUARDED_BY(mutex2);",
8851                getGoogleStyleWithColumns(40));
8852   verifyFormat("Tttttt f(int a, int b)\n"
8853                "    ABSL_GUARDED_BY(mutex1)\n"
8854                "        ABSL_GUARDED_BY(mutex2);",
8855                getGoogleStyleWithColumns(40));
8856   // * typedefs
8857   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
8858 
8859   Style = getGNUStyle();
8860 
8861   // Test for comments at the end of function declarations.
8862   verifyFormat("void\n"
8863                "foo (int a, /*abc*/ int b) // def\n"
8864                "{\n"
8865                "}\n",
8866                Style);
8867 
8868   verifyFormat("void\n"
8869                "foo (int a, /* abc */ int b) /* def */\n"
8870                "{\n"
8871                "}\n",
8872                Style);
8873 
8874   // Definitions that should not break after return type
8875   verifyFormat("void foo (int a, int b); // def\n", Style);
8876   verifyFormat("void foo (int a, int b); /* def */\n", Style);
8877   verifyFormat("void foo (int a, int b);\n", Style);
8878 }
8879 
8880 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
8881   FormatStyle NoBreak = getLLVMStyle();
8882   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
8883   FormatStyle Break = getLLVMStyle();
8884   Break.AlwaysBreakBeforeMultilineStrings = true;
8885   verifyFormat("aaaa = \"bbbb\"\n"
8886                "       \"cccc\";",
8887                NoBreak);
8888   verifyFormat("aaaa =\n"
8889                "    \"bbbb\"\n"
8890                "    \"cccc\";",
8891                Break);
8892   verifyFormat("aaaa(\"bbbb\"\n"
8893                "     \"cccc\");",
8894                NoBreak);
8895   verifyFormat("aaaa(\n"
8896                "    \"bbbb\"\n"
8897                "    \"cccc\");",
8898                Break);
8899   verifyFormat("aaaa(qqq, \"bbbb\"\n"
8900                "          \"cccc\");",
8901                NoBreak);
8902   verifyFormat("aaaa(qqq,\n"
8903                "     \"bbbb\"\n"
8904                "     \"cccc\");",
8905                Break);
8906   verifyFormat("aaaa(qqq,\n"
8907                "     L\"bbbb\"\n"
8908                "     L\"cccc\");",
8909                Break);
8910   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
8911                "                      \"bbbb\"));",
8912                Break);
8913   verifyFormat("string s = someFunction(\n"
8914                "    \"abc\"\n"
8915                "    \"abc\");",
8916                Break);
8917 
8918   // As we break before unary operators, breaking right after them is bad.
8919   verifyFormat("string foo = abc ? \"x\"\n"
8920                "                   \"blah blah blah blah blah blah\"\n"
8921                "                 : \"y\";",
8922                Break);
8923 
8924   // Don't break if there is no column gain.
8925   verifyFormat("f(\"aaaa\"\n"
8926                "  \"bbbb\");",
8927                Break);
8928 
8929   // Treat literals with escaped newlines like multi-line string literals.
8930   EXPECT_EQ("x = \"a\\\n"
8931             "b\\\n"
8932             "c\";",
8933             format("x = \"a\\\n"
8934                    "b\\\n"
8935                    "c\";",
8936                    NoBreak));
8937   EXPECT_EQ("xxxx =\n"
8938             "    \"a\\\n"
8939             "b\\\n"
8940             "c\";",
8941             format("xxxx = \"a\\\n"
8942                    "b\\\n"
8943                    "c\";",
8944                    Break));
8945 
8946   EXPECT_EQ("NSString *const kString =\n"
8947             "    @\"aaaa\"\n"
8948             "    @\"bbbb\";",
8949             format("NSString *const kString = @\"aaaa\"\n"
8950                    "@\"bbbb\";",
8951                    Break));
8952 
8953   Break.ColumnLimit = 0;
8954   verifyFormat("const char *hello = \"hello llvm\";", Break);
8955 }
8956 
8957 TEST_F(FormatTest, AlignsPipes) {
8958   verifyFormat(
8959       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8960       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8961       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8962   verifyFormat(
8963       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
8964       "                     << aaaaaaaaaaaaaaaaaaaa;");
8965   verifyFormat(
8966       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8967       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8968   verifyFormat(
8969       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
8970       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8971   verifyFormat(
8972       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
8973       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
8974       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
8975   verifyFormat(
8976       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8977       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8978       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8979   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8980                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8981                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8982                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8983   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
8984                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
8985   verifyFormat(
8986       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8987       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8988   verifyFormat(
8989       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
8990       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
8991 
8992   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
8993                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
8994   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8995                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8996                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
8997                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
8998   verifyFormat("LOG_IF(aaa == //\n"
8999                "       bbb)\n"
9000                "    << a << b;");
9001 
9002   // But sometimes, breaking before the first "<<" is desirable.
9003   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9004                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
9005   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
9006                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9007                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9008   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
9009                "    << BEF << IsTemplate << Description << E->getType();");
9010   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9011                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9012                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9013   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9014                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9015                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9016                "    << aaa;");
9017 
9018   verifyFormat(
9019       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9020       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9021 
9022   // Incomplete string literal.
9023   EXPECT_EQ("llvm::errs() << \"\n"
9024             "             << a;",
9025             format("llvm::errs() << \"\n<<a;"));
9026 
9027   verifyFormat("void f() {\n"
9028                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
9029                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
9030                "}");
9031 
9032   // Handle 'endl'.
9033   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
9034                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9035   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9036 
9037   // Handle '\n'.
9038   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
9039                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9040   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
9041                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
9042   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
9043                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
9044   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9045 }
9046 
9047 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
9048   verifyFormat("return out << \"somepacket = {\\n\"\n"
9049                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
9050                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
9051                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
9052                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
9053                "           << \"}\";");
9054 
9055   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9056                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9057                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
9058   verifyFormat(
9059       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
9060       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
9061       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
9062       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
9063       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
9064   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
9065                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9066   verifyFormat(
9067       "void f() {\n"
9068       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
9069       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
9070       "}");
9071 
9072   // Breaking before the first "<<" is generally not desirable.
9073   verifyFormat(
9074       "llvm::errs()\n"
9075       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9076       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9077       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9078       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9079       getLLVMStyleWithColumns(70));
9080   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9081                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9082                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9083                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9084                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9085                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9086                getLLVMStyleWithColumns(70));
9087 
9088   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9089                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9090                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
9091   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9092                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9093                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
9094   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
9095                "           (aaaa + aaaa);",
9096                getLLVMStyleWithColumns(40));
9097   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
9098                "                  (aaaaaaa + aaaaa));",
9099                getLLVMStyleWithColumns(40));
9100   verifyFormat(
9101       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
9102       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
9103       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
9104 }
9105 
9106 TEST_F(FormatTest, UnderstandsEquals) {
9107   verifyFormat(
9108       "aaaaaaaaaaaaaaaaa =\n"
9109       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9110   verifyFormat(
9111       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9112       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9113   verifyFormat(
9114       "if (a) {\n"
9115       "  f();\n"
9116       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9117       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
9118       "}");
9119 
9120   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9121                "        100000000 + 10000000) {\n}");
9122 }
9123 
9124 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
9125   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9126                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
9127 
9128   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9129                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
9130 
9131   verifyFormat(
9132       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
9133       "                                                          Parameter2);");
9134 
9135   verifyFormat(
9136       "ShortObject->shortFunction(\n"
9137       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
9138       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
9139 
9140   verifyFormat("loooooooooooooongFunction(\n"
9141                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
9142 
9143   verifyFormat(
9144       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
9145       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
9146 
9147   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9148                "    .WillRepeatedly(Return(SomeValue));");
9149   verifyFormat("void f() {\n"
9150                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9151                "      .Times(2)\n"
9152                "      .WillRepeatedly(Return(SomeValue));\n"
9153                "}");
9154   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
9155                "    ccccccccccccccccccccccc);");
9156   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9157                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9158                "          .aaaaa(aaaaa),\n"
9159                "      aaaaaaaaaaaaaaaaaaaaa);");
9160   verifyFormat("void f() {\n"
9161                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9162                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
9163                "}");
9164   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9165                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9166                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9167                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9168                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9169   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9170                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9171                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9172                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
9173                "}");
9174 
9175   // Here, it is not necessary to wrap at "." or "->".
9176   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
9177                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9178   verifyFormat(
9179       "aaaaaaaaaaa->aaaaaaaaa(\n"
9180       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9181       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
9182 
9183   verifyFormat(
9184       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9185       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
9186   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
9187                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9188   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
9189                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9190 
9191   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9192                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9193                "    .a();");
9194 
9195   FormatStyle NoBinPacking = getLLVMStyle();
9196   NoBinPacking.BinPackParameters = false;
9197   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9198                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9199                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
9200                "                         aaaaaaaaaaaaaaaaaaa,\n"
9201                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
9202                NoBinPacking);
9203 
9204   // If there is a subsequent call, change to hanging indentation.
9205   verifyFormat(
9206       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9207       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
9208       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9209   verifyFormat(
9210       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9211       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
9212   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9213                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9214                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9215   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9216                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9217                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9218 }
9219 
9220 TEST_F(FormatTest, WrapsTemplateDeclarations) {
9221   verifyFormat("template <typename T>\n"
9222                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9223   verifyFormat("template <typename T>\n"
9224                "// T should be one of {A, B}.\n"
9225                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9226   verifyFormat(
9227       "template <typename T>\n"
9228       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
9229   verifyFormat("template <typename T>\n"
9230                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
9231                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
9232   verifyFormat(
9233       "template <typename T>\n"
9234       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
9235       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
9236   verifyFormat(
9237       "template <typename T>\n"
9238       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
9239       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
9240       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9241   verifyFormat("template <typename T>\n"
9242                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9243                "    int aaaaaaaaaaaaaaaaaaaaaa);");
9244   verifyFormat(
9245       "template <typename T1, typename T2 = char, typename T3 = char,\n"
9246       "          typename T4 = char>\n"
9247       "void f();");
9248   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
9249                "          template <typename> class cccccccccccccccccccccc,\n"
9250                "          typename ddddddddddddd>\n"
9251                "class C {};");
9252   verifyFormat(
9253       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
9254       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9255 
9256   verifyFormat("void f() {\n"
9257                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
9258                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
9259                "}");
9260 
9261   verifyFormat("template <typename T> class C {};");
9262   verifyFormat("template <typename T> void f();");
9263   verifyFormat("template <typename T> void f() {}");
9264   verifyFormat(
9265       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9266       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9267       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
9268       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9269       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9270       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
9271       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
9272       getLLVMStyleWithColumns(72));
9273   EXPECT_EQ("static_cast<A< //\n"
9274             "    B> *>(\n"
9275             "\n"
9276             ");",
9277             format("static_cast<A<//\n"
9278                    "    B>*>(\n"
9279                    "\n"
9280                    "    );"));
9281   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9282                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
9283 
9284   FormatStyle AlwaysBreak = getLLVMStyle();
9285   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9286   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
9287   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
9288   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
9289   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9290                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9291                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
9292   verifyFormat("template <template <typename> class Fooooooo,\n"
9293                "          template <typename> class Baaaaaaar>\n"
9294                "struct C {};",
9295                AlwaysBreak);
9296   verifyFormat("template <typename T> // T can be A, B or C.\n"
9297                "struct C {};",
9298                AlwaysBreak);
9299   verifyFormat("template <enum E> class A {\n"
9300                "public:\n"
9301                "  E *f();\n"
9302                "};");
9303 
9304   FormatStyle NeverBreak = getLLVMStyle();
9305   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
9306   verifyFormat("template <typename T> class C {};", NeverBreak);
9307   verifyFormat("template <typename T> void f();", NeverBreak);
9308   verifyFormat("template <typename T> void f() {}", NeverBreak);
9309   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9310                "bbbbbbbbbbbbbbbbbbbb) {}",
9311                NeverBreak);
9312   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9313                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9314                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
9315                NeverBreak);
9316   verifyFormat("template <template <typename> class Fooooooo,\n"
9317                "          template <typename> class Baaaaaaar>\n"
9318                "struct C {};",
9319                NeverBreak);
9320   verifyFormat("template <typename T> // T can be A, B or C.\n"
9321                "struct C {};",
9322                NeverBreak);
9323   verifyFormat("template <enum E> class A {\n"
9324                "public:\n"
9325                "  E *f();\n"
9326                "};",
9327                NeverBreak);
9328   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
9329   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9330                "bbbbbbbbbbbbbbbbbbbb) {}",
9331                NeverBreak);
9332 }
9333 
9334 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
9335   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9336   Style.ColumnLimit = 60;
9337   EXPECT_EQ("// Baseline - no comments.\n"
9338             "template <\n"
9339             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9340             "void f() {}",
9341             format("// Baseline - no comments.\n"
9342                    "template <\n"
9343                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9344                    "void f() {}",
9345                    Style));
9346 
9347   EXPECT_EQ("template <\n"
9348             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9349             "void f() {}",
9350             format("template <\n"
9351                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9352                    "void f() {}",
9353                    Style));
9354 
9355   EXPECT_EQ(
9356       "template <\n"
9357       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
9358       "void f() {}",
9359       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
9360              "void f() {}",
9361              Style));
9362 
9363   EXPECT_EQ(
9364       "template <\n"
9365       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9366       "                                               // multiline\n"
9367       "void f() {}",
9368       format("template <\n"
9369              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9370              "                                              // multiline\n"
9371              "void f() {}",
9372              Style));
9373 
9374   EXPECT_EQ(
9375       "template <typename aaaaaaaaaa<\n"
9376       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
9377       "void f() {}",
9378       format(
9379           "template <\n"
9380           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
9381           "void f() {}",
9382           Style));
9383 }
9384 
9385 TEST_F(FormatTest, WrapsTemplateParameters) {
9386   FormatStyle Style = getLLVMStyle();
9387   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9388   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9389   verifyFormat(
9390       "template <typename... a> struct q {};\n"
9391       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9392       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9393       "    y;",
9394       Style);
9395   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9396   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9397   verifyFormat(
9398       "template <typename... a> struct r {};\n"
9399       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9400       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9401       "    y;",
9402       Style);
9403   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9404   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9405   verifyFormat("template <typename... a> struct s {};\n"
9406                "extern s<\n"
9407                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9408                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9409                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9410                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9411                "    y;",
9412                Style);
9413   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9414   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9415   verifyFormat("template <typename... a> struct t {};\n"
9416                "extern t<\n"
9417                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9418                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9419                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9420                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9421                "    y;",
9422                Style);
9423 }
9424 
9425 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9426   verifyFormat(
9427       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9428       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9429   verifyFormat(
9430       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9431       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9432       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9433 
9434   // FIXME: Should we have the extra indent after the second break?
9435   verifyFormat(
9436       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9437       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9438       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9439 
9440   verifyFormat(
9441       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9442       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9443 
9444   // Breaking at nested name specifiers is generally not desirable.
9445   verifyFormat(
9446       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9447       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9448 
9449   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9450                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9451                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9452                "                   aaaaaaaaaaaaaaaaaaaaa);",
9453                getLLVMStyleWithColumns(74));
9454 
9455   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9456                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9457                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9458 }
9459 
9460 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9461   verifyFormat("A<int> a;");
9462   verifyFormat("A<A<A<int>>> a;");
9463   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9464   verifyFormat("bool x = a < 1 || 2 > a;");
9465   verifyFormat("bool x = 5 < f<int>();");
9466   verifyFormat("bool x = f<int>() > 5;");
9467   verifyFormat("bool x = 5 < a<int>::x;");
9468   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9469   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9470 
9471   verifyGoogleFormat("A<A<int>> a;");
9472   verifyGoogleFormat("A<A<A<int>>> a;");
9473   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9474   verifyGoogleFormat("A<A<int> > a;");
9475   verifyGoogleFormat("A<A<A<int> > > a;");
9476   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9477   verifyGoogleFormat("A<::A<int>> a;");
9478   verifyGoogleFormat("A<::A> a;");
9479   verifyGoogleFormat("A< ::A> a;");
9480   verifyGoogleFormat("A< ::A<int> > a;");
9481   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9482   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9483   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9484   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9485   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9486             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9487 
9488   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9489 
9490   // template closer followed by a token that starts with > or =
9491   verifyFormat("bool b = a<1> > 1;");
9492   verifyFormat("bool b = a<1> >= 1;");
9493   verifyFormat("int i = a<1> >> 1;");
9494   FormatStyle Style = getLLVMStyle();
9495   Style.SpaceBeforeAssignmentOperators = false;
9496   verifyFormat("bool b= a<1> == 1;", Style);
9497   verifyFormat("a<int> = 1;", Style);
9498   verifyFormat("a<int> >>= 1;", Style);
9499 
9500   verifyFormat("test < a | b >> c;");
9501   verifyFormat("test<test<a | b>> c;");
9502   verifyFormat("test >> a >> b;");
9503   verifyFormat("test << a >> b;");
9504 
9505   verifyFormat("f<int>();");
9506   verifyFormat("template <typename T> void f() {}");
9507   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9508   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9509                "sizeof(char)>::type>;");
9510   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9511   verifyFormat("f(a.operator()<A>());");
9512   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9513                "      .template operator()<A>());",
9514                getLLVMStyleWithColumns(35));
9515 
9516   // Not template parameters.
9517   verifyFormat("return a < b && c > d;");
9518   verifyFormat("void f() {\n"
9519                "  while (a < b && c > d) {\n"
9520                "  }\n"
9521                "}");
9522   verifyFormat("template <typename... Types>\n"
9523                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9524 
9525   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9526                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9527                getLLVMStyleWithColumns(60));
9528   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9529   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9530   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9531   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9532 }
9533 
9534 TEST_F(FormatTest, UnderstandsShiftOperators) {
9535   verifyFormat("if (i < x >> 1)");
9536   verifyFormat("while (i < x >> 1)");
9537   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9538   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9539   verifyFormat(
9540       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9541   verifyFormat("Foo.call<Bar<Function>>()");
9542   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9543   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9544                "++i, v = v >> 1)");
9545   verifyFormat("if (w<u<v<x>>, 1>::t)");
9546 }
9547 
9548 TEST_F(FormatTest, BitshiftOperatorWidth) {
9549   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9550             "                   bar */",
9551             format("int    a=1<<2;  /* foo\n"
9552                    "                   bar */"));
9553 
9554   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9555             "                     bar */",
9556             format("int  b  =256>>1 ;  /* foo\n"
9557                    "                      bar */"));
9558 }
9559 
9560 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9561   verifyFormat("COMPARE(a, ==, b);");
9562   verifyFormat("auto s = sizeof...(Ts) - 1;");
9563 }
9564 
9565 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9566   verifyFormat("int A::*x;");
9567   verifyFormat("int (S::*func)(void *);");
9568   verifyFormat("void f() { int (S::*func)(void *); }");
9569   verifyFormat("typedef bool *(Class::*Member)() const;");
9570   verifyFormat("void f() {\n"
9571                "  (a->*f)();\n"
9572                "  a->*x;\n"
9573                "  (a.*f)();\n"
9574                "  ((*a).*f)();\n"
9575                "  a.*x;\n"
9576                "}");
9577   verifyFormat("void f() {\n"
9578                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9579                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9580                "}");
9581   verifyFormat(
9582       "(aaaaaaaaaa->*bbbbbbb)(\n"
9583       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9584   FormatStyle Style = getLLVMStyle();
9585   Style.PointerAlignment = FormatStyle::PAS_Left;
9586   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9587 }
9588 
9589 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9590   verifyFormat("int a = -2;");
9591   verifyFormat("f(-1, -2, -3);");
9592   verifyFormat("a[-1] = 5;");
9593   verifyFormat("int a = 5 + -2;");
9594   verifyFormat("if (i == -1) {\n}");
9595   verifyFormat("if (i != -1) {\n}");
9596   verifyFormat("if (i > -1) {\n}");
9597   verifyFormat("if (i < -1) {\n}");
9598   verifyFormat("++(a->f());");
9599   verifyFormat("--(a->f());");
9600   verifyFormat("(a->f())++;");
9601   verifyFormat("a[42]++;");
9602   verifyFormat("if (!(a->f())) {\n}");
9603   verifyFormat("if (!+i) {\n}");
9604   verifyFormat("~&a;");
9605 
9606   verifyFormat("a-- > b;");
9607   verifyFormat("b ? -a : c;");
9608   verifyFormat("n * sizeof char16;");
9609   verifyFormat("n * alignof char16;", getGoogleStyle());
9610   verifyFormat("sizeof(char);");
9611   verifyFormat("alignof(char);", getGoogleStyle());
9612 
9613   verifyFormat("return -1;");
9614   verifyFormat("throw -1;");
9615   verifyFormat("switch (a) {\n"
9616                "case -1:\n"
9617                "  break;\n"
9618                "}");
9619   verifyFormat("#define X -1");
9620   verifyFormat("#define X -kConstant");
9621 
9622   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9623   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9624 
9625   verifyFormat("int a = /* confusing comment */ -1;");
9626   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9627   verifyFormat("int a = i /* confusing comment */++;");
9628 
9629   verifyFormat("co_yield -1;");
9630   verifyFormat("co_return -1;");
9631 
9632   // Check that * is not treated as a binary operator when we set
9633   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9634   FormatStyle PASLeftStyle = getLLVMStyle();
9635   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9636   verifyFormat("co_return *a;", PASLeftStyle);
9637   verifyFormat("co_await *a;", PASLeftStyle);
9638   verifyFormat("co_yield *a", PASLeftStyle);
9639   verifyFormat("return *a;", PASLeftStyle);
9640 }
9641 
9642 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9643   verifyFormat("if (!aaaaaaaaaa( // break\n"
9644                "        aaaaa)) {\n"
9645                "}");
9646   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9647                "    aaaaa));");
9648   verifyFormat("*aaa = aaaaaaa( // break\n"
9649                "    bbbbbb);");
9650 }
9651 
9652 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9653   verifyFormat("bool operator<();");
9654   verifyFormat("bool operator>();");
9655   verifyFormat("bool operator=();");
9656   verifyFormat("bool operator==();");
9657   verifyFormat("bool operator!=();");
9658   verifyFormat("int operator+();");
9659   verifyFormat("int operator++();");
9660   verifyFormat("int operator++(int) volatile noexcept;");
9661   verifyFormat("bool operator,();");
9662   verifyFormat("bool operator();");
9663   verifyFormat("bool operator()();");
9664   verifyFormat("bool operator[]();");
9665   verifyFormat("operator bool();");
9666   verifyFormat("operator int();");
9667   verifyFormat("operator void *();");
9668   verifyFormat("operator SomeType<int>();");
9669   verifyFormat("operator SomeType<int, int>();");
9670   verifyFormat("operator SomeType<SomeType<int>>();");
9671   verifyFormat("operator< <>();");
9672   verifyFormat("operator<< <>();");
9673   verifyFormat("< <>");
9674 
9675   verifyFormat("void *operator new(std::size_t size);");
9676   verifyFormat("void *operator new[](std::size_t size);");
9677   verifyFormat("void operator delete(void *ptr);");
9678   verifyFormat("void operator delete[](void *ptr);");
9679   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9680                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9681   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9682                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9683 
9684   verifyFormat(
9685       "ostream &operator<<(ostream &OutputStream,\n"
9686       "                    SomeReallyLongType WithSomeReallyLongValue);");
9687   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9688                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9689                "  return left.group < right.group;\n"
9690                "}");
9691   verifyFormat("SomeType &operator=(const SomeType &S);");
9692   verifyFormat("f.template operator()<int>();");
9693 
9694   verifyGoogleFormat("operator void*();");
9695   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9696   verifyGoogleFormat("operator ::A();");
9697 
9698   verifyFormat("using A::operator+;");
9699   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9700                "int i;");
9701 
9702   // Calling an operator as a member function.
9703   verifyFormat("void f() { a.operator*(); }");
9704   verifyFormat("void f() { a.operator*(b & b); }");
9705   verifyFormat("void f() { a->operator&(a * b); }");
9706   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9707   // TODO: Calling an operator as a non-member function is hard to distinguish.
9708   // https://llvm.org/PR50629
9709   // verifyFormat("void f() { operator*(a & a); }");
9710   // verifyFormat("void f() { operator&(a, b * b); }");
9711 
9712   verifyFormat("::operator delete(foo);");
9713   verifyFormat("::operator new(n * sizeof(foo));");
9714   verifyFormat("foo() { ::operator delete(foo); }");
9715   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9716 }
9717 
9718 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9719   verifyFormat("void A::b() && {}");
9720   verifyFormat("void A::b() &&noexcept {}");
9721   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9722   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9723   verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
9724   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9725   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9726   verifyFormat("Deleted &operator=(const Deleted &) &;");
9727   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9728   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9729   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9730   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9731   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9732   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9733   verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
9734   verifyFormat("void Fn(T const &) const &;");
9735   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9736   verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
9737   verifyFormat("template <typename T>\n"
9738                "void F(T) && = delete;",
9739                getGoogleStyle());
9740 
9741   FormatStyle AlignLeft = getLLVMStyle();
9742   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9743   verifyFormat("void A::b() && {}", AlignLeft);
9744   verifyFormat("void A::b() && noexcept {}", AlignLeft);
9745   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9746   verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
9747                AlignLeft);
9748   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9749                AlignLeft);
9750   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9751   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9752   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9753   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9754   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9755   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9756   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9757   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9758   verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
9759                AlignLeft);
9760 
9761   FormatStyle AlignMiddle = getLLVMStyle();
9762   AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9763   verifyFormat("void A::b() && {}", AlignMiddle);
9764   verifyFormat("void A::b() && noexcept {}", AlignMiddle);
9765   verifyFormat("Deleted & operator=(const Deleted &) & = default;",
9766                AlignMiddle);
9767   verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
9768                AlignMiddle);
9769   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
9770                AlignMiddle);
9771   verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
9772   verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
9773   verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
9774   verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
9775   verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
9776   verifyFormat("auto Function(T) & -> void;", AlignMiddle);
9777   verifyFormat("void Fn(T const &) const &;", AlignMiddle);
9778   verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
9779   verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
9780                AlignMiddle);
9781 
9782   FormatStyle Spaces = getLLVMStyle();
9783   Spaces.SpacesInCStyleCastParentheses = true;
9784   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9785   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9786   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9787   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9788 
9789   Spaces.SpacesInCStyleCastParentheses = false;
9790   Spaces.SpacesInParentheses = true;
9791   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9792   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9793                Spaces);
9794   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9795   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9796 
9797   FormatStyle BreakTemplate = getLLVMStyle();
9798   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9799 
9800   verifyFormat("struct f {\n"
9801                "  template <class T>\n"
9802                "  int &foo(const std::string &str) &noexcept {}\n"
9803                "};",
9804                BreakTemplate);
9805 
9806   verifyFormat("struct f {\n"
9807                "  template <class T>\n"
9808                "  int &foo(const std::string &str) &&noexcept {}\n"
9809                "};",
9810                BreakTemplate);
9811 
9812   verifyFormat("struct f {\n"
9813                "  template <class T>\n"
9814                "  int &foo(const std::string &str) const &noexcept {}\n"
9815                "};",
9816                BreakTemplate);
9817 
9818   verifyFormat("struct f {\n"
9819                "  template <class T>\n"
9820                "  int &foo(const std::string &str) const &noexcept {}\n"
9821                "};",
9822                BreakTemplate);
9823 
9824   verifyFormat("struct f {\n"
9825                "  template <class T>\n"
9826                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
9827                "};",
9828                BreakTemplate);
9829 
9830   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
9831   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
9832       FormatStyle::BTDS_Yes;
9833   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
9834 
9835   verifyFormat("struct f {\n"
9836                "  template <class T>\n"
9837                "  int& foo(const std::string& str) & noexcept {}\n"
9838                "};",
9839                AlignLeftBreakTemplate);
9840 
9841   verifyFormat("struct f {\n"
9842                "  template <class T>\n"
9843                "  int& foo(const std::string& str) && noexcept {}\n"
9844                "};",
9845                AlignLeftBreakTemplate);
9846 
9847   verifyFormat("struct f {\n"
9848                "  template <class T>\n"
9849                "  int& foo(const std::string& str) const& noexcept {}\n"
9850                "};",
9851                AlignLeftBreakTemplate);
9852 
9853   verifyFormat("struct f {\n"
9854                "  template <class T>\n"
9855                "  int& foo(const std::string& str) const&& noexcept {}\n"
9856                "};",
9857                AlignLeftBreakTemplate);
9858 
9859   verifyFormat("struct f {\n"
9860                "  template <class T>\n"
9861                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
9862                "};",
9863                AlignLeftBreakTemplate);
9864 
9865   // The `&` in `Type&` should not be confused with a trailing `&` of
9866   // DEPRECATED(reason) member function.
9867   verifyFormat("struct f {\n"
9868                "  template <class T>\n"
9869                "  DEPRECATED(reason)\n"
9870                "  Type &foo(arguments) {}\n"
9871                "};",
9872                BreakTemplate);
9873 
9874   verifyFormat("struct f {\n"
9875                "  template <class T>\n"
9876                "  DEPRECATED(reason)\n"
9877                "  Type& foo(arguments) {}\n"
9878                "};",
9879                AlignLeftBreakTemplate);
9880 
9881   verifyFormat("void (*foopt)(int) = &func;");
9882 
9883   FormatStyle DerivePointerAlignment = getLLVMStyle();
9884   DerivePointerAlignment.DerivePointerAlignment = true;
9885   // There's always a space between the function and its trailing qualifiers.
9886   // This isn't evidence for PAS_Right (or for PAS_Left).
9887   std::string Prefix = "void a() &;\n"
9888                        "void b() &;\n";
9889   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
9890   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
9891   // Same if the function is an overloaded operator, and with &&.
9892   Prefix = "void operator()() &&;\n"
9893            "void operator()() &&;\n";
9894   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
9895   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
9896   // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
9897   Prefix = "void a() const &;\n"
9898            "void b() const &;\n";
9899   EXPECT_EQ(Prefix + "int *x;",
9900             format(Prefix + "int* x;", DerivePointerAlignment));
9901 }
9902 
9903 TEST_F(FormatTest, UnderstandsNewAndDelete) {
9904   verifyFormat("void f() {\n"
9905                "  A *a = new A;\n"
9906                "  A *a = new (placement) A;\n"
9907                "  delete a;\n"
9908                "  delete (A *)a;\n"
9909                "}");
9910   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9911                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9912   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9913                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9914                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9915   verifyFormat("delete[] h->p;");
9916   verifyFormat("delete[] (void *)p;");
9917 
9918   verifyFormat("void operator delete(void *foo) ATTRIB;");
9919   verifyFormat("void operator new(void *foo) ATTRIB;");
9920   verifyFormat("void operator delete[](void *foo) ATTRIB;");
9921   verifyFormat("void operator delete(void *ptr) noexcept;");
9922 }
9923 
9924 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
9925   verifyFormat("int *f(int *a) {}");
9926   verifyFormat("int main(int argc, char **argv) {}");
9927   verifyFormat("Test::Test(int b) : a(b * b) {}");
9928   verifyIndependentOfContext("f(a, *a);");
9929   verifyFormat("void g() { f(*a); }");
9930   verifyIndependentOfContext("int a = b * 10;");
9931   verifyIndependentOfContext("int a = 10 * b;");
9932   verifyIndependentOfContext("int a = b * c;");
9933   verifyIndependentOfContext("int a += b * c;");
9934   verifyIndependentOfContext("int a -= b * c;");
9935   verifyIndependentOfContext("int a *= b * c;");
9936   verifyIndependentOfContext("int a /= b * c;");
9937   verifyIndependentOfContext("int a = *b;");
9938   verifyIndependentOfContext("int a = *b * c;");
9939   verifyIndependentOfContext("int a = b * *c;");
9940   verifyIndependentOfContext("int a = b * (10);");
9941   verifyIndependentOfContext("S << b * (10);");
9942   verifyIndependentOfContext("return 10 * b;");
9943   verifyIndependentOfContext("return *b * *c;");
9944   verifyIndependentOfContext("return a & ~b;");
9945   verifyIndependentOfContext("f(b ? *c : *d);");
9946   verifyIndependentOfContext("int a = b ? *c : *d;");
9947   verifyIndependentOfContext("*b = a;");
9948   verifyIndependentOfContext("a * ~b;");
9949   verifyIndependentOfContext("a * !b;");
9950   verifyIndependentOfContext("a * +b;");
9951   verifyIndependentOfContext("a * -b;");
9952   verifyIndependentOfContext("a * ++b;");
9953   verifyIndependentOfContext("a * --b;");
9954   verifyIndependentOfContext("a[4] * b;");
9955   verifyIndependentOfContext("a[a * a] = 1;");
9956   verifyIndependentOfContext("f() * b;");
9957   verifyIndependentOfContext("a * [self dostuff];");
9958   verifyIndependentOfContext("int x = a * (a + b);");
9959   verifyIndependentOfContext("(a *)(a + b);");
9960   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
9961   verifyIndependentOfContext("int *pa = (int *)&a;");
9962   verifyIndependentOfContext("return sizeof(int **);");
9963   verifyIndependentOfContext("return sizeof(int ******);");
9964   verifyIndependentOfContext("return (int **&)a;");
9965   verifyIndependentOfContext("f((*PointerToArray)[10]);");
9966   verifyFormat("void f(Type (*parameter)[10]) {}");
9967   verifyFormat("void f(Type (&parameter)[10]) {}");
9968   verifyGoogleFormat("return sizeof(int**);");
9969   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
9970   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
9971   verifyFormat("auto a = [](int **&, int ***) {};");
9972   verifyFormat("auto PointerBinding = [](const char *S) {};");
9973   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
9974   verifyFormat("[](const decltype(*a) &value) {}");
9975   verifyFormat("[](const typeof(*a) &value) {}");
9976   verifyFormat("[](const _Atomic(a *) &value) {}");
9977   verifyFormat("[](const __underlying_type(a) &value) {}");
9978   verifyFormat("decltype(a * b) F();");
9979   verifyFormat("typeof(a * b) F();");
9980   verifyFormat("#define MACRO() [](A *a) { return 1; }");
9981   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
9982   verifyIndependentOfContext("typedef void (*f)(int *a);");
9983   verifyIndependentOfContext("int i{a * b};");
9984   verifyIndependentOfContext("aaa && aaa->f();");
9985   verifyIndependentOfContext("int x = ~*p;");
9986   verifyFormat("Constructor() : a(a), area(width * height) {}");
9987   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
9988   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
9989   verifyFormat("void f() { f(a, c * d); }");
9990   verifyFormat("void f() { f(new a(), c * d); }");
9991   verifyFormat("void f(const MyOverride &override);");
9992   verifyFormat("void f(const MyFinal &final);");
9993   verifyIndependentOfContext("bool a = f() && override.f();");
9994   verifyIndependentOfContext("bool a = f() && final.f();");
9995 
9996   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
9997 
9998   verifyIndependentOfContext("A<int *> a;");
9999   verifyIndependentOfContext("A<int **> a;");
10000   verifyIndependentOfContext("A<int *, int *> a;");
10001   verifyIndependentOfContext("A<int *[]> a;");
10002   verifyIndependentOfContext(
10003       "const char *const p = reinterpret_cast<const char *const>(q);");
10004   verifyIndependentOfContext("A<int **, int **> a;");
10005   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
10006   verifyFormat("for (char **a = b; *a; ++a) {\n}");
10007   verifyFormat("for (; a && b;) {\n}");
10008   verifyFormat("bool foo = true && [] { return false; }();");
10009 
10010   verifyFormat(
10011       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10012       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10013 
10014   verifyGoogleFormat("int const* a = &b;");
10015   verifyGoogleFormat("**outparam = 1;");
10016   verifyGoogleFormat("*outparam = a * b;");
10017   verifyGoogleFormat("int main(int argc, char** argv) {}");
10018   verifyGoogleFormat("A<int*> a;");
10019   verifyGoogleFormat("A<int**> a;");
10020   verifyGoogleFormat("A<int*, int*> a;");
10021   verifyGoogleFormat("A<int**, int**> a;");
10022   verifyGoogleFormat("f(b ? *c : *d);");
10023   verifyGoogleFormat("int a = b ? *c : *d;");
10024   verifyGoogleFormat("Type* t = **x;");
10025   verifyGoogleFormat("Type* t = *++*x;");
10026   verifyGoogleFormat("*++*x;");
10027   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
10028   verifyGoogleFormat("Type* t = x++ * y;");
10029   verifyGoogleFormat(
10030       "const char* const p = reinterpret_cast<const char* const>(q);");
10031   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
10032   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
10033   verifyGoogleFormat("template <typename T>\n"
10034                      "void f(int i = 0, SomeType** temps = NULL);");
10035 
10036   FormatStyle Left = getLLVMStyle();
10037   Left.PointerAlignment = FormatStyle::PAS_Left;
10038   verifyFormat("x = *a(x) = *a(y);", Left);
10039   verifyFormat("for (;; *a = b) {\n}", Left);
10040   verifyFormat("return *this += 1;", Left);
10041   verifyFormat("throw *x;", Left);
10042   verifyFormat("delete *x;", Left);
10043   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
10044   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
10045   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
10046   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
10047   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
10048   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
10049   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
10050   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
10051   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
10052 
10053   verifyIndependentOfContext("a = *(x + y);");
10054   verifyIndependentOfContext("a = &(x + y);");
10055   verifyIndependentOfContext("*(x + y).call();");
10056   verifyIndependentOfContext("&(x + y)->call();");
10057   verifyFormat("void f() { &(*I).first; }");
10058 
10059   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
10060   verifyFormat("f(* /* confusing comment */ foo);");
10061   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
10062   verifyFormat("void foo(int * // this is the first paramters\n"
10063                "         ,\n"
10064                "         int second);");
10065   verifyFormat("double term = a * // first\n"
10066                "              b;");
10067   verifyFormat(
10068       "int *MyValues = {\n"
10069       "    *A, // Operator detection might be confused by the '{'\n"
10070       "    *BB // Operator detection might be confused by previous comment\n"
10071       "};");
10072 
10073   verifyIndependentOfContext("if (int *a = &b)");
10074   verifyIndependentOfContext("if (int &a = *b)");
10075   verifyIndependentOfContext("if (a & b[i])");
10076   verifyIndependentOfContext("if constexpr (a & b[i])");
10077   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
10078   verifyIndependentOfContext("if (a * (b * c))");
10079   verifyIndependentOfContext("if constexpr (a * (b * c))");
10080   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
10081   verifyIndependentOfContext("if (a::b::c::d & b[i])");
10082   verifyIndependentOfContext("if (*b[i])");
10083   verifyIndependentOfContext("if (int *a = (&b))");
10084   verifyIndependentOfContext("while (int *a = &b)");
10085   verifyIndependentOfContext("while (a * (b * c))");
10086   verifyIndependentOfContext("size = sizeof *a;");
10087   verifyIndependentOfContext("if (a && (b = c))");
10088   verifyFormat("void f() {\n"
10089                "  for (const int &v : Values) {\n"
10090                "  }\n"
10091                "}");
10092   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
10093   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
10094   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
10095 
10096   verifyFormat("#define A (!a * b)");
10097   verifyFormat("#define MACRO     \\\n"
10098                "  int *i = a * b; \\\n"
10099                "  void f(a *b);",
10100                getLLVMStyleWithColumns(19));
10101 
10102   verifyIndependentOfContext("A = new SomeType *[Length];");
10103   verifyIndependentOfContext("A = new SomeType *[Length]();");
10104   verifyIndependentOfContext("T **t = new T *;");
10105   verifyIndependentOfContext("T **t = new T *();");
10106   verifyGoogleFormat("A = new SomeType*[Length]();");
10107   verifyGoogleFormat("A = new SomeType*[Length];");
10108   verifyGoogleFormat("T** t = new T*;");
10109   verifyGoogleFormat("T** t = new T*();");
10110 
10111   verifyFormat("STATIC_ASSERT((a & b) == 0);");
10112   verifyFormat("STATIC_ASSERT(0 == (a & b));");
10113   verifyFormat("template <bool a, bool b> "
10114                "typename t::if<x && y>::type f() {}");
10115   verifyFormat("template <int *y> f() {}");
10116   verifyFormat("vector<int *> v;");
10117   verifyFormat("vector<int *const> v;");
10118   verifyFormat("vector<int *const **const *> v;");
10119   verifyFormat("vector<int *volatile> v;");
10120   verifyFormat("vector<a *_Nonnull> v;");
10121   verifyFormat("vector<a *_Nullable> v;");
10122   verifyFormat("vector<a *_Null_unspecified> v;");
10123   verifyFormat("vector<a *__ptr32> v;");
10124   verifyFormat("vector<a *__ptr64> v;");
10125   verifyFormat("vector<a *__capability> v;");
10126   FormatStyle TypeMacros = getLLVMStyle();
10127   TypeMacros.TypenameMacros = {"LIST"};
10128   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
10129   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
10130   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
10131   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
10132   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
10133 
10134   FormatStyle CustomQualifier = getLLVMStyle();
10135   // Add identifiers that should not be parsed as a qualifier by default.
10136   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10137   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
10138   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
10139   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
10140   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
10141   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
10142   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
10143   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
10144   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
10145   verifyFormat("vector<a * _NotAQualifier> v;");
10146   verifyFormat("vector<a * __not_a_qualifier> v;");
10147   verifyFormat("vector<a * b> v;");
10148   verifyFormat("foo<b && false>();");
10149   verifyFormat("foo<b & 1>();");
10150   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
10151   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
10152   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
10153   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
10154   verifyFormat(
10155       "template <class T, class = typename std::enable_if<\n"
10156       "                       std::is_integral<T>::value &&\n"
10157       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
10158       "void F();",
10159       getLLVMStyleWithColumns(70));
10160   verifyFormat("template <class T,\n"
10161                "          class = typename std::enable_if<\n"
10162                "              std::is_integral<T>::value &&\n"
10163                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
10164                "          class U>\n"
10165                "void F();",
10166                getLLVMStyleWithColumns(70));
10167   verifyFormat(
10168       "template <class T,\n"
10169       "          class = typename ::std::enable_if<\n"
10170       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
10171       "void F();",
10172       getGoogleStyleWithColumns(68));
10173 
10174   verifyIndependentOfContext("MACRO(int *i);");
10175   verifyIndependentOfContext("MACRO(auto *a);");
10176   verifyIndependentOfContext("MACRO(const A *a);");
10177   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
10178   verifyIndependentOfContext("MACRO(decltype(A) *a);");
10179   verifyIndependentOfContext("MACRO(typeof(A) *a);");
10180   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
10181   verifyIndependentOfContext("MACRO(A *const a);");
10182   verifyIndependentOfContext("MACRO(A *restrict a);");
10183   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
10184   verifyIndependentOfContext("MACRO(A *__restrict a);");
10185   verifyIndependentOfContext("MACRO(A *volatile a);");
10186   verifyIndependentOfContext("MACRO(A *__volatile a);");
10187   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
10188   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
10189   verifyIndependentOfContext("MACRO(A *_Nullable a);");
10190   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
10191   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
10192   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
10193   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
10194   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
10195   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
10196   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
10197   verifyIndependentOfContext("MACRO(A *__capability);");
10198   verifyIndependentOfContext("MACRO(A &__capability);");
10199   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
10200   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
10201   // If we add __my_qualifier to AttributeMacros it should always be parsed as
10202   // a type declaration:
10203   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
10204   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
10205   // Also check that TypenameMacros prevents parsing it as multiplication:
10206   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
10207   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
10208 
10209   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
10210   verifyFormat("void f() { f(float{1}, a * a); }");
10211   verifyFormat("void f() { f(float(1), a * a); }");
10212 
10213   verifyFormat("f((void (*)(int))g);");
10214   verifyFormat("f((void (&)(int))g);");
10215   verifyFormat("f((void (^)(int))g);");
10216 
10217   // FIXME: Is there a way to make this work?
10218   // verifyIndependentOfContext("MACRO(A *a);");
10219   verifyFormat("MACRO(A &B);");
10220   verifyFormat("MACRO(A *B);");
10221   verifyFormat("void f() { MACRO(A * B); }");
10222   verifyFormat("void f() { MACRO(A & B); }");
10223 
10224   // This lambda was mis-formatted after D88956 (treating it as a binop):
10225   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
10226   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
10227   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
10228   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
10229 
10230   verifyFormat("DatumHandle const *operator->() const { return input_; }");
10231   verifyFormat("return options != nullptr && operator==(*options);");
10232 
10233   EXPECT_EQ("#define OP(x)                                    \\\n"
10234             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
10235             "    return s << a.DebugString();                 \\\n"
10236             "  }",
10237             format("#define OP(x) \\\n"
10238                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
10239                    "    return s << a.DebugString(); \\\n"
10240                    "  }",
10241                    getLLVMStyleWithColumns(50)));
10242 
10243   // FIXME: We cannot handle this case yet; we might be able to figure out that
10244   // foo<x> d > v; doesn't make sense.
10245   verifyFormat("foo<a<b && c> d> v;");
10246 
10247   FormatStyle PointerMiddle = getLLVMStyle();
10248   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10249   verifyFormat("delete *x;", PointerMiddle);
10250   verifyFormat("int * x;", PointerMiddle);
10251   verifyFormat("int *[] x;", PointerMiddle);
10252   verifyFormat("template <int * y> f() {}", PointerMiddle);
10253   verifyFormat("int * f(int * a) {}", PointerMiddle);
10254   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
10255   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10256   verifyFormat("A<int *> a;", PointerMiddle);
10257   verifyFormat("A<int **> a;", PointerMiddle);
10258   verifyFormat("A<int *, int *> a;", PointerMiddle);
10259   verifyFormat("A<int *[]> a;", PointerMiddle);
10260   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10261   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10262   verifyFormat("T ** t = new T *;", PointerMiddle);
10263 
10264   // Member function reference qualifiers aren't binary operators.
10265   verifyFormat("string // break\n"
10266                "operator()() & {}");
10267   verifyFormat("string // break\n"
10268                "operator()() && {}");
10269   verifyGoogleFormat("template <typename T>\n"
10270                      "auto x() & -> int {}");
10271 
10272   // Should be binary operators when used as an argument expression (overloaded
10273   // operator invoked as a member function).
10274   verifyFormat("void f() { a.operator()(a * a); }");
10275   verifyFormat("void f() { a->operator()(a & a); }");
10276   verifyFormat("void f() { a.operator()(*a & *a); }");
10277   verifyFormat("void f() { a->operator()(*a * *a); }");
10278 
10279   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10280   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10281 }
10282 
10283 TEST_F(FormatTest, UnderstandsAttributes) {
10284   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10285   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10286                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10287   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10288   FormatStyle AfterType = getLLVMStyle();
10289   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10290   verifyFormat("__attribute__((nodebug)) void\n"
10291                "foo() {}\n",
10292                AfterType);
10293   verifyFormat("__unused void\n"
10294                "foo() {}",
10295                AfterType);
10296 
10297   FormatStyle CustomAttrs = getLLVMStyle();
10298   CustomAttrs.AttributeMacros.push_back("__unused");
10299   CustomAttrs.AttributeMacros.push_back("__attr1");
10300   CustomAttrs.AttributeMacros.push_back("__attr2");
10301   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10302   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10303   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10304   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10305   // Check that it is parsed as a multiplication without AttributeMacros and
10306   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10307   verifyFormat("vector<SomeType * __attr1> v;");
10308   verifyFormat("vector<SomeType __attr1 *> v;");
10309   verifyFormat("vector<SomeType __attr1 *const> v;");
10310   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10311   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10312   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10313   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10314   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10315   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10316   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10317   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10318 
10319   // Check that these are not parsed as function declarations:
10320   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10321   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10322   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10323   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10324   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10325   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10326   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10327   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10328   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10329   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10330 }
10331 
10332 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10333   // Check that qualifiers on pointers don't break parsing of casts.
10334   verifyFormat("x = (foo *const)*v;");
10335   verifyFormat("x = (foo *volatile)*v;");
10336   verifyFormat("x = (foo *restrict)*v;");
10337   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10338   verifyFormat("x = (foo *_Nonnull)*v;");
10339   verifyFormat("x = (foo *_Nullable)*v;");
10340   verifyFormat("x = (foo *_Null_unspecified)*v;");
10341   verifyFormat("x = (foo *_Nonnull)*v;");
10342   verifyFormat("x = (foo *[[clang::attr]])*v;");
10343   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10344   verifyFormat("x = (foo *__ptr32)*v;");
10345   verifyFormat("x = (foo *__ptr64)*v;");
10346   verifyFormat("x = (foo *__capability)*v;");
10347 
10348   // Check that we handle multiple trailing qualifiers and skip them all to
10349   // determine that the expression is a cast to a pointer type.
10350   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10351   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10352   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10353   StringRef AllQualifiers =
10354       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10355       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10356   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10357   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10358 
10359   // Also check that address-of is not parsed as a binary bitwise-and:
10360   verifyFormat("x = (foo *const)&v;");
10361   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10362   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10363 
10364   // Check custom qualifiers:
10365   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10366   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10367   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10368   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10369   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10370                CustomQualifier);
10371   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10372                CustomQualifier);
10373 
10374   // Check that unknown identifiers result in binary operator parsing:
10375   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10376   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10377 }
10378 
10379 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10380   verifyFormat("SomeType s [[unused]] (InitValue);");
10381   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10382   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10383   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10384   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10385   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10386                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10387   verifyFormat("[[nodiscard]] bool f() { return false; }");
10388   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10389   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10390   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10391   verifyFormat("[[nodiscard]] ::qualified_type f();");
10392 
10393   // Make sure we do not mistake attributes for array subscripts.
10394   verifyFormat("int a() {}\n"
10395                "[[unused]] int b() {}\n");
10396   verifyFormat("NSArray *arr;\n"
10397                "arr[[Foo() bar]];");
10398 
10399   // On the other hand, we still need to correctly find array subscripts.
10400   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10401 
10402   // Make sure that we do not mistake Objective-C method inside array literals
10403   // as attributes, even if those method names are also keywords.
10404   verifyFormat("@[ [foo bar] ];");
10405   verifyFormat("@[ [NSArray class] ];");
10406   verifyFormat("@[ [foo enum] ];");
10407 
10408   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10409 
10410   // Make sure we do not parse attributes as lambda introducers.
10411   FormatStyle MultiLineFunctions = getLLVMStyle();
10412   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10413   verifyFormat("[[unused]] int b() {\n"
10414                "  return 42;\n"
10415                "}\n",
10416                MultiLineFunctions);
10417 }
10418 
10419 TEST_F(FormatTest, AttributeClass) {
10420   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10421   verifyFormat("class S {\n"
10422                "  S(S&&) = default;\n"
10423                "};",
10424                Style);
10425   verifyFormat("class [[nodiscard]] S {\n"
10426                "  S(S&&) = default;\n"
10427                "};",
10428                Style);
10429   verifyFormat("class __attribute((maybeunused)) S {\n"
10430                "  S(S&&) = default;\n"
10431                "};",
10432                Style);
10433   verifyFormat("struct S {\n"
10434                "  S(S&&) = default;\n"
10435                "};",
10436                Style);
10437   verifyFormat("struct [[nodiscard]] S {\n"
10438                "  S(S&&) = default;\n"
10439                "};",
10440                Style);
10441 }
10442 
10443 TEST_F(FormatTest, AttributesAfterMacro) {
10444   FormatStyle Style = getLLVMStyle();
10445   verifyFormat("MACRO;\n"
10446                "__attribute__((maybe_unused)) int foo() {\n"
10447                "  //...\n"
10448                "}");
10449 
10450   verifyFormat("MACRO;\n"
10451                "[[nodiscard]] int foo() {\n"
10452                "  //...\n"
10453                "}");
10454 
10455   EXPECT_EQ("MACRO\n\n"
10456             "__attribute__((maybe_unused)) int foo() {\n"
10457             "  //...\n"
10458             "}",
10459             format("MACRO\n\n"
10460                    "__attribute__((maybe_unused)) int foo() {\n"
10461                    "  //...\n"
10462                    "}"));
10463 
10464   EXPECT_EQ("MACRO\n\n"
10465             "[[nodiscard]] int foo() {\n"
10466             "  //...\n"
10467             "}",
10468             format("MACRO\n\n"
10469                    "[[nodiscard]] int foo() {\n"
10470                    "  //...\n"
10471                    "}"));
10472 }
10473 
10474 TEST_F(FormatTest, AttributePenaltyBreaking) {
10475   FormatStyle Style = getLLVMStyle();
10476   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10477                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10478                Style);
10479   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10480                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10481                Style);
10482   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10483                "shared_ptr<ALongTypeName> &C d) {\n}",
10484                Style);
10485 }
10486 
10487 TEST_F(FormatTest, UnderstandsEllipsis) {
10488   FormatStyle Style = getLLVMStyle();
10489   verifyFormat("int printf(const char *fmt, ...);");
10490   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10491   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10492 
10493   verifyFormat("template <int *...PP> a;", Style);
10494 
10495   Style.PointerAlignment = FormatStyle::PAS_Left;
10496   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10497 
10498   verifyFormat("template <int*... PP> a;", Style);
10499 
10500   Style.PointerAlignment = FormatStyle::PAS_Middle;
10501   verifyFormat("template <int *... PP> a;", Style);
10502 }
10503 
10504 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10505   EXPECT_EQ("int *a;\n"
10506             "int *a;\n"
10507             "int *a;",
10508             format("int *a;\n"
10509                    "int* a;\n"
10510                    "int *a;",
10511                    getGoogleStyle()));
10512   EXPECT_EQ("int* a;\n"
10513             "int* a;\n"
10514             "int* a;",
10515             format("int* a;\n"
10516                    "int* a;\n"
10517                    "int *a;",
10518                    getGoogleStyle()));
10519   EXPECT_EQ("int *a;\n"
10520             "int *a;\n"
10521             "int *a;",
10522             format("int *a;\n"
10523                    "int * a;\n"
10524                    "int *  a;",
10525                    getGoogleStyle()));
10526   EXPECT_EQ("auto x = [] {\n"
10527             "  int *a;\n"
10528             "  int *a;\n"
10529             "  int *a;\n"
10530             "};",
10531             format("auto x=[]{int *a;\n"
10532                    "int * a;\n"
10533                    "int *  a;};",
10534                    getGoogleStyle()));
10535 }
10536 
10537 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10538   verifyFormat("int f(int &&a) {}");
10539   verifyFormat("int f(int a, char &&b) {}");
10540   verifyFormat("void f() { int &&a = b; }");
10541   verifyGoogleFormat("int f(int a, char&& b) {}");
10542   verifyGoogleFormat("void f() { int&& a = b; }");
10543 
10544   verifyIndependentOfContext("A<int &&> a;");
10545   verifyIndependentOfContext("A<int &&, int &&> a;");
10546   verifyGoogleFormat("A<int&&> a;");
10547   verifyGoogleFormat("A<int&&, int&&> a;");
10548 
10549   // Not rvalue references:
10550   verifyFormat("template <bool B, bool C> class A {\n"
10551                "  static_assert(B && C, \"Something is wrong\");\n"
10552                "};");
10553   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10554   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10555   verifyFormat("#define A(a, b) (a && b)");
10556 }
10557 
10558 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10559   verifyFormat("void f() {\n"
10560                "  x[aaaaaaaaa -\n"
10561                "    b] = 23;\n"
10562                "}",
10563                getLLVMStyleWithColumns(15));
10564 }
10565 
10566 TEST_F(FormatTest, FormatsCasts) {
10567   verifyFormat("Type *A = static_cast<Type *>(P);");
10568   verifyFormat("Type *A = (Type *)P;");
10569   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10570   verifyFormat("int a = (int)(2.0f);");
10571   verifyFormat("int a = (int)2.0f;");
10572   verifyFormat("x[(int32)y];");
10573   verifyFormat("x = (int32)y;");
10574   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10575   verifyFormat("int a = (int)*b;");
10576   verifyFormat("int a = (int)2.0f;");
10577   verifyFormat("int a = (int)~0;");
10578   verifyFormat("int a = (int)++a;");
10579   verifyFormat("int a = (int)sizeof(int);");
10580   verifyFormat("int a = (int)+2;");
10581   verifyFormat("my_int a = (my_int)2.0f;");
10582   verifyFormat("my_int a = (my_int)sizeof(int);");
10583   verifyFormat("return (my_int)aaa;");
10584   verifyFormat("#define x ((int)-1)");
10585   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10586   verifyFormat("#define p(q) ((int *)&q)");
10587   verifyFormat("fn(a)(b) + 1;");
10588 
10589   verifyFormat("void f() { my_int a = (my_int)*b; }");
10590   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10591   verifyFormat("my_int a = (my_int)~0;");
10592   verifyFormat("my_int a = (my_int)++a;");
10593   verifyFormat("my_int a = (my_int)-2;");
10594   verifyFormat("my_int a = (my_int)1;");
10595   verifyFormat("my_int a = (my_int *)1;");
10596   verifyFormat("my_int a = (const my_int)-1;");
10597   verifyFormat("my_int a = (const my_int *)-1;");
10598   verifyFormat("my_int a = (my_int)(my_int)-1;");
10599   verifyFormat("my_int a = (ns::my_int)-2;");
10600   verifyFormat("case (my_int)ONE:");
10601   verifyFormat("auto x = (X)this;");
10602   // Casts in Obj-C style calls used to not be recognized as such.
10603   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10604 
10605   // FIXME: single value wrapped with paren will be treated as cast.
10606   verifyFormat("void f(int i = (kValue)*kMask) {}");
10607 
10608   verifyFormat("{ (void)F; }");
10609 
10610   // Don't break after a cast's
10611   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10612                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10613                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10614 
10615   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10616   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10617   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10618   verifyFormat("bool *y = (bool *)(void *)(x);");
10619   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10620   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10621   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10622   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10623 
10624   // These are not casts.
10625   verifyFormat("void f(int *) {}");
10626   verifyFormat("f(foo)->b;");
10627   verifyFormat("f(foo).b;");
10628   verifyFormat("f(foo)(b);");
10629   verifyFormat("f(foo)[b];");
10630   verifyFormat("[](foo) { return 4; }(bar);");
10631   verifyFormat("(*funptr)(foo)[4];");
10632   verifyFormat("funptrs[4](foo)[4];");
10633   verifyFormat("void f(int *);");
10634   verifyFormat("void f(int *) = 0;");
10635   verifyFormat("void f(SmallVector<int>) {}");
10636   verifyFormat("void f(SmallVector<int>);");
10637   verifyFormat("void f(SmallVector<int>) = 0;");
10638   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10639   verifyFormat("int a = sizeof(int) * b;");
10640   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10641   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10642   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10643   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10644 
10645   // These are not casts, but at some point were confused with casts.
10646   verifyFormat("virtual void foo(int *) override;");
10647   verifyFormat("virtual void foo(char &) const;");
10648   verifyFormat("virtual void foo(int *a, char *) const;");
10649   verifyFormat("int a = sizeof(int *) + b;");
10650   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10651   verifyFormat("bool b = f(g<int>) && c;");
10652   verifyFormat("typedef void (*f)(int i) func;");
10653   verifyFormat("void operator++(int) noexcept;");
10654   verifyFormat("void operator++(int &) noexcept;");
10655   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10656                "&) noexcept;");
10657   verifyFormat(
10658       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10659   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10660   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10661   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10662   verifyFormat("void operator delete(foo &) noexcept;");
10663   verifyFormat("void operator delete(foo) noexcept;");
10664   verifyFormat("void operator delete(int) noexcept;");
10665   verifyFormat("void operator delete(int &) noexcept;");
10666   verifyFormat("void operator delete(int &) volatile noexcept;");
10667   verifyFormat("void operator delete(int &) const");
10668   verifyFormat("void operator delete(int &) = default");
10669   verifyFormat("void operator delete(int &) = delete");
10670   verifyFormat("void operator delete(int &) [[noreturn]]");
10671   verifyFormat("void operator delete(int &) throw();");
10672   verifyFormat("void operator delete(int &) throw(int);");
10673   verifyFormat("auto operator delete(int &) -> int;");
10674   verifyFormat("auto operator delete(int &) override");
10675   verifyFormat("auto operator delete(int &) final");
10676 
10677   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10678                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10679   // FIXME: The indentation here is not ideal.
10680   verifyFormat(
10681       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10682       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10683       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10684 }
10685 
10686 TEST_F(FormatTest, FormatsFunctionTypes) {
10687   verifyFormat("A<bool()> a;");
10688   verifyFormat("A<SomeType()> a;");
10689   verifyFormat("A<void (*)(int, std::string)> a;");
10690   verifyFormat("A<void *(int)>;");
10691   verifyFormat("void *(*a)(int *, SomeType *);");
10692   verifyFormat("int (*func)(void *);");
10693   verifyFormat("void f() { int (*func)(void *); }");
10694   verifyFormat("template <class CallbackClass>\n"
10695                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10696 
10697   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10698   verifyGoogleFormat("void* (*a)(int);");
10699   verifyGoogleFormat(
10700       "template <class CallbackClass>\n"
10701       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10702 
10703   // Other constructs can look somewhat like function types:
10704   verifyFormat("A<sizeof(*x)> a;");
10705   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10706   verifyFormat("some_var = function(*some_pointer_var)[0];");
10707   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10708   verifyFormat("int x = f(&h)();");
10709   verifyFormat("returnsFunction(&param1, &param2)(param);");
10710   verifyFormat("std::function<\n"
10711                "    LooooooooooongTemplatedType<\n"
10712                "        SomeType>*(\n"
10713                "        LooooooooooooooooongType type)>\n"
10714                "    function;",
10715                getGoogleStyleWithColumns(40));
10716 }
10717 
10718 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10719   verifyFormat("A (*foo_)[6];");
10720   verifyFormat("vector<int> (*foo_)[6];");
10721 }
10722 
10723 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10724   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10725                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10726   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10727                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10728   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10729                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10730 
10731   // Different ways of ()-initializiation.
10732   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10733                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10734   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10735                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10736   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10737                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10738   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10739                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10740 
10741   // Lambdas should not confuse the variable declaration heuristic.
10742   verifyFormat("LooooooooooooooooongType\n"
10743                "    variable(nullptr, [](A *a) {});",
10744                getLLVMStyleWithColumns(40));
10745 }
10746 
10747 TEST_F(FormatTest, BreaksLongDeclarations) {
10748   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10749                "    AnotherNameForTheLongType;");
10750   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10751                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10752   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10753                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10754   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10755                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10756   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10757                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10758   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10759                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10760   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10761                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10762   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10763                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10764   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10765                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10766   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10767                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10768   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10769                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10770   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10771                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10772   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10773                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10774   FormatStyle Indented = getLLVMStyle();
10775   Indented.IndentWrappedFunctionNames = true;
10776   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10777                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10778                Indented);
10779   verifyFormat(
10780       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10781       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10782       Indented);
10783   verifyFormat(
10784       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10785       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10786       Indented);
10787   verifyFormat(
10788       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10789       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10790       Indented);
10791 
10792   // FIXME: Without the comment, this breaks after "(".
10793   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10794                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10795                getGoogleStyle());
10796 
10797   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
10798                "                  int LoooooooooooooooooooongParam2) {}");
10799   verifyFormat(
10800       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
10801       "                                   SourceLocation L, IdentifierIn *II,\n"
10802       "                                   Type *T) {}");
10803   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
10804                "ReallyReaaallyLongFunctionName(\n"
10805                "    const std::string &SomeParameter,\n"
10806                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10807                "        &ReallyReallyLongParameterName,\n"
10808                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10809                "        &AnotherLongParameterName) {}");
10810   verifyFormat("template <typename A>\n"
10811                "SomeLoooooooooooooooooooooongType<\n"
10812                "    typename some_namespace::SomeOtherType<A>::Type>\n"
10813                "Function() {}");
10814 
10815   verifyGoogleFormat(
10816       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
10817       "    aaaaaaaaaaaaaaaaaaaaaaa;");
10818   verifyGoogleFormat(
10819       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
10820       "                                   SourceLocation L) {}");
10821   verifyGoogleFormat(
10822       "some_namespace::LongReturnType\n"
10823       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
10824       "    int first_long_parameter, int second_parameter) {}");
10825 
10826   verifyGoogleFormat("template <typename T>\n"
10827                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10828                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
10829   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10830                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
10831 
10832   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
10833                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10834                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10835   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10836                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10837                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
10838   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10839                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
10840                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
10841                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10842 
10843   verifyFormat("template <typename T> // Templates on own line.\n"
10844                "static int            // Some comment.\n"
10845                "MyFunction(int a);",
10846                getLLVMStyle());
10847 }
10848 
10849 TEST_F(FormatTest, FormatsAccessModifiers) {
10850   FormatStyle Style = getLLVMStyle();
10851   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
10852             FormatStyle::ELBAMS_LogicalBlock);
10853   verifyFormat("struct foo {\n"
10854                "private:\n"
10855                "  void f() {}\n"
10856                "\n"
10857                "private:\n"
10858                "  int i;\n"
10859                "\n"
10860                "protected:\n"
10861                "  int j;\n"
10862                "};\n",
10863                Style);
10864   verifyFormat("struct foo {\n"
10865                "private:\n"
10866                "  void f() {}\n"
10867                "\n"
10868                "private:\n"
10869                "  int i;\n"
10870                "\n"
10871                "protected:\n"
10872                "  int j;\n"
10873                "};\n",
10874                "struct foo {\n"
10875                "private:\n"
10876                "  void f() {}\n"
10877                "private:\n"
10878                "  int i;\n"
10879                "protected:\n"
10880                "  int j;\n"
10881                "};\n",
10882                Style);
10883   verifyFormat("struct foo { /* comment */\n"
10884                "private:\n"
10885                "  int i;\n"
10886                "  // comment\n"
10887                "private:\n"
10888                "  int j;\n"
10889                "};\n",
10890                Style);
10891   verifyFormat("struct foo {\n"
10892                "#ifdef FOO\n"
10893                "#endif\n"
10894                "private:\n"
10895                "  int i;\n"
10896                "#ifdef FOO\n"
10897                "private:\n"
10898                "#endif\n"
10899                "  int j;\n"
10900                "};\n",
10901                Style);
10902   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10903   verifyFormat("struct foo {\n"
10904                "private:\n"
10905                "  void f() {}\n"
10906                "private:\n"
10907                "  int i;\n"
10908                "protected:\n"
10909                "  int j;\n"
10910                "};\n",
10911                Style);
10912   verifyFormat("struct foo {\n"
10913                "private:\n"
10914                "  void f() {}\n"
10915                "private:\n"
10916                "  int i;\n"
10917                "protected:\n"
10918                "  int j;\n"
10919                "};\n",
10920                "struct foo {\n"
10921                "\n"
10922                "private:\n"
10923                "  void f() {}\n"
10924                "\n"
10925                "private:\n"
10926                "  int i;\n"
10927                "\n"
10928                "protected:\n"
10929                "  int j;\n"
10930                "};\n",
10931                Style);
10932   verifyFormat("struct foo { /* comment */\n"
10933                "private:\n"
10934                "  int i;\n"
10935                "  // comment\n"
10936                "private:\n"
10937                "  int j;\n"
10938                "};\n",
10939                "struct foo { /* comment */\n"
10940                "\n"
10941                "private:\n"
10942                "  int i;\n"
10943                "  // comment\n"
10944                "\n"
10945                "private:\n"
10946                "  int j;\n"
10947                "};\n",
10948                Style);
10949   verifyFormat("struct foo {\n"
10950                "#ifdef FOO\n"
10951                "#endif\n"
10952                "private:\n"
10953                "  int i;\n"
10954                "#ifdef FOO\n"
10955                "private:\n"
10956                "#endif\n"
10957                "  int j;\n"
10958                "};\n",
10959                "struct foo {\n"
10960                "#ifdef FOO\n"
10961                "#endif\n"
10962                "\n"
10963                "private:\n"
10964                "  int i;\n"
10965                "#ifdef FOO\n"
10966                "\n"
10967                "private:\n"
10968                "#endif\n"
10969                "  int j;\n"
10970                "};\n",
10971                Style);
10972   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10973   verifyFormat("struct foo {\n"
10974                "private:\n"
10975                "  void f() {}\n"
10976                "\n"
10977                "private:\n"
10978                "  int i;\n"
10979                "\n"
10980                "protected:\n"
10981                "  int j;\n"
10982                "};\n",
10983                Style);
10984   verifyFormat("struct foo {\n"
10985                "private:\n"
10986                "  void f() {}\n"
10987                "\n"
10988                "private:\n"
10989                "  int i;\n"
10990                "\n"
10991                "protected:\n"
10992                "  int j;\n"
10993                "};\n",
10994                "struct foo {\n"
10995                "private:\n"
10996                "  void f() {}\n"
10997                "private:\n"
10998                "  int i;\n"
10999                "protected:\n"
11000                "  int j;\n"
11001                "};\n",
11002                Style);
11003   verifyFormat("struct foo { /* comment */\n"
11004                "private:\n"
11005                "  int i;\n"
11006                "  // comment\n"
11007                "\n"
11008                "private:\n"
11009                "  int j;\n"
11010                "};\n",
11011                "struct foo { /* comment */\n"
11012                "private:\n"
11013                "  int i;\n"
11014                "  // comment\n"
11015                "\n"
11016                "private:\n"
11017                "  int j;\n"
11018                "};\n",
11019                Style);
11020   verifyFormat("struct foo {\n"
11021                "#ifdef FOO\n"
11022                "#endif\n"
11023                "\n"
11024                "private:\n"
11025                "  int i;\n"
11026                "#ifdef FOO\n"
11027                "\n"
11028                "private:\n"
11029                "#endif\n"
11030                "  int j;\n"
11031                "};\n",
11032                "struct foo {\n"
11033                "#ifdef FOO\n"
11034                "#endif\n"
11035                "private:\n"
11036                "  int i;\n"
11037                "#ifdef FOO\n"
11038                "private:\n"
11039                "#endif\n"
11040                "  int j;\n"
11041                "};\n",
11042                Style);
11043   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11044   EXPECT_EQ("struct foo {\n"
11045             "\n"
11046             "private:\n"
11047             "  void f() {}\n"
11048             "\n"
11049             "private:\n"
11050             "  int i;\n"
11051             "\n"
11052             "protected:\n"
11053             "  int j;\n"
11054             "};\n",
11055             format("struct foo {\n"
11056                    "\n"
11057                    "private:\n"
11058                    "  void f() {}\n"
11059                    "\n"
11060                    "private:\n"
11061                    "  int i;\n"
11062                    "\n"
11063                    "protected:\n"
11064                    "  int j;\n"
11065                    "};\n",
11066                    Style));
11067   verifyFormat("struct foo {\n"
11068                "private:\n"
11069                "  void f() {}\n"
11070                "private:\n"
11071                "  int i;\n"
11072                "protected:\n"
11073                "  int j;\n"
11074                "};\n",
11075                Style);
11076   EXPECT_EQ("struct foo { /* comment */\n"
11077             "\n"
11078             "private:\n"
11079             "  int i;\n"
11080             "  // comment\n"
11081             "\n"
11082             "private:\n"
11083             "  int j;\n"
11084             "};\n",
11085             format("struct foo { /* comment */\n"
11086                    "\n"
11087                    "private:\n"
11088                    "  int i;\n"
11089                    "  // comment\n"
11090                    "\n"
11091                    "private:\n"
11092                    "  int j;\n"
11093                    "};\n",
11094                    Style));
11095   verifyFormat("struct foo { /* comment */\n"
11096                "private:\n"
11097                "  int i;\n"
11098                "  // comment\n"
11099                "private:\n"
11100                "  int j;\n"
11101                "};\n",
11102                Style);
11103   EXPECT_EQ("struct foo {\n"
11104             "#ifdef FOO\n"
11105             "#endif\n"
11106             "\n"
11107             "private:\n"
11108             "  int i;\n"
11109             "#ifdef FOO\n"
11110             "\n"
11111             "private:\n"
11112             "#endif\n"
11113             "  int j;\n"
11114             "};\n",
11115             format("struct foo {\n"
11116                    "#ifdef FOO\n"
11117                    "#endif\n"
11118                    "\n"
11119                    "private:\n"
11120                    "  int i;\n"
11121                    "#ifdef FOO\n"
11122                    "\n"
11123                    "private:\n"
11124                    "#endif\n"
11125                    "  int j;\n"
11126                    "};\n",
11127                    Style));
11128   verifyFormat("struct foo {\n"
11129                "#ifdef FOO\n"
11130                "#endif\n"
11131                "private:\n"
11132                "  int i;\n"
11133                "#ifdef FOO\n"
11134                "private:\n"
11135                "#endif\n"
11136                "  int j;\n"
11137                "};\n",
11138                Style);
11139 
11140   FormatStyle NoEmptyLines = getLLVMStyle();
11141   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11142   verifyFormat("struct foo {\n"
11143                "private:\n"
11144                "  void f() {}\n"
11145                "\n"
11146                "private:\n"
11147                "  int i;\n"
11148                "\n"
11149                "public:\n"
11150                "protected:\n"
11151                "  int j;\n"
11152                "};\n",
11153                NoEmptyLines);
11154 
11155   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11156   verifyFormat("struct foo {\n"
11157                "private:\n"
11158                "  void f() {}\n"
11159                "private:\n"
11160                "  int i;\n"
11161                "public:\n"
11162                "protected:\n"
11163                "  int j;\n"
11164                "};\n",
11165                NoEmptyLines);
11166 
11167   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11168   verifyFormat("struct foo {\n"
11169                "private:\n"
11170                "  void f() {}\n"
11171                "\n"
11172                "private:\n"
11173                "  int i;\n"
11174                "\n"
11175                "public:\n"
11176                "\n"
11177                "protected:\n"
11178                "  int j;\n"
11179                "};\n",
11180                NoEmptyLines);
11181 }
11182 
11183 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
11184 
11185   FormatStyle Style = getLLVMStyle();
11186   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
11187   verifyFormat("struct foo {\n"
11188                "private:\n"
11189                "  void f() {}\n"
11190                "\n"
11191                "private:\n"
11192                "  int i;\n"
11193                "\n"
11194                "protected:\n"
11195                "  int j;\n"
11196                "};\n",
11197                Style);
11198 
11199   // Check if lines are removed.
11200   verifyFormat("struct foo {\n"
11201                "private:\n"
11202                "  void f() {}\n"
11203                "\n"
11204                "private:\n"
11205                "  int i;\n"
11206                "\n"
11207                "protected:\n"
11208                "  int j;\n"
11209                "};\n",
11210                "struct foo {\n"
11211                "private:\n"
11212                "\n"
11213                "  void f() {}\n"
11214                "\n"
11215                "private:\n"
11216                "\n"
11217                "  int i;\n"
11218                "\n"
11219                "protected:\n"
11220                "\n"
11221                "  int j;\n"
11222                "};\n",
11223                Style);
11224 
11225   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11226   verifyFormat("struct foo {\n"
11227                "private:\n"
11228                "\n"
11229                "  void f() {}\n"
11230                "\n"
11231                "private:\n"
11232                "\n"
11233                "  int i;\n"
11234                "\n"
11235                "protected:\n"
11236                "\n"
11237                "  int j;\n"
11238                "};\n",
11239                Style);
11240 
11241   // Check if lines are added.
11242   verifyFormat("struct foo {\n"
11243                "private:\n"
11244                "\n"
11245                "  void f() {}\n"
11246                "\n"
11247                "private:\n"
11248                "\n"
11249                "  int i;\n"
11250                "\n"
11251                "protected:\n"
11252                "\n"
11253                "  int j;\n"
11254                "};\n",
11255                "struct foo {\n"
11256                "private:\n"
11257                "  void f() {}\n"
11258                "\n"
11259                "private:\n"
11260                "  int i;\n"
11261                "\n"
11262                "protected:\n"
11263                "  int j;\n"
11264                "};\n",
11265                Style);
11266 
11267   // Leave tests rely on the code layout, test::messUp can not be used.
11268   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11269   Style.MaxEmptyLinesToKeep = 0u;
11270   verifyFormat("struct foo {\n"
11271                "private:\n"
11272                "  void f() {}\n"
11273                "\n"
11274                "private:\n"
11275                "  int i;\n"
11276                "\n"
11277                "protected:\n"
11278                "  int j;\n"
11279                "};\n",
11280                Style);
11281 
11282   // Check if MaxEmptyLinesToKeep is respected.
11283   EXPECT_EQ("struct foo {\n"
11284             "private:\n"
11285             "  void f() {}\n"
11286             "\n"
11287             "private:\n"
11288             "  int i;\n"
11289             "\n"
11290             "protected:\n"
11291             "  int j;\n"
11292             "};\n",
11293             format("struct foo {\n"
11294                    "private:\n"
11295                    "\n\n\n"
11296                    "  void f() {}\n"
11297                    "\n"
11298                    "private:\n"
11299                    "\n\n\n"
11300                    "  int i;\n"
11301                    "\n"
11302                    "protected:\n"
11303                    "\n\n\n"
11304                    "  int j;\n"
11305                    "};\n",
11306                    Style));
11307 
11308   Style.MaxEmptyLinesToKeep = 1u;
11309   EXPECT_EQ("struct foo {\n"
11310             "private:\n"
11311             "\n"
11312             "  void f() {}\n"
11313             "\n"
11314             "private:\n"
11315             "\n"
11316             "  int i;\n"
11317             "\n"
11318             "protected:\n"
11319             "\n"
11320             "  int j;\n"
11321             "};\n",
11322             format("struct foo {\n"
11323                    "private:\n"
11324                    "\n"
11325                    "  void f() {}\n"
11326                    "\n"
11327                    "private:\n"
11328                    "\n"
11329                    "  int i;\n"
11330                    "\n"
11331                    "protected:\n"
11332                    "\n"
11333                    "  int j;\n"
11334                    "};\n",
11335                    Style));
11336   // Check if no lines are kept.
11337   EXPECT_EQ("struct foo {\n"
11338             "private:\n"
11339             "  void f() {}\n"
11340             "\n"
11341             "private:\n"
11342             "  int i;\n"
11343             "\n"
11344             "protected:\n"
11345             "  int j;\n"
11346             "};\n",
11347             format("struct foo {\n"
11348                    "private:\n"
11349                    "  void f() {}\n"
11350                    "\n"
11351                    "private:\n"
11352                    "  int i;\n"
11353                    "\n"
11354                    "protected:\n"
11355                    "  int j;\n"
11356                    "};\n",
11357                    Style));
11358   // Check if MaxEmptyLinesToKeep is respected.
11359   EXPECT_EQ("struct foo {\n"
11360             "private:\n"
11361             "\n"
11362             "  void f() {}\n"
11363             "\n"
11364             "private:\n"
11365             "\n"
11366             "  int i;\n"
11367             "\n"
11368             "protected:\n"
11369             "\n"
11370             "  int j;\n"
11371             "};\n",
11372             format("struct foo {\n"
11373                    "private:\n"
11374                    "\n\n\n"
11375                    "  void f() {}\n"
11376                    "\n"
11377                    "private:\n"
11378                    "\n\n\n"
11379                    "  int i;\n"
11380                    "\n"
11381                    "protected:\n"
11382                    "\n\n\n"
11383                    "  int j;\n"
11384                    "};\n",
11385                    Style));
11386 
11387   Style.MaxEmptyLinesToKeep = 10u;
11388   EXPECT_EQ("struct foo {\n"
11389             "private:\n"
11390             "\n\n\n"
11391             "  void f() {}\n"
11392             "\n"
11393             "private:\n"
11394             "\n\n\n"
11395             "  int i;\n"
11396             "\n"
11397             "protected:\n"
11398             "\n\n\n"
11399             "  int j;\n"
11400             "};\n",
11401             format("struct foo {\n"
11402                    "private:\n"
11403                    "\n\n\n"
11404                    "  void f() {}\n"
11405                    "\n"
11406                    "private:\n"
11407                    "\n\n\n"
11408                    "  int i;\n"
11409                    "\n"
11410                    "protected:\n"
11411                    "\n\n\n"
11412                    "  int j;\n"
11413                    "};\n",
11414                    Style));
11415 
11416   // Test with comments.
11417   Style = getLLVMStyle();
11418   verifyFormat("struct foo {\n"
11419                "private:\n"
11420                "  // comment\n"
11421                "  void f() {}\n"
11422                "\n"
11423                "private: /* comment */\n"
11424                "  int i;\n"
11425                "};\n",
11426                Style);
11427   verifyFormat("struct foo {\n"
11428                "private:\n"
11429                "  // comment\n"
11430                "  void f() {}\n"
11431                "\n"
11432                "private: /* comment */\n"
11433                "  int i;\n"
11434                "};\n",
11435                "struct foo {\n"
11436                "private:\n"
11437                "\n"
11438                "  // comment\n"
11439                "  void f() {}\n"
11440                "\n"
11441                "private: /* comment */\n"
11442                "\n"
11443                "  int i;\n"
11444                "};\n",
11445                Style);
11446 
11447   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11448   verifyFormat("struct foo {\n"
11449                "private:\n"
11450                "\n"
11451                "  // comment\n"
11452                "  void f() {}\n"
11453                "\n"
11454                "private: /* comment */\n"
11455                "\n"
11456                "  int i;\n"
11457                "};\n",
11458                "struct foo {\n"
11459                "private:\n"
11460                "  // comment\n"
11461                "  void f() {}\n"
11462                "\n"
11463                "private: /* comment */\n"
11464                "  int i;\n"
11465                "};\n",
11466                Style);
11467   verifyFormat("struct foo {\n"
11468                "private:\n"
11469                "\n"
11470                "  // comment\n"
11471                "  void f() {}\n"
11472                "\n"
11473                "private: /* comment */\n"
11474                "\n"
11475                "  int i;\n"
11476                "};\n",
11477                Style);
11478 
11479   // Test with preprocessor defines.
11480   Style = getLLVMStyle();
11481   verifyFormat("struct foo {\n"
11482                "private:\n"
11483                "#ifdef FOO\n"
11484                "#endif\n"
11485                "  void f() {}\n"
11486                "};\n",
11487                Style);
11488   verifyFormat("struct foo {\n"
11489                "private:\n"
11490                "#ifdef FOO\n"
11491                "#endif\n"
11492                "  void f() {}\n"
11493                "};\n",
11494                "struct foo {\n"
11495                "private:\n"
11496                "\n"
11497                "#ifdef FOO\n"
11498                "#endif\n"
11499                "  void f() {}\n"
11500                "};\n",
11501                Style);
11502 
11503   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11504   verifyFormat("struct foo {\n"
11505                "private:\n"
11506                "\n"
11507                "#ifdef FOO\n"
11508                "#endif\n"
11509                "  void f() {}\n"
11510                "};\n",
11511                "struct foo {\n"
11512                "private:\n"
11513                "#ifdef FOO\n"
11514                "#endif\n"
11515                "  void f() {}\n"
11516                "};\n",
11517                Style);
11518   verifyFormat("struct foo {\n"
11519                "private:\n"
11520                "\n"
11521                "#ifdef FOO\n"
11522                "#endif\n"
11523                "  void f() {}\n"
11524                "};\n",
11525                Style);
11526 }
11527 
11528 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11529   // Combined tests of EmptyLineAfterAccessModifier and
11530   // EmptyLineBeforeAccessModifier.
11531   FormatStyle Style = getLLVMStyle();
11532   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11533   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11534   verifyFormat("struct foo {\n"
11535                "private:\n"
11536                "\n"
11537                "protected:\n"
11538                "};\n",
11539                Style);
11540 
11541   Style.MaxEmptyLinesToKeep = 10u;
11542   // Both remove all new lines.
11543   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11544   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11545   verifyFormat("struct foo {\n"
11546                "private:\n"
11547                "protected:\n"
11548                "};\n",
11549                "struct foo {\n"
11550                "private:\n"
11551                "\n\n\n"
11552                "protected:\n"
11553                "};\n",
11554                Style);
11555 
11556   // Leave tests rely on the code layout, test::messUp can not be used.
11557   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11558   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11559   Style.MaxEmptyLinesToKeep = 10u;
11560   EXPECT_EQ("struct foo {\n"
11561             "private:\n"
11562             "\n\n\n"
11563             "protected:\n"
11564             "};\n",
11565             format("struct foo {\n"
11566                    "private:\n"
11567                    "\n\n\n"
11568                    "protected:\n"
11569                    "};\n",
11570                    Style));
11571   Style.MaxEmptyLinesToKeep = 3u;
11572   EXPECT_EQ("struct foo {\n"
11573             "private:\n"
11574             "\n\n\n"
11575             "protected:\n"
11576             "};\n",
11577             format("struct foo {\n"
11578                    "private:\n"
11579                    "\n\n\n"
11580                    "protected:\n"
11581                    "};\n",
11582                    Style));
11583   Style.MaxEmptyLinesToKeep = 1u;
11584   EXPECT_EQ("struct foo {\n"
11585             "private:\n"
11586             "\n\n\n"
11587             "protected:\n"
11588             "};\n",
11589             format("struct foo {\n"
11590                    "private:\n"
11591                    "\n\n\n"
11592                    "protected:\n"
11593                    "};\n",
11594                    Style)); // Based on new lines in original document and not
11595                             // on the setting.
11596 
11597   Style.MaxEmptyLinesToKeep = 10u;
11598   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11599   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11600   // Newlines are kept if they are greater than zero,
11601   // test::messUp removes all new lines which changes the logic
11602   EXPECT_EQ("struct foo {\n"
11603             "private:\n"
11604             "\n\n\n"
11605             "protected:\n"
11606             "};\n",
11607             format("struct foo {\n"
11608                    "private:\n"
11609                    "\n\n\n"
11610                    "protected:\n"
11611                    "};\n",
11612                    Style));
11613 
11614   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11615   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11616   // test::messUp removes all new lines which changes the logic
11617   EXPECT_EQ("struct foo {\n"
11618             "private:\n"
11619             "\n\n\n"
11620             "protected:\n"
11621             "};\n",
11622             format("struct foo {\n"
11623                    "private:\n"
11624                    "\n\n\n"
11625                    "protected:\n"
11626                    "};\n",
11627                    Style));
11628 
11629   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11630   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11631   EXPECT_EQ("struct foo {\n"
11632             "private:\n"
11633             "\n\n\n"
11634             "protected:\n"
11635             "};\n",
11636             format("struct foo {\n"
11637                    "private:\n"
11638                    "\n\n\n"
11639                    "protected:\n"
11640                    "};\n",
11641                    Style)); // test::messUp removes all new lines which changes
11642                             // the logic.
11643 
11644   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11645   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11646   verifyFormat("struct foo {\n"
11647                "private:\n"
11648                "protected:\n"
11649                "};\n",
11650                "struct foo {\n"
11651                "private:\n"
11652                "\n\n\n"
11653                "protected:\n"
11654                "};\n",
11655                Style);
11656 
11657   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11658   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11659   EXPECT_EQ("struct foo {\n"
11660             "private:\n"
11661             "\n\n\n"
11662             "protected:\n"
11663             "};\n",
11664             format("struct foo {\n"
11665                    "private:\n"
11666                    "\n\n\n"
11667                    "protected:\n"
11668                    "};\n",
11669                    Style)); // test::messUp removes all new lines which changes
11670                             // the logic.
11671 
11672   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11673   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11674   verifyFormat("struct foo {\n"
11675                "private:\n"
11676                "protected:\n"
11677                "};\n",
11678                "struct foo {\n"
11679                "private:\n"
11680                "\n\n\n"
11681                "protected:\n"
11682                "};\n",
11683                Style);
11684 
11685   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11686   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11687   verifyFormat("struct foo {\n"
11688                "private:\n"
11689                "protected:\n"
11690                "};\n",
11691                "struct foo {\n"
11692                "private:\n"
11693                "\n\n\n"
11694                "protected:\n"
11695                "};\n",
11696                Style);
11697 
11698   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11699   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11700   verifyFormat("struct foo {\n"
11701                "private:\n"
11702                "protected:\n"
11703                "};\n",
11704                "struct foo {\n"
11705                "private:\n"
11706                "\n\n\n"
11707                "protected:\n"
11708                "};\n",
11709                Style);
11710 
11711   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11712   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11713   verifyFormat("struct foo {\n"
11714                "private:\n"
11715                "protected:\n"
11716                "};\n",
11717                "struct foo {\n"
11718                "private:\n"
11719                "\n\n\n"
11720                "protected:\n"
11721                "};\n",
11722                Style);
11723 }
11724 
11725 TEST_F(FormatTest, FormatsArrays) {
11726   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11727                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11728   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11729                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11730   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11731                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11732   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11733                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11734   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11735                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11736   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11737                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11738                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11739   verifyFormat(
11740       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11741       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11742       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11743   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11744                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11745 
11746   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11747                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11748   verifyFormat(
11749       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11750       "                                  .aaaaaaa[0]\n"
11751       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11752   verifyFormat("a[::b::c];");
11753 
11754   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11755 
11756   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11757   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11758 }
11759 
11760 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11761   verifyFormat("(a)->b();");
11762   verifyFormat("--a;");
11763 }
11764 
11765 TEST_F(FormatTest, HandlesIncludeDirectives) {
11766   verifyFormat("#include <string>\n"
11767                "#include <a/b/c.h>\n"
11768                "#include \"a/b/string\"\n"
11769                "#include \"string.h\"\n"
11770                "#include \"string.h\"\n"
11771                "#include <a-a>\n"
11772                "#include < path with space >\n"
11773                "#include_next <test.h>"
11774                "#include \"abc.h\" // this is included for ABC\n"
11775                "#include \"some long include\" // with a comment\n"
11776                "#include \"some very long include path\"\n"
11777                "#include <some/very/long/include/path>\n",
11778                getLLVMStyleWithColumns(35));
11779   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11780   EXPECT_EQ("#include <a>", format("#include<a>"));
11781 
11782   verifyFormat("#import <string>");
11783   verifyFormat("#import <a/b/c.h>");
11784   verifyFormat("#import \"a/b/string\"");
11785   verifyFormat("#import \"string.h\"");
11786   verifyFormat("#import \"string.h\"");
11787   verifyFormat("#if __has_include(<strstream>)\n"
11788                "#include <strstream>\n"
11789                "#endif");
11790 
11791   verifyFormat("#define MY_IMPORT <a/b>");
11792 
11793   verifyFormat("#if __has_include(<a/b>)");
11794   verifyFormat("#if __has_include_next(<a/b>)");
11795   verifyFormat("#define F __has_include(<a/b>)");
11796   verifyFormat("#define F __has_include_next(<a/b>)");
11797 
11798   // Protocol buffer definition or missing "#".
11799   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
11800                getLLVMStyleWithColumns(30));
11801 
11802   FormatStyle Style = getLLVMStyle();
11803   Style.AlwaysBreakBeforeMultilineStrings = true;
11804   Style.ColumnLimit = 0;
11805   verifyFormat("#import \"abc.h\"", Style);
11806 
11807   // But 'import' might also be a regular C++ namespace.
11808   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11809                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11810 }
11811 
11812 //===----------------------------------------------------------------------===//
11813 // Error recovery tests.
11814 //===----------------------------------------------------------------------===//
11815 
11816 TEST_F(FormatTest, IncompleteParameterLists) {
11817   FormatStyle NoBinPacking = getLLVMStyle();
11818   NoBinPacking.BinPackParameters = false;
11819   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
11820                "                        double *min_x,\n"
11821                "                        double *max_x,\n"
11822                "                        double *min_y,\n"
11823                "                        double *max_y,\n"
11824                "                        double *min_z,\n"
11825                "                        double *max_z, ) {}",
11826                NoBinPacking);
11827 }
11828 
11829 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
11830   verifyFormat("void f() { return; }\n42");
11831   verifyFormat("void f() {\n"
11832                "  if (0)\n"
11833                "    return;\n"
11834                "}\n"
11835                "42");
11836   verifyFormat("void f() { return }\n42");
11837   verifyFormat("void f() {\n"
11838                "  if (0)\n"
11839                "    return\n"
11840                "}\n"
11841                "42");
11842 }
11843 
11844 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
11845   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
11846   EXPECT_EQ("void f() {\n"
11847             "  if (a)\n"
11848             "    return\n"
11849             "}",
11850             format("void  f  (  )  {  if  ( a )  return  }"));
11851   EXPECT_EQ("namespace N {\n"
11852             "void f()\n"
11853             "}",
11854             format("namespace  N  {  void f()  }"));
11855   EXPECT_EQ("namespace N {\n"
11856             "void f() {}\n"
11857             "void g()\n"
11858             "} // namespace N",
11859             format("namespace N  { void f( ) { } void g( ) }"));
11860 }
11861 
11862 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
11863   verifyFormat("int aaaaaaaa =\n"
11864                "    // Overlylongcomment\n"
11865                "    b;",
11866                getLLVMStyleWithColumns(20));
11867   verifyFormat("function(\n"
11868                "    ShortArgument,\n"
11869                "    LoooooooooooongArgument);\n",
11870                getLLVMStyleWithColumns(20));
11871 }
11872 
11873 TEST_F(FormatTest, IncorrectAccessSpecifier) {
11874   verifyFormat("public:");
11875   verifyFormat("class A {\n"
11876                "public\n"
11877                "  void f() {}\n"
11878                "};");
11879   verifyFormat("public\n"
11880                "int qwerty;");
11881   verifyFormat("public\n"
11882                "B {}");
11883   verifyFormat("public\n"
11884                "{}");
11885   verifyFormat("public\n"
11886                "B { int x; }");
11887 }
11888 
11889 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
11890   verifyFormat("{");
11891   verifyFormat("#})");
11892   verifyNoCrash("(/**/[:!] ?[).");
11893 }
11894 
11895 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
11896   // Found by oss-fuzz:
11897   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
11898   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
11899   Style.ColumnLimit = 60;
11900   verifyNoCrash(
11901       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
11902       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
11903       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
11904       Style);
11905 }
11906 
11907 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
11908   verifyFormat("do {\n}");
11909   verifyFormat("do {\n}\n"
11910                "f();");
11911   verifyFormat("do {\n}\n"
11912                "wheeee(fun);");
11913   verifyFormat("do {\n"
11914                "  f();\n"
11915                "}");
11916 }
11917 
11918 TEST_F(FormatTest, IncorrectCodeMissingParens) {
11919   verifyFormat("if {\n  foo;\n  foo();\n}");
11920   verifyFormat("switch {\n  foo;\n  foo();\n}");
11921   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
11922   verifyFormat("while {\n  foo;\n  foo();\n}");
11923   verifyFormat("do {\n  foo;\n  foo();\n} while;");
11924 }
11925 
11926 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
11927   verifyIncompleteFormat("namespace {\n"
11928                          "class Foo { Foo (\n"
11929                          "};\n"
11930                          "} // namespace");
11931 }
11932 
11933 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
11934   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
11935   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
11936   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
11937   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
11938 
11939   EXPECT_EQ("{\n"
11940             "  {\n"
11941             "    breakme(\n"
11942             "        qwe);\n"
11943             "  }\n",
11944             format("{\n"
11945                    "    {\n"
11946                    " breakme(qwe);\n"
11947                    "}\n",
11948                    getLLVMStyleWithColumns(10)));
11949 }
11950 
11951 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
11952   verifyFormat("int x = {\n"
11953                "    avariable,\n"
11954                "    b(alongervariable)};",
11955                getLLVMStyleWithColumns(25));
11956 }
11957 
11958 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
11959   verifyFormat("return (a)(b){1, 2, 3};");
11960 }
11961 
11962 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
11963   verifyFormat("vector<int> x{1, 2, 3, 4};");
11964   verifyFormat("vector<int> x{\n"
11965                "    1,\n"
11966                "    2,\n"
11967                "    3,\n"
11968                "    4,\n"
11969                "};");
11970   verifyFormat("vector<T> x{{}, {}, {}, {}};");
11971   verifyFormat("f({1, 2});");
11972   verifyFormat("auto v = Foo{-1};");
11973   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
11974   verifyFormat("Class::Class : member{1, 2, 3} {}");
11975   verifyFormat("new vector<int>{1, 2, 3};");
11976   verifyFormat("new int[3]{1, 2, 3};");
11977   verifyFormat("new int{1};");
11978   verifyFormat("return {arg1, arg2};");
11979   verifyFormat("return {arg1, SomeType{parameter}};");
11980   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
11981   verifyFormat("new T{arg1, arg2};");
11982   verifyFormat("f(MyMap[{composite, key}]);");
11983   verifyFormat("class Class {\n"
11984                "  T member = {arg1, arg2};\n"
11985                "};");
11986   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
11987   verifyFormat("const struct A a = {.a = 1, .b = 2};");
11988   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
11989   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
11990   verifyFormat("int a = std::is_integral<int>{} + 0;");
11991 
11992   verifyFormat("int foo(int i) { return fo1{}(i); }");
11993   verifyFormat("int foo(int i) { return fo1{}(i); }");
11994   verifyFormat("auto i = decltype(x){};");
11995   verifyFormat("auto i = typeof(x){};");
11996   verifyFormat("auto i = _Atomic(x){};");
11997   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
11998   verifyFormat("Node n{1, Node{1000}, //\n"
11999                "       2};");
12000   verifyFormat("Aaaa aaaaaaa{\n"
12001                "    {\n"
12002                "        aaaa,\n"
12003                "    },\n"
12004                "};");
12005   verifyFormat("class C : public D {\n"
12006                "  SomeClass SC{2};\n"
12007                "};");
12008   verifyFormat("class C : public A {\n"
12009                "  class D : public B {\n"
12010                "    void f() { int i{2}; }\n"
12011                "  };\n"
12012                "};");
12013   verifyFormat("#define A {a, a},");
12014   // Don't confuse braced list initializers with compound statements.
12015   verifyFormat(
12016       "class A {\n"
12017       "  A() : a{} {}\n"
12018       "  A(int b) : b(b) {}\n"
12019       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
12020       "  int a, b;\n"
12021       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
12022       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
12023       "{}\n"
12024       "};");
12025 
12026   // Avoid breaking between equal sign and opening brace
12027   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
12028   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
12029   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
12030                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
12031                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
12032                "     {\"ccccccccccccccccccccc\", 2}};",
12033                AvoidBreakingFirstArgument);
12034 
12035   // Binpacking only if there is no trailing comma
12036   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
12037                "                      cccccccccc, dddddddddd};",
12038                getLLVMStyleWithColumns(50));
12039   verifyFormat("const Aaaaaa aaaaa = {\n"
12040                "    aaaaaaaaaaa,\n"
12041                "    bbbbbbbbbbb,\n"
12042                "    ccccccccccc,\n"
12043                "    ddddddddddd,\n"
12044                "};",
12045                getLLVMStyleWithColumns(50));
12046 
12047   // Cases where distinguising braced lists and blocks is hard.
12048   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
12049   verifyFormat("void f() {\n"
12050                "  return; // comment\n"
12051                "}\n"
12052                "SomeType t;");
12053   verifyFormat("void f() {\n"
12054                "  if (a) {\n"
12055                "    f();\n"
12056                "  }\n"
12057                "}\n"
12058                "SomeType t;");
12059 
12060   // In combination with BinPackArguments = false.
12061   FormatStyle NoBinPacking = getLLVMStyle();
12062   NoBinPacking.BinPackArguments = false;
12063   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
12064                "                      bbbbb,\n"
12065                "                      ccccc,\n"
12066                "                      ddddd,\n"
12067                "                      eeeee,\n"
12068                "                      ffffff,\n"
12069                "                      ggggg,\n"
12070                "                      hhhhhh,\n"
12071                "                      iiiiii,\n"
12072                "                      jjjjjj,\n"
12073                "                      kkkkkk};",
12074                NoBinPacking);
12075   verifyFormat("const Aaaaaa aaaaa = {\n"
12076                "    aaaaa,\n"
12077                "    bbbbb,\n"
12078                "    ccccc,\n"
12079                "    ddddd,\n"
12080                "    eeeee,\n"
12081                "    ffffff,\n"
12082                "    ggggg,\n"
12083                "    hhhhhh,\n"
12084                "    iiiiii,\n"
12085                "    jjjjjj,\n"
12086                "    kkkkkk,\n"
12087                "};",
12088                NoBinPacking);
12089   verifyFormat(
12090       "const Aaaaaa aaaaa = {\n"
12091       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
12092       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
12093       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
12094       "};",
12095       NoBinPacking);
12096 
12097   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12098   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
12099             "    CDDDP83848_BMCR_REGISTER,\n"
12100             "    CDDDP83848_BMSR_REGISTER,\n"
12101             "    CDDDP83848_RBR_REGISTER};",
12102             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
12103                    "                                CDDDP83848_BMSR_REGISTER,\n"
12104                    "                                CDDDP83848_RBR_REGISTER};",
12105                    NoBinPacking));
12106 
12107   // FIXME: The alignment of these trailing comments might be bad. Then again,
12108   // this might be utterly useless in real code.
12109   verifyFormat("Constructor::Constructor()\n"
12110                "    : some_value{         //\n"
12111                "                 aaaaaaa, //\n"
12112                "                 bbbbbbb} {}");
12113 
12114   // In braced lists, the first comment is always assumed to belong to the
12115   // first element. Thus, it can be moved to the next or previous line as
12116   // appropriate.
12117   EXPECT_EQ("function({// First element:\n"
12118             "          1,\n"
12119             "          // Second element:\n"
12120             "          2});",
12121             format("function({\n"
12122                    "    // First element:\n"
12123                    "    1,\n"
12124                    "    // Second element:\n"
12125                    "    2});"));
12126   EXPECT_EQ("std::vector<int> MyNumbers{\n"
12127             "    // First element:\n"
12128             "    1,\n"
12129             "    // Second element:\n"
12130             "    2};",
12131             format("std::vector<int> MyNumbers{// First element:\n"
12132                    "                           1,\n"
12133                    "                           // Second element:\n"
12134                    "                           2};",
12135                    getLLVMStyleWithColumns(30)));
12136   // A trailing comma should still lead to an enforced line break and no
12137   // binpacking.
12138   EXPECT_EQ("vector<int> SomeVector = {\n"
12139             "    // aaa\n"
12140             "    1,\n"
12141             "    2,\n"
12142             "};",
12143             format("vector<int> SomeVector = { // aaa\n"
12144                    "    1, 2, };"));
12145 
12146   // C++11 brace initializer list l-braces should not be treated any differently
12147   // when breaking before lambda bodies is enabled
12148   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
12149   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
12150   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
12151   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
12152   verifyFormat(
12153       "std::runtime_error{\n"
12154       "    \"Long string which will force a break onto the next line...\"};",
12155       BreakBeforeLambdaBody);
12156 
12157   FormatStyle ExtraSpaces = getLLVMStyle();
12158   ExtraSpaces.Cpp11BracedListStyle = false;
12159   ExtraSpaces.ColumnLimit = 75;
12160   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
12161   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
12162   verifyFormat("f({ 1, 2 });", ExtraSpaces);
12163   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
12164   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
12165   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
12166   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
12167   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
12168   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
12169   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
12170   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
12171   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
12172   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
12173   verifyFormat("class Class {\n"
12174                "  T member = { arg1, arg2 };\n"
12175                "};",
12176                ExtraSpaces);
12177   verifyFormat(
12178       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12179       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
12180       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
12181       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
12182       ExtraSpaces);
12183   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
12184   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
12185                ExtraSpaces);
12186   verifyFormat(
12187       "someFunction(OtherParam,\n"
12188       "             BracedList{ // comment 1 (Forcing interesting break)\n"
12189       "                         param1, param2,\n"
12190       "                         // comment 2\n"
12191       "                         param3, param4 });",
12192       ExtraSpaces);
12193   verifyFormat(
12194       "std::this_thread::sleep_for(\n"
12195       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
12196       ExtraSpaces);
12197   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
12198                "    aaaaaaa,\n"
12199                "    aaaaaaaaaa,\n"
12200                "    aaaaa,\n"
12201                "    aaaaaaaaaaaaaaa,\n"
12202                "    aaa,\n"
12203                "    aaaaaaaaaa,\n"
12204                "    a,\n"
12205                "    aaaaaaaaaaaaaaaaaaaaa,\n"
12206                "    aaaaaaaaaaaa,\n"
12207                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
12208                "    aaaaaaa,\n"
12209                "    a};");
12210   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
12211   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
12212   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
12213 
12214   // Avoid breaking between initializer/equal sign and opening brace
12215   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
12216   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
12217                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12218                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12219                "  { \"ccccccccccccccccccccc\", 2 }\n"
12220                "};",
12221                ExtraSpaces);
12222   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
12223                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12224                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12225                "  { \"ccccccccccccccccccccc\", 2 }\n"
12226                "};",
12227                ExtraSpaces);
12228 
12229   FormatStyle SpaceBeforeBrace = getLLVMStyle();
12230   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
12231   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
12232   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
12233 
12234   FormatStyle SpaceBetweenBraces = getLLVMStyle();
12235   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
12236   SpaceBetweenBraces.SpacesInParentheses = true;
12237   SpaceBetweenBraces.SpacesInSquareBrackets = true;
12238   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
12239   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
12240   verifyFormat("vector< int > x{ // comment 1\n"
12241                "                 1, 2, 3, 4 };",
12242                SpaceBetweenBraces);
12243   SpaceBetweenBraces.ColumnLimit = 20;
12244   EXPECT_EQ("vector< int > x{\n"
12245             "    1, 2, 3, 4 };",
12246             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12247   SpaceBetweenBraces.ColumnLimit = 24;
12248   EXPECT_EQ("vector< int > x{ 1, 2,\n"
12249             "                 3, 4 };",
12250             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12251   EXPECT_EQ("vector< int > x{\n"
12252             "    1,\n"
12253             "    2,\n"
12254             "    3,\n"
12255             "    4,\n"
12256             "};",
12257             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12258   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12259   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12260   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12261 }
12262 
12263 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12264   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12265                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12266                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12267                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12268                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12269                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12270   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12271                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12272                "                 1, 22, 333, 4444, 55555, //\n"
12273                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12274                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12275   verifyFormat(
12276       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12277       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12278       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12279       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12280       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12281       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12282       "                 7777777};");
12283   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12284                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12285                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12286   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12287                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12288                "    // Separating comment.\n"
12289                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12290   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12291                "    // Leading comment\n"
12292                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12293                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12294   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12295                "                 1, 1, 1, 1};",
12296                getLLVMStyleWithColumns(39));
12297   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12298                "                 1, 1, 1, 1};",
12299                getLLVMStyleWithColumns(38));
12300   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12301                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12302                getLLVMStyleWithColumns(43));
12303   verifyFormat(
12304       "static unsigned SomeValues[10][3] = {\n"
12305       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12306       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12307   verifyFormat("static auto fields = new vector<string>{\n"
12308                "    \"aaaaaaaaaaaaa\",\n"
12309                "    \"aaaaaaaaaaaaa\",\n"
12310                "    \"aaaaaaaaaaaa\",\n"
12311                "    \"aaaaaaaaaaaaaa\",\n"
12312                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12313                "    \"aaaaaaaaaaaa\",\n"
12314                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12315                "};");
12316   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12317   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12318                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12319                "                 3, cccccccccccccccccccccc};",
12320                getLLVMStyleWithColumns(60));
12321 
12322   // Trailing commas.
12323   verifyFormat("vector<int> x = {\n"
12324                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12325                "};",
12326                getLLVMStyleWithColumns(39));
12327   verifyFormat("vector<int> x = {\n"
12328                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12329                "};",
12330                getLLVMStyleWithColumns(39));
12331   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12332                "                 1, 1, 1, 1,\n"
12333                "                 /**/ /**/};",
12334                getLLVMStyleWithColumns(39));
12335 
12336   // Trailing comment in the first line.
12337   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12338                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12339                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12340                "    11111111,   22222222,   333333333,   44444444};");
12341   // Trailing comment in the last line.
12342   verifyFormat("int aaaaa[] = {\n"
12343                "    1, 2, 3, // comment\n"
12344                "    4, 5, 6  // comment\n"
12345                "};");
12346 
12347   // With nested lists, we should either format one item per line or all nested
12348   // lists one on line.
12349   // FIXME: For some nested lists, we can do better.
12350   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12351                "        {aaaaaaaaaaaaaaaaaaa},\n"
12352                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12353                "        {aaaaaaaaaaaaaaaaa}};",
12354                getLLVMStyleWithColumns(60));
12355   verifyFormat(
12356       "SomeStruct my_struct_array = {\n"
12357       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12358       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12359       "    {aaa, aaa},\n"
12360       "    {aaa, aaa},\n"
12361       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12362       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12363       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12364 
12365   // No column layout should be used here.
12366   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12367                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12368 
12369   verifyNoCrash("a<,");
12370 
12371   // No braced initializer here.
12372   verifyFormat("void f() {\n"
12373                "  struct Dummy {};\n"
12374                "  f(v);\n"
12375                "}");
12376 
12377   // Long lists should be formatted in columns even if they are nested.
12378   verifyFormat(
12379       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12380       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12381       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12382       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12383       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12384       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12385 
12386   // Allow "single-column" layout even if that violates the column limit. There
12387   // isn't going to be a better way.
12388   verifyFormat("std::vector<int> a = {\n"
12389                "    aaaaaaaa,\n"
12390                "    aaaaaaaa,\n"
12391                "    aaaaaaaa,\n"
12392                "    aaaaaaaa,\n"
12393                "    aaaaaaaaaa,\n"
12394                "    aaaaaaaa,\n"
12395                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12396                getLLVMStyleWithColumns(30));
12397   verifyFormat("vector<int> aaaa = {\n"
12398                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12399                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12400                "    aaaaaa.aaaaaaa,\n"
12401                "    aaaaaa.aaaaaaa,\n"
12402                "    aaaaaa.aaaaaaa,\n"
12403                "    aaaaaa.aaaaaaa,\n"
12404                "};");
12405 
12406   // Don't create hanging lists.
12407   verifyFormat("someFunction(Param, {List1, List2,\n"
12408                "                     List3});",
12409                getLLVMStyleWithColumns(35));
12410   verifyFormat("someFunction(Param, Param,\n"
12411                "             {List1, List2,\n"
12412                "              List3});",
12413                getLLVMStyleWithColumns(35));
12414   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12415                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12416 }
12417 
12418 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12419   FormatStyle DoNotMerge = getLLVMStyle();
12420   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12421 
12422   verifyFormat("void f() { return 42; }");
12423   verifyFormat("void f() {\n"
12424                "  return 42;\n"
12425                "}",
12426                DoNotMerge);
12427   verifyFormat("void f() {\n"
12428                "  // Comment\n"
12429                "}");
12430   verifyFormat("{\n"
12431                "#error {\n"
12432                "  int a;\n"
12433                "}");
12434   verifyFormat("{\n"
12435                "  int a;\n"
12436                "#error {\n"
12437                "}");
12438   verifyFormat("void f() {} // comment");
12439   verifyFormat("void f() { int a; } // comment");
12440   verifyFormat("void f() {\n"
12441                "} // comment",
12442                DoNotMerge);
12443   verifyFormat("void f() {\n"
12444                "  int a;\n"
12445                "} // comment",
12446                DoNotMerge);
12447   verifyFormat("void f() {\n"
12448                "} // comment",
12449                getLLVMStyleWithColumns(15));
12450 
12451   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12452   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12453 
12454   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12455   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12456   verifyFormat("class C {\n"
12457                "  C()\n"
12458                "      : iiiiiiii(nullptr),\n"
12459                "        kkkkkkk(nullptr),\n"
12460                "        mmmmmmm(nullptr),\n"
12461                "        nnnnnnn(nullptr) {}\n"
12462                "};",
12463                getGoogleStyle());
12464 
12465   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12466   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12467   EXPECT_EQ("class C {\n"
12468             "  A() : b(0) {}\n"
12469             "};",
12470             format("class C{A():b(0){}};", NoColumnLimit));
12471   EXPECT_EQ("A()\n"
12472             "    : b(0) {\n"
12473             "}",
12474             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12475 
12476   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12477   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12478       FormatStyle::SFS_None;
12479   EXPECT_EQ("A()\n"
12480             "    : b(0) {\n"
12481             "}",
12482             format("A():b(0){}", DoNotMergeNoColumnLimit));
12483   EXPECT_EQ("A()\n"
12484             "    : b(0) {\n"
12485             "}",
12486             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12487 
12488   verifyFormat("#define A          \\\n"
12489                "  void f() {       \\\n"
12490                "    int i;         \\\n"
12491                "  }",
12492                getLLVMStyleWithColumns(20));
12493   verifyFormat("#define A           \\\n"
12494                "  void f() { int i; }",
12495                getLLVMStyleWithColumns(21));
12496   verifyFormat("#define A            \\\n"
12497                "  void f() {         \\\n"
12498                "    int i;           \\\n"
12499                "  }                  \\\n"
12500                "  int j;",
12501                getLLVMStyleWithColumns(22));
12502   verifyFormat("#define A             \\\n"
12503                "  void f() { int i; } \\\n"
12504                "  int j;",
12505                getLLVMStyleWithColumns(23));
12506 }
12507 
12508 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12509   FormatStyle MergeEmptyOnly = getLLVMStyle();
12510   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12511   verifyFormat("class C {\n"
12512                "  int f() {}\n"
12513                "};",
12514                MergeEmptyOnly);
12515   verifyFormat("class C {\n"
12516                "  int f() {\n"
12517                "    return 42;\n"
12518                "  }\n"
12519                "};",
12520                MergeEmptyOnly);
12521   verifyFormat("int f() {}", MergeEmptyOnly);
12522   verifyFormat("int f() {\n"
12523                "  return 42;\n"
12524                "}",
12525                MergeEmptyOnly);
12526 
12527   // Also verify behavior when BraceWrapping.AfterFunction = true
12528   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12529   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12530   verifyFormat("int f() {}", MergeEmptyOnly);
12531   verifyFormat("class C {\n"
12532                "  int f() {}\n"
12533                "};",
12534                MergeEmptyOnly);
12535 }
12536 
12537 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12538   FormatStyle MergeInlineOnly = getLLVMStyle();
12539   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12540   verifyFormat("class C {\n"
12541                "  int f() { return 42; }\n"
12542                "};",
12543                MergeInlineOnly);
12544   verifyFormat("int f() {\n"
12545                "  return 42;\n"
12546                "}",
12547                MergeInlineOnly);
12548 
12549   // SFS_Inline implies SFS_Empty
12550   verifyFormat("class C {\n"
12551                "  int f() {}\n"
12552                "};",
12553                MergeInlineOnly);
12554   verifyFormat("int f() {}", MergeInlineOnly);
12555 
12556   // Also verify behavior when BraceWrapping.AfterFunction = true
12557   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12558   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12559   verifyFormat("class C {\n"
12560                "  int f() { return 42; }\n"
12561                "};",
12562                MergeInlineOnly);
12563   verifyFormat("int f()\n"
12564                "{\n"
12565                "  return 42;\n"
12566                "}",
12567                MergeInlineOnly);
12568 
12569   // SFS_Inline implies SFS_Empty
12570   verifyFormat("int f() {}", MergeInlineOnly);
12571   verifyFormat("class C {\n"
12572                "  int f() {}\n"
12573                "};",
12574                MergeInlineOnly);
12575 
12576   MergeInlineOnly.BraceWrapping.AfterClass = true;
12577   MergeInlineOnly.BraceWrapping.AfterStruct = true;
12578   verifyFormat("class C\n"
12579                "{\n"
12580                "  int f() { return 42; }\n"
12581                "};",
12582                MergeInlineOnly);
12583   verifyFormat("struct C\n"
12584                "{\n"
12585                "  int f() { return 42; }\n"
12586                "};",
12587                MergeInlineOnly);
12588   verifyFormat("int f()\n"
12589                "{\n"
12590                "  return 42;\n"
12591                "}",
12592                MergeInlineOnly);
12593   verifyFormat("int f() {}", MergeInlineOnly);
12594   verifyFormat("class C\n"
12595                "{\n"
12596                "  int f() { return 42; }\n"
12597                "};",
12598                MergeInlineOnly);
12599   verifyFormat("struct C\n"
12600                "{\n"
12601                "  int f() { return 42; }\n"
12602                "};",
12603                MergeInlineOnly);
12604   verifyFormat("struct C\n"
12605                "// comment\n"
12606                "/* comment */\n"
12607                "// comment\n"
12608                "{\n"
12609                "  int f() { return 42; }\n"
12610                "};",
12611                MergeInlineOnly);
12612   verifyFormat("/* comment */ struct C\n"
12613                "{\n"
12614                "  int f() { return 42; }\n"
12615                "};",
12616                MergeInlineOnly);
12617 }
12618 
12619 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12620   FormatStyle MergeInlineOnly = getLLVMStyle();
12621   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12622       FormatStyle::SFS_InlineOnly;
12623   verifyFormat("class C {\n"
12624                "  int f() { return 42; }\n"
12625                "};",
12626                MergeInlineOnly);
12627   verifyFormat("int f() {\n"
12628                "  return 42;\n"
12629                "}",
12630                MergeInlineOnly);
12631 
12632   // SFS_InlineOnly does not imply SFS_Empty
12633   verifyFormat("class C {\n"
12634                "  int f() {}\n"
12635                "};",
12636                MergeInlineOnly);
12637   verifyFormat("int f() {\n"
12638                "}",
12639                MergeInlineOnly);
12640 
12641   // Also verify behavior when BraceWrapping.AfterFunction = true
12642   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12643   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12644   verifyFormat("class C {\n"
12645                "  int f() { return 42; }\n"
12646                "};",
12647                MergeInlineOnly);
12648   verifyFormat("int f()\n"
12649                "{\n"
12650                "  return 42;\n"
12651                "}",
12652                MergeInlineOnly);
12653 
12654   // SFS_InlineOnly does not imply SFS_Empty
12655   verifyFormat("int f()\n"
12656                "{\n"
12657                "}",
12658                MergeInlineOnly);
12659   verifyFormat("class C {\n"
12660                "  int f() {}\n"
12661                "};",
12662                MergeInlineOnly);
12663 }
12664 
12665 TEST_F(FormatTest, SplitEmptyFunction) {
12666   FormatStyle Style = getLLVMStyleWithColumns(40);
12667   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12668   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12669   Style.BraceWrapping.AfterFunction = true;
12670   Style.BraceWrapping.SplitEmptyFunction = false;
12671 
12672   verifyFormat("int f()\n"
12673                "{}",
12674                Style);
12675   verifyFormat("int f()\n"
12676                "{\n"
12677                "  return 42;\n"
12678                "}",
12679                Style);
12680   verifyFormat("int f()\n"
12681                "{\n"
12682                "  // some comment\n"
12683                "}",
12684                Style);
12685 
12686   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12687   verifyFormat("int f() {}", Style);
12688   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12689                "{}",
12690                Style);
12691   verifyFormat("int f()\n"
12692                "{\n"
12693                "  return 0;\n"
12694                "}",
12695                Style);
12696 
12697   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12698   verifyFormat("class Foo {\n"
12699                "  int f() {}\n"
12700                "};\n",
12701                Style);
12702   verifyFormat("class Foo {\n"
12703                "  int f() { return 0; }\n"
12704                "};\n",
12705                Style);
12706   verifyFormat("class Foo {\n"
12707                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12708                "  {}\n"
12709                "};\n",
12710                Style);
12711   verifyFormat("class Foo {\n"
12712                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12713                "  {\n"
12714                "    return 0;\n"
12715                "  }\n"
12716                "};\n",
12717                Style);
12718 
12719   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12720   verifyFormat("int f() {}", Style);
12721   verifyFormat("int f() { return 0; }", Style);
12722   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12723                "{}",
12724                Style);
12725   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12726                "{\n"
12727                "  return 0;\n"
12728                "}",
12729                Style);
12730 }
12731 
12732 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12733   FormatStyle Style = getLLVMStyleWithColumns(40);
12734   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12735   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12736   Style.BraceWrapping.AfterFunction = true;
12737   Style.BraceWrapping.SplitEmptyFunction = true;
12738   Style.BraceWrapping.SplitEmptyRecord = false;
12739 
12740   verifyFormat("class C {};", Style);
12741   verifyFormat("struct C {};", Style);
12742   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12743                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12744                "{\n"
12745                "}",
12746                Style);
12747   verifyFormat("class C {\n"
12748                "  C()\n"
12749                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12750                "        bbbbbbbbbbbbbbbbbbb()\n"
12751                "  {\n"
12752                "  }\n"
12753                "  void\n"
12754                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12755                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12756                "  {\n"
12757                "  }\n"
12758                "};",
12759                Style);
12760 }
12761 
12762 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12763   FormatStyle Style = getLLVMStyle();
12764   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12765   verifyFormat("#ifdef A\n"
12766                "int f() {}\n"
12767                "#else\n"
12768                "int g() {}\n"
12769                "#endif",
12770                Style);
12771 }
12772 
12773 TEST_F(FormatTest, SplitEmptyClass) {
12774   FormatStyle Style = getLLVMStyle();
12775   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12776   Style.BraceWrapping.AfterClass = true;
12777   Style.BraceWrapping.SplitEmptyRecord = false;
12778 
12779   verifyFormat("class Foo\n"
12780                "{};",
12781                Style);
12782   verifyFormat("/* something */ class Foo\n"
12783                "{};",
12784                Style);
12785   verifyFormat("template <typename X> class Foo\n"
12786                "{};",
12787                Style);
12788   verifyFormat("class Foo\n"
12789                "{\n"
12790                "  Foo();\n"
12791                "};",
12792                Style);
12793   verifyFormat("typedef class Foo\n"
12794                "{\n"
12795                "} Foo_t;",
12796                Style);
12797 
12798   Style.BraceWrapping.SplitEmptyRecord = true;
12799   Style.BraceWrapping.AfterStruct = true;
12800   verifyFormat("class rep\n"
12801                "{\n"
12802                "};",
12803                Style);
12804   verifyFormat("struct rep\n"
12805                "{\n"
12806                "};",
12807                Style);
12808   verifyFormat("template <typename T> class rep\n"
12809                "{\n"
12810                "};",
12811                Style);
12812   verifyFormat("template <typename T> struct rep\n"
12813                "{\n"
12814                "};",
12815                Style);
12816   verifyFormat("class rep\n"
12817                "{\n"
12818                "  int x;\n"
12819                "};",
12820                Style);
12821   verifyFormat("struct rep\n"
12822                "{\n"
12823                "  int x;\n"
12824                "};",
12825                Style);
12826   verifyFormat("template <typename T> class rep\n"
12827                "{\n"
12828                "  int x;\n"
12829                "};",
12830                Style);
12831   verifyFormat("template <typename T> struct rep\n"
12832                "{\n"
12833                "  int x;\n"
12834                "};",
12835                Style);
12836   verifyFormat("template <typename T> class rep // Foo\n"
12837                "{\n"
12838                "  int x;\n"
12839                "};",
12840                Style);
12841   verifyFormat("template <typename T> struct rep // Bar\n"
12842                "{\n"
12843                "  int x;\n"
12844                "};",
12845                Style);
12846 
12847   verifyFormat("template <typename T> class rep<T>\n"
12848                "{\n"
12849                "  int x;\n"
12850                "};",
12851                Style);
12852 
12853   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12854                "{\n"
12855                "  int x;\n"
12856                "};",
12857                Style);
12858   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12859                "{\n"
12860                "};",
12861                Style);
12862 
12863   verifyFormat("#include \"stdint.h\"\n"
12864                "namespace rep {}",
12865                Style);
12866   verifyFormat("#include <stdint.h>\n"
12867                "namespace rep {}",
12868                Style);
12869   verifyFormat("#include <stdint.h>\n"
12870                "namespace rep {}",
12871                "#include <stdint.h>\n"
12872                "namespace rep {\n"
12873                "\n"
12874                "\n"
12875                "}",
12876                Style);
12877 }
12878 
12879 TEST_F(FormatTest, SplitEmptyStruct) {
12880   FormatStyle Style = getLLVMStyle();
12881   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12882   Style.BraceWrapping.AfterStruct = true;
12883   Style.BraceWrapping.SplitEmptyRecord = false;
12884 
12885   verifyFormat("struct Foo\n"
12886                "{};",
12887                Style);
12888   verifyFormat("/* something */ struct Foo\n"
12889                "{};",
12890                Style);
12891   verifyFormat("template <typename X> struct Foo\n"
12892                "{};",
12893                Style);
12894   verifyFormat("struct Foo\n"
12895                "{\n"
12896                "  Foo();\n"
12897                "};",
12898                Style);
12899   verifyFormat("typedef struct Foo\n"
12900                "{\n"
12901                "} Foo_t;",
12902                Style);
12903   // typedef struct Bar {} Bar_t;
12904 }
12905 
12906 TEST_F(FormatTest, SplitEmptyUnion) {
12907   FormatStyle Style = getLLVMStyle();
12908   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12909   Style.BraceWrapping.AfterUnion = true;
12910   Style.BraceWrapping.SplitEmptyRecord = false;
12911 
12912   verifyFormat("union Foo\n"
12913                "{};",
12914                Style);
12915   verifyFormat("/* something */ union Foo\n"
12916                "{};",
12917                Style);
12918   verifyFormat("union Foo\n"
12919                "{\n"
12920                "  A,\n"
12921                "};",
12922                Style);
12923   verifyFormat("typedef union Foo\n"
12924                "{\n"
12925                "} Foo_t;",
12926                Style);
12927 }
12928 
12929 TEST_F(FormatTest, SplitEmptyNamespace) {
12930   FormatStyle Style = getLLVMStyle();
12931   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12932   Style.BraceWrapping.AfterNamespace = true;
12933   Style.BraceWrapping.SplitEmptyNamespace = false;
12934 
12935   verifyFormat("namespace Foo\n"
12936                "{};",
12937                Style);
12938   verifyFormat("/* something */ namespace Foo\n"
12939                "{};",
12940                Style);
12941   verifyFormat("inline namespace Foo\n"
12942                "{};",
12943                Style);
12944   verifyFormat("/* something */ inline namespace Foo\n"
12945                "{};",
12946                Style);
12947   verifyFormat("export namespace Foo\n"
12948                "{};",
12949                Style);
12950   verifyFormat("namespace Foo\n"
12951                "{\n"
12952                "void Bar();\n"
12953                "};",
12954                Style);
12955 }
12956 
12957 TEST_F(FormatTest, NeverMergeShortRecords) {
12958   FormatStyle Style = getLLVMStyle();
12959 
12960   verifyFormat("class Foo {\n"
12961                "  Foo();\n"
12962                "};",
12963                Style);
12964   verifyFormat("typedef class Foo {\n"
12965                "  Foo();\n"
12966                "} Foo_t;",
12967                Style);
12968   verifyFormat("struct Foo {\n"
12969                "  Foo();\n"
12970                "};",
12971                Style);
12972   verifyFormat("typedef struct Foo {\n"
12973                "  Foo();\n"
12974                "} Foo_t;",
12975                Style);
12976   verifyFormat("union Foo {\n"
12977                "  A,\n"
12978                "};",
12979                Style);
12980   verifyFormat("typedef union Foo {\n"
12981                "  A,\n"
12982                "} Foo_t;",
12983                Style);
12984   verifyFormat("namespace Foo {\n"
12985                "void Bar();\n"
12986                "};",
12987                Style);
12988 
12989   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12990   Style.BraceWrapping.AfterClass = true;
12991   Style.BraceWrapping.AfterStruct = true;
12992   Style.BraceWrapping.AfterUnion = true;
12993   Style.BraceWrapping.AfterNamespace = true;
12994   verifyFormat("class Foo\n"
12995                "{\n"
12996                "  Foo();\n"
12997                "};",
12998                Style);
12999   verifyFormat("typedef class Foo\n"
13000                "{\n"
13001                "  Foo();\n"
13002                "} Foo_t;",
13003                Style);
13004   verifyFormat("struct Foo\n"
13005                "{\n"
13006                "  Foo();\n"
13007                "};",
13008                Style);
13009   verifyFormat("typedef struct Foo\n"
13010                "{\n"
13011                "  Foo();\n"
13012                "} Foo_t;",
13013                Style);
13014   verifyFormat("union Foo\n"
13015                "{\n"
13016                "  A,\n"
13017                "};",
13018                Style);
13019   verifyFormat("typedef union Foo\n"
13020                "{\n"
13021                "  A,\n"
13022                "} Foo_t;",
13023                Style);
13024   verifyFormat("namespace Foo\n"
13025                "{\n"
13026                "void Bar();\n"
13027                "};",
13028                Style);
13029 }
13030 
13031 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
13032   // Elaborate type variable declarations.
13033   verifyFormat("struct foo a = {bar};\nint n;");
13034   verifyFormat("class foo a = {bar};\nint n;");
13035   verifyFormat("union foo a = {bar};\nint n;");
13036 
13037   // Elaborate types inside function definitions.
13038   verifyFormat("struct foo f() {}\nint n;");
13039   verifyFormat("class foo f() {}\nint n;");
13040   verifyFormat("union foo f() {}\nint n;");
13041 
13042   // Templates.
13043   verifyFormat("template <class X> void f() {}\nint n;");
13044   verifyFormat("template <struct X> void f() {}\nint n;");
13045   verifyFormat("template <union X> void f() {}\nint n;");
13046 
13047   // Actual definitions...
13048   verifyFormat("struct {\n} n;");
13049   verifyFormat(
13050       "template <template <class T, class Y>, class Z> class X {\n} n;");
13051   verifyFormat("union Z {\n  int n;\n} x;");
13052   verifyFormat("class MACRO Z {\n} n;");
13053   verifyFormat("class MACRO(X) Z {\n} n;");
13054   verifyFormat("class __attribute__(X) Z {\n} n;");
13055   verifyFormat("class __declspec(X) Z {\n} n;");
13056   verifyFormat("class A##B##C {\n} n;");
13057   verifyFormat("class alignas(16) Z {\n} n;");
13058   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
13059   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
13060 
13061   // Redefinition from nested context:
13062   verifyFormat("class A::B::C {\n} n;");
13063 
13064   // Template definitions.
13065   verifyFormat(
13066       "template <typename F>\n"
13067       "Matcher(const Matcher<F> &Other,\n"
13068       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
13069       "                             !is_same<F, T>::value>::type * = 0)\n"
13070       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
13071 
13072   // FIXME: This is still incorrectly handled at the formatter side.
13073   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
13074   verifyFormat("int i = SomeFunction(a<b, a> b);");
13075 
13076   // FIXME:
13077   // This now gets parsed incorrectly as class definition.
13078   // verifyFormat("class A<int> f() {\n}\nint n;");
13079 
13080   // Elaborate types where incorrectly parsing the structural element would
13081   // break the indent.
13082   verifyFormat("if (true)\n"
13083                "  class X x;\n"
13084                "else\n"
13085                "  f();\n");
13086 
13087   // This is simply incomplete. Formatting is not important, but must not crash.
13088   verifyFormat("class A:");
13089 }
13090 
13091 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
13092   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
13093             format("#error Leave     all         white!!!!! space* alone!\n"));
13094   EXPECT_EQ(
13095       "#warning Leave     all         white!!!!! space* alone!\n",
13096       format("#warning Leave     all         white!!!!! space* alone!\n"));
13097   EXPECT_EQ("#error 1", format("  #  error   1"));
13098   EXPECT_EQ("#warning 1", format("  #  warning 1"));
13099 }
13100 
13101 TEST_F(FormatTest, FormatHashIfExpressions) {
13102   verifyFormat("#if AAAA && BBBB");
13103   verifyFormat("#if (AAAA && BBBB)");
13104   verifyFormat("#elif (AAAA && BBBB)");
13105   // FIXME: Come up with a better indentation for #elif.
13106   verifyFormat(
13107       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
13108       "    defined(BBBBBBBB)\n"
13109       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
13110       "    defined(BBBBBBBB)\n"
13111       "#endif",
13112       getLLVMStyleWithColumns(65));
13113 }
13114 
13115 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
13116   FormatStyle AllowsMergedIf = getGoogleStyle();
13117   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
13118       FormatStyle::SIS_WithoutElse;
13119   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
13120   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
13121   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
13122   EXPECT_EQ("if (true) return 42;",
13123             format("if (true)\nreturn 42;", AllowsMergedIf));
13124   FormatStyle ShortMergedIf = AllowsMergedIf;
13125   ShortMergedIf.ColumnLimit = 25;
13126   verifyFormat("#define A \\\n"
13127                "  if (true) return 42;",
13128                ShortMergedIf);
13129   verifyFormat("#define A \\\n"
13130                "  f();    \\\n"
13131                "  if (true)\n"
13132                "#define B",
13133                ShortMergedIf);
13134   verifyFormat("#define A \\\n"
13135                "  f();    \\\n"
13136                "  if (true)\n"
13137                "g();",
13138                ShortMergedIf);
13139   verifyFormat("{\n"
13140                "#ifdef A\n"
13141                "  // Comment\n"
13142                "  if (true) continue;\n"
13143                "#endif\n"
13144                "  // Comment\n"
13145                "  if (true) continue;\n"
13146                "}",
13147                ShortMergedIf);
13148   ShortMergedIf.ColumnLimit = 33;
13149   verifyFormat("#define A \\\n"
13150                "  if constexpr (true) return 42;",
13151                ShortMergedIf);
13152   verifyFormat("#define A \\\n"
13153                "  if CONSTEXPR (true) return 42;",
13154                ShortMergedIf);
13155   ShortMergedIf.ColumnLimit = 29;
13156   verifyFormat("#define A                   \\\n"
13157                "  if (aaaaaaaaaa) return 1; \\\n"
13158                "  return 2;",
13159                ShortMergedIf);
13160   ShortMergedIf.ColumnLimit = 28;
13161   verifyFormat("#define A         \\\n"
13162                "  if (aaaaaaaaaa) \\\n"
13163                "    return 1;     \\\n"
13164                "  return 2;",
13165                ShortMergedIf);
13166   verifyFormat("#define A                \\\n"
13167                "  if constexpr (aaaaaaa) \\\n"
13168                "    return 1;            \\\n"
13169                "  return 2;",
13170                ShortMergedIf);
13171   verifyFormat("#define A                \\\n"
13172                "  if CONSTEXPR (aaaaaaa) \\\n"
13173                "    return 1;            \\\n"
13174                "  return 2;",
13175                ShortMergedIf);
13176 }
13177 
13178 TEST_F(FormatTest, FormatStarDependingOnContext) {
13179   verifyFormat("void f(int *a);");
13180   verifyFormat("void f() { f(fint * b); }");
13181   verifyFormat("class A {\n  void f(int *a);\n};");
13182   verifyFormat("class A {\n  int *a;\n};");
13183   verifyFormat("namespace a {\n"
13184                "namespace b {\n"
13185                "class A {\n"
13186                "  void f() {}\n"
13187                "  int *a;\n"
13188                "};\n"
13189                "} // namespace b\n"
13190                "} // namespace a");
13191 }
13192 
13193 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13194   verifyFormat("while");
13195   verifyFormat("operator");
13196 }
13197 
13198 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13199   // This code would be painfully slow to format if we didn't skip it.
13200   std::string Code("A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" // 20x
13201                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13202                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13203                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13204                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13205                    "A(1, 1)\n"
13206                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
13207                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13208                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13209                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13210                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13211                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13212                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13213                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13214                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13215                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
13216   // Deeply nested part is untouched, rest is formatted.
13217   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13218             format(std::string("int    i;\n") + Code + "int    j;\n",
13219                    getLLVMStyle(), SC_ExpectIncomplete));
13220 }
13221 
13222 //===----------------------------------------------------------------------===//
13223 // Objective-C tests.
13224 //===----------------------------------------------------------------------===//
13225 
13226 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13227   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13228   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13229             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13230   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13231   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13232   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13233             format("-(NSInteger)Method3:(id)anObject;"));
13234   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13235             format("-(NSInteger)Method4:(id)anObject;"));
13236   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13237             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13238   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13239             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13240   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13241             "forAllCells:(BOOL)flag;",
13242             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13243                    "forAllCells:(BOOL)flag;"));
13244 
13245   // Very long objectiveC method declaration.
13246   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13247                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13248   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13249                "                    inRange:(NSRange)range\n"
13250                "                   outRange:(NSRange)out_range\n"
13251                "                  outRange1:(NSRange)out_range1\n"
13252                "                  outRange2:(NSRange)out_range2\n"
13253                "                  outRange3:(NSRange)out_range3\n"
13254                "                  outRange4:(NSRange)out_range4\n"
13255                "                  outRange5:(NSRange)out_range5\n"
13256                "                  outRange6:(NSRange)out_range6\n"
13257                "                  outRange7:(NSRange)out_range7\n"
13258                "                  outRange8:(NSRange)out_range8\n"
13259                "                  outRange9:(NSRange)out_range9;");
13260 
13261   // When the function name has to be wrapped.
13262   FormatStyle Style = getLLVMStyle();
13263   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13264   // and always indents instead.
13265   Style.IndentWrappedFunctionNames = false;
13266   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13267                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13268                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13269                "}",
13270                Style);
13271   Style.IndentWrappedFunctionNames = true;
13272   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13273                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13274                "               anotherName:(NSString)dddddddddddddd {\n"
13275                "}",
13276                Style);
13277 
13278   verifyFormat("- (int)sum:(vector<int>)numbers;");
13279   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13280   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13281   // protocol lists (but not for template classes):
13282   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13283 
13284   verifyFormat("- (int (*)())foo:(int (*)())f;");
13285   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13286 
13287   // If there's no return type (very rare in practice!), LLVM and Google style
13288   // agree.
13289   verifyFormat("- foo;");
13290   verifyFormat("- foo:(int)f;");
13291   verifyGoogleFormat("- foo:(int)foo;");
13292 }
13293 
13294 TEST_F(FormatTest, BreaksStringLiterals) {
13295   EXPECT_EQ("\"some text \"\n"
13296             "\"other\";",
13297             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13298   EXPECT_EQ("\"some text \"\n"
13299             "\"other\";",
13300             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13301   EXPECT_EQ(
13302       "#define A  \\\n"
13303       "  \"some \"  \\\n"
13304       "  \"text \"  \\\n"
13305       "  \"other\";",
13306       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13307   EXPECT_EQ(
13308       "#define A  \\\n"
13309       "  \"so \"    \\\n"
13310       "  \"text \"  \\\n"
13311       "  \"other\";",
13312       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13313 
13314   EXPECT_EQ("\"some text\"",
13315             format("\"some text\"", getLLVMStyleWithColumns(1)));
13316   EXPECT_EQ("\"some text\"",
13317             format("\"some text\"", getLLVMStyleWithColumns(11)));
13318   EXPECT_EQ("\"some \"\n"
13319             "\"text\"",
13320             format("\"some text\"", getLLVMStyleWithColumns(10)));
13321   EXPECT_EQ("\"some \"\n"
13322             "\"text\"",
13323             format("\"some text\"", getLLVMStyleWithColumns(7)));
13324   EXPECT_EQ("\"some\"\n"
13325             "\" tex\"\n"
13326             "\"t\"",
13327             format("\"some text\"", getLLVMStyleWithColumns(6)));
13328   EXPECT_EQ("\"some\"\n"
13329             "\" tex\"\n"
13330             "\" and\"",
13331             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13332   EXPECT_EQ("\"some\"\n"
13333             "\"/tex\"\n"
13334             "\"/and\"",
13335             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13336 
13337   EXPECT_EQ("variable =\n"
13338             "    \"long string \"\n"
13339             "    \"literal\";",
13340             format("variable = \"long string literal\";",
13341                    getLLVMStyleWithColumns(20)));
13342 
13343   EXPECT_EQ("variable = f(\n"
13344             "    \"long string \"\n"
13345             "    \"literal\",\n"
13346             "    short,\n"
13347             "    loooooooooooooooooooong);",
13348             format("variable = f(\"long string literal\", short, "
13349                    "loooooooooooooooooooong);",
13350                    getLLVMStyleWithColumns(20)));
13351 
13352   EXPECT_EQ(
13353       "f(g(\"long string \"\n"
13354       "    \"literal\"),\n"
13355       "  b);",
13356       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13357   EXPECT_EQ("f(g(\"long string \"\n"
13358             "    \"literal\",\n"
13359             "    a),\n"
13360             "  b);",
13361             format("f(g(\"long string literal\", a), b);",
13362                    getLLVMStyleWithColumns(20)));
13363   EXPECT_EQ(
13364       "f(\"one two\".split(\n"
13365       "    variable));",
13366       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13367   EXPECT_EQ("f(\"one two three four five six \"\n"
13368             "  \"seven\".split(\n"
13369             "      really_looooong_variable));",
13370             format("f(\"one two three four five six seven\"."
13371                    "split(really_looooong_variable));",
13372                    getLLVMStyleWithColumns(33)));
13373 
13374   EXPECT_EQ("f(\"some \"\n"
13375             "  \"text\",\n"
13376             "  other);",
13377             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13378 
13379   // Only break as a last resort.
13380   verifyFormat(
13381       "aaaaaaaaaaaaaaaaaaaa(\n"
13382       "    aaaaaaaaaaaaaaaaaaaa,\n"
13383       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13384 
13385   EXPECT_EQ("\"splitmea\"\n"
13386             "\"trandomp\"\n"
13387             "\"oint\"",
13388             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13389 
13390   EXPECT_EQ("\"split/\"\n"
13391             "\"pathat/\"\n"
13392             "\"slashes\"",
13393             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13394 
13395   EXPECT_EQ("\"split/\"\n"
13396             "\"pathat/\"\n"
13397             "\"slashes\"",
13398             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13399   EXPECT_EQ("\"split at \"\n"
13400             "\"spaces/at/\"\n"
13401             "\"slashes.at.any$\"\n"
13402             "\"non-alphanumeric%\"\n"
13403             "\"1111111111characte\"\n"
13404             "\"rs\"",
13405             format("\"split at "
13406                    "spaces/at/"
13407                    "slashes.at."
13408                    "any$non-"
13409                    "alphanumeric%"
13410                    "1111111111characte"
13411                    "rs\"",
13412                    getLLVMStyleWithColumns(20)));
13413 
13414   // Verify that splitting the strings understands
13415   // Style::AlwaysBreakBeforeMultilineStrings.
13416   EXPECT_EQ("aaaaaaaaaaaa(\n"
13417             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13418             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13419             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13420                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13421                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13422                    getGoogleStyle()));
13423   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13424             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13425             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13426                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13427                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13428                    getGoogleStyle()));
13429   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13430             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13431             format("llvm::outs() << "
13432                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13433                    "aaaaaaaaaaaaaaaaaaa\";"));
13434   EXPECT_EQ("ffff(\n"
13435             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13436             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13437             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13438                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13439                    getGoogleStyle()));
13440 
13441   FormatStyle Style = getLLVMStyleWithColumns(12);
13442   Style.BreakStringLiterals = false;
13443   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13444 
13445   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13446   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13447   EXPECT_EQ("#define A \\\n"
13448             "  \"some \" \\\n"
13449             "  \"text \" \\\n"
13450             "  \"other\";",
13451             format("#define A \"some text other\";", AlignLeft));
13452 }
13453 
13454 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13455   EXPECT_EQ("C a = \"some more \"\n"
13456             "      \"text\";",
13457             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13458 }
13459 
13460 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13461   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13462   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13463   EXPECT_EQ("int i = a(b());",
13464             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13465 }
13466 
13467 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13468   EXPECT_EQ(
13469       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13470       "(\n"
13471       "    \"x\t\");",
13472       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13473              "aaaaaaa("
13474              "\"x\t\");"));
13475 }
13476 
13477 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13478   EXPECT_EQ(
13479       "u8\"utf8 string \"\n"
13480       "u8\"literal\";",
13481       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13482   EXPECT_EQ(
13483       "u\"utf16 string \"\n"
13484       "u\"literal\";",
13485       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13486   EXPECT_EQ(
13487       "U\"utf32 string \"\n"
13488       "U\"literal\";",
13489       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13490   EXPECT_EQ("L\"wide string \"\n"
13491             "L\"literal\";",
13492             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13493   EXPECT_EQ("@\"NSString \"\n"
13494             "@\"literal\";",
13495             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13496   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13497 
13498   // This input makes clang-format try to split the incomplete unicode escape
13499   // sequence, which used to lead to a crasher.
13500   verifyNoCrash(
13501       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13502       getLLVMStyleWithColumns(60));
13503 }
13504 
13505 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13506   FormatStyle Style = getGoogleStyleWithColumns(15);
13507   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13508   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13509   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13510   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13511   EXPECT_EQ("u8R\"x(raw literal)x\";",
13512             format("u8R\"x(raw literal)x\";", Style));
13513 }
13514 
13515 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13516   FormatStyle Style = getLLVMStyleWithColumns(20);
13517   EXPECT_EQ(
13518       "_T(\"aaaaaaaaaaaaaa\")\n"
13519       "_T(\"aaaaaaaaaaaaaa\")\n"
13520       "_T(\"aaaaaaaaaaaa\")",
13521       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13522   EXPECT_EQ("f(x,\n"
13523             "  _T(\"aaaaaaaaaaaa\")\n"
13524             "  _T(\"aaa\"),\n"
13525             "  z);",
13526             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13527 
13528   // FIXME: Handle embedded spaces in one iteration.
13529   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13530   //            "_T(\"aaaaaaaaaaaaa\")\n"
13531   //            "_T(\"aaaaaaaaaaaaa\")\n"
13532   //            "_T(\"a\")",
13533   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13534   //                   getLLVMStyleWithColumns(20)));
13535   EXPECT_EQ(
13536       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13537       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13538   EXPECT_EQ("f(\n"
13539             "#if !TEST\n"
13540             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13541             "#endif\n"
13542             ");",
13543             format("f(\n"
13544                    "#if !TEST\n"
13545                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13546                    "#endif\n"
13547                    ");"));
13548   EXPECT_EQ("f(\n"
13549             "\n"
13550             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13551             format("f(\n"
13552                    "\n"
13553                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13554   // Regression test for accessing tokens past the end of a vector in the
13555   // TokenLexer.
13556   verifyNoCrash(R"(_T(
13557 "
13558 )
13559 )");
13560 }
13561 
13562 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13563   // In a function call with two operands, the second can be broken with no line
13564   // break before it.
13565   EXPECT_EQ(
13566       "func(a, \"long long \"\n"
13567       "        \"long long\");",
13568       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13569   // In a function call with three operands, the second must be broken with a
13570   // line break before it.
13571   EXPECT_EQ("func(a,\n"
13572             "     \"long long long \"\n"
13573             "     \"long\",\n"
13574             "     c);",
13575             format("func(a, \"long long long long\", c);",
13576                    getLLVMStyleWithColumns(24)));
13577   // In a function call with three operands, the third must be broken with a
13578   // line break before it.
13579   EXPECT_EQ("func(a, b,\n"
13580             "     \"long long long \"\n"
13581             "     \"long\");",
13582             format("func(a, b, \"long long long long\");",
13583                    getLLVMStyleWithColumns(24)));
13584   // In a function call with three operands, both the second and the third must
13585   // be broken with a line break before them.
13586   EXPECT_EQ("func(a,\n"
13587             "     \"long long long \"\n"
13588             "     \"long\",\n"
13589             "     \"long long long \"\n"
13590             "     \"long\");",
13591             format("func(a, \"long long long long\", \"long long long long\");",
13592                    getLLVMStyleWithColumns(24)));
13593   // In a chain of << with two operands, the second can be broken with no line
13594   // break before it.
13595   EXPECT_EQ("a << \"line line \"\n"
13596             "     \"line\";",
13597             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13598   // In a chain of << with three operands, the second can be broken with no line
13599   // break before it.
13600   EXPECT_EQ(
13601       "abcde << \"line \"\n"
13602       "         \"line line\"\n"
13603       "      << c;",
13604       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13605   // In a chain of << with three operands, the third must be broken with a line
13606   // break before it.
13607   EXPECT_EQ(
13608       "a << b\n"
13609       "  << \"line line \"\n"
13610       "     \"line\";",
13611       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13612   // In a chain of << with three operands, the second can be broken with no line
13613   // break before it and the third must be broken with a line break before it.
13614   EXPECT_EQ("abcd << \"line line \"\n"
13615             "        \"line\"\n"
13616             "     << \"line line \"\n"
13617             "        \"line\";",
13618             format("abcd << \"line line line\" << \"line line line\";",
13619                    getLLVMStyleWithColumns(20)));
13620   // In a chain of binary operators with two operands, the second can be broken
13621   // with no line break before it.
13622   EXPECT_EQ(
13623       "abcd + \"line line \"\n"
13624       "       \"line line\";",
13625       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13626   // In a chain of binary operators with three operands, the second must be
13627   // broken with a line break before it.
13628   EXPECT_EQ("abcd +\n"
13629             "    \"line line \"\n"
13630             "    \"line line\" +\n"
13631             "    e;",
13632             format("abcd + \"line line line line\" + e;",
13633                    getLLVMStyleWithColumns(20)));
13634   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13635   // the first must be broken with a line break before it.
13636   FormatStyle Style = getLLVMStyleWithColumns(25);
13637   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13638   EXPECT_EQ("someFunction(\n"
13639             "    \"long long long \"\n"
13640             "    \"long\",\n"
13641             "    a);",
13642             format("someFunction(\"long long long long\", a);", Style));
13643 }
13644 
13645 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13646   EXPECT_EQ(
13647       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13648       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13649       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13650       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13651              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13652              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13653 }
13654 
13655 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13656   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13657             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13658   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13659             "multiline raw string literal xxxxxxxxxxxxxx\n"
13660             ")x\",\n"
13661             "              a),\n"
13662             "            b);",
13663             format("fffffffffff(g(R\"x(\n"
13664                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13665                    ")x\", a), b);",
13666                    getGoogleStyleWithColumns(20)));
13667   EXPECT_EQ("fffffffffff(\n"
13668             "    g(R\"x(qqq\n"
13669             "multiline raw string literal xxxxxxxxxxxxxx\n"
13670             ")x\",\n"
13671             "      a),\n"
13672             "    b);",
13673             format("fffffffffff(g(R\"x(qqq\n"
13674                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13675                    ")x\", a), b);",
13676                    getGoogleStyleWithColumns(20)));
13677 
13678   EXPECT_EQ("fffffffffff(R\"x(\n"
13679             "multiline raw string literal xxxxxxxxxxxxxx\n"
13680             ")x\");",
13681             format("fffffffffff(R\"x(\n"
13682                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13683                    ")x\");",
13684                    getGoogleStyleWithColumns(20)));
13685   EXPECT_EQ("fffffffffff(R\"x(\n"
13686             "multiline raw string literal xxxxxxxxxxxxxx\n"
13687             ")x\" + bbbbbb);",
13688             format("fffffffffff(R\"x(\n"
13689                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13690                    ")x\" +   bbbbbb);",
13691                    getGoogleStyleWithColumns(20)));
13692   EXPECT_EQ("fffffffffff(\n"
13693             "    R\"x(\n"
13694             "multiline raw string literal xxxxxxxxxxxxxx\n"
13695             ")x\" +\n"
13696             "    bbbbbb);",
13697             format("fffffffffff(\n"
13698                    " R\"x(\n"
13699                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13700                    ")x\" + bbbbbb);",
13701                    getGoogleStyleWithColumns(20)));
13702   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13703             format("fffffffffff(\n"
13704                    " R\"(single line raw string)\" + bbbbbb);"));
13705 }
13706 
13707 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13708   verifyFormat("string a = \"unterminated;");
13709   EXPECT_EQ("function(\"unterminated,\n"
13710             "         OtherParameter);",
13711             format("function(  \"unterminated,\n"
13712                    "    OtherParameter);"));
13713 }
13714 
13715 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13716   FormatStyle Style = getLLVMStyle();
13717   Style.Standard = FormatStyle::LS_Cpp03;
13718   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13719             format("#define x(_a) printf(\"foo\"_a);", Style));
13720 }
13721 
13722 TEST_F(FormatTest, CppLexVersion) {
13723   FormatStyle Style = getLLVMStyle();
13724   // Formatting of x * y differs if x is a type.
13725   verifyFormat("void foo() { MACRO(a * b); }", Style);
13726   verifyFormat("void foo() { MACRO(int *b); }", Style);
13727 
13728   // LLVM style uses latest lexer.
13729   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13730   Style.Standard = FormatStyle::LS_Cpp17;
13731   // But in c++17, char8_t isn't a keyword.
13732   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13733 }
13734 
13735 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13736 
13737 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13738   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13739             "             \"ddeeefff\");",
13740             format("someFunction(\"aaabbbcccdddeeefff\");",
13741                    getLLVMStyleWithColumns(25)));
13742   EXPECT_EQ("someFunction1234567890(\n"
13743             "    \"aaabbbcccdddeeefff\");",
13744             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13745                    getLLVMStyleWithColumns(26)));
13746   EXPECT_EQ("someFunction1234567890(\n"
13747             "    \"aaabbbcccdddeeeff\"\n"
13748             "    \"f\");",
13749             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13750                    getLLVMStyleWithColumns(25)));
13751   EXPECT_EQ("someFunction1234567890(\n"
13752             "    \"aaabbbcccdddeeeff\"\n"
13753             "    \"f\");",
13754             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13755                    getLLVMStyleWithColumns(24)));
13756   EXPECT_EQ("someFunction(\n"
13757             "    \"aaabbbcc ddde \"\n"
13758             "    \"efff\");",
13759             format("someFunction(\"aaabbbcc ddde efff\");",
13760                    getLLVMStyleWithColumns(25)));
13761   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13762             "             \"ddeeefff\");",
13763             format("someFunction(\"aaabbbccc ddeeefff\");",
13764                    getLLVMStyleWithColumns(25)));
13765   EXPECT_EQ("someFunction1234567890(\n"
13766             "    \"aaabb \"\n"
13767             "    \"cccdddeeefff\");",
13768             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13769                    getLLVMStyleWithColumns(25)));
13770   EXPECT_EQ("#define A          \\\n"
13771             "  string s =       \\\n"
13772             "      \"123456789\"  \\\n"
13773             "      \"0\";         \\\n"
13774             "  int i;",
13775             format("#define A string s = \"1234567890\"; int i;",
13776                    getLLVMStyleWithColumns(20)));
13777   EXPECT_EQ("someFunction(\n"
13778             "    \"aaabbbcc \"\n"
13779             "    \"dddeeefff\");",
13780             format("someFunction(\"aaabbbcc dddeeefff\");",
13781                    getLLVMStyleWithColumns(25)));
13782 }
13783 
13784 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13785   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13786   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13787   EXPECT_EQ("\"test\"\n"
13788             "\"\\n\"",
13789             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
13790   EXPECT_EQ("\"tes\\\\\"\n"
13791             "\"n\"",
13792             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
13793   EXPECT_EQ("\"\\\\\\\\\"\n"
13794             "\"\\n\"",
13795             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
13796   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
13797   EXPECT_EQ("\"\\uff01\"\n"
13798             "\"test\"",
13799             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
13800   EXPECT_EQ("\"\\Uff01ff02\"",
13801             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
13802   EXPECT_EQ("\"\\x000000000001\"\n"
13803             "\"next\"",
13804             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
13805   EXPECT_EQ("\"\\x000000000001next\"",
13806             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
13807   EXPECT_EQ("\"\\x000000000001\"",
13808             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
13809   EXPECT_EQ("\"test\"\n"
13810             "\"\\000000\"\n"
13811             "\"000001\"",
13812             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
13813   EXPECT_EQ("\"test\\000\"\n"
13814             "\"00000000\"\n"
13815             "\"1\"",
13816             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
13817 }
13818 
13819 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
13820   verifyFormat("void f() {\n"
13821                "  return g() {}\n"
13822                "  void h() {}");
13823   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
13824                "g();\n"
13825                "}");
13826 }
13827 
13828 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
13829   verifyFormat(
13830       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
13831 }
13832 
13833 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
13834   verifyFormat("class X {\n"
13835                "  void f() {\n"
13836                "  }\n"
13837                "};",
13838                getLLVMStyleWithColumns(12));
13839 }
13840 
13841 TEST_F(FormatTest, ConfigurableIndentWidth) {
13842   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
13843   EightIndent.IndentWidth = 8;
13844   EightIndent.ContinuationIndentWidth = 8;
13845   verifyFormat("void f() {\n"
13846                "        someFunction();\n"
13847                "        if (true) {\n"
13848                "                f();\n"
13849                "        }\n"
13850                "}",
13851                EightIndent);
13852   verifyFormat("class X {\n"
13853                "        void f() {\n"
13854                "        }\n"
13855                "};",
13856                EightIndent);
13857   verifyFormat("int x[] = {\n"
13858                "        call(),\n"
13859                "        call()};",
13860                EightIndent);
13861 }
13862 
13863 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
13864   verifyFormat("double\n"
13865                "f();",
13866                getLLVMStyleWithColumns(8));
13867 }
13868 
13869 TEST_F(FormatTest, ConfigurableUseOfTab) {
13870   FormatStyle Tab = getLLVMStyleWithColumns(42);
13871   Tab.IndentWidth = 8;
13872   Tab.UseTab = FormatStyle::UT_Always;
13873   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13874 
13875   EXPECT_EQ("if (aaaaaaaa && // q\n"
13876             "    bb)\t\t// w\n"
13877             "\t;",
13878             format("if (aaaaaaaa &&// q\n"
13879                    "bb)// w\n"
13880                    ";",
13881                    Tab));
13882   EXPECT_EQ("if (aaa && bbb) // w\n"
13883             "\t;",
13884             format("if(aaa&&bbb)// w\n"
13885                    ";",
13886                    Tab));
13887 
13888   verifyFormat("class X {\n"
13889                "\tvoid f() {\n"
13890                "\t\tsomeFunction(parameter1,\n"
13891                "\t\t\t     parameter2);\n"
13892                "\t}\n"
13893                "};",
13894                Tab);
13895   verifyFormat("#define A                        \\\n"
13896                "\tvoid f() {               \\\n"
13897                "\t\tsomeFunction(    \\\n"
13898                "\t\t    parameter1,  \\\n"
13899                "\t\t    parameter2); \\\n"
13900                "\t}",
13901                Tab);
13902   verifyFormat("int a;\t      // x\n"
13903                "int bbbbbbbb; // x\n",
13904                Tab);
13905 
13906   Tab.TabWidth = 4;
13907   Tab.IndentWidth = 8;
13908   verifyFormat("class TabWidth4Indent8 {\n"
13909                "\t\tvoid f() {\n"
13910                "\t\t\t\tsomeFunction(parameter1,\n"
13911                "\t\t\t\t\t\t\t parameter2);\n"
13912                "\t\t}\n"
13913                "};",
13914                Tab);
13915 
13916   Tab.TabWidth = 4;
13917   Tab.IndentWidth = 4;
13918   verifyFormat("class TabWidth4Indent4 {\n"
13919                "\tvoid f() {\n"
13920                "\t\tsomeFunction(parameter1,\n"
13921                "\t\t\t\t\t parameter2);\n"
13922                "\t}\n"
13923                "};",
13924                Tab);
13925 
13926   Tab.TabWidth = 8;
13927   Tab.IndentWidth = 4;
13928   verifyFormat("class TabWidth8Indent4 {\n"
13929                "    void f() {\n"
13930                "\tsomeFunction(parameter1,\n"
13931                "\t\t     parameter2);\n"
13932                "    }\n"
13933                "};",
13934                Tab);
13935 
13936   Tab.TabWidth = 8;
13937   Tab.IndentWidth = 8;
13938   EXPECT_EQ("/*\n"
13939             "\t      a\t\tcomment\n"
13940             "\t      in multiple lines\n"
13941             "       */",
13942             format("   /*\t \t \n"
13943                    " \t \t a\t\tcomment\t \t\n"
13944                    " \t \t in multiple lines\t\n"
13945                    " \t  */",
13946                    Tab));
13947 
13948   Tab.UseTab = FormatStyle::UT_ForIndentation;
13949   verifyFormat("{\n"
13950                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13951                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13952                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13953                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13954                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13955                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13956                "};",
13957                Tab);
13958   verifyFormat("enum AA {\n"
13959                "\ta1, // Force multiple lines\n"
13960                "\ta2,\n"
13961                "\ta3\n"
13962                "};",
13963                Tab);
13964   EXPECT_EQ("if (aaaaaaaa && // q\n"
13965             "    bb)         // w\n"
13966             "\t;",
13967             format("if (aaaaaaaa &&// q\n"
13968                    "bb)// w\n"
13969                    ";",
13970                    Tab));
13971   verifyFormat("class X {\n"
13972                "\tvoid f() {\n"
13973                "\t\tsomeFunction(parameter1,\n"
13974                "\t\t             parameter2);\n"
13975                "\t}\n"
13976                "};",
13977                Tab);
13978   verifyFormat("{\n"
13979                "\tQ(\n"
13980                "\t    {\n"
13981                "\t\t    int a;\n"
13982                "\t\t    someFunction(aaaaaaaa,\n"
13983                "\t\t                 bbbbbbb);\n"
13984                "\t    },\n"
13985                "\t    p);\n"
13986                "}",
13987                Tab);
13988   EXPECT_EQ("{\n"
13989             "\t/* aaaa\n"
13990             "\t   bbbb */\n"
13991             "}",
13992             format("{\n"
13993                    "/* aaaa\n"
13994                    "   bbbb */\n"
13995                    "}",
13996                    Tab));
13997   EXPECT_EQ("{\n"
13998             "\t/*\n"
13999             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14000             "\t  bbbbbbbbbbbbb\n"
14001             "\t*/\n"
14002             "}",
14003             format("{\n"
14004                    "/*\n"
14005                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14006                    "*/\n"
14007                    "}",
14008                    Tab));
14009   EXPECT_EQ("{\n"
14010             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14011             "\t// bbbbbbbbbbbbb\n"
14012             "}",
14013             format("{\n"
14014                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14015                    "}",
14016                    Tab));
14017   EXPECT_EQ("{\n"
14018             "\t/*\n"
14019             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14020             "\t  bbbbbbbbbbbbb\n"
14021             "\t*/\n"
14022             "}",
14023             format("{\n"
14024                    "\t/*\n"
14025                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14026                    "\t*/\n"
14027                    "}",
14028                    Tab));
14029   EXPECT_EQ("{\n"
14030             "\t/*\n"
14031             "\n"
14032             "\t*/\n"
14033             "}",
14034             format("{\n"
14035                    "\t/*\n"
14036                    "\n"
14037                    "\t*/\n"
14038                    "}",
14039                    Tab));
14040   EXPECT_EQ("{\n"
14041             "\t/*\n"
14042             " asdf\n"
14043             "\t*/\n"
14044             "}",
14045             format("{\n"
14046                    "\t/*\n"
14047                    " asdf\n"
14048                    "\t*/\n"
14049                    "}",
14050                    Tab));
14051 
14052   verifyFormat("void f() {\n"
14053                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14054                "\t            : bbbbbbbbbbbbbbbbbb\n"
14055                "}",
14056                Tab);
14057   FormatStyle TabNoBreak = Tab;
14058   TabNoBreak.BreakBeforeTernaryOperators = false;
14059   verifyFormat("void f() {\n"
14060                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14061                "\t              bbbbbbbbbbbbbbbbbb\n"
14062                "}",
14063                TabNoBreak);
14064   verifyFormat("void f() {\n"
14065                "\treturn true ?\n"
14066                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14067                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14068                "}",
14069                TabNoBreak);
14070 
14071   Tab.UseTab = FormatStyle::UT_Never;
14072   EXPECT_EQ("/*\n"
14073             "              a\t\tcomment\n"
14074             "              in multiple lines\n"
14075             "       */",
14076             format("   /*\t \t \n"
14077                    " \t \t a\t\tcomment\t \t\n"
14078                    " \t \t in multiple lines\t\n"
14079                    " \t  */",
14080                    Tab));
14081   EXPECT_EQ("/* some\n"
14082             "   comment */",
14083             format(" \t \t /* some\n"
14084                    " \t \t    comment */",
14085                    Tab));
14086   EXPECT_EQ("int a; /* some\n"
14087             "   comment */",
14088             format(" \t \t int a; /* some\n"
14089                    " \t \t    comment */",
14090                    Tab));
14091 
14092   EXPECT_EQ("int a; /* some\n"
14093             "comment */",
14094             format(" \t \t int\ta; /* some\n"
14095                    " \t \t    comment */",
14096                    Tab));
14097   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14098             "    comment */",
14099             format(" \t \t f(\"\t\t\"); /* some\n"
14100                    " \t \t    comment */",
14101                    Tab));
14102   EXPECT_EQ("{\n"
14103             "        /*\n"
14104             "         * Comment\n"
14105             "         */\n"
14106             "        int i;\n"
14107             "}",
14108             format("{\n"
14109                    "\t/*\n"
14110                    "\t * Comment\n"
14111                    "\t */\n"
14112                    "\t int i;\n"
14113                    "}",
14114                    Tab));
14115 
14116   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14117   Tab.TabWidth = 8;
14118   Tab.IndentWidth = 8;
14119   EXPECT_EQ("if (aaaaaaaa && // q\n"
14120             "    bb)         // w\n"
14121             "\t;",
14122             format("if (aaaaaaaa &&// q\n"
14123                    "bb)// w\n"
14124                    ";",
14125                    Tab));
14126   EXPECT_EQ("if (aaa && bbb) // w\n"
14127             "\t;",
14128             format("if(aaa&&bbb)// w\n"
14129                    ";",
14130                    Tab));
14131   verifyFormat("class X {\n"
14132                "\tvoid f() {\n"
14133                "\t\tsomeFunction(parameter1,\n"
14134                "\t\t\t     parameter2);\n"
14135                "\t}\n"
14136                "};",
14137                Tab);
14138   verifyFormat("#define A                        \\\n"
14139                "\tvoid f() {               \\\n"
14140                "\t\tsomeFunction(    \\\n"
14141                "\t\t    parameter1,  \\\n"
14142                "\t\t    parameter2); \\\n"
14143                "\t}",
14144                Tab);
14145   Tab.TabWidth = 4;
14146   Tab.IndentWidth = 8;
14147   verifyFormat("class TabWidth4Indent8 {\n"
14148                "\t\tvoid f() {\n"
14149                "\t\t\t\tsomeFunction(parameter1,\n"
14150                "\t\t\t\t\t\t\t parameter2);\n"
14151                "\t\t}\n"
14152                "};",
14153                Tab);
14154   Tab.TabWidth = 4;
14155   Tab.IndentWidth = 4;
14156   verifyFormat("class TabWidth4Indent4 {\n"
14157                "\tvoid f() {\n"
14158                "\t\tsomeFunction(parameter1,\n"
14159                "\t\t\t\t\t parameter2);\n"
14160                "\t}\n"
14161                "};",
14162                Tab);
14163   Tab.TabWidth = 8;
14164   Tab.IndentWidth = 4;
14165   verifyFormat("class TabWidth8Indent4 {\n"
14166                "    void f() {\n"
14167                "\tsomeFunction(parameter1,\n"
14168                "\t\t     parameter2);\n"
14169                "    }\n"
14170                "};",
14171                Tab);
14172   Tab.TabWidth = 8;
14173   Tab.IndentWidth = 8;
14174   EXPECT_EQ("/*\n"
14175             "\t      a\t\tcomment\n"
14176             "\t      in multiple lines\n"
14177             "       */",
14178             format("   /*\t \t \n"
14179                    " \t \t a\t\tcomment\t \t\n"
14180                    " \t \t in multiple lines\t\n"
14181                    " \t  */",
14182                    Tab));
14183   verifyFormat("{\n"
14184                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14185                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14186                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14187                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14188                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14189                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14190                "};",
14191                Tab);
14192   verifyFormat("enum AA {\n"
14193                "\ta1, // Force multiple lines\n"
14194                "\ta2,\n"
14195                "\ta3\n"
14196                "};",
14197                Tab);
14198   EXPECT_EQ("if (aaaaaaaa && // q\n"
14199             "    bb)         // w\n"
14200             "\t;",
14201             format("if (aaaaaaaa &&// q\n"
14202                    "bb)// w\n"
14203                    ";",
14204                    Tab));
14205   verifyFormat("class X {\n"
14206                "\tvoid f() {\n"
14207                "\t\tsomeFunction(parameter1,\n"
14208                "\t\t\t     parameter2);\n"
14209                "\t}\n"
14210                "};",
14211                Tab);
14212   verifyFormat("{\n"
14213                "\tQ(\n"
14214                "\t    {\n"
14215                "\t\t    int a;\n"
14216                "\t\t    someFunction(aaaaaaaa,\n"
14217                "\t\t\t\t bbbbbbb);\n"
14218                "\t    },\n"
14219                "\t    p);\n"
14220                "}",
14221                Tab);
14222   EXPECT_EQ("{\n"
14223             "\t/* aaaa\n"
14224             "\t   bbbb */\n"
14225             "}",
14226             format("{\n"
14227                    "/* aaaa\n"
14228                    "   bbbb */\n"
14229                    "}",
14230                    Tab));
14231   EXPECT_EQ("{\n"
14232             "\t/*\n"
14233             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14234             "\t  bbbbbbbbbbbbb\n"
14235             "\t*/\n"
14236             "}",
14237             format("{\n"
14238                    "/*\n"
14239                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14240                    "*/\n"
14241                    "}",
14242                    Tab));
14243   EXPECT_EQ("{\n"
14244             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14245             "\t// bbbbbbbbbbbbb\n"
14246             "}",
14247             format("{\n"
14248                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14249                    "}",
14250                    Tab));
14251   EXPECT_EQ("{\n"
14252             "\t/*\n"
14253             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14254             "\t  bbbbbbbbbbbbb\n"
14255             "\t*/\n"
14256             "}",
14257             format("{\n"
14258                    "\t/*\n"
14259                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14260                    "\t*/\n"
14261                    "}",
14262                    Tab));
14263   EXPECT_EQ("{\n"
14264             "\t/*\n"
14265             "\n"
14266             "\t*/\n"
14267             "}",
14268             format("{\n"
14269                    "\t/*\n"
14270                    "\n"
14271                    "\t*/\n"
14272                    "}",
14273                    Tab));
14274   EXPECT_EQ("{\n"
14275             "\t/*\n"
14276             " asdf\n"
14277             "\t*/\n"
14278             "}",
14279             format("{\n"
14280                    "\t/*\n"
14281                    " asdf\n"
14282                    "\t*/\n"
14283                    "}",
14284                    Tab));
14285   EXPECT_EQ("/* some\n"
14286             "   comment */",
14287             format(" \t \t /* some\n"
14288                    " \t \t    comment */",
14289                    Tab));
14290   EXPECT_EQ("int a; /* some\n"
14291             "   comment */",
14292             format(" \t \t int a; /* some\n"
14293                    " \t \t    comment */",
14294                    Tab));
14295   EXPECT_EQ("int a; /* some\n"
14296             "comment */",
14297             format(" \t \t int\ta; /* some\n"
14298                    " \t \t    comment */",
14299                    Tab));
14300   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14301             "    comment */",
14302             format(" \t \t f(\"\t\t\"); /* some\n"
14303                    " \t \t    comment */",
14304                    Tab));
14305   EXPECT_EQ("{\n"
14306             "\t/*\n"
14307             "\t * Comment\n"
14308             "\t */\n"
14309             "\tint i;\n"
14310             "}",
14311             format("{\n"
14312                    "\t/*\n"
14313                    "\t * Comment\n"
14314                    "\t */\n"
14315                    "\t int i;\n"
14316                    "}",
14317                    Tab));
14318   Tab.TabWidth = 2;
14319   Tab.IndentWidth = 2;
14320   EXPECT_EQ("{\n"
14321             "\t/* aaaa\n"
14322             "\t\t bbbb */\n"
14323             "}",
14324             format("{\n"
14325                    "/* aaaa\n"
14326                    "\t bbbb */\n"
14327                    "}",
14328                    Tab));
14329   EXPECT_EQ("{\n"
14330             "\t/*\n"
14331             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14332             "\t\tbbbbbbbbbbbbb\n"
14333             "\t*/\n"
14334             "}",
14335             format("{\n"
14336                    "/*\n"
14337                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14338                    "*/\n"
14339                    "}",
14340                    Tab));
14341   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14342   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14343   Tab.TabWidth = 4;
14344   Tab.IndentWidth = 4;
14345   verifyFormat("class Assign {\n"
14346                "\tvoid f() {\n"
14347                "\t\tint         x      = 123;\n"
14348                "\t\tint         random = 4;\n"
14349                "\t\tstd::string alphabet =\n"
14350                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14351                "\t}\n"
14352                "};",
14353                Tab);
14354 
14355   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14356   Tab.TabWidth = 8;
14357   Tab.IndentWidth = 8;
14358   EXPECT_EQ("if (aaaaaaaa && // q\n"
14359             "    bb)         // w\n"
14360             "\t;",
14361             format("if (aaaaaaaa &&// q\n"
14362                    "bb)// w\n"
14363                    ";",
14364                    Tab));
14365   EXPECT_EQ("if (aaa && bbb) // w\n"
14366             "\t;",
14367             format("if(aaa&&bbb)// w\n"
14368                    ";",
14369                    Tab));
14370   verifyFormat("class X {\n"
14371                "\tvoid f() {\n"
14372                "\t\tsomeFunction(parameter1,\n"
14373                "\t\t             parameter2);\n"
14374                "\t}\n"
14375                "};",
14376                Tab);
14377   verifyFormat("#define A                        \\\n"
14378                "\tvoid f() {               \\\n"
14379                "\t\tsomeFunction(    \\\n"
14380                "\t\t    parameter1,  \\\n"
14381                "\t\t    parameter2); \\\n"
14382                "\t}",
14383                Tab);
14384   Tab.TabWidth = 4;
14385   Tab.IndentWidth = 8;
14386   verifyFormat("class TabWidth4Indent8 {\n"
14387                "\t\tvoid f() {\n"
14388                "\t\t\t\tsomeFunction(parameter1,\n"
14389                "\t\t\t\t             parameter2);\n"
14390                "\t\t}\n"
14391                "};",
14392                Tab);
14393   Tab.TabWidth = 4;
14394   Tab.IndentWidth = 4;
14395   verifyFormat("class TabWidth4Indent4 {\n"
14396                "\tvoid f() {\n"
14397                "\t\tsomeFunction(parameter1,\n"
14398                "\t\t             parameter2);\n"
14399                "\t}\n"
14400                "};",
14401                Tab);
14402   Tab.TabWidth = 8;
14403   Tab.IndentWidth = 4;
14404   verifyFormat("class TabWidth8Indent4 {\n"
14405                "    void f() {\n"
14406                "\tsomeFunction(parameter1,\n"
14407                "\t             parameter2);\n"
14408                "    }\n"
14409                "};",
14410                Tab);
14411   Tab.TabWidth = 8;
14412   Tab.IndentWidth = 8;
14413   EXPECT_EQ("/*\n"
14414             "              a\t\tcomment\n"
14415             "              in multiple lines\n"
14416             "       */",
14417             format("   /*\t \t \n"
14418                    " \t \t a\t\tcomment\t \t\n"
14419                    " \t \t in multiple lines\t\n"
14420                    " \t  */",
14421                    Tab));
14422   verifyFormat("{\n"
14423                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14424                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14425                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14426                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14427                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14428                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14429                "};",
14430                Tab);
14431   verifyFormat("enum AA {\n"
14432                "\ta1, // Force multiple lines\n"
14433                "\ta2,\n"
14434                "\ta3\n"
14435                "};",
14436                Tab);
14437   EXPECT_EQ("if (aaaaaaaa && // q\n"
14438             "    bb)         // w\n"
14439             "\t;",
14440             format("if (aaaaaaaa &&// q\n"
14441                    "bb)// w\n"
14442                    ";",
14443                    Tab));
14444   verifyFormat("class X {\n"
14445                "\tvoid f() {\n"
14446                "\t\tsomeFunction(parameter1,\n"
14447                "\t\t             parameter2);\n"
14448                "\t}\n"
14449                "};",
14450                Tab);
14451   verifyFormat("{\n"
14452                "\tQ(\n"
14453                "\t    {\n"
14454                "\t\t    int a;\n"
14455                "\t\t    someFunction(aaaaaaaa,\n"
14456                "\t\t                 bbbbbbb);\n"
14457                "\t    },\n"
14458                "\t    p);\n"
14459                "}",
14460                Tab);
14461   EXPECT_EQ("{\n"
14462             "\t/* aaaa\n"
14463             "\t   bbbb */\n"
14464             "}",
14465             format("{\n"
14466                    "/* aaaa\n"
14467                    "   bbbb */\n"
14468                    "}",
14469                    Tab));
14470   EXPECT_EQ("{\n"
14471             "\t/*\n"
14472             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14473             "\t  bbbbbbbbbbbbb\n"
14474             "\t*/\n"
14475             "}",
14476             format("{\n"
14477                    "/*\n"
14478                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14479                    "*/\n"
14480                    "}",
14481                    Tab));
14482   EXPECT_EQ("{\n"
14483             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14484             "\t// bbbbbbbbbbbbb\n"
14485             "}",
14486             format("{\n"
14487                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14488                    "}",
14489                    Tab));
14490   EXPECT_EQ("{\n"
14491             "\t/*\n"
14492             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14493             "\t  bbbbbbbbbbbbb\n"
14494             "\t*/\n"
14495             "}",
14496             format("{\n"
14497                    "\t/*\n"
14498                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14499                    "\t*/\n"
14500                    "}",
14501                    Tab));
14502   EXPECT_EQ("{\n"
14503             "\t/*\n"
14504             "\n"
14505             "\t*/\n"
14506             "}",
14507             format("{\n"
14508                    "\t/*\n"
14509                    "\n"
14510                    "\t*/\n"
14511                    "}",
14512                    Tab));
14513   EXPECT_EQ("{\n"
14514             "\t/*\n"
14515             " asdf\n"
14516             "\t*/\n"
14517             "}",
14518             format("{\n"
14519                    "\t/*\n"
14520                    " asdf\n"
14521                    "\t*/\n"
14522                    "}",
14523                    Tab));
14524   EXPECT_EQ("/* some\n"
14525             "   comment */",
14526             format(" \t \t /* some\n"
14527                    " \t \t    comment */",
14528                    Tab));
14529   EXPECT_EQ("int a; /* some\n"
14530             "   comment */",
14531             format(" \t \t int a; /* some\n"
14532                    " \t \t    comment */",
14533                    Tab));
14534   EXPECT_EQ("int a; /* some\n"
14535             "comment */",
14536             format(" \t \t int\ta; /* some\n"
14537                    " \t \t    comment */",
14538                    Tab));
14539   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14540             "    comment */",
14541             format(" \t \t f(\"\t\t\"); /* some\n"
14542                    " \t \t    comment */",
14543                    Tab));
14544   EXPECT_EQ("{\n"
14545             "\t/*\n"
14546             "\t * Comment\n"
14547             "\t */\n"
14548             "\tint i;\n"
14549             "}",
14550             format("{\n"
14551                    "\t/*\n"
14552                    "\t * Comment\n"
14553                    "\t */\n"
14554                    "\t int i;\n"
14555                    "}",
14556                    Tab));
14557   Tab.TabWidth = 2;
14558   Tab.IndentWidth = 2;
14559   EXPECT_EQ("{\n"
14560             "\t/* aaaa\n"
14561             "\t   bbbb */\n"
14562             "}",
14563             format("{\n"
14564                    "/* aaaa\n"
14565                    "   bbbb */\n"
14566                    "}",
14567                    Tab));
14568   EXPECT_EQ("{\n"
14569             "\t/*\n"
14570             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14571             "\t  bbbbbbbbbbbbb\n"
14572             "\t*/\n"
14573             "}",
14574             format("{\n"
14575                    "/*\n"
14576                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14577                    "*/\n"
14578                    "}",
14579                    Tab));
14580   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14581   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14582   Tab.TabWidth = 4;
14583   Tab.IndentWidth = 4;
14584   verifyFormat("class Assign {\n"
14585                "\tvoid f() {\n"
14586                "\t\tint         x      = 123;\n"
14587                "\t\tint         random = 4;\n"
14588                "\t\tstd::string alphabet =\n"
14589                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14590                "\t}\n"
14591                "};",
14592                Tab);
14593   Tab.AlignOperands = FormatStyle::OAS_Align;
14594   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14595                "                 cccccccccccccccccccc;",
14596                Tab);
14597   // no alignment
14598   verifyFormat("int aaaaaaaaaa =\n"
14599                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14600                Tab);
14601   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14602                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14603                "                        : 333333333333333;",
14604                Tab);
14605   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14606   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14607   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14608                "               + cccccccccccccccccccc;",
14609                Tab);
14610 }
14611 
14612 TEST_F(FormatTest, ZeroTabWidth) {
14613   FormatStyle Tab = getLLVMStyleWithColumns(42);
14614   Tab.IndentWidth = 8;
14615   Tab.UseTab = FormatStyle::UT_Never;
14616   Tab.TabWidth = 0;
14617   EXPECT_EQ("void a(){\n"
14618             "    // line starts with '\t'\n"
14619             "};",
14620             format("void a(){\n"
14621                    "\t// line starts with '\t'\n"
14622                    "};",
14623                    Tab));
14624 
14625   EXPECT_EQ("void a(){\n"
14626             "    // line starts with '\t'\n"
14627             "};",
14628             format("void a(){\n"
14629                    "\t\t// line starts with '\t'\n"
14630                    "};",
14631                    Tab));
14632 
14633   Tab.UseTab = FormatStyle::UT_ForIndentation;
14634   EXPECT_EQ("void a(){\n"
14635             "    // line starts with '\t'\n"
14636             "};",
14637             format("void a(){\n"
14638                    "\t// line starts with '\t'\n"
14639                    "};",
14640                    Tab));
14641 
14642   EXPECT_EQ("void a(){\n"
14643             "    // line starts with '\t'\n"
14644             "};",
14645             format("void a(){\n"
14646                    "\t\t// line starts with '\t'\n"
14647                    "};",
14648                    Tab));
14649 
14650   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14651   EXPECT_EQ("void a(){\n"
14652             "    // line starts with '\t'\n"
14653             "};",
14654             format("void a(){\n"
14655                    "\t// line starts with '\t'\n"
14656                    "};",
14657                    Tab));
14658 
14659   EXPECT_EQ("void a(){\n"
14660             "    // line starts with '\t'\n"
14661             "};",
14662             format("void a(){\n"
14663                    "\t\t// line starts with '\t'\n"
14664                    "};",
14665                    Tab));
14666 
14667   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14668   EXPECT_EQ("void a(){\n"
14669             "    // line starts with '\t'\n"
14670             "};",
14671             format("void a(){\n"
14672                    "\t// line starts with '\t'\n"
14673                    "};",
14674                    Tab));
14675 
14676   EXPECT_EQ("void a(){\n"
14677             "    // line starts with '\t'\n"
14678             "};",
14679             format("void a(){\n"
14680                    "\t\t// line starts with '\t'\n"
14681                    "};",
14682                    Tab));
14683 
14684   Tab.UseTab = FormatStyle::UT_Always;
14685   EXPECT_EQ("void a(){\n"
14686             "// line starts with '\t'\n"
14687             "};",
14688             format("void a(){\n"
14689                    "\t// line starts with '\t'\n"
14690                    "};",
14691                    Tab));
14692 
14693   EXPECT_EQ("void a(){\n"
14694             "// line starts with '\t'\n"
14695             "};",
14696             format("void a(){\n"
14697                    "\t\t// line starts with '\t'\n"
14698                    "};",
14699                    Tab));
14700 }
14701 
14702 TEST_F(FormatTest, CalculatesOriginalColumn) {
14703   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14704             "q\"; /* some\n"
14705             "       comment */",
14706             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14707                    "q\"; /* some\n"
14708                    "       comment */",
14709                    getLLVMStyle()));
14710   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14711             "/* some\n"
14712             "   comment */",
14713             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14714                    " /* some\n"
14715                    "    comment */",
14716                    getLLVMStyle()));
14717   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14718             "qqq\n"
14719             "/* some\n"
14720             "   comment */",
14721             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14722                    "qqq\n"
14723                    " /* some\n"
14724                    "    comment */",
14725                    getLLVMStyle()));
14726   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14727             "wwww; /* some\n"
14728             "         comment */",
14729             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14730                    "wwww; /* some\n"
14731                    "         comment */",
14732                    getLLVMStyle()));
14733 }
14734 
14735 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14736   FormatStyle NoSpace = getLLVMStyle();
14737   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14738 
14739   verifyFormat("while(true)\n"
14740                "  continue;",
14741                NoSpace);
14742   verifyFormat("for(;;)\n"
14743                "  continue;",
14744                NoSpace);
14745   verifyFormat("if(true)\n"
14746                "  f();\n"
14747                "else if(true)\n"
14748                "  f();",
14749                NoSpace);
14750   verifyFormat("do {\n"
14751                "  do_something();\n"
14752                "} while(something());",
14753                NoSpace);
14754   verifyFormat("switch(x) {\n"
14755                "default:\n"
14756                "  break;\n"
14757                "}",
14758                NoSpace);
14759   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14760   verifyFormat("size_t x = sizeof(x);", NoSpace);
14761   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14762   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14763   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14764   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14765   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14766   verifyFormat("alignas(128) char a[128];", NoSpace);
14767   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14768   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14769   verifyFormat("int f() throw(Deprecated);", NoSpace);
14770   verifyFormat("typedef void (*cb)(int);", NoSpace);
14771   verifyFormat("T A::operator()();", NoSpace);
14772   verifyFormat("X A::operator++(T);", NoSpace);
14773   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14774 
14775   FormatStyle Space = getLLVMStyle();
14776   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14777 
14778   verifyFormat("int f ();", Space);
14779   verifyFormat("void f (int a, T b) {\n"
14780                "  while (true)\n"
14781                "    continue;\n"
14782                "}",
14783                Space);
14784   verifyFormat("if (true)\n"
14785                "  f ();\n"
14786                "else if (true)\n"
14787                "  f ();",
14788                Space);
14789   verifyFormat("do {\n"
14790                "  do_something ();\n"
14791                "} while (something ());",
14792                Space);
14793   verifyFormat("switch (x) {\n"
14794                "default:\n"
14795                "  break;\n"
14796                "}",
14797                Space);
14798   verifyFormat("A::A () : a (1) {}", Space);
14799   verifyFormat("void f () __attribute__ ((asdf));", Space);
14800   verifyFormat("*(&a + 1);\n"
14801                "&((&a)[1]);\n"
14802                "a[(b + c) * d];\n"
14803                "(((a + 1) * 2) + 3) * 4;",
14804                Space);
14805   verifyFormat("#define A(x) x", Space);
14806   verifyFormat("#define A (x) x", Space);
14807   verifyFormat("#if defined(x)\n"
14808                "#endif",
14809                Space);
14810   verifyFormat("auto i = std::make_unique<int> (5);", Space);
14811   verifyFormat("size_t x = sizeof (x);", Space);
14812   verifyFormat("auto f (int x) -> decltype (x);", Space);
14813   verifyFormat("auto f (int x) -> typeof (x);", Space);
14814   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
14815   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
14816   verifyFormat("int f (T x) noexcept (x.create ());", Space);
14817   verifyFormat("alignas (128) char a[128];", Space);
14818   verifyFormat("size_t x = alignof (MyType);", Space);
14819   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
14820   verifyFormat("int f () throw (Deprecated);", Space);
14821   verifyFormat("typedef void (*cb) (int);", Space);
14822   // FIXME these tests regressed behaviour.
14823   // verifyFormat("T A::operator() ();", Space);
14824   // verifyFormat("X A::operator++ (T);", Space);
14825   verifyFormat("auto lambda = [] () { return 0; };", Space);
14826   verifyFormat("int x = int (y);", Space);
14827 
14828   FormatStyle SomeSpace = getLLVMStyle();
14829   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
14830 
14831   verifyFormat("[]() -> float {}", SomeSpace);
14832   verifyFormat("[] (auto foo) {}", SomeSpace);
14833   verifyFormat("[foo]() -> int {}", SomeSpace);
14834   verifyFormat("int f();", SomeSpace);
14835   verifyFormat("void f (int a, T b) {\n"
14836                "  while (true)\n"
14837                "    continue;\n"
14838                "}",
14839                SomeSpace);
14840   verifyFormat("if (true)\n"
14841                "  f();\n"
14842                "else if (true)\n"
14843                "  f();",
14844                SomeSpace);
14845   verifyFormat("do {\n"
14846                "  do_something();\n"
14847                "} while (something());",
14848                SomeSpace);
14849   verifyFormat("switch (x) {\n"
14850                "default:\n"
14851                "  break;\n"
14852                "}",
14853                SomeSpace);
14854   verifyFormat("A::A() : a (1) {}", SomeSpace);
14855   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
14856   verifyFormat("*(&a + 1);\n"
14857                "&((&a)[1]);\n"
14858                "a[(b + c) * d];\n"
14859                "(((a + 1) * 2) + 3) * 4;",
14860                SomeSpace);
14861   verifyFormat("#define A(x) x", SomeSpace);
14862   verifyFormat("#define A (x) x", SomeSpace);
14863   verifyFormat("#if defined(x)\n"
14864                "#endif",
14865                SomeSpace);
14866   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
14867   verifyFormat("size_t x = sizeof (x);", SomeSpace);
14868   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
14869   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
14870   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
14871   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
14872   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
14873   verifyFormat("alignas (128) char a[128];", SomeSpace);
14874   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
14875   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14876                SomeSpace);
14877   verifyFormat("int f() throw (Deprecated);", SomeSpace);
14878   verifyFormat("typedef void (*cb) (int);", SomeSpace);
14879   verifyFormat("T A::operator()();", SomeSpace);
14880   // FIXME these tests regressed behaviour.
14881   // verifyFormat("X A::operator++ (T);", SomeSpace);
14882   verifyFormat("int x = int (y);", SomeSpace);
14883   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
14884 
14885   FormatStyle SpaceControlStatements = getLLVMStyle();
14886   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14887   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
14888 
14889   verifyFormat("while (true)\n"
14890                "  continue;",
14891                SpaceControlStatements);
14892   verifyFormat("if (true)\n"
14893                "  f();\n"
14894                "else if (true)\n"
14895                "  f();",
14896                SpaceControlStatements);
14897   verifyFormat("for (;;) {\n"
14898                "  do_something();\n"
14899                "}",
14900                SpaceControlStatements);
14901   verifyFormat("do {\n"
14902                "  do_something();\n"
14903                "} while (something());",
14904                SpaceControlStatements);
14905   verifyFormat("switch (x) {\n"
14906                "default:\n"
14907                "  break;\n"
14908                "}",
14909                SpaceControlStatements);
14910 
14911   FormatStyle SpaceFuncDecl = getLLVMStyle();
14912   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14913   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
14914 
14915   verifyFormat("int f ();", SpaceFuncDecl);
14916   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
14917   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
14918   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
14919   verifyFormat("#define A(x) x", SpaceFuncDecl);
14920   verifyFormat("#define A (x) x", SpaceFuncDecl);
14921   verifyFormat("#if defined(x)\n"
14922                "#endif",
14923                SpaceFuncDecl);
14924   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
14925   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
14926   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
14927   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
14928   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
14929   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
14930   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
14931   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
14932   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
14933   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14934                SpaceFuncDecl);
14935   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
14936   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
14937   // FIXME these tests regressed behaviour.
14938   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
14939   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
14940   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
14941   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
14942   verifyFormat("int x = int(y);", SpaceFuncDecl);
14943   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14944                SpaceFuncDecl);
14945 
14946   FormatStyle SpaceFuncDef = getLLVMStyle();
14947   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14948   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
14949 
14950   verifyFormat("int f();", SpaceFuncDef);
14951   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
14952   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
14953   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
14954   verifyFormat("#define A(x) x", SpaceFuncDef);
14955   verifyFormat("#define A (x) x", SpaceFuncDef);
14956   verifyFormat("#if defined(x)\n"
14957                "#endif",
14958                SpaceFuncDef);
14959   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
14960   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
14961   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
14962   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
14963   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
14964   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
14965   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
14966   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
14967   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
14968   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14969                SpaceFuncDef);
14970   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
14971   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
14972   verifyFormat("T A::operator()();", SpaceFuncDef);
14973   verifyFormat("X A::operator++(T);", SpaceFuncDef);
14974   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
14975   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
14976   verifyFormat("int x = int(y);", SpaceFuncDef);
14977   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14978                SpaceFuncDef);
14979 
14980   FormatStyle SpaceIfMacros = getLLVMStyle();
14981   SpaceIfMacros.IfMacros.clear();
14982   SpaceIfMacros.IfMacros.push_back("MYIF");
14983   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14984   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
14985   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
14986   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
14987   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
14988 
14989   FormatStyle SpaceForeachMacros = getLLVMStyle();
14990   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
14991             FormatStyle::SBS_Never);
14992   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
14993   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14994   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
14995   verifyFormat("for (;;) {\n"
14996                "}",
14997                SpaceForeachMacros);
14998   verifyFormat("foreach (Item *item, itemlist) {\n"
14999                "}",
15000                SpaceForeachMacros);
15001   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15002                "}",
15003                SpaceForeachMacros);
15004   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15005                "}",
15006                SpaceForeachMacros);
15007   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15008 
15009   FormatStyle SomeSpace2 = getLLVMStyle();
15010   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15011   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15012   verifyFormat("[]() -> float {}", SomeSpace2);
15013   verifyFormat("[] (auto foo) {}", SomeSpace2);
15014   verifyFormat("[foo]() -> int {}", SomeSpace2);
15015   verifyFormat("int f();", SomeSpace2);
15016   verifyFormat("void f (int a, T b) {\n"
15017                "  while (true)\n"
15018                "    continue;\n"
15019                "}",
15020                SomeSpace2);
15021   verifyFormat("if (true)\n"
15022                "  f();\n"
15023                "else if (true)\n"
15024                "  f();",
15025                SomeSpace2);
15026   verifyFormat("do {\n"
15027                "  do_something();\n"
15028                "} while (something());",
15029                SomeSpace2);
15030   verifyFormat("switch (x) {\n"
15031                "default:\n"
15032                "  break;\n"
15033                "}",
15034                SomeSpace2);
15035   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15036   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15037   verifyFormat("*(&a + 1);\n"
15038                "&((&a)[1]);\n"
15039                "a[(b + c) * d];\n"
15040                "(((a + 1) * 2) + 3) * 4;",
15041                SomeSpace2);
15042   verifyFormat("#define A(x) x", SomeSpace2);
15043   verifyFormat("#define A (x) x", SomeSpace2);
15044   verifyFormat("#if defined(x)\n"
15045                "#endif",
15046                SomeSpace2);
15047   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15048   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15049   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15050   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15051   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15052   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15053   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15054   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15055   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15056   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15057                SomeSpace2);
15058   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15059   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15060   verifyFormat("T A::operator()();", SomeSpace2);
15061   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15062   verifyFormat("int x = int (y);", SomeSpace2);
15063   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15064 
15065   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15066   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15067   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15068       .AfterOverloadedOperator = true;
15069 
15070   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15071   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15072   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15073   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15074 
15075   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15076       .AfterOverloadedOperator = false;
15077 
15078   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15079   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15080   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15081   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15082 
15083   auto SpaceAfterRequires = getLLVMStyle();
15084   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15085   EXPECT_FALSE(
15086       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15087   EXPECT_FALSE(
15088       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15089   verifyFormat("void f(auto x)\n"
15090                "  requires requires(int i) { x + i; }\n"
15091                "{}",
15092                SpaceAfterRequires);
15093   verifyFormat("void f(auto x)\n"
15094                "  requires(requires(int i) { x + i; })\n"
15095                "{}",
15096                SpaceAfterRequires);
15097   verifyFormat("if (requires(int i) { x + i; })\n"
15098                "  return;",
15099                SpaceAfterRequires);
15100   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15101   verifyFormat("template <typename T>\n"
15102                "  requires(Foo<T>)\n"
15103                "class Bar;",
15104                SpaceAfterRequires);
15105 
15106   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15107   verifyFormat("void f(auto x)\n"
15108                "  requires requires(int i) { x + i; }\n"
15109                "{}",
15110                SpaceAfterRequires);
15111   verifyFormat("void f(auto x)\n"
15112                "  requires (requires(int i) { x + i; })\n"
15113                "{}",
15114                SpaceAfterRequires);
15115   verifyFormat("if (requires(int i) { x + i; })\n"
15116                "  return;",
15117                SpaceAfterRequires);
15118   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15119   verifyFormat("template <typename T>\n"
15120                "  requires (Foo<T>)\n"
15121                "class Bar;",
15122                SpaceAfterRequires);
15123 
15124   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15125   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15126   verifyFormat("void f(auto x)\n"
15127                "  requires requires (int i) { x + i; }\n"
15128                "{}",
15129                SpaceAfterRequires);
15130   verifyFormat("void f(auto x)\n"
15131                "  requires(requires (int i) { x + i; })\n"
15132                "{}",
15133                SpaceAfterRequires);
15134   verifyFormat("if (requires (int i) { x + i; })\n"
15135                "  return;",
15136                SpaceAfterRequires);
15137   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15138   verifyFormat("template <typename T>\n"
15139                "  requires(Foo<T>)\n"
15140                "class Bar;",
15141                SpaceAfterRequires);
15142 
15143   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15144   verifyFormat("void f(auto x)\n"
15145                "  requires requires (int i) { x + i; }\n"
15146                "{}",
15147                SpaceAfterRequires);
15148   verifyFormat("void f(auto x)\n"
15149                "  requires (requires (int i) { x + i; })\n"
15150                "{}",
15151                SpaceAfterRequires);
15152   verifyFormat("if (requires (int i) { x + i; })\n"
15153                "  return;",
15154                SpaceAfterRequires);
15155   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15156   verifyFormat("template <typename T>\n"
15157                "  requires (Foo<T>)\n"
15158                "class Bar;",
15159                SpaceAfterRequires);
15160 }
15161 
15162 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15163   FormatStyle Spaces = getLLVMStyle();
15164   Spaces.SpaceAfterLogicalNot = true;
15165 
15166   verifyFormat("bool x = ! y", Spaces);
15167   verifyFormat("if (! isFailure())", Spaces);
15168   verifyFormat("if (! (a && b))", Spaces);
15169   verifyFormat("\"Error!\"", Spaces);
15170   verifyFormat("! ! x", Spaces);
15171 }
15172 
15173 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15174   FormatStyle Spaces = getLLVMStyle();
15175 
15176   Spaces.SpacesInParentheses = true;
15177   verifyFormat("do_something( ::globalVar );", Spaces);
15178   verifyFormat("call( x, y, z );", Spaces);
15179   verifyFormat("call();", Spaces);
15180   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15181   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15182                Spaces);
15183   verifyFormat("while ( (bool)1 )\n"
15184                "  continue;",
15185                Spaces);
15186   verifyFormat("for ( ;; )\n"
15187                "  continue;",
15188                Spaces);
15189   verifyFormat("if ( true )\n"
15190                "  f();\n"
15191                "else if ( true )\n"
15192                "  f();",
15193                Spaces);
15194   verifyFormat("do {\n"
15195                "  do_something( (int)i );\n"
15196                "} while ( something() );",
15197                Spaces);
15198   verifyFormat("switch ( x ) {\n"
15199                "default:\n"
15200                "  break;\n"
15201                "}",
15202                Spaces);
15203 
15204   Spaces.SpacesInParentheses = false;
15205   Spaces.SpacesInCStyleCastParentheses = true;
15206   verifyFormat("Type *A = ( Type * )P;", Spaces);
15207   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15208   verifyFormat("x = ( int32 )y;", Spaces);
15209   verifyFormat("int a = ( int )(2.0f);", Spaces);
15210   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15211   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15212   verifyFormat("#define x (( int )-1)", Spaces);
15213 
15214   // Run the first set of tests again with:
15215   Spaces.SpacesInParentheses = false;
15216   Spaces.SpaceInEmptyParentheses = true;
15217   Spaces.SpacesInCStyleCastParentheses = true;
15218   verifyFormat("call(x, y, z);", Spaces);
15219   verifyFormat("call( );", Spaces);
15220   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15221   verifyFormat("while (( bool )1)\n"
15222                "  continue;",
15223                Spaces);
15224   verifyFormat("for (;;)\n"
15225                "  continue;",
15226                Spaces);
15227   verifyFormat("if (true)\n"
15228                "  f( );\n"
15229                "else if (true)\n"
15230                "  f( );",
15231                Spaces);
15232   verifyFormat("do {\n"
15233                "  do_something(( int )i);\n"
15234                "} while (something( ));",
15235                Spaces);
15236   verifyFormat("switch (x) {\n"
15237                "default:\n"
15238                "  break;\n"
15239                "}",
15240                Spaces);
15241 
15242   // Run the first set of tests again with:
15243   Spaces.SpaceAfterCStyleCast = true;
15244   verifyFormat("call(x, y, z);", Spaces);
15245   verifyFormat("call( );", Spaces);
15246   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15247   verifyFormat("while (( bool ) 1)\n"
15248                "  continue;",
15249                Spaces);
15250   verifyFormat("for (;;)\n"
15251                "  continue;",
15252                Spaces);
15253   verifyFormat("if (true)\n"
15254                "  f( );\n"
15255                "else if (true)\n"
15256                "  f( );",
15257                Spaces);
15258   verifyFormat("do {\n"
15259                "  do_something(( int ) i);\n"
15260                "} while (something( ));",
15261                Spaces);
15262   verifyFormat("switch (x) {\n"
15263                "default:\n"
15264                "  break;\n"
15265                "}",
15266                Spaces);
15267   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15268   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15269   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15270   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15271   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15272 
15273   // Run subset of tests again with:
15274   Spaces.SpacesInCStyleCastParentheses = false;
15275   Spaces.SpaceAfterCStyleCast = true;
15276   verifyFormat("while ((bool) 1)\n"
15277                "  continue;",
15278                Spaces);
15279   verifyFormat("do {\n"
15280                "  do_something((int) i);\n"
15281                "} while (something( ));",
15282                Spaces);
15283 
15284   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15285   verifyFormat("size_t idx = (size_t) a;", Spaces);
15286   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15287   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15288   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15289   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15290   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15291   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15292   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15293   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15294   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15295   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15296   Spaces.ColumnLimit = 80;
15297   Spaces.IndentWidth = 4;
15298   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15299   verifyFormat("void foo( ) {\n"
15300                "    size_t foo = (*(function))(\n"
15301                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15302                "BarrrrrrrrrrrrLong,\n"
15303                "        FoooooooooLooooong);\n"
15304                "}",
15305                Spaces);
15306   Spaces.SpaceAfterCStyleCast = false;
15307   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15308   verifyFormat("size_t idx = (size_t)a;", Spaces);
15309   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15310   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15311   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15312   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15313   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15314 
15315   verifyFormat("void foo( ) {\n"
15316                "    size_t foo = (*(function))(\n"
15317                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15318                "BarrrrrrrrrrrrLong,\n"
15319                "        FoooooooooLooooong);\n"
15320                "}",
15321                Spaces);
15322 }
15323 
15324 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15325   verifyFormat("int a[5];");
15326   verifyFormat("a[3] += 42;");
15327 
15328   FormatStyle Spaces = getLLVMStyle();
15329   Spaces.SpacesInSquareBrackets = true;
15330   // Not lambdas.
15331   verifyFormat("int a[ 5 ];", Spaces);
15332   verifyFormat("a[ 3 ] += 42;", Spaces);
15333   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15334   verifyFormat("double &operator[](int i) { return 0; }\n"
15335                "int i;",
15336                Spaces);
15337   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15338   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15339   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15340   // Lambdas.
15341   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15342   verifyFormat("return [ i, args... ] {};", Spaces);
15343   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15344   verifyFormat("int foo = [ = ]() {};", Spaces);
15345   verifyFormat("int foo = [ & ]() {};", Spaces);
15346   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15347   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15348 }
15349 
15350 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15351   FormatStyle NoSpaceStyle = getLLVMStyle();
15352   verifyFormat("int a[5];", NoSpaceStyle);
15353   verifyFormat("a[3] += 42;", NoSpaceStyle);
15354 
15355   verifyFormat("int a[1];", NoSpaceStyle);
15356   verifyFormat("int 1 [a];", NoSpaceStyle);
15357   verifyFormat("int a[1][2];", NoSpaceStyle);
15358   verifyFormat("a[7] = 5;", NoSpaceStyle);
15359   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15360   verifyFormat("f([] {})", NoSpaceStyle);
15361 
15362   FormatStyle Space = getLLVMStyle();
15363   Space.SpaceBeforeSquareBrackets = true;
15364   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15365   verifyFormat("return [i, args...] {};", Space);
15366 
15367   verifyFormat("int a [5];", Space);
15368   verifyFormat("a [3] += 42;", Space);
15369   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15370   verifyFormat("double &operator[](int i) { return 0; }\n"
15371                "int i;",
15372                Space);
15373   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15374   verifyFormat("int i = a [a][a]->f();", Space);
15375   verifyFormat("int i = (*b) [a]->f();", Space);
15376 
15377   verifyFormat("int a [1];", Space);
15378   verifyFormat("int 1 [a];", Space);
15379   verifyFormat("int a [1][2];", Space);
15380   verifyFormat("a [7] = 5;", Space);
15381   verifyFormat("int a = (f()) [23];", Space);
15382   verifyFormat("f([] {})", Space);
15383 }
15384 
15385 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15386   verifyFormat("int a = 5;");
15387   verifyFormat("a += 42;");
15388   verifyFormat("a or_eq 8;");
15389 
15390   FormatStyle Spaces = getLLVMStyle();
15391   Spaces.SpaceBeforeAssignmentOperators = false;
15392   verifyFormat("int a= 5;", Spaces);
15393   verifyFormat("a+= 42;", Spaces);
15394   verifyFormat("a or_eq 8;", Spaces);
15395 }
15396 
15397 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15398   verifyFormat("class Foo : public Bar {};");
15399   verifyFormat("Foo::Foo() : foo(1) {}");
15400   verifyFormat("for (auto a : b) {\n}");
15401   verifyFormat("int x = a ? b : c;");
15402   verifyFormat("{\n"
15403                "label0:\n"
15404                "  int x = 0;\n"
15405                "}");
15406   verifyFormat("switch (x) {\n"
15407                "case 1:\n"
15408                "default:\n"
15409                "}");
15410   verifyFormat("switch (allBraces) {\n"
15411                "case 1: {\n"
15412                "  break;\n"
15413                "}\n"
15414                "case 2: {\n"
15415                "  [[fallthrough]];\n"
15416                "}\n"
15417                "default: {\n"
15418                "  break;\n"
15419                "}\n"
15420                "}");
15421 
15422   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15423   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15424   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15425   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15426   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15427   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15428   verifyFormat("{\n"
15429                "label1:\n"
15430                "  int x = 0;\n"
15431                "}",
15432                CtorInitializerStyle);
15433   verifyFormat("switch (x) {\n"
15434                "case 1:\n"
15435                "default:\n"
15436                "}",
15437                CtorInitializerStyle);
15438   verifyFormat("switch (allBraces) {\n"
15439                "case 1: {\n"
15440                "  break;\n"
15441                "}\n"
15442                "case 2: {\n"
15443                "  [[fallthrough]];\n"
15444                "}\n"
15445                "default: {\n"
15446                "  break;\n"
15447                "}\n"
15448                "}",
15449                CtorInitializerStyle);
15450   CtorInitializerStyle.BreakConstructorInitializers =
15451       FormatStyle::BCIS_AfterColon;
15452   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15453                "    aaaaaaaaaaaaaaaa(1),\n"
15454                "    bbbbbbbbbbbbbbbb(2) {}",
15455                CtorInitializerStyle);
15456   CtorInitializerStyle.BreakConstructorInitializers =
15457       FormatStyle::BCIS_BeforeComma;
15458   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15459                "    : aaaaaaaaaaaaaaaa(1)\n"
15460                "    , bbbbbbbbbbbbbbbb(2) {}",
15461                CtorInitializerStyle);
15462   CtorInitializerStyle.BreakConstructorInitializers =
15463       FormatStyle::BCIS_BeforeColon;
15464   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15465                "    : aaaaaaaaaaaaaaaa(1),\n"
15466                "      bbbbbbbbbbbbbbbb(2) {}",
15467                CtorInitializerStyle);
15468   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15469   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15470                ": aaaaaaaaaaaaaaaa(1),\n"
15471                "  bbbbbbbbbbbbbbbb(2) {}",
15472                CtorInitializerStyle);
15473 
15474   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15475   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15476   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15477   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15478   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15479   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15480   verifyFormat("{\n"
15481                "label2:\n"
15482                "  int x = 0;\n"
15483                "}",
15484                InheritanceStyle);
15485   verifyFormat("switch (x) {\n"
15486                "case 1:\n"
15487                "default:\n"
15488                "}",
15489                InheritanceStyle);
15490   verifyFormat("switch (allBraces) {\n"
15491                "case 1: {\n"
15492                "  break;\n"
15493                "}\n"
15494                "case 2: {\n"
15495                "  [[fallthrough]];\n"
15496                "}\n"
15497                "default: {\n"
15498                "  break;\n"
15499                "}\n"
15500                "}",
15501                InheritanceStyle);
15502   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15503   verifyFormat("class Foooooooooooooooooooooo\n"
15504                "    : public aaaaaaaaaaaaaaaaaa,\n"
15505                "      public bbbbbbbbbbbbbbbbbb {\n"
15506                "}",
15507                InheritanceStyle);
15508   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15509   verifyFormat("class Foooooooooooooooooooooo:\n"
15510                "    public aaaaaaaaaaaaaaaaaa,\n"
15511                "    public bbbbbbbbbbbbbbbbbb {\n"
15512                "}",
15513                InheritanceStyle);
15514   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15515   verifyFormat("class Foooooooooooooooooooooo\n"
15516                "    : public aaaaaaaaaaaaaaaaaa\n"
15517                "    , public bbbbbbbbbbbbbbbbbb {\n"
15518                "}",
15519                InheritanceStyle);
15520   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15521   verifyFormat("class Foooooooooooooooooooooo\n"
15522                "    : public aaaaaaaaaaaaaaaaaa,\n"
15523                "      public bbbbbbbbbbbbbbbbbb {\n"
15524                "}",
15525                InheritanceStyle);
15526   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15527   verifyFormat("class Foooooooooooooooooooooo\n"
15528                ": public aaaaaaaaaaaaaaaaaa,\n"
15529                "  public bbbbbbbbbbbbbbbbbb {}",
15530                InheritanceStyle);
15531 
15532   FormatStyle ForLoopStyle = getLLVMStyle();
15533   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15534   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15535   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15536   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15537   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15538   verifyFormat("{\n"
15539                "label2:\n"
15540                "  int x = 0;\n"
15541                "}",
15542                ForLoopStyle);
15543   verifyFormat("switch (x) {\n"
15544                "case 1:\n"
15545                "default:\n"
15546                "}",
15547                ForLoopStyle);
15548   verifyFormat("switch (allBraces) {\n"
15549                "case 1: {\n"
15550                "  break;\n"
15551                "}\n"
15552                "case 2: {\n"
15553                "  [[fallthrough]];\n"
15554                "}\n"
15555                "default: {\n"
15556                "  break;\n"
15557                "}\n"
15558                "}",
15559                ForLoopStyle);
15560 
15561   FormatStyle CaseStyle = getLLVMStyle();
15562   CaseStyle.SpaceBeforeCaseColon = true;
15563   verifyFormat("class Foo : public Bar {};", CaseStyle);
15564   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15565   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15566   verifyFormat("int x = a ? b : c;", CaseStyle);
15567   verifyFormat("switch (x) {\n"
15568                "case 1 :\n"
15569                "default :\n"
15570                "}",
15571                CaseStyle);
15572   verifyFormat("switch (allBraces) {\n"
15573                "case 1 : {\n"
15574                "  break;\n"
15575                "}\n"
15576                "case 2 : {\n"
15577                "  [[fallthrough]];\n"
15578                "}\n"
15579                "default : {\n"
15580                "  break;\n"
15581                "}\n"
15582                "}",
15583                CaseStyle);
15584 
15585   FormatStyle NoSpaceStyle = getLLVMStyle();
15586   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15587   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15588   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15589   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15590   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15591   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15592   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15593   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15594   verifyFormat("{\n"
15595                "label3:\n"
15596                "  int x = 0;\n"
15597                "}",
15598                NoSpaceStyle);
15599   verifyFormat("switch (x) {\n"
15600                "case 1:\n"
15601                "default:\n"
15602                "}",
15603                NoSpaceStyle);
15604   verifyFormat("switch (allBraces) {\n"
15605                "case 1: {\n"
15606                "  break;\n"
15607                "}\n"
15608                "case 2: {\n"
15609                "  [[fallthrough]];\n"
15610                "}\n"
15611                "default: {\n"
15612                "  break;\n"
15613                "}\n"
15614                "}",
15615                NoSpaceStyle);
15616 
15617   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15618   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15619   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15620   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15621   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15622   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15623   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15624   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15625   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15626   verifyFormat("{\n"
15627                "label3:\n"
15628                "  int x = 0;\n"
15629                "}",
15630                InvertedSpaceStyle);
15631   verifyFormat("switch (x) {\n"
15632                "case 1 :\n"
15633                "case 2 : {\n"
15634                "  break;\n"
15635                "}\n"
15636                "default :\n"
15637                "  break;\n"
15638                "}",
15639                InvertedSpaceStyle);
15640   verifyFormat("switch (allBraces) {\n"
15641                "case 1 : {\n"
15642                "  break;\n"
15643                "}\n"
15644                "case 2 : {\n"
15645                "  [[fallthrough]];\n"
15646                "}\n"
15647                "default : {\n"
15648                "  break;\n"
15649                "}\n"
15650                "}",
15651                InvertedSpaceStyle);
15652 }
15653 
15654 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15655   FormatStyle Style = getLLVMStyle();
15656 
15657   Style.PointerAlignment = FormatStyle::PAS_Left;
15658   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15659   verifyFormat("void* const* x = NULL;", Style);
15660 
15661 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15662   do {                                                                         \
15663     Style.PointerAlignment = FormatStyle::Pointers;                            \
15664     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15665     verifyFormat(Code, Style);                                                 \
15666   } while (false)
15667 
15668   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15669   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15670   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15671 
15672   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15673   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15674   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15675 
15676   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15677   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15678   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15679 
15680   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15681   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15682   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15683 
15684   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15685   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15686                         SAPQ_Default);
15687   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15688                         SAPQ_Default);
15689 
15690   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15691   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15692                         SAPQ_Before);
15693   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15694                         SAPQ_Before);
15695 
15696   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15697   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15698   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15699                         SAPQ_After);
15700 
15701   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15702   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15703   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15704 
15705 #undef verifyQualifierSpaces
15706 
15707   FormatStyle Spaces = getLLVMStyle();
15708   Spaces.AttributeMacros.push_back("qualified");
15709   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15710   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15711   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15712   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15713   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15714   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15715   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15716   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15717   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15718   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15719   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15720   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15721   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15722 
15723   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15724   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15725   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15726   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15727   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15728   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15729   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15730   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15731   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15732   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15733   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15734   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15735   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15736   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15737   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15738 
15739   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15740   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15741   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15742   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15743   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15744   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15745   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15746   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15747 }
15748 
15749 TEST_F(FormatTest, AlignConsecutiveMacros) {
15750   FormatStyle Style = getLLVMStyle();
15751   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15752   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15753   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15754 
15755   verifyFormat("#define a 3\n"
15756                "#define bbbb 4\n"
15757                "#define ccc (5)",
15758                Style);
15759 
15760   verifyFormat("#define f(x) (x * x)\n"
15761                "#define fff(x, y, z) (x * y + z)\n"
15762                "#define ffff(x, y) (x - y)",
15763                Style);
15764 
15765   verifyFormat("#define foo(x, y) (x + y)\n"
15766                "#define bar (5, 6)(2 + 2)",
15767                Style);
15768 
15769   verifyFormat("#define a 3\n"
15770                "#define bbbb 4\n"
15771                "#define ccc (5)\n"
15772                "#define f(x) (x * x)\n"
15773                "#define fff(x, y, z) (x * y + z)\n"
15774                "#define ffff(x, y) (x - y)",
15775                Style);
15776 
15777   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15778   verifyFormat("#define a    3\n"
15779                "#define bbbb 4\n"
15780                "#define ccc  (5)",
15781                Style);
15782 
15783   verifyFormat("#define f(x)         (x * x)\n"
15784                "#define fff(x, y, z) (x * y + z)\n"
15785                "#define ffff(x, y)   (x - y)",
15786                Style);
15787 
15788   verifyFormat("#define foo(x, y) (x + y)\n"
15789                "#define bar       (5, 6)(2 + 2)",
15790                Style);
15791 
15792   verifyFormat("#define a            3\n"
15793                "#define bbbb         4\n"
15794                "#define ccc          (5)\n"
15795                "#define f(x)         (x * x)\n"
15796                "#define fff(x, y, z) (x * y + z)\n"
15797                "#define ffff(x, y)   (x - y)",
15798                Style);
15799 
15800   verifyFormat("#define a         5\n"
15801                "#define foo(x, y) (x + y)\n"
15802                "#define CCC       (6)\n"
15803                "auto lambda = []() {\n"
15804                "  auto  ii = 0;\n"
15805                "  float j  = 0;\n"
15806                "  return 0;\n"
15807                "};\n"
15808                "int   i  = 0;\n"
15809                "float i2 = 0;\n"
15810                "auto  v  = type{\n"
15811                "    i = 1,   //\n"
15812                "    (i = 2), //\n"
15813                "    i = 3    //\n"
15814                "};",
15815                Style);
15816 
15817   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15818   Style.ColumnLimit = 20;
15819 
15820   verifyFormat("#define a          \\\n"
15821                "  \"aabbbbbbbbbbbb\"\n"
15822                "#define D          \\\n"
15823                "  \"aabbbbbbbbbbbb\" \\\n"
15824                "  \"ccddeeeeeeeee\"\n"
15825                "#define B          \\\n"
15826                "  \"QQQQQQQQQQQQQ\"  \\\n"
15827                "  \"FFFFFFFFFFFFF\"  \\\n"
15828                "  \"LLLLLLLL\"\n",
15829                Style);
15830 
15831   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15832   verifyFormat("#define a          \\\n"
15833                "  \"aabbbbbbbbbbbb\"\n"
15834                "#define D          \\\n"
15835                "  \"aabbbbbbbbbbbb\" \\\n"
15836                "  \"ccddeeeeeeeee\"\n"
15837                "#define B          \\\n"
15838                "  \"QQQQQQQQQQQQQ\"  \\\n"
15839                "  \"FFFFFFFFFFFFF\"  \\\n"
15840                "  \"LLLLLLLL\"\n",
15841                Style);
15842 
15843   // Test across comments
15844   Style.MaxEmptyLinesToKeep = 10;
15845   Style.ReflowComments = false;
15846   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
15847   EXPECT_EQ("#define a    3\n"
15848             "// line comment\n"
15849             "#define bbbb 4\n"
15850             "#define ccc  (5)",
15851             format("#define a 3\n"
15852                    "// line comment\n"
15853                    "#define bbbb 4\n"
15854                    "#define ccc (5)",
15855                    Style));
15856 
15857   EXPECT_EQ("#define a    3\n"
15858             "/* block comment */\n"
15859             "#define bbbb 4\n"
15860             "#define ccc  (5)",
15861             format("#define a  3\n"
15862                    "/* block comment */\n"
15863                    "#define bbbb 4\n"
15864                    "#define ccc (5)",
15865                    Style));
15866 
15867   EXPECT_EQ("#define a    3\n"
15868             "/* multi-line *\n"
15869             " * block comment */\n"
15870             "#define bbbb 4\n"
15871             "#define ccc  (5)",
15872             format("#define a 3\n"
15873                    "/* multi-line *\n"
15874                    " * block comment */\n"
15875                    "#define bbbb 4\n"
15876                    "#define ccc (5)",
15877                    Style));
15878 
15879   EXPECT_EQ("#define a    3\n"
15880             "// multi-line line comment\n"
15881             "//\n"
15882             "#define bbbb 4\n"
15883             "#define ccc  (5)",
15884             format("#define a  3\n"
15885                    "// multi-line line comment\n"
15886                    "//\n"
15887                    "#define bbbb 4\n"
15888                    "#define ccc (5)",
15889                    Style));
15890 
15891   EXPECT_EQ("#define a 3\n"
15892             "// empty lines still break.\n"
15893             "\n"
15894             "#define bbbb 4\n"
15895             "#define ccc  (5)",
15896             format("#define a     3\n"
15897                    "// empty lines still break.\n"
15898                    "\n"
15899                    "#define bbbb     4\n"
15900                    "#define ccc  (5)",
15901                    Style));
15902 
15903   // Test across empty lines
15904   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
15905   EXPECT_EQ("#define a    3\n"
15906             "\n"
15907             "#define bbbb 4\n"
15908             "#define ccc  (5)",
15909             format("#define a 3\n"
15910                    "\n"
15911                    "#define bbbb 4\n"
15912                    "#define ccc (5)",
15913                    Style));
15914 
15915   EXPECT_EQ("#define a    3\n"
15916             "\n"
15917             "\n"
15918             "\n"
15919             "#define bbbb 4\n"
15920             "#define ccc  (5)",
15921             format("#define a        3\n"
15922                    "\n"
15923                    "\n"
15924                    "\n"
15925                    "#define bbbb 4\n"
15926                    "#define ccc (5)",
15927                    Style));
15928 
15929   EXPECT_EQ("#define a 3\n"
15930             "// comments should break alignment\n"
15931             "//\n"
15932             "#define bbbb 4\n"
15933             "#define ccc  (5)",
15934             format("#define a        3\n"
15935                    "// comments should break alignment\n"
15936                    "//\n"
15937                    "#define bbbb 4\n"
15938                    "#define ccc (5)",
15939                    Style));
15940 
15941   // Test across empty lines and comments
15942   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
15943   verifyFormat("#define a    3\n"
15944                "\n"
15945                "// line comment\n"
15946                "#define bbbb 4\n"
15947                "#define ccc  (5)",
15948                Style);
15949 
15950   EXPECT_EQ("#define a    3\n"
15951             "\n"
15952             "\n"
15953             "/* multi-line *\n"
15954             " * block comment */\n"
15955             "\n"
15956             "\n"
15957             "#define bbbb 4\n"
15958             "#define ccc  (5)",
15959             format("#define a 3\n"
15960                    "\n"
15961                    "\n"
15962                    "/* multi-line *\n"
15963                    " * block comment */\n"
15964                    "\n"
15965                    "\n"
15966                    "#define bbbb 4\n"
15967                    "#define ccc (5)",
15968                    Style));
15969 
15970   EXPECT_EQ("#define a    3\n"
15971             "\n"
15972             "\n"
15973             "/* multi-line *\n"
15974             " * block comment */\n"
15975             "\n"
15976             "\n"
15977             "#define bbbb 4\n"
15978             "#define ccc  (5)",
15979             format("#define a 3\n"
15980                    "\n"
15981                    "\n"
15982                    "/* multi-line *\n"
15983                    " * block comment */\n"
15984                    "\n"
15985                    "\n"
15986                    "#define bbbb 4\n"
15987                    "#define ccc       (5)",
15988                    Style));
15989 }
15990 
15991 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
15992   FormatStyle Alignment = getLLVMStyle();
15993   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15994   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
15995 
15996   Alignment.MaxEmptyLinesToKeep = 10;
15997   /* Test alignment across empty lines */
15998   EXPECT_EQ("int a           = 5;\n"
15999             "\n"
16000             "int oneTwoThree = 123;",
16001             format("int a       = 5;\n"
16002                    "\n"
16003                    "int oneTwoThree= 123;",
16004                    Alignment));
16005   EXPECT_EQ("int a           = 5;\n"
16006             "int one         = 1;\n"
16007             "\n"
16008             "int oneTwoThree = 123;",
16009             format("int a = 5;\n"
16010                    "int one = 1;\n"
16011                    "\n"
16012                    "int oneTwoThree = 123;",
16013                    Alignment));
16014   EXPECT_EQ("int a           = 5;\n"
16015             "int one         = 1;\n"
16016             "\n"
16017             "int oneTwoThree = 123;\n"
16018             "int oneTwo      = 12;",
16019             format("int a = 5;\n"
16020                    "int one = 1;\n"
16021                    "\n"
16022                    "int oneTwoThree = 123;\n"
16023                    "int oneTwo = 12;",
16024                    Alignment));
16025 
16026   /* Test across comments */
16027   EXPECT_EQ("int a = 5;\n"
16028             "/* block comment */\n"
16029             "int oneTwoThree = 123;",
16030             format("int a = 5;\n"
16031                    "/* block comment */\n"
16032                    "int oneTwoThree=123;",
16033                    Alignment));
16034 
16035   EXPECT_EQ("int a = 5;\n"
16036             "// line comment\n"
16037             "int oneTwoThree = 123;",
16038             format("int a = 5;\n"
16039                    "// line comment\n"
16040                    "int oneTwoThree=123;",
16041                    Alignment));
16042 
16043   /* Test across comments and newlines */
16044   EXPECT_EQ("int a = 5;\n"
16045             "\n"
16046             "/* block comment */\n"
16047             "int oneTwoThree = 123;",
16048             format("int a = 5;\n"
16049                    "\n"
16050                    "/* block comment */\n"
16051                    "int oneTwoThree=123;",
16052                    Alignment));
16053 
16054   EXPECT_EQ("int a = 5;\n"
16055             "\n"
16056             "// line comment\n"
16057             "int oneTwoThree = 123;",
16058             format("int a = 5;\n"
16059                    "\n"
16060                    "// line comment\n"
16061                    "int oneTwoThree=123;",
16062                    Alignment));
16063 }
16064 
16065 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16066   FormatStyle Alignment = getLLVMStyle();
16067   Alignment.AlignConsecutiveDeclarations =
16068       FormatStyle::ACS_AcrossEmptyLinesAndComments;
16069   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16070 
16071   Alignment.MaxEmptyLinesToKeep = 10;
16072   /* Test alignment across empty lines */
16073   EXPECT_EQ("int         a = 5;\n"
16074             "\n"
16075             "float const oneTwoThree = 123;",
16076             format("int a = 5;\n"
16077                    "\n"
16078                    "float const oneTwoThree = 123;",
16079                    Alignment));
16080   EXPECT_EQ("int         a = 5;\n"
16081             "float const one = 1;\n"
16082             "\n"
16083             "int         oneTwoThree = 123;",
16084             format("int a = 5;\n"
16085                    "float const one = 1;\n"
16086                    "\n"
16087                    "int oneTwoThree = 123;",
16088                    Alignment));
16089 
16090   /* Test across comments */
16091   EXPECT_EQ("float const a = 5;\n"
16092             "/* block comment */\n"
16093             "int         oneTwoThree = 123;",
16094             format("float const a = 5;\n"
16095                    "/* block comment */\n"
16096                    "int oneTwoThree=123;",
16097                    Alignment));
16098 
16099   EXPECT_EQ("float const a = 5;\n"
16100             "// line comment\n"
16101             "int         oneTwoThree = 123;",
16102             format("float const a = 5;\n"
16103                    "// line comment\n"
16104                    "int oneTwoThree=123;",
16105                    Alignment));
16106 
16107   /* Test across comments and newlines */
16108   EXPECT_EQ("float const a = 5;\n"
16109             "\n"
16110             "/* block comment */\n"
16111             "int         oneTwoThree = 123;",
16112             format("float const a = 5;\n"
16113                    "\n"
16114                    "/* block comment */\n"
16115                    "int         oneTwoThree=123;",
16116                    Alignment));
16117 
16118   EXPECT_EQ("float const a = 5;\n"
16119             "\n"
16120             "// line comment\n"
16121             "int         oneTwoThree = 123;",
16122             format("float const a = 5;\n"
16123                    "\n"
16124                    "// line comment\n"
16125                    "int oneTwoThree=123;",
16126                    Alignment));
16127 }
16128 
16129 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16130   FormatStyle Alignment = getLLVMStyle();
16131   Alignment.AlignConsecutiveBitFields =
16132       FormatStyle::ACS_AcrossEmptyLinesAndComments;
16133 
16134   Alignment.MaxEmptyLinesToKeep = 10;
16135   /* Test alignment across empty lines */
16136   EXPECT_EQ("int a            : 5;\n"
16137             "\n"
16138             "int longbitfield : 6;",
16139             format("int a : 5;\n"
16140                    "\n"
16141                    "int longbitfield : 6;",
16142                    Alignment));
16143   EXPECT_EQ("int a            : 5;\n"
16144             "int one          : 1;\n"
16145             "\n"
16146             "int longbitfield : 6;",
16147             format("int a : 5;\n"
16148                    "int one : 1;\n"
16149                    "\n"
16150                    "int longbitfield : 6;",
16151                    Alignment));
16152 
16153   /* Test across comments */
16154   EXPECT_EQ("int a            : 5;\n"
16155             "/* block comment */\n"
16156             "int longbitfield : 6;",
16157             format("int a : 5;\n"
16158                    "/* block comment */\n"
16159                    "int longbitfield : 6;",
16160                    Alignment));
16161   EXPECT_EQ("int a            : 5;\n"
16162             "int one          : 1;\n"
16163             "// line comment\n"
16164             "int longbitfield : 6;",
16165             format("int a : 5;\n"
16166                    "int one : 1;\n"
16167                    "// line comment\n"
16168                    "int longbitfield : 6;",
16169                    Alignment));
16170 
16171   /* Test across comments and newlines */
16172   EXPECT_EQ("int a            : 5;\n"
16173             "/* block comment */\n"
16174             "\n"
16175             "int longbitfield : 6;",
16176             format("int a : 5;\n"
16177                    "/* block comment */\n"
16178                    "\n"
16179                    "int longbitfield : 6;",
16180                    Alignment));
16181   EXPECT_EQ("int a            : 5;\n"
16182             "int one          : 1;\n"
16183             "\n"
16184             "// line comment\n"
16185             "\n"
16186             "int longbitfield : 6;",
16187             format("int a : 5;\n"
16188                    "int one : 1;\n"
16189                    "\n"
16190                    "// line comment \n"
16191                    "\n"
16192                    "int longbitfield : 6;",
16193                    Alignment));
16194 }
16195 
16196 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16197   FormatStyle Alignment = getLLVMStyle();
16198   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16199   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
16200 
16201   Alignment.MaxEmptyLinesToKeep = 10;
16202   /* Test alignment across empty lines */
16203   EXPECT_EQ("int a = 5;\n"
16204             "\n"
16205             "int oneTwoThree = 123;",
16206             format("int a       = 5;\n"
16207                    "\n"
16208                    "int oneTwoThree= 123;",
16209                    Alignment));
16210   EXPECT_EQ("int a   = 5;\n"
16211             "int one = 1;\n"
16212             "\n"
16213             "int oneTwoThree = 123;",
16214             format("int a = 5;\n"
16215                    "int one = 1;\n"
16216                    "\n"
16217                    "int oneTwoThree = 123;",
16218                    Alignment));
16219 
16220   /* Test across comments */
16221   EXPECT_EQ("int a           = 5;\n"
16222             "/* block comment */\n"
16223             "int oneTwoThree = 123;",
16224             format("int a = 5;\n"
16225                    "/* block comment */\n"
16226                    "int oneTwoThree=123;",
16227                    Alignment));
16228 
16229   EXPECT_EQ("int a           = 5;\n"
16230             "// line comment\n"
16231             "int oneTwoThree = 123;",
16232             format("int a = 5;\n"
16233                    "// line comment\n"
16234                    "int oneTwoThree=123;",
16235                    Alignment));
16236 
16237   EXPECT_EQ("int a           = 5;\n"
16238             "/*\n"
16239             " * multi-line block comment\n"
16240             " */\n"
16241             "int oneTwoThree = 123;",
16242             format("int a = 5;\n"
16243                    "/*\n"
16244                    " * multi-line block comment\n"
16245                    " */\n"
16246                    "int oneTwoThree=123;",
16247                    Alignment));
16248 
16249   EXPECT_EQ("int a           = 5;\n"
16250             "//\n"
16251             "// multi-line line comment\n"
16252             "//\n"
16253             "int oneTwoThree = 123;",
16254             format("int a = 5;\n"
16255                    "//\n"
16256                    "// multi-line line comment\n"
16257                    "//\n"
16258                    "int oneTwoThree=123;",
16259                    Alignment));
16260 
16261   /* Test across comments and newlines */
16262   EXPECT_EQ("int a = 5;\n"
16263             "\n"
16264             "/* block comment */\n"
16265             "int oneTwoThree = 123;",
16266             format("int a = 5;\n"
16267                    "\n"
16268                    "/* block comment */\n"
16269                    "int oneTwoThree=123;",
16270                    Alignment));
16271 
16272   EXPECT_EQ("int a = 5;\n"
16273             "\n"
16274             "// line comment\n"
16275             "int oneTwoThree = 123;",
16276             format("int a = 5;\n"
16277                    "\n"
16278                    "// line comment\n"
16279                    "int oneTwoThree=123;",
16280                    Alignment));
16281 }
16282 
16283 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16284   FormatStyle Alignment = getLLVMStyle();
16285   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16286   Alignment.AlignConsecutiveAssignments =
16287       FormatStyle::ACS_AcrossEmptyLinesAndComments;
16288   verifyFormat("int a           = 5;\n"
16289                "int oneTwoThree = 123;",
16290                Alignment);
16291   verifyFormat("int a           = method();\n"
16292                "int oneTwoThree = 133;",
16293                Alignment);
16294   verifyFormat("a &= 5;\n"
16295                "bcd *= 5;\n"
16296                "ghtyf += 5;\n"
16297                "dvfvdb -= 5;\n"
16298                "a /= 5;\n"
16299                "vdsvsv %= 5;\n"
16300                "sfdbddfbdfbb ^= 5;\n"
16301                "dvsdsv |= 5;\n"
16302                "int dsvvdvsdvvv = 123;",
16303                Alignment);
16304   verifyFormat("int i = 1, j = 10;\n"
16305                "something = 2000;",
16306                Alignment);
16307   verifyFormat("something = 2000;\n"
16308                "int i = 1, j = 10;\n",
16309                Alignment);
16310   verifyFormat("something = 2000;\n"
16311                "another   = 911;\n"
16312                "int i = 1, j = 10;\n"
16313                "oneMore = 1;\n"
16314                "i       = 2;",
16315                Alignment);
16316   verifyFormat("int a   = 5;\n"
16317                "int one = 1;\n"
16318                "method();\n"
16319                "int oneTwoThree = 123;\n"
16320                "int oneTwo      = 12;",
16321                Alignment);
16322   verifyFormat("int oneTwoThree = 123;\n"
16323                "int oneTwo      = 12;\n"
16324                "method();\n",
16325                Alignment);
16326   verifyFormat("int oneTwoThree = 123; // comment\n"
16327                "int oneTwo      = 12;  // comment",
16328                Alignment);
16329 
16330   // Bug 25167
16331   /* Uncomment when fixed
16332     verifyFormat("#if A\n"
16333                  "#else\n"
16334                  "int aaaaaaaa = 12;\n"
16335                  "#endif\n"
16336                  "#if B\n"
16337                  "#else\n"
16338                  "int a = 12;\n"
16339                  "#endif\n",
16340                  Alignment);
16341     verifyFormat("enum foo {\n"
16342                  "#if A\n"
16343                  "#else\n"
16344                  "  aaaaaaaa = 12;\n"
16345                  "#endif\n"
16346                  "#if B\n"
16347                  "#else\n"
16348                  "  a = 12;\n"
16349                  "#endif\n"
16350                  "};\n",
16351                  Alignment);
16352   */
16353 
16354   Alignment.MaxEmptyLinesToKeep = 10;
16355   /* Test alignment across empty lines */
16356   EXPECT_EQ("int a           = 5;\n"
16357             "\n"
16358             "int oneTwoThree = 123;",
16359             format("int a       = 5;\n"
16360                    "\n"
16361                    "int oneTwoThree= 123;",
16362                    Alignment));
16363   EXPECT_EQ("int a           = 5;\n"
16364             "int one         = 1;\n"
16365             "\n"
16366             "int oneTwoThree = 123;",
16367             format("int a = 5;\n"
16368                    "int one = 1;\n"
16369                    "\n"
16370                    "int oneTwoThree = 123;",
16371                    Alignment));
16372   EXPECT_EQ("int a           = 5;\n"
16373             "int one         = 1;\n"
16374             "\n"
16375             "int oneTwoThree = 123;\n"
16376             "int oneTwo      = 12;",
16377             format("int a = 5;\n"
16378                    "int one = 1;\n"
16379                    "\n"
16380                    "int oneTwoThree = 123;\n"
16381                    "int oneTwo = 12;",
16382                    Alignment));
16383 
16384   /* Test across comments */
16385   EXPECT_EQ("int a           = 5;\n"
16386             "/* block comment */\n"
16387             "int oneTwoThree = 123;",
16388             format("int a = 5;\n"
16389                    "/* block comment */\n"
16390                    "int oneTwoThree=123;",
16391                    Alignment));
16392 
16393   EXPECT_EQ("int a           = 5;\n"
16394             "// line comment\n"
16395             "int oneTwoThree = 123;",
16396             format("int a = 5;\n"
16397                    "// line comment\n"
16398                    "int oneTwoThree=123;",
16399                    Alignment));
16400 
16401   /* Test across comments and newlines */
16402   EXPECT_EQ("int a           = 5;\n"
16403             "\n"
16404             "/* block comment */\n"
16405             "int oneTwoThree = 123;",
16406             format("int a = 5;\n"
16407                    "\n"
16408                    "/* block comment */\n"
16409                    "int oneTwoThree=123;",
16410                    Alignment));
16411 
16412   EXPECT_EQ("int a           = 5;\n"
16413             "\n"
16414             "// line comment\n"
16415             "int oneTwoThree = 123;",
16416             format("int a = 5;\n"
16417                    "\n"
16418                    "// line comment\n"
16419                    "int oneTwoThree=123;",
16420                    Alignment));
16421 
16422   EXPECT_EQ("int a           = 5;\n"
16423             "//\n"
16424             "// multi-line line comment\n"
16425             "//\n"
16426             "int oneTwoThree = 123;",
16427             format("int a = 5;\n"
16428                    "//\n"
16429                    "// multi-line line comment\n"
16430                    "//\n"
16431                    "int oneTwoThree=123;",
16432                    Alignment));
16433 
16434   EXPECT_EQ("int a           = 5;\n"
16435             "/*\n"
16436             " *  multi-line block comment\n"
16437             " */\n"
16438             "int oneTwoThree = 123;",
16439             format("int a = 5;\n"
16440                    "/*\n"
16441                    " *  multi-line block comment\n"
16442                    " */\n"
16443                    "int oneTwoThree=123;",
16444                    Alignment));
16445 
16446   EXPECT_EQ("int a           = 5;\n"
16447             "\n"
16448             "/* block comment */\n"
16449             "\n"
16450             "\n"
16451             "\n"
16452             "int oneTwoThree = 123;",
16453             format("int a = 5;\n"
16454                    "\n"
16455                    "/* block comment */\n"
16456                    "\n"
16457                    "\n"
16458                    "\n"
16459                    "int oneTwoThree=123;",
16460                    Alignment));
16461 
16462   EXPECT_EQ("int a           = 5;\n"
16463             "\n"
16464             "// line comment\n"
16465             "\n"
16466             "\n"
16467             "\n"
16468             "int oneTwoThree = 123;",
16469             format("int a = 5;\n"
16470                    "\n"
16471                    "// line comment\n"
16472                    "\n"
16473                    "\n"
16474                    "\n"
16475                    "int oneTwoThree=123;",
16476                    Alignment));
16477 
16478   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16479   verifyFormat("#define A \\\n"
16480                "  int aaaa       = 12; \\\n"
16481                "  int b          = 23; \\\n"
16482                "  int ccc        = 234; \\\n"
16483                "  int dddddddddd = 2345;",
16484                Alignment);
16485   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16486   verifyFormat("#define A               \\\n"
16487                "  int aaaa       = 12;  \\\n"
16488                "  int b          = 23;  \\\n"
16489                "  int ccc        = 234; \\\n"
16490                "  int dddddddddd = 2345;",
16491                Alignment);
16492   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16493   verifyFormat("#define A                                                      "
16494                "                \\\n"
16495                "  int aaaa       = 12;                                         "
16496                "                \\\n"
16497                "  int b          = 23;                                         "
16498                "                \\\n"
16499                "  int ccc        = 234;                                        "
16500                "                \\\n"
16501                "  int dddddddddd = 2345;",
16502                Alignment);
16503   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16504                "k = 4, int l = 5,\n"
16505                "                  int m = 6) {\n"
16506                "  int j      = 10;\n"
16507                "  otherThing = 1;\n"
16508                "}",
16509                Alignment);
16510   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16511                "  int i   = 1;\n"
16512                "  int j   = 2;\n"
16513                "  int big = 10000;\n"
16514                "}",
16515                Alignment);
16516   verifyFormat("class C {\n"
16517                "public:\n"
16518                "  int i            = 1;\n"
16519                "  virtual void f() = 0;\n"
16520                "};",
16521                Alignment);
16522   verifyFormat("int i = 1;\n"
16523                "if (SomeType t = getSomething()) {\n"
16524                "}\n"
16525                "int j   = 2;\n"
16526                "int big = 10000;",
16527                Alignment);
16528   verifyFormat("int j = 7;\n"
16529                "for (int k = 0; k < N; ++k) {\n"
16530                "}\n"
16531                "int j   = 2;\n"
16532                "int big = 10000;\n"
16533                "}",
16534                Alignment);
16535   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16536   verifyFormat("int i = 1;\n"
16537                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16538                "    = someLooooooooooooooooongFunction();\n"
16539                "int j = 2;",
16540                Alignment);
16541   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16542   verifyFormat("int i = 1;\n"
16543                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16544                "    someLooooooooooooooooongFunction();\n"
16545                "int j = 2;",
16546                Alignment);
16547 
16548   verifyFormat("auto lambda = []() {\n"
16549                "  auto i = 0;\n"
16550                "  return 0;\n"
16551                "};\n"
16552                "int i  = 0;\n"
16553                "auto v = type{\n"
16554                "    i = 1,   //\n"
16555                "    (i = 2), //\n"
16556                "    i = 3    //\n"
16557                "};",
16558                Alignment);
16559 
16560   verifyFormat(
16561       "int i      = 1;\n"
16562       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16563       "                          loooooooooooooooooooooongParameterB);\n"
16564       "int j      = 2;",
16565       Alignment);
16566 
16567   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16568                "          typename B   = very_long_type_name_1,\n"
16569                "          typename T_2 = very_long_type_name_2>\n"
16570                "auto foo() {}\n",
16571                Alignment);
16572   verifyFormat("int a, b = 1;\n"
16573                "int c  = 2;\n"
16574                "int dd = 3;\n",
16575                Alignment);
16576   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16577                "float b[1][] = {{3.f}};\n",
16578                Alignment);
16579   verifyFormat("for (int i = 0; i < 1; i++)\n"
16580                "  int x = 1;\n",
16581                Alignment);
16582   verifyFormat("for (i = 0; i < 1; i++)\n"
16583                "  x = 1;\n"
16584                "y = 1;\n",
16585                Alignment);
16586 
16587   Alignment.ReflowComments = true;
16588   Alignment.ColumnLimit = 50;
16589   EXPECT_EQ("int x   = 0;\n"
16590             "int yy  = 1; /// specificlennospace\n"
16591             "int zzz = 2;\n",
16592             format("int x   = 0;\n"
16593                    "int yy  = 1; ///specificlennospace\n"
16594                    "int zzz = 2;\n",
16595                    Alignment));
16596 }
16597 
16598 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16599   FormatStyle Alignment = getLLVMStyle();
16600   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16601   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16602   verifyFormat("int a = 5;\n"
16603                "int oneTwoThree = 123;",
16604                Alignment);
16605   verifyFormat("int a = 5;\n"
16606                "int oneTwoThree = 123;",
16607                Alignment);
16608 
16609   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16610   verifyFormat("int a           = 5;\n"
16611                "int oneTwoThree = 123;",
16612                Alignment);
16613   verifyFormat("int a           = method();\n"
16614                "int oneTwoThree = 133;",
16615                Alignment);
16616   verifyFormat("a &= 5;\n"
16617                "bcd *= 5;\n"
16618                "ghtyf += 5;\n"
16619                "dvfvdb -= 5;\n"
16620                "a /= 5;\n"
16621                "vdsvsv %= 5;\n"
16622                "sfdbddfbdfbb ^= 5;\n"
16623                "dvsdsv |= 5;\n"
16624                "int dsvvdvsdvvv = 123;",
16625                Alignment);
16626   verifyFormat("int i = 1, j = 10;\n"
16627                "something = 2000;",
16628                Alignment);
16629   verifyFormat("something = 2000;\n"
16630                "int i = 1, j = 10;\n",
16631                Alignment);
16632   verifyFormat("something = 2000;\n"
16633                "another   = 911;\n"
16634                "int i = 1, j = 10;\n"
16635                "oneMore = 1;\n"
16636                "i       = 2;",
16637                Alignment);
16638   verifyFormat("int a   = 5;\n"
16639                "int one = 1;\n"
16640                "method();\n"
16641                "int oneTwoThree = 123;\n"
16642                "int oneTwo      = 12;",
16643                Alignment);
16644   verifyFormat("int oneTwoThree = 123;\n"
16645                "int oneTwo      = 12;\n"
16646                "method();\n",
16647                Alignment);
16648   verifyFormat("int oneTwoThree = 123; // comment\n"
16649                "int oneTwo      = 12;  // comment",
16650                Alignment);
16651   verifyFormat("int f()         = default;\n"
16652                "int &operator() = default;\n"
16653                "int &operator=() {",
16654                Alignment);
16655   verifyFormat("int f()         = delete;\n"
16656                "int &operator() = delete;\n"
16657                "int &operator=() {",
16658                Alignment);
16659   verifyFormat("int f()         = default; // comment\n"
16660                "int &operator() = default; // comment\n"
16661                "int &operator=() {",
16662                Alignment);
16663   verifyFormat("int f()         = default;\n"
16664                "int &operator() = default;\n"
16665                "int &operator==() {",
16666                Alignment);
16667   verifyFormat("int f()         = default;\n"
16668                "int &operator() = default;\n"
16669                "int &operator<=() {",
16670                Alignment);
16671   verifyFormat("int f()         = default;\n"
16672                "int &operator() = default;\n"
16673                "int &operator!=() {",
16674                Alignment);
16675   verifyFormat("int f()         = default;\n"
16676                "int &operator() = default;\n"
16677                "int &operator=();",
16678                Alignment);
16679   verifyFormat("int f()         = delete;\n"
16680                "int &operator() = delete;\n"
16681                "int &operator=();",
16682                Alignment);
16683   verifyFormat("/* long long padding */ int f() = default;\n"
16684                "int &operator()                 = default;\n"
16685                "int &operator/**/ =();",
16686                Alignment);
16687   // https://llvm.org/PR33697
16688   FormatStyle AlignmentWithPenalty = getLLVMStyle();
16689   AlignmentWithPenalty.AlignConsecutiveAssignments =
16690       FormatStyle::ACS_Consecutive;
16691   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
16692   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
16693                "  void f() = delete;\n"
16694                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
16695                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
16696                "};\n",
16697                AlignmentWithPenalty);
16698 
16699   // Bug 25167
16700   /* Uncomment when fixed
16701     verifyFormat("#if A\n"
16702                  "#else\n"
16703                  "int aaaaaaaa = 12;\n"
16704                  "#endif\n"
16705                  "#if B\n"
16706                  "#else\n"
16707                  "int a = 12;\n"
16708                  "#endif\n",
16709                  Alignment);
16710     verifyFormat("enum foo {\n"
16711                  "#if A\n"
16712                  "#else\n"
16713                  "  aaaaaaaa = 12;\n"
16714                  "#endif\n"
16715                  "#if B\n"
16716                  "#else\n"
16717                  "  a = 12;\n"
16718                  "#endif\n"
16719                  "};\n",
16720                  Alignment);
16721   */
16722 
16723   EXPECT_EQ("int a = 5;\n"
16724             "\n"
16725             "int oneTwoThree = 123;",
16726             format("int a       = 5;\n"
16727                    "\n"
16728                    "int oneTwoThree= 123;",
16729                    Alignment));
16730   EXPECT_EQ("int a   = 5;\n"
16731             "int one = 1;\n"
16732             "\n"
16733             "int oneTwoThree = 123;",
16734             format("int a = 5;\n"
16735                    "int one = 1;\n"
16736                    "\n"
16737                    "int oneTwoThree = 123;",
16738                    Alignment));
16739   EXPECT_EQ("int a   = 5;\n"
16740             "int one = 1;\n"
16741             "\n"
16742             "int oneTwoThree = 123;\n"
16743             "int oneTwo      = 12;",
16744             format("int a = 5;\n"
16745                    "int one = 1;\n"
16746                    "\n"
16747                    "int oneTwoThree = 123;\n"
16748                    "int oneTwo = 12;",
16749                    Alignment));
16750   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16751   verifyFormat("#define A \\\n"
16752                "  int aaaa       = 12; \\\n"
16753                "  int b          = 23; \\\n"
16754                "  int ccc        = 234; \\\n"
16755                "  int dddddddddd = 2345;",
16756                Alignment);
16757   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16758   verifyFormat("#define A               \\\n"
16759                "  int aaaa       = 12;  \\\n"
16760                "  int b          = 23;  \\\n"
16761                "  int ccc        = 234; \\\n"
16762                "  int dddddddddd = 2345;",
16763                Alignment);
16764   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16765   verifyFormat("#define A                                                      "
16766                "                \\\n"
16767                "  int aaaa       = 12;                                         "
16768                "                \\\n"
16769                "  int b          = 23;                                         "
16770                "                \\\n"
16771                "  int ccc        = 234;                                        "
16772                "                \\\n"
16773                "  int dddddddddd = 2345;",
16774                Alignment);
16775   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16776                "k = 4, int l = 5,\n"
16777                "                  int m = 6) {\n"
16778                "  int j      = 10;\n"
16779                "  otherThing = 1;\n"
16780                "}",
16781                Alignment);
16782   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16783                "  int i   = 1;\n"
16784                "  int j   = 2;\n"
16785                "  int big = 10000;\n"
16786                "}",
16787                Alignment);
16788   verifyFormat("class C {\n"
16789                "public:\n"
16790                "  int i            = 1;\n"
16791                "  virtual void f() = 0;\n"
16792                "};",
16793                Alignment);
16794   verifyFormat("int i = 1;\n"
16795                "if (SomeType t = getSomething()) {\n"
16796                "}\n"
16797                "int j   = 2;\n"
16798                "int big = 10000;",
16799                Alignment);
16800   verifyFormat("int j = 7;\n"
16801                "for (int k = 0; k < N; ++k) {\n"
16802                "}\n"
16803                "int j   = 2;\n"
16804                "int big = 10000;\n"
16805                "}",
16806                Alignment);
16807   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16808   verifyFormat("int i = 1;\n"
16809                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16810                "    = someLooooooooooooooooongFunction();\n"
16811                "int j = 2;",
16812                Alignment);
16813   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16814   verifyFormat("int i = 1;\n"
16815                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16816                "    someLooooooooooooooooongFunction();\n"
16817                "int j = 2;",
16818                Alignment);
16819 
16820   verifyFormat("auto lambda = []() {\n"
16821                "  auto i = 0;\n"
16822                "  return 0;\n"
16823                "};\n"
16824                "int i  = 0;\n"
16825                "auto v = type{\n"
16826                "    i = 1,   //\n"
16827                "    (i = 2), //\n"
16828                "    i = 3    //\n"
16829                "};",
16830                Alignment);
16831 
16832   verifyFormat(
16833       "int i      = 1;\n"
16834       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16835       "                          loooooooooooooooooooooongParameterB);\n"
16836       "int j      = 2;",
16837       Alignment);
16838 
16839   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16840                "          typename B   = very_long_type_name_1,\n"
16841                "          typename T_2 = very_long_type_name_2>\n"
16842                "auto foo() {}\n",
16843                Alignment);
16844   verifyFormat("int a, b = 1;\n"
16845                "int c  = 2;\n"
16846                "int dd = 3;\n",
16847                Alignment);
16848   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16849                "float b[1][] = {{3.f}};\n",
16850                Alignment);
16851   verifyFormat("for (int i = 0; i < 1; i++)\n"
16852                "  int x = 1;\n",
16853                Alignment);
16854   verifyFormat("for (i = 0; i < 1; i++)\n"
16855                "  x = 1;\n"
16856                "y = 1;\n",
16857                Alignment);
16858 
16859   EXPECT_EQ(Alignment.ReflowComments, true);
16860   Alignment.ColumnLimit = 50;
16861   EXPECT_EQ("int x   = 0;\n"
16862             "int yy  = 1; /// specificlennospace\n"
16863             "int zzz = 2;\n",
16864             format("int x   = 0;\n"
16865                    "int yy  = 1; ///specificlennospace\n"
16866                    "int zzz = 2;\n",
16867                    Alignment));
16868 
16869   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
16870                "auto b                     = [] {\n"
16871                "  f();\n"
16872                "  return;\n"
16873                "};",
16874                Alignment);
16875   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
16876                "auto b                     = g([] {\n"
16877                "  f();\n"
16878                "  return;\n"
16879                "});",
16880                Alignment);
16881   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
16882                "auto b                     = g(param, [] {\n"
16883                "  f();\n"
16884                "  return;\n"
16885                "});",
16886                Alignment);
16887   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
16888                "auto b                     = [] {\n"
16889                "  if (condition) {\n"
16890                "    return;\n"
16891                "  }\n"
16892                "};",
16893                Alignment);
16894 
16895   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
16896                "           ccc ? aaaaa : bbbbb,\n"
16897                "           dddddddddddddddddddddddddd);",
16898                Alignment);
16899   // FIXME: https://llvm.org/PR53497
16900   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
16901   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
16902   //              "    ccc ? aaaaa : bbbbb,\n"
16903   //              "    dddddddddddddddddddddddddd);",
16904   //              Alignment);
16905 }
16906 
16907 TEST_F(FormatTest, AlignConsecutiveBitFields) {
16908   FormatStyle Alignment = getLLVMStyle();
16909   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
16910   verifyFormat("int const a     : 5;\n"
16911                "int oneTwoThree : 23;",
16912                Alignment);
16913 
16914   // Initializers are allowed starting with c++2a
16915   verifyFormat("int const a     : 5 = 1;\n"
16916                "int oneTwoThree : 23 = 0;",
16917                Alignment);
16918 
16919   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16920   verifyFormat("int const a           : 5;\n"
16921                "int       oneTwoThree : 23;",
16922                Alignment);
16923 
16924   verifyFormat("int const a           : 5;  // comment\n"
16925                "int       oneTwoThree : 23; // comment",
16926                Alignment);
16927 
16928   verifyFormat("int const a           : 5 = 1;\n"
16929                "int       oneTwoThree : 23 = 0;",
16930                Alignment);
16931 
16932   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16933   verifyFormat("int const a           : 5  = 1;\n"
16934                "int       oneTwoThree : 23 = 0;",
16935                Alignment);
16936   verifyFormat("int const a           : 5  = {1};\n"
16937                "int       oneTwoThree : 23 = 0;",
16938                Alignment);
16939 
16940   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
16941   verifyFormat("int const a          :5;\n"
16942                "int       oneTwoThree:23;",
16943                Alignment);
16944 
16945   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
16946   verifyFormat("int const a           :5;\n"
16947                "int       oneTwoThree :23;",
16948                Alignment);
16949 
16950   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
16951   verifyFormat("int const a          : 5;\n"
16952                "int       oneTwoThree: 23;",
16953                Alignment);
16954 
16955   // Known limitations: ':' is only recognized as a bitfield colon when
16956   // followed by a number.
16957   /*
16958   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
16959                "int a           : 5;",
16960                Alignment);
16961   */
16962 }
16963 
16964 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
16965   FormatStyle Alignment = getLLVMStyle();
16966   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16967   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16968   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16969   verifyFormat("float const a = 5;\n"
16970                "int oneTwoThree = 123;",
16971                Alignment);
16972   verifyFormat("int a = 5;\n"
16973                "float const oneTwoThree = 123;",
16974                Alignment);
16975 
16976   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16977   verifyFormat("float const a = 5;\n"
16978                "int         oneTwoThree = 123;",
16979                Alignment);
16980   verifyFormat("int         a = method();\n"
16981                "float const oneTwoThree = 133;",
16982                Alignment);
16983   verifyFormat("int i = 1, j = 10;\n"
16984                "something = 2000;",
16985                Alignment);
16986   verifyFormat("something = 2000;\n"
16987                "int i = 1, j = 10;\n",
16988                Alignment);
16989   verifyFormat("float      something = 2000;\n"
16990                "double     another = 911;\n"
16991                "int        i = 1, j = 10;\n"
16992                "const int *oneMore = 1;\n"
16993                "unsigned   i = 2;",
16994                Alignment);
16995   verifyFormat("float a = 5;\n"
16996                "int   one = 1;\n"
16997                "method();\n"
16998                "const double       oneTwoThree = 123;\n"
16999                "const unsigned int oneTwo = 12;",
17000                Alignment);
17001   verifyFormat("int      oneTwoThree{0}; // comment\n"
17002                "unsigned oneTwo;         // comment",
17003                Alignment);
17004   verifyFormat("unsigned int       *a;\n"
17005                "int                *b;\n"
17006                "unsigned int Const *c;\n"
17007                "unsigned int const *d;\n"
17008                "unsigned int Const &e;\n"
17009                "unsigned int const &f;",
17010                Alignment);
17011   verifyFormat("Const unsigned int *c;\n"
17012                "const unsigned int *d;\n"
17013                "Const unsigned int &e;\n"
17014                "const unsigned int &f;\n"
17015                "const unsigned      g;\n"
17016                "Const unsigned      h;",
17017                Alignment);
17018   EXPECT_EQ("float const a = 5;\n"
17019             "\n"
17020             "int oneTwoThree = 123;",
17021             format("float const   a = 5;\n"
17022                    "\n"
17023                    "int           oneTwoThree= 123;",
17024                    Alignment));
17025   EXPECT_EQ("float a = 5;\n"
17026             "int   one = 1;\n"
17027             "\n"
17028             "unsigned oneTwoThree = 123;",
17029             format("float    a = 5;\n"
17030                    "int      one = 1;\n"
17031                    "\n"
17032                    "unsigned oneTwoThree = 123;",
17033                    Alignment));
17034   EXPECT_EQ("float a = 5;\n"
17035             "int   one = 1;\n"
17036             "\n"
17037             "unsigned oneTwoThree = 123;\n"
17038             "int      oneTwo = 12;",
17039             format("float    a = 5;\n"
17040                    "int one = 1;\n"
17041                    "\n"
17042                    "unsigned oneTwoThree = 123;\n"
17043                    "int oneTwo = 12;",
17044                    Alignment));
17045   // Function prototype alignment
17046   verifyFormat("int    a();\n"
17047                "double b();",
17048                Alignment);
17049   verifyFormat("int    a(int x);\n"
17050                "double b();",
17051                Alignment);
17052   unsigned OldColumnLimit = Alignment.ColumnLimit;
17053   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17054   // otherwise the function parameters will be re-flowed onto a single line.
17055   Alignment.ColumnLimit = 0;
17056   EXPECT_EQ("int    a(int   x,\n"
17057             "         float y);\n"
17058             "double b(int    x,\n"
17059             "         double y);",
17060             format("int a(int x,\n"
17061                    " float y);\n"
17062                    "double b(int x,\n"
17063                    " double y);",
17064                    Alignment));
17065   // This ensures that function parameters of function declarations are
17066   // correctly indented when their owning functions are indented.
17067   // The failure case here is for 'double y' to not be indented enough.
17068   EXPECT_EQ("double a(int x);\n"
17069             "int    b(int    y,\n"
17070             "         double z);",
17071             format("double a(int x);\n"
17072                    "int b(int y,\n"
17073                    " double z);",
17074                    Alignment));
17075   // Set ColumnLimit low so that we induce wrapping immediately after
17076   // the function name and opening paren.
17077   Alignment.ColumnLimit = 13;
17078   verifyFormat("int function(\n"
17079                "    int  x,\n"
17080                "    bool y);",
17081                Alignment);
17082   Alignment.ColumnLimit = OldColumnLimit;
17083   // Ensure function pointers don't screw up recursive alignment
17084   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17085                "double b();",
17086                Alignment);
17087   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17088   // Ensure recursive alignment is broken by function braces, so that the
17089   // "a = 1" does not align with subsequent assignments inside the function
17090   // body.
17091   verifyFormat("int func(int a = 1) {\n"
17092                "  int b  = 2;\n"
17093                "  int cc = 3;\n"
17094                "}",
17095                Alignment);
17096   verifyFormat("float      something = 2000;\n"
17097                "double     another   = 911;\n"
17098                "int        i = 1, j = 10;\n"
17099                "const int *oneMore = 1;\n"
17100                "unsigned   i       = 2;",
17101                Alignment);
17102   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17103                "unsigned oneTwo      = 0;   // comment",
17104                Alignment);
17105   // Make sure that scope is correctly tracked, in the absence of braces
17106   verifyFormat("for (int i = 0; i < n; i++)\n"
17107                "  j = i;\n"
17108                "double x = 1;\n",
17109                Alignment);
17110   verifyFormat("if (int i = 0)\n"
17111                "  j = i;\n"
17112                "double x = 1;\n",
17113                Alignment);
17114   // Ensure operator[] and operator() are comprehended
17115   verifyFormat("struct test {\n"
17116                "  long long int foo();\n"
17117                "  int           operator[](int a);\n"
17118                "  double        bar();\n"
17119                "};\n",
17120                Alignment);
17121   verifyFormat("struct test {\n"
17122                "  long long int foo();\n"
17123                "  int           operator()(int a);\n"
17124                "  double        bar();\n"
17125                "};\n",
17126                Alignment);
17127   // http://llvm.org/PR52914
17128   verifyFormat("char *a[]     = {\"a\", // comment\n"
17129                "                 \"bb\"};\n"
17130                "int   bbbbbbb = 0;",
17131                Alignment);
17132 
17133   // PAS_Right
17134   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17135             "  int const i   = 1;\n"
17136             "  int      *j   = 2;\n"
17137             "  int       big = 10000;\n"
17138             "\n"
17139             "  unsigned oneTwoThree = 123;\n"
17140             "  int      oneTwo      = 12;\n"
17141             "  method();\n"
17142             "  float k  = 2;\n"
17143             "  int   ll = 10000;\n"
17144             "}",
17145             format("void SomeFunction(int parameter= 0) {\n"
17146                    " int const  i= 1;\n"
17147                    "  int *j=2;\n"
17148                    " int big  =  10000;\n"
17149                    "\n"
17150                    "unsigned oneTwoThree  =123;\n"
17151                    "int oneTwo = 12;\n"
17152                    "  method();\n"
17153                    "float k= 2;\n"
17154                    "int ll=10000;\n"
17155                    "}",
17156                    Alignment));
17157   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17158             "  int const i   = 1;\n"
17159             "  int     **j   = 2, ***k;\n"
17160             "  int      &k   = i;\n"
17161             "  int     &&l   = i + j;\n"
17162             "  int       big = 10000;\n"
17163             "\n"
17164             "  unsigned oneTwoThree = 123;\n"
17165             "  int      oneTwo      = 12;\n"
17166             "  method();\n"
17167             "  float k  = 2;\n"
17168             "  int   ll = 10000;\n"
17169             "}",
17170             format("void SomeFunction(int parameter= 0) {\n"
17171                    " int const  i= 1;\n"
17172                    "  int **j=2,***k;\n"
17173                    "int &k=i;\n"
17174                    "int &&l=i+j;\n"
17175                    " int big  =  10000;\n"
17176                    "\n"
17177                    "unsigned oneTwoThree  =123;\n"
17178                    "int oneTwo = 12;\n"
17179                    "  method();\n"
17180                    "float k= 2;\n"
17181                    "int ll=10000;\n"
17182                    "}",
17183                    Alignment));
17184   // variables are aligned at their name, pointers are at the right most
17185   // position
17186   verifyFormat("int   *a;\n"
17187                "int  **b;\n"
17188                "int ***c;\n"
17189                "int    foobar;\n",
17190                Alignment);
17191 
17192   // PAS_Left
17193   FormatStyle AlignmentLeft = Alignment;
17194   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17195   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17196             "  int const i   = 1;\n"
17197             "  int*      j   = 2;\n"
17198             "  int       big = 10000;\n"
17199             "\n"
17200             "  unsigned oneTwoThree = 123;\n"
17201             "  int      oneTwo      = 12;\n"
17202             "  method();\n"
17203             "  float k  = 2;\n"
17204             "  int   ll = 10000;\n"
17205             "}",
17206             format("void SomeFunction(int parameter= 0) {\n"
17207                    " int const  i= 1;\n"
17208                    "  int *j=2;\n"
17209                    " int big  =  10000;\n"
17210                    "\n"
17211                    "unsigned oneTwoThree  =123;\n"
17212                    "int oneTwo = 12;\n"
17213                    "  method();\n"
17214                    "float k= 2;\n"
17215                    "int ll=10000;\n"
17216                    "}",
17217                    AlignmentLeft));
17218   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17219             "  int const i   = 1;\n"
17220             "  int**     j   = 2;\n"
17221             "  int&      k   = i;\n"
17222             "  int&&     l   = i + j;\n"
17223             "  int       big = 10000;\n"
17224             "\n"
17225             "  unsigned oneTwoThree = 123;\n"
17226             "  int      oneTwo      = 12;\n"
17227             "  method();\n"
17228             "  float k  = 2;\n"
17229             "  int   ll = 10000;\n"
17230             "}",
17231             format("void SomeFunction(int parameter= 0) {\n"
17232                    " int const  i= 1;\n"
17233                    "  int **j=2;\n"
17234                    "int &k=i;\n"
17235                    "int &&l=i+j;\n"
17236                    " int big  =  10000;\n"
17237                    "\n"
17238                    "unsigned oneTwoThree  =123;\n"
17239                    "int oneTwo = 12;\n"
17240                    "  method();\n"
17241                    "float k= 2;\n"
17242                    "int ll=10000;\n"
17243                    "}",
17244                    AlignmentLeft));
17245   // variables are aligned at their name, pointers are at the left most position
17246   verifyFormat("int*   a;\n"
17247                "int**  b;\n"
17248                "int*** c;\n"
17249                "int    foobar;\n",
17250                AlignmentLeft);
17251 
17252   // PAS_Middle
17253   FormatStyle AlignmentMiddle = Alignment;
17254   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17255   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17256             "  int const i   = 1;\n"
17257             "  int *     j   = 2;\n"
17258             "  int       big = 10000;\n"
17259             "\n"
17260             "  unsigned oneTwoThree = 123;\n"
17261             "  int      oneTwo      = 12;\n"
17262             "  method();\n"
17263             "  float k  = 2;\n"
17264             "  int   ll = 10000;\n"
17265             "}",
17266             format("void SomeFunction(int parameter= 0) {\n"
17267                    " int const  i= 1;\n"
17268                    "  int *j=2;\n"
17269                    " int big  =  10000;\n"
17270                    "\n"
17271                    "unsigned oneTwoThree  =123;\n"
17272                    "int oneTwo = 12;\n"
17273                    "  method();\n"
17274                    "float k= 2;\n"
17275                    "int ll=10000;\n"
17276                    "}",
17277                    AlignmentMiddle));
17278   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17279             "  int const i   = 1;\n"
17280             "  int **    j   = 2, ***k;\n"
17281             "  int &     k   = i;\n"
17282             "  int &&    l   = i + j;\n"
17283             "  int       big = 10000;\n"
17284             "\n"
17285             "  unsigned oneTwoThree = 123;\n"
17286             "  int      oneTwo      = 12;\n"
17287             "  method();\n"
17288             "  float k  = 2;\n"
17289             "  int   ll = 10000;\n"
17290             "}",
17291             format("void SomeFunction(int parameter= 0) {\n"
17292                    " int const  i= 1;\n"
17293                    "  int **j=2,***k;\n"
17294                    "int &k=i;\n"
17295                    "int &&l=i+j;\n"
17296                    " int big  =  10000;\n"
17297                    "\n"
17298                    "unsigned oneTwoThree  =123;\n"
17299                    "int oneTwo = 12;\n"
17300                    "  method();\n"
17301                    "float k= 2;\n"
17302                    "int ll=10000;\n"
17303                    "}",
17304                    AlignmentMiddle));
17305   // variables are aligned at their name, pointers are in the middle
17306   verifyFormat("int *   a;\n"
17307                "int *   b;\n"
17308                "int *** c;\n"
17309                "int     foobar;\n",
17310                AlignmentMiddle);
17311 
17312   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17313   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17314   verifyFormat("#define A \\\n"
17315                "  int       aaaa = 12; \\\n"
17316                "  float     b = 23; \\\n"
17317                "  const int ccc = 234; \\\n"
17318                "  unsigned  dddddddddd = 2345;",
17319                Alignment);
17320   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17321   verifyFormat("#define A              \\\n"
17322                "  int       aaaa = 12; \\\n"
17323                "  float     b = 23;    \\\n"
17324                "  const int ccc = 234; \\\n"
17325                "  unsigned  dddddddddd = 2345;",
17326                Alignment);
17327   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17328   Alignment.ColumnLimit = 30;
17329   verifyFormat("#define A                    \\\n"
17330                "  int       aaaa = 12;       \\\n"
17331                "  float     b = 23;          \\\n"
17332                "  const int ccc = 234;       \\\n"
17333                "  int       dddddddddd = 2345;",
17334                Alignment);
17335   Alignment.ColumnLimit = 80;
17336   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17337                "k = 4, int l = 5,\n"
17338                "                  int m = 6) {\n"
17339                "  const int j = 10;\n"
17340                "  otherThing = 1;\n"
17341                "}",
17342                Alignment);
17343   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17344                "  int const i = 1;\n"
17345                "  int      *j = 2;\n"
17346                "  int       big = 10000;\n"
17347                "}",
17348                Alignment);
17349   verifyFormat("class C {\n"
17350                "public:\n"
17351                "  int          i = 1;\n"
17352                "  virtual void f() = 0;\n"
17353                "};",
17354                Alignment);
17355   verifyFormat("float i = 1;\n"
17356                "if (SomeType t = getSomething()) {\n"
17357                "}\n"
17358                "const unsigned j = 2;\n"
17359                "int            big = 10000;",
17360                Alignment);
17361   verifyFormat("float j = 7;\n"
17362                "for (int k = 0; k < N; ++k) {\n"
17363                "}\n"
17364                "unsigned j = 2;\n"
17365                "int      big = 10000;\n"
17366                "}",
17367                Alignment);
17368   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17369   verifyFormat("float              i = 1;\n"
17370                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17371                "    = someLooooooooooooooooongFunction();\n"
17372                "int j = 2;",
17373                Alignment);
17374   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17375   verifyFormat("int                i = 1;\n"
17376                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17377                "    someLooooooooooooooooongFunction();\n"
17378                "int j = 2;",
17379                Alignment);
17380 
17381   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17382   verifyFormat("auto lambda = []() {\n"
17383                "  auto  ii = 0;\n"
17384                "  float j  = 0;\n"
17385                "  return 0;\n"
17386                "};\n"
17387                "int   i  = 0;\n"
17388                "float i2 = 0;\n"
17389                "auto  v  = type{\n"
17390                "    i = 1,   //\n"
17391                "    (i = 2), //\n"
17392                "    i = 3    //\n"
17393                "};",
17394                Alignment);
17395   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17396 
17397   verifyFormat(
17398       "int      i = 1;\n"
17399       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17400       "                          loooooooooooooooooooooongParameterB);\n"
17401       "int      j = 2;",
17402       Alignment);
17403 
17404   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17405   // We expect declarations and assignments to align, as long as it doesn't
17406   // exceed the column limit, starting a new alignment sequence whenever it
17407   // happens.
17408   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17409   Alignment.ColumnLimit = 30;
17410   verifyFormat("float    ii              = 1;\n"
17411                "unsigned j               = 2;\n"
17412                "int someVerylongVariable = 1;\n"
17413                "AnotherLongType  ll = 123456;\n"
17414                "VeryVeryLongType k  = 2;\n"
17415                "int              myvar = 1;",
17416                Alignment);
17417   Alignment.ColumnLimit = 80;
17418   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17419 
17420   verifyFormat(
17421       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17422       "          typename LongType, typename B>\n"
17423       "auto foo() {}\n",
17424       Alignment);
17425   verifyFormat("float a, b = 1;\n"
17426                "int   c = 2;\n"
17427                "int   dd = 3;\n",
17428                Alignment);
17429   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17430                "float b[1][] = {{3.f}};\n",
17431                Alignment);
17432   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17433   verifyFormat("float a, b = 1;\n"
17434                "int   c  = 2;\n"
17435                "int   dd = 3;\n",
17436                Alignment);
17437   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17438                "float b[1][] = {{3.f}};\n",
17439                Alignment);
17440   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17441 
17442   Alignment.ColumnLimit = 30;
17443   Alignment.BinPackParameters = false;
17444   verifyFormat("void foo(float     a,\n"
17445                "         float     b,\n"
17446                "         int       c,\n"
17447                "         uint32_t *d) {\n"
17448                "  int   *e = 0;\n"
17449                "  float  f = 0;\n"
17450                "  double g = 0;\n"
17451                "}\n"
17452                "void bar(ino_t     a,\n"
17453                "         int       b,\n"
17454                "         uint32_t *c,\n"
17455                "         bool      d) {}\n",
17456                Alignment);
17457   Alignment.BinPackParameters = true;
17458   Alignment.ColumnLimit = 80;
17459 
17460   // Bug 33507
17461   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17462   verifyFormat(
17463       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
17464       "  static const Version verVs2017;\n"
17465       "  return true;\n"
17466       "});\n",
17467       Alignment);
17468   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17469 
17470   // See llvm.org/PR35641
17471   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17472   verifyFormat("int func() { //\n"
17473                "  int      b;\n"
17474                "  unsigned c;\n"
17475                "}",
17476                Alignment);
17477 
17478   // See PR37175
17479   FormatStyle Style = getMozillaStyle();
17480   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17481   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
17482             "foo(int a);",
17483             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
17484 
17485   Alignment.PointerAlignment = FormatStyle::PAS_Left;
17486   verifyFormat("unsigned int*       a;\n"
17487                "int*                b;\n"
17488                "unsigned int Const* c;\n"
17489                "unsigned int const* d;\n"
17490                "unsigned int Const& e;\n"
17491                "unsigned int const& f;",
17492                Alignment);
17493   verifyFormat("Const unsigned int* c;\n"
17494                "const unsigned int* d;\n"
17495                "Const unsigned int& e;\n"
17496                "const unsigned int& f;\n"
17497                "const unsigned      g;\n"
17498                "Const unsigned      h;",
17499                Alignment);
17500 
17501   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17502   verifyFormat("unsigned int *       a;\n"
17503                "int *                b;\n"
17504                "unsigned int Const * c;\n"
17505                "unsigned int const * d;\n"
17506                "unsigned int Const & e;\n"
17507                "unsigned int const & f;",
17508                Alignment);
17509   verifyFormat("Const unsigned int * c;\n"
17510                "const unsigned int * d;\n"
17511                "Const unsigned int & e;\n"
17512                "const unsigned int & f;\n"
17513                "const unsigned       g;\n"
17514                "Const unsigned       h;",
17515                Alignment);
17516 
17517   // See PR46529
17518   FormatStyle BracedAlign = getLLVMStyle();
17519   BracedAlign.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17520   verifyFormat("const auto result{[]() {\n"
17521                "  const auto something = 1;\n"
17522                "  return 2;\n"
17523                "}};",
17524                BracedAlign);
17525   verifyFormat("int foo{[]() {\n"
17526                "  int bar{0};\n"
17527                "  return 0;\n"
17528                "}()};",
17529                BracedAlign);
17530   BracedAlign.Cpp11BracedListStyle = false;
17531   verifyFormat("const auto result{ []() {\n"
17532                "  const auto something = 1;\n"
17533                "  return 2;\n"
17534                "} };",
17535                BracedAlign);
17536   verifyFormat("int foo{ []() {\n"
17537                "  int bar{ 0 };\n"
17538                "  return 0;\n"
17539                "}() };",
17540                BracedAlign);
17541 }
17542 
17543 TEST_F(FormatTest, AlignWithLineBreaks) {
17544   auto Style = getLLVMStyleWithColumns(120);
17545 
17546   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
17547   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
17548   verifyFormat("void foo() {\n"
17549                "  int myVar = 5;\n"
17550                "  double x = 3.14;\n"
17551                "  auto str = \"Hello \"\n"
17552                "             \"World\";\n"
17553                "  auto s = \"Hello \"\n"
17554                "           \"Again\";\n"
17555                "}",
17556                Style);
17557 
17558   // clang-format off
17559   verifyFormat("void foo() {\n"
17560                "  const int capacityBefore = Entries.capacity();\n"
17561                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17562                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17563                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17564                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17565                "}",
17566                Style);
17567   // clang-format on
17568 
17569   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17570   verifyFormat("void foo() {\n"
17571                "  int myVar = 5;\n"
17572                "  double x  = 3.14;\n"
17573                "  auto str  = \"Hello \"\n"
17574                "              \"World\";\n"
17575                "  auto s    = \"Hello \"\n"
17576                "              \"Again\";\n"
17577                "}",
17578                Style);
17579 
17580   // clang-format off
17581   verifyFormat("void foo() {\n"
17582                "  const int capacityBefore = Entries.capacity();\n"
17583                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17584                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17585                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17586                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17587                "}",
17588                Style);
17589   // clang-format on
17590 
17591   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17592   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17593   verifyFormat("void foo() {\n"
17594                "  int    myVar = 5;\n"
17595                "  double x = 3.14;\n"
17596                "  auto   str = \"Hello \"\n"
17597                "               \"World\";\n"
17598                "  auto   s = \"Hello \"\n"
17599                "             \"Again\";\n"
17600                "}",
17601                Style);
17602 
17603   // clang-format off
17604   verifyFormat("void foo() {\n"
17605                "  const int  capacityBefore = Entries.capacity();\n"
17606                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17607                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17608                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17609                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17610                "}",
17611                Style);
17612   // clang-format on
17613 
17614   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17615   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17616 
17617   verifyFormat("void foo() {\n"
17618                "  int    myVar = 5;\n"
17619                "  double x     = 3.14;\n"
17620                "  auto   str   = \"Hello \"\n"
17621                "                 \"World\";\n"
17622                "  auto   s     = \"Hello \"\n"
17623                "                 \"Again\";\n"
17624                "}",
17625                Style);
17626 
17627   // clang-format off
17628   verifyFormat("void foo() {\n"
17629                "  const int  capacityBefore = Entries.capacity();\n"
17630                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17631                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17632                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17633                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17634                "}",
17635                Style);
17636   // clang-format on
17637 
17638   Style = getLLVMStyleWithColumns(120);
17639   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17640   Style.ContinuationIndentWidth = 4;
17641   Style.IndentWidth = 4;
17642 
17643   // clang-format off
17644   verifyFormat("void SomeFunc() {\n"
17645                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17646                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17647                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17648                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17649                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17650                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17651                "}",
17652                Style);
17653   // clang-format on
17654 
17655   Style.BinPackArguments = false;
17656 
17657   // clang-format off
17658   verifyFormat("void SomeFunc() {\n"
17659                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
17660                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17661                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
17662                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17663                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
17664                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17665                "}",
17666                Style);
17667   // clang-format on
17668 }
17669 
17670 TEST_F(FormatTest, AlignWithInitializerPeriods) {
17671   auto Style = getLLVMStyleWithColumns(60);
17672 
17673   verifyFormat("void foo1(void) {\n"
17674                "  BYTE p[1] = 1;\n"
17675                "  A B = {.one_foooooooooooooooo = 2,\n"
17676                "         .two_fooooooooooooo = 3,\n"
17677                "         .three_fooooooooooooo = 4};\n"
17678                "  BYTE payload = 2;\n"
17679                "}",
17680                Style);
17681 
17682   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17683   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
17684   verifyFormat("void foo2(void) {\n"
17685                "  BYTE p[1]    = 1;\n"
17686                "  A B          = {.one_foooooooooooooooo = 2,\n"
17687                "                  .two_fooooooooooooo    = 3,\n"
17688                "                  .three_fooooooooooooo  = 4};\n"
17689                "  BYTE payload = 2;\n"
17690                "}",
17691                Style);
17692 
17693   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17694   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17695   verifyFormat("void foo3(void) {\n"
17696                "  BYTE p[1] = 1;\n"
17697                "  A    B = {.one_foooooooooooooooo = 2,\n"
17698                "            .two_fooooooooooooo = 3,\n"
17699                "            .three_fooooooooooooo = 4};\n"
17700                "  BYTE payload = 2;\n"
17701                "}",
17702                Style);
17703 
17704   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17705   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17706   verifyFormat("void foo4(void) {\n"
17707                "  BYTE p[1]    = 1;\n"
17708                "  A    B       = {.one_foooooooooooooooo = 2,\n"
17709                "                  .two_fooooooooooooo    = 3,\n"
17710                "                  .three_fooooooooooooo  = 4};\n"
17711                "  BYTE payload = 2;\n"
17712                "}",
17713                Style);
17714 }
17715 
17716 TEST_F(FormatTest, LinuxBraceBreaking) {
17717   FormatStyle LinuxBraceStyle = getLLVMStyle();
17718   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
17719   verifyFormat("namespace a\n"
17720                "{\n"
17721                "class A\n"
17722                "{\n"
17723                "  void f()\n"
17724                "  {\n"
17725                "    if (true) {\n"
17726                "      a();\n"
17727                "      b();\n"
17728                "    } else {\n"
17729                "      a();\n"
17730                "    }\n"
17731                "  }\n"
17732                "  void g() { return; }\n"
17733                "};\n"
17734                "struct B {\n"
17735                "  int x;\n"
17736                "};\n"
17737                "} // namespace a\n",
17738                LinuxBraceStyle);
17739   verifyFormat("enum X {\n"
17740                "  Y = 0,\n"
17741                "}\n",
17742                LinuxBraceStyle);
17743   verifyFormat("struct S {\n"
17744                "  int Type;\n"
17745                "  union {\n"
17746                "    int x;\n"
17747                "    double y;\n"
17748                "  } Value;\n"
17749                "  class C\n"
17750                "  {\n"
17751                "    MyFavoriteType Value;\n"
17752                "  } Class;\n"
17753                "}\n",
17754                LinuxBraceStyle);
17755 }
17756 
17757 TEST_F(FormatTest, MozillaBraceBreaking) {
17758   FormatStyle MozillaBraceStyle = getLLVMStyle();
17759   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
17760   MozillaBraceStyle.FixNamespaceComments = false;
17761   verifyFormat("namespace a {\n"
17762                "class A\n"
17763                "{\n"
17764                "  void f()\n"
17765                "  {\n"
17766                "    if (true) {\n"
17767                "      a();\n"
17768                "      b();\n"
17769                "    }\n"
17770                "  }\n"
17771                "  void g() { return; }\n"
17772                "};\n"
17773                "enum E\n"
17774                "{\n"
17775                "  A,\n"
17776                "  // foo\n"
17777                "  B,\n"
17778                "  C\n"
17779                "};\n"
17780                "struct B\n"
17781                "{\n"
17782                "  int x;\n"
17783                "};\n"
17784                "}\n",
17785                MozillaBraceStyle);
17786   verifyFormat("struct S\n"
17787                "{\n"
17788                "  int Type;\n"
17789                "  union\n"
17790                "  {\n"
17791                "    int x;\n"
17792                "    double y;\n"
17793                "  } Value;\n"
17794                "  class C\n"
17795                "  {\n"
17796                "    MyFavoriteType Value;\n"
17797                "  } Class;\n"
17798                "}\n",
17799                MozillaBraceStyle);
17800 }
17801 
17802 TEST_F(FormatTest, StroustrupBraceBreaking) {
17803   FormatStyle StroustrupBraceStyle = getLLVMStyle();
17804   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
17805   verifyFormat("namespace a {\n"
17806                "class A {\n"
17807                "  void f()\n"
17808                "  {\n"
17809                "    if (true) {\n"
17810                "      a();\n"
17811                "      b();\n"
17812                "    }\n"
17813                "  }\n"
17814                "  void g() { return; }\n"
17815                "};\n"
17816                "struct B {\n"
17817                "  int x;\n"
17818                "};\n"
17819                "} // namespace a\n",
17820                StroustrupBraceStyle);
17821 
17822   verifyFormat("void foo()\n"
17823                "{\n"
17824                "  if (a) {\n"
17825                "    a();\n"
17826                "  }\n"
17827                "  else {\n"
17828                "    b();\n"
17829                "  }\n"
17830                "}\n",
17831                StroustrupBraceStyle);
17832 
17833   verifyFormat("#ifdef _DEBUG\n"
17834                "int foo(int i = 0)\n"
17835                "#else\n"
17836                "int foo(int i = 5)\n"
17837                "#endif\n"
17838                "{\n"
17839                "  return i;\n"
17840                "}",
17841                StroustrupBraceStyle);
17842 
17843   verifyFormat("void foo() {}\n"
17844                "void bar()\n"
17845                "#ifdef _DEBUG\n"
17846                "{\n"
17847                "  foo();\n"
17848                "}\n"
17849                "#else\n"
17850                "{\n"
17851                "}\n"
17852                "#endif",
17853                StroustrupBraceStyle);
17854 
17855   verifyFormat("void foobar() { int i = 5; }\n"
17856                "#ifdef _DEBUG\n"
17857                "void bar() {}\n"
17858                "#else\n"
17859                "void bar() { foobar(); }\n"
17860                "#endif",
17861                StroustrupBraceStyle);
17862 }
17863 
17864 TEST_F(FormatTest, AllmanBraceBreaking) {
17865   FormatStyle AllmanBraceStyle = getLLVMStyle();
17866   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
17867 
17868   EXPECT_EQ("namespace a\n"
17869             "{\n"
17870             "void f();\n"
17871             "void g();\n"
17872             "} // namespace a\n",
17873             format("namespace a\n"
17874                    "{\n"
17875                    "void f();\n"
17876                    "void g();\n"
17877                    "}\n",
17878                    AllmanBraceStyle));
17879 
17880   verifyFormat("namespace a\n"
17881                "{\n"
17882                "class A\n"
17883                "{\n"
17884                "  void f()\n"
17885                "  {\n"
17886                "    if (true)\n"
17887                "    {\n"
17888                "      a();\n"
17889                "      b();\n"
17890                "    }\n"
17891                "  }\n"
17892                "  void g() { return; }\n"
17893                "};\n"
17894                "struct B\n"
17895                "{\n"
17896                "  int x;\n"
17897                "};\n"
17898                "union C\n"
17899                "{\n"
17900                "};\n"
17901                "} // namespace a",
17902                AllmanBraceStyle);
17903 
17904   verifyFormat("void f()\n"
17905                "{\n"
17906                "  if (true)\n"
17907                "  {\n"
17908                "    a();\n"
17909                "  }\n"
17910                "  else if (false)\n"
17911                "  {\n"
17912                "    b();\n"
17913                "  }\n"
17914                "  else\n"
17915                "  {\n"
17916                "    c();\n"
17917                "  }\n"
17918                "}\n",
17919                AllmanBraceStyle);
17920 
17921   verifyFormat("void f()\n"
17922                "{\n"
17923                "  for (int i = 0; i < 10; ++i)\n"
17924                "  {\n"
17925                "    a();\n"
17926                "  }\n"
17927                "  while (false)\n"
17928                "  {\n"
17929                "    b();\n"
17930                "  }\n"
17931                "  do\n"
17932                "  {\n"
17933                "    c();\n"
17934                "  } while (false)\n"
17935                "}\n",
17936                AllmanBraceStyle);
17937 
17938   verifyFormat("void f(int a)\n"
17939                "{\n"
17940                "  switch (a)\n"
17941                "  {\n"
17942                "  case 0:\n"
17943                "    break;\n"
17944                "  case 1:\n"
17945                "  {\n"
17946                "    break;\n"
17947                "  }\n"
17948                "  case 2:\n"
17949                "  {\n"
17950                "  }\n"
17951                "  break;\n"
17952                "  default:\n"
17953                "    break;\n"
17954                "  }\n"
17955                "}\n",
17956                AllmanBraceStyle);
17957 
17958   verifyFormat("enum X\n"
17959                "{\n"
17960                "  Y = 0,\n"
17961                "}\n",
17962                AllmanBraceStyle);
17963   verifyFormat("enum X\n"
17964                "{\n"
17965                "  Y = 0\n"
17966                "}\n",
17967                AllmanBraceStyle);
17968 
17969   verifyFormat("@interface BSApplicationController ()\n"
17970                "{\n"
17971                "@private\n"
17972                "  id _extraIvar;\n"
17973                "}\n"
17974                "@end\n",
17975                AllmanBraceStyle);
17976 
17977   verifyFormat("#ifdef _DEBUG\n"
17978                "int foo(int i = 0)\n"
17979                "#else\n"
17980                "int foo(int i = 5)\n"
17981                "#endif\n"
17982                "{\n"
17983                "  return i;\n"
17984                "}",
17985                AllmanBraceStyle);
17986 
17987   verifyFormat("void foo() {}\n"
17988                "void bar()\n"
17989                "#ifdef _DEBUG\n"
17990                "{\n"
17991                "  foo();\n"
17992                "}\n"
17993                "#else\n"
17994                "{\n"
17995                "}\n"
17996                "#endif",
17997                AllmanBraceStyle);
17998 
17999   verifyFormat("void foobar() { int i = 5; }\n"
18000                "#ifdef _DEBUG\n"
18001                "void bar() {}\n"
18002                "#else\n"
18003                "void bar() { foobar(); }\n"
18004                "#endif",
18005                AllmanBraceStyle);
18006 
18007   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18008             FormatStyle::SLS_All);
18009 
18010   verifyFormat("[](int i) { return i + 2; };\n"
18011                "[](int i, int j)\n"
18012                "{\n"
18013                "  auto x = i + j;\n"
18014                "  auto y = i * j;\n"
18015                "  return x ^ y;\n"
18016                "};\n"
18017                "void foo()\n"
18018                "{\n"
18019                "  auto shortLambda = [](int i) { return i + 2; };\n"
18020                "  auto longLambda = [](int i, int j)\n"
18021                "  {\n"
18022                "    auto x = i + j;\n"
18023                "    auto y = i * j;\n"
18024                "    return x ^ y;\n"
18025                "  };\n"
18026                "}",
18027                AllmanBraceStyle);
18028 
18029   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18030 
18031   verifyFormat("[](int i)\n"
18032                "{\n"
18033                "  return i + 2;\n"
18034                "};\n"
18035                "[](int i, int j)\n"
18036                "{\n"
18037                "  auto x = i + j;\n"
18038                "  auto y = i * j;\n"
18039                "  return x ^ y;\n"
18040                "};\n"
18041                "void foo()\n"
18042                "{\n"
18043                "  auto shortLambda = [](int i)\n"
18044                "  {\n"
18045                "    return i + 2;\n"
18046                "  };\n"
18047                "  auto longLambda = [](int i, int j)\n"
18048                "  {\n"
18049                "    auto x = i + j;\n"
18050                "    auto y = i * j;\n"
18051                "    return x ^ y;\n"
18052                "  };\n"
18053                "}",
18054                AllmanBraceStyle);
18055 
18056   // Reset
18057   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18058 
18059   // This shouldn't affect ObjC blocks..
18060   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18061                "  // ...\n"
18062                "  int i;\n"
18063                "}];",
18064                AllmanBraceStyle);
18065   verifyFormat("void (^block)(void) = ^{\n"
18066                "  // ...\n"
18067                "  int i;\n"
18068                "};",
18069                AllmanBraceStyle);
18070   // .. or dict literals.
18071   verifyFormat("void f()\n"
18072                "{\n"
18073                "  // ...\n"
18074                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18075                "}",
18076                AllmanBraceStyle);
18077   verifyFormat("void f()\n"
18078                "{\n"
18079                "  // ...\n"
18080                "  [object someMethod:@{a : @\"b\"}];\n"
18081                "}",
18082                AllmanBraceStyle);
18083   verifyFormat("int f()\n"
18084                "{ // comment\n"
18085                "  return 42;\n"
18086                "}",
18087                AllmanBraceStyle);
18088 
18089   AllmanBraceStyle.ColumnLimit = 19;
18090   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18091   AllmanBraceStyle.ColumnLimit = 18;
18092   verifyFormat("void f()\n"
18093                "{\n"
18094                "  int i;\n"
18095                "}",
18096                AllmanBraceStyle);
18097   AllmanBraceStyle.ColumnLimit = 80;
18098 
18099   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18100   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18101       FormatStyle::SIS_WithoutElse;
18102   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18103   verifyFormat("void f(bool b)\n"
18104                "{\n"
18105                "  if (b)\n"
18106                "  {\n"
18107                "    return;\n"
18108                "  }\n"
18109                "}\n",
18110                BreakBeforeBraceShortIfs);
18111   verifyFormat("void f(bool b)\n"
18112                "{\n"
18113                "  if constexpr (b)\n"
18114                "  {\n"
18115                "    return;\n"
18116                "  }\n"
18117                "}\n",
18118                BreakBeforeBraceShortIfs);
18119   verifyFormat("void f(bool b)\n"
18120                "{\n"
18121                "  if CONSTEXPR (b)\n"
18122                "  {\n"
18123                "    return;\n"
18124                "  }\n"
18125                "}\n",
18126                BreakBeforeBraceShortIfs);
18127   verifyFormat("void f(bool b)\n"
18128                "{\n"
18129                "  if (b) return;\n"
18130                "}\n",
18131                BreakBeforeBraceShortIfs);
18132   verifyFormat("void f(bool b)\n"
18133                "{\n"
18134                "  if constexpr (b) return;\n"
18135                "}\n",
18136                BreakBeforeBraceShortIfs);
18137   verifyFormat("void f(bool b)\n"
18138                "{\n"
18139                "  if CONSTEXPR (b) return;\n"
18140                "}\n",
18141                BreakBeforeBraceShortIfs);
18142   verifyFormat("void f(bool b)\n"
18143                "{\n"
18144                "  while (b)\n"
18145                "  {\n"
18146                "    return;\n"
18147                "  }\n"
18148                "}\n",
18149                BreakBeforeBraceShortIfs);
18150 }
18151 
18152 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18153   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18154   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18155 
18156   // Make a few changes to the style for testing purposes
18157   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18158       FormatStyle::SFS_Empty;
18159   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18160 
18161   // FIXME: this test case can't decide whether there should be a blank line
18162   // after the ~D() line or not. It adds one if one doesn't exist in the test
18163   // and it removes the line if one exists.
18164   /*
18165   verifyFormat("class A;\n"
18166                "namespace B\n"
18167                "  {\n"
18168                "class C;\n"
18169                "// Comment\n"
18170                "class D\n"
18171                "  {\n"
18172                "public:\n"
18173                "  D();\n"
18174                "  ~D() {}\n"
18175                "private:\n"
18176                "  enum E\n"
18177                "    {\n"
18178                "    F\n"
18179                "    }\n"
18180                "  };\n"
18181                "  } // namespace B\n",
18182                WhitesmithsBraceStyle);
18183   */
18184 
18185   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18186   verifyFormat("namespace a\n"
18187                "  {\n"
18188                "class A\n"
18189                "  {\n"
18190                "  void f()\n"
18191                "    {\n"
18192                "    if (true)\n"
18193                "      {\n"
18194                "      a();\n"
18195                "      b();\n"
18196                "      }\n"
18197                "    }\n"
18198                "  void g()\n"
18199                "    {\n"
18200                "    return;\n"
18201                "    }\n"
18202                "  };\n"
18203                "struct B\n"
18204                "  {\n"
18205                "  int x;\n"
18206                "  };\n"
18207                "  } // namespace a",
18208                WhitesmithsBraceStyle);
18209 
18210   verifyFormat("namespace a\n"
18211                "  {\n"
18212                "namespace b\n"
18213                "  {\n"
18214                "class A\n"
18215                "  {\n"
18216                "  void f()\n"
18217                "    {\n"
18218                "    if (true)\n"
18219                "      {\n"
18220                "      a();\n"
18221                "      b();\n"
18222                "      }\n"
18223                "    }\n"
18224                "  void g()\n"
18225                "    {\n"
18226                "    return;\n"
18227                "    }\n"
18228                "  };\n"
18229                "struct B\n"
18230                "  {\n"
18231                "  int x;\n"
18232                "  };\n"
18233                "  } // namespace b\n"
18234                "  } // namespace a",
18235                WhitesmithsBraceStyle);
18236 
18237   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18238   verifyFormat("namespace a\n"
18239                "  {\n"
18240                "namespace b\n"
18241                "  {\n"
18242                "  class A\n"
18243                "    {\n"
18244                "    void f()\n"
18245                "      {\n"
18246                "      if (true)\n"
18247                "        {\n"
18248                "        a();\n"
18249                "        b();\n"
18250                "        }\n"
18251                "      }\n"
18252                "    void g()\n"
18253                "      {\n"
18254                "      return;\n"
18255                "      }\n"
18256                "    };\n"
18257                "  struct B\n"
18258                "    {\n"
18259                "    int x;\n"
18260                "    };\n"
18261                "  } // namespace b\n"
18262                "  } // namespace a",
18263                WhitesmithsBraceStyle);
18264 
18265   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18266   verifyFormat("namespace a\n"
18267                "  {\n"
18268                "  namespace b\n"
18269                "    {\n"
18270                "    class A\n"
18271                "      {\n"
18272                "      void f()\n"
18273                "        {\n"
18274                "        if (true)\n"
18275                "          {\n"
18276                "          a();\n"
18277                "          b();\n"
18278                "          }\n"
18279                "        }\n"
18280                "      void g()\n"
18281                "        {\n"
18282                "        return;\n"
18283                "        }\n"
18284                "      };\n"
18285                "    struct B\n"
18286                "      {\n"
18287                "      int x;\n"
18288                "      };\n"
18289                "    } // namespace b\n"
18290                "  }   // namespace a",
18291                WhitesmithsBraceStyle);
18292 
18293   verifyFormat("void f()\n"
18294                "  {\n"
18295                "  if (true)\n"
18296                "    {\n"
18297                "    a();\n"
18298                "    }\n"
18299                "  else if (false)\n"
18300                "    {\n"
18301                "    b();\n"
18302                "    }\n"
18303                "  else\n"
18304                "    {\n"
18305                "    c();\n"
18306                "    }\n"
18307                "  }\n",
18308                WhitesmithsBraceStyle);
18309 
18310   verifyFormat("void f()\n"
18311                "  {\n"
18312                "  for (int i = 0; i < 10; ++i)\n"
18313                "    {\n"
18314                "    a();\n"
18315                "    }\n"
18316                "  while (false)\n"
18317                "    {\n"
18318                "    b();\n"
18319                "    }\n"
18320                "  do\n"
18321                "    {\n"
18322                "    c();\n"
18323                "    } while (false)\n"
18324                "  }\n",
18325                WhitesmithsBraceStyle);
18326 
18327   WhitesmithsBraceStyle.IndentCaseLabels = true;
18328   verifyFormat("void switchTest1(int a)\n"
18329                "  {\n"
18330                "  switch (a)\n"
18331                "    {\n"
18332                "    case 2:\n"
18333                "      {\n"
18334                "      }\n"
18335                "      break;\n"
18336                "    }\n"
18337                "  }\n",
18338                WhitesmithsBraceStyle);
18339 
18340   verifyFormat("void switchTest2(int a)\n"
18341                "  {\n"
18342                "  switch (a)\n"
18343                "    {\n"
18344                "    case 0:\n"
18345                "      break;\n"
18346                "    case 1:\n"
18347                "      {\n"
18348                "      break;\n"
18349                "      }\n"
18350                "    case 2:\n"
18351                "      {\n"
18352                "      }\n"
18353                "      break;\n"
18354                "    default:\n"
18355                "      break;\n"
18356                "    }\n"
18357                "  }\n",
18358                WhitesmithsBraceStyle);
18359 
18360   verifyFormat("void switchTest3(int a)\n"
18361                "  {\n"
18362                "  switch (a)\n"
18363                "    {\n"
18364                "    case 0:\n"
18365                "      {\n"
18366                "      foo(x);\n"
18367                "      }\n"
18368                "      break;\n"
18369                "    default:\n"
18370                "      {\n"
18371                "      foo(1);\n"
18372                "      }\n"
18373                "      break;\n"
18374                "    }\n"
18375                "  }\n",
18376                WhitesmithsBraceStyle);
18377 
18378   WhitesmithsBraceStyle.IndentCaseLabels = false;
18379 
18380   verifyFormat("void switchTest4(int a)\n"
18381                "  {\n"
18382                "  switch (a)\n"
18383                "    {\n"
18384                "  case 2:\n"
18385                "    {\n"
18386                "    }\n"
18387                "    break;\n"
18388                "    }\n"
18389                "  }\n",
18390                WhitesmithsBraceStyle);
18391 
18392   verifyFormat("void switchTest5(int a)\n"
18393                "  {\n"
18394                "  switch (a)\n"
18395                "    {\n"
18396                "  case 0:\n"
18397                "    break;\n"
18398                "  case 1:\n"
18399                "    {\n"
18400                "    foo();\n"
18401                "    break;\n"
18402                "    }\n"
18403                "  case 2:\n"
18404                "    {\n"
18405                "    }\n"
18406                "    break;\n"
18407                "  default:\n"
18408                "    break;\n"
18409                "    }\n"
18410                "  }\n",
18411                WhitesmithsBraceStyle);
18412 
18413   verifyFormat("void switchTest6(int a)\n"
18414                "  {\n"
18415                "  switch (a)\n"
18416                "    {\n"
18417                "  case 0:\n"
18418                "    {\n"
18419                "    foo(x);\n"
18420                "    }\n"
18421                "    break;\n"
18422                "  default:\n"
18423                "    {\n"
18424                "    foo(1);\n"
18425                "    }\n"
18426                "    break;\n"
18427                "    }\n"
18428                "  }\n",
18429                WhitesmithsBraceStyle);
18430 
18431   verifyFormat("enum X\n"
18432                "  {\n"
18433                "  Y = 0, // testing\n"
18434                "  }\n",
18435                WhitesmithsBraceStyle);
18436 
18437   verifyFormat("enum X\n"
18438                "  {\n"
18439                "  Y = 0\n"
18440                "  }\n",
18441                WhitesmithsBraceStyle);
18442   verifyFormat("enum X\n"
18443                "  {\n"
18444                "  Y = 0,\n"
18445                "  Z = 1\n"
18446                "  };\n",
18447                WhitesmithsBraceStyle);
18448 
18449   verifyFormat("@interface BSApplicationController ()\n"
18450                "  {\n"
18451                "@private\n"
18452                "  id _extraIvar;\n"
18453                "  }\n"
18454                "@end\n",
18455                WhitesmithsBraceStyle);
18456 
18457   verifyFormat("#ifdef _DEBUG\n"
18458                "int foo(int i = 0)\n"
18459                "#else\n"
18460                "int foo(int i = 5)\n"
18461                "#endif\n"
18462                "  {\n"
18463                "  return i;\n"
18464                "  }",
18465                WhitesmithsBraceStyle);
18466 
18467   verifyFormat("void foo() {}\n"
18468                "void bar()\n"
18469                "#ifdef _DEBUG\n"
18470                "  {\n"
18471                "  foo();\n"
18472                "  }\n"
18473                "#else\n"
18474                "  {\n"
18475                "  }\n"
18476                "#endif",
18477                WhitesmithsBraceStyle);
18478 
18479   verifyFormat("void foobar()\n"
18480                "  {\n"
18481                "  int i = 5;\n"
18482                "  }\n"
18483                "#ifdef _DEBUG\n"
18484                "void bar()\n"
18485                "  {\n"
18486                "  }\n"
18487                "#else\n"
18488                "void bar()\n"
18489                "  {\n"
18490                "  foobar();\n"
18491                "  }\n"
18492                "#endif",
18493                WhitesmithsBraceStyle);
18494 
18495   // This shouldn't affect ObjC blocks..
18496   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18497                "  // ...\n"
18498                "  int i;\n"
18499                "}];",
18500                WhitesmithsBraceStyle);
18501   verifyFormat("void (^block)(void) = ^{\n"
18502                "  // ...\n"
18503                "  int i;\n"
18504                "};",
18505                WhitesmithsBraceStyle);
18506   // .. or dict literals.
18507   verifyFormat("void f()\n"
18508                "  {\n"
18509                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18510                "  }",
18511                WhitesmithsBraceStyle);
18512 
18513   verifyFormat("int f()\n"
18514                "  { // comment\n"
18515                "  return 42;\n"
18516                "  }",
18517                WhitesmithsBraceStyle);
18518 
18519   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
18520   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18521       FormatStyle::SIS_OnlyFirstIf;
18522   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18523   verifyFormat("void f(bool b)\n"
18524                "  {\n"
18525                "  if (b)\n"
18526                "    {\n"
18527                "    return;\n"
18528                "    }\n"
18529                "  }\n",
18530                BreakBeforeBraceShortIfs);
18531   verifyFormat("void f(bool b)\n"
18532                "  {\n"
18533                "  if (b) return;\n"
18534                "  }\n",
18535                BreakBeforeBraceShortIfs);
18536   verifyFormat("void f(bool b)\n"
18537                "  {\n"
18538                "  while (b)\n"
18539                "    {\n"
18540                "    return;\n"
18541                "    }\n"
18542                "  }\n",
18543                BreakBeforeBraceShortIfs);
18544 }
18545 
18546 TEST_F(FormatTest, GNUBraceBreaking) {
18547   FormatStyle GNUBraceStyle = getLLVMStyle();
18548   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
18549   verifyFormat("namespace a\n"
18550                "{\n"
18551                "class A\n"
18552                "{\n"
18553                "  void f()\n"
18554                "  {\n"
18555                "    int a;\n"
18556                "    {\n"
18557                "      int b;\n"
18558                "    }\n"
18559                "    if (true)\n"
18560                "      {\n"
18561                "        a();\n"
18562                "        b();\n"
18563                "      }\n"
18564                "  }\n"
18565                "  void g() { return; }\n"
18566                "}\n"
18567                "} // namespace a",
18568                GNUBraceStyle);
18569 
18570   verifyFormat("void f()\n"
18571                "{\n"
18572                "  if (true)\n"
18573                "    {\n"
18574                "      a();\n"
18575                "    }\n"
18576                "  else if (false)\n"
18577                "    {\n"
18578                "      b();\n"
18579                "    }\n"
18580                "  else\n"
18581                "    {\n"
18582                "      c();\n"
18583                "    }\n"
18584                "}\n",
18585                GNUBraceStyle);
18586 
18587   verifyFormat("void f()\n"
18588                "{\n"
18589                "  for (int i = 0; i < 10; ++i)\n"
18590                "    {\n"
18591                "      a();\n"
18592                "    }\n"
18593                "  while (false)\n"
18594                "    {\n"
18595                "      b();\n"
18596                "    }\n"
18597                "  do\n"
18598                "    {\n"
18599                "      c();\n"
18600                "    }\n"
18601                "  while (false);\n"
18602                "}\n",
18603                GNUBraceStyle);
18604 
18605   verifyFormat("void f(int a)\n"
18606                "{\n"
18607                "  switch (a)\n"
18608                "    {\n"
18609                "    case 0:\n"
18610                "      break;\n"
18611                "    case 1:\n"
18612                "      {\n"
18613                "        break;\n"
18614                "      }\n"
18615                "    case 2:\n"
18616                "      {\n"
18617                "      }\n"
18618                "      break;\n"
18619                "    default:\n"
18620                "      break;\n"
18621                "    }\n"
18622                "}\n",
18623                GNUBraceStyle);
18624 
18625   verifyFormat("enum X\n"
18626                "{\n"
18627                "  Y = 0,\n"
18628                "}\n",
18629                GNUBraceStyle);
18630 
18631   verifyFormat("@interface BSApplicationController ()\n"
18632                "{\n"
18633                "@private\n"
18634                "  id _extraIvar;\n"
18635                "}\n"
18636                "@end\n",
18637                GNUBraceStyle);
18638 
18639   verifyFormat("#ifdef _DEBUG\n"
18640                "int foo(int i = 0)\n"
18641                "#else\n"
18642                "int foo(int i = 5)\n"
18643                "#endif\n"
18644                "{\n"
18645                "  return i;\n"
18646                "}",
18647                GNUBraceStyle);
18648 
18649   verifyFormat("void foo() {}\n"
18650                "void bar()\n"
18651                "#ifdef _DEBUG\n"
18652                "{\n"
18653                "  foo();\n"
18654                "}\n"
18655                "#else\n"
18656                "{\n"
18657                "}\n"
18658                "#endif",
18659                GNUBraceStyle);
18660 
18661   verifyFormat("void foobar() { int i = 5; }\n"
18662                "#ifdef _DEBUG\n"
18663                "void bar() {}\n"
18664                "#else\n"
18665                "void bar() { foobar(); }\n"
18666                "#endif",
18667                GNUBraceStyle);
18668 }
18669 
18670 TEST_F(FormatTest, WebKitBraceBreaking) {
18671   FormatStyle WebKitBraceStyle = getLLVMStyle();
18672   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
18673   WebKitBraceStyle.FixNamespaceComments = false;
18674   verifyFormat("namespace a {\n"
18675                "class A {\n"
18676                "  void f()\n"
18677                "  {\n"
18678                "    if (true) {\n"
18679                "      a();\n"
18680                "      b();\n"
18681                "    }\n"
18682                "  }\n"
18683                "  void g() { return; }\n"
18684                "};\n"
18685                "enum E {\n"
18686                "  A,\n"
18687                "  // foo\n"
18688                "  B,\n"
18689                "  C\n"
18690                "};\n"
18691                "struct B {\n"
18692                "  int x;\n"
18693                "};\n"
18694                "}\n",
18695                WebKitBraceStyle);
18696   verifyFormat("struct S {\n"
18697                "  int Type;\n"
18698                "  union {\n"
18699                "    int x;\n"
18700                "    double y;\n"
18701                "  } Value;\n"
18702                "  class C {\n"
18703                "    MyFavoriteType Value;\n"
18704                "  } Class;\n"
18705                "};\n",
18706                WebKitBraceStyle);
18707 }
18708 
18709 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
18710   verifyFormat("void f() {\n"
18711                "  try {\n"
18712                "  } catch (const Exception &e) {\n"
18713                "  }\n"
18714                "}\n",
18715                getLLVMStyle());
18716 }
18717 
18718 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
18719   auto Style = getLLVMStyle();
18720   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18721   Style.AlignConsecutiveAssignments =
18722       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18723   Style.AlignConsecutiveDeclarations =
18724       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18725   verifyFormat("struct test demo[] = {\n"
18726                "    {56,    23, \"hello\"},\n"
18727                "    {-1, 93463, \"world\"},\n"
18728                "    { 7,     5,    \"!!\"}\n"
18729                "};\n",
18730                Style);
18731 
18732   verifyFormat("struct test demo[] = {\n"
18733                "    {56,    23, \"hello\"}, // first line\n"
18734                "    {-1, 93463, \"world\"}, // second line\n"
18735                "    { 7,     5,    \"!!\"}  // third line\n"
18736                "};\n",
18737                Style);
18738 
18739   verifyFormat("struct test demo[4] = {\n"
18740                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18741                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18742                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18743                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18744                "};\n",
18745                Style);
18746 
18747   verifyFormat("struct test demo[3] = {\n"
18748                "    {56,    23, \"hello\"},\n"
18749                "    {-1, 93463, \"world\"},\n"
18750                "    { 7,     5,    \"!!\"}\n"
18751                "};\n",
18752                Style);
18753 
18754   verifyFormat("struct test demo[3] = {\n"
18755                "    {int{56},    23, \"hello\"},\n"
18756                "    {int{-1}, 93463, \"world\"},\n"
18757                "    { int{7},     5,    \"!!\"}\n"
18758                "};\n",
18759                Style);
18760 
18761   verifyFormat("struct test demo[] = {\n"
18762                "    {56,    23, \"hello\"},\n"
18763                "    {-1, 93463, \"world\"},\n"
18764                "    { 7,     5,    \"!!\"},\n"
18765                "};\n",
18766                Style);
18767 
18768   verifyFormat("test demo[] = {\n"
18769                "    {56,    23, \"hello\"},\n"
18770                "    {-1, 93463, \"world\"},\n"
18771                "    { 7,     5,    \"!!\"},\n"
18772                "};\n",
18773                Style);
18774 
18775   verifyFormat("demo = std::array<struct test, 3>{\n"
18776                "    test{56,    23, \"hello\"},\n"
18777                "    test{-1, 93463, \"world\"},\n"
18778                "    test{ 7,     5,    \"!!\"},\n"
18779                "};\n",
18780                Style);
18781 
18782   verifyFormat("test demo[] = {\n"
18783                "    {56,    23, \"hello\"},\n"
18784                "#if X\n"
18785                "    {-1, 93463, \"world\"},\n"
18786                "#endif\n"
18787                "    { 7,     5,    \"!!\"}\n"
18788                "};\n",
18789                Style);
18790 
18791   verifyFormat(
18792       "test demo[] = {\n"
18793       "    { 7,    23,\n"
18794       "     \"hello world i am a very long line that really, in any\"\n"
18795       "     \"just world, ought to be split over multiple lines\"},\n"
18796       "    {-1, 93463,                                  \"world\"},\n"
18797       "    {56,     5,                                     \"!!\"}\n"
18798       "};\n",
18799       Style);
18800 
18801   verifyFormat("return GradForUnaryCwise(g, {\n"
18802                "                                {{\"sign\"}, \"Sign\",  "
18803                "  {\"x\", \"dy\"}},\n"
18804                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
18805                ", \"sign\"}},\n"
18806                "});\n",
18807                Style);
18808 
18809   Style.ColumnLimit = 0;
18810   EXPECT_EQ(
18811       "test demo[] = {\n"
18812       "    {56,    23, \"hello world i am a very long line that really, "
18813       "in any just world, ought to be split over multiple lines\"},\n"
18814       "    {-1, 93463,                                                  "
18815       "                                                 \"world\"},\n"
18816       "    { 7,     5,                                                  "
18817       "                                                    \"!!\"},\n"
18818       "};",
18819       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18820              "that really, in any just world, ought to be split over multiple "
18821              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18822              Style));
18823 
18824   Style.ColumnLimit = 80;
18825   verifyFormat("test demo[] = {\n"
18826                "    {56,    23, /* a comment */ \"hello\"},\n"
18827                "    {-1, 93463,                 \"world\"},\n"
18828                "    { 7,     5,                    \"!!\"}\n"
18829                "};\n",
18830                Style);
18831 
18832   verifyFormat("test demo[] = {\n"
18833                "    {56,    23,                    \"hello\"},\n"
18834                "    {-1, 93463, \"world\" /* comment here */},\n"
18835                "    { 7,     5,                       \"!!\"}\n"
18836                "};\n",
18837                Style);
18838 
18839   verifyFormat("test demo[] = {\n"
18840                "    {56, /* a comment */ 23, \"hello\"},\n"
18841                "    {-1,              93463, \"world\"},\n"
18842                "    { 7,                  5,    \"!!\"}\n"
18843                "};\n",
18844                Style);
18845 
18846   Style.ColumnLimit = 20;
18847   EXPECT_EQ(
18848       "demo = std::array<\n"
18849       "    struct test, 3>{\n"
18850       "    test{\n"
18851       "         56,    23,\n"
18852       "         \"hello \"\n"
18853       "         \"world i \"\n"
18854       "         \"am a very \"\n"
18855       "         \"long line \"\n"
18856       "         \"that \"\n"
18857       "         \"really, \"\n"
18858       "         \"in any \"\n"
18859       "         \"just \"\n"
18860       "         \"world, \"\n"
18861       "         \"ought to \"\n"
18862       "         \"be split \"\n"
18863       "         \"over \"\n"
18864       "         \"multiple \"\n"
18865       "         \"lines\"},\n"
18866       "    test{-1, 93463,\n"
18867       "         \"world\"},\n"
18868       "    test{ 7,     5,\n"
18869       "         \"!!\"   },\n"
18870       "};",
18871       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18872              "i am a very long line that really, in any just world, ought "
18873              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18874              "test{7, 5, \"!!\"},};",
18875              Style));
18876   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18877   Style = getLLVMStyleWithColumns(50);
18878   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18879   verifyFormat("static A x = {\n"
18880                "    {{init1, init2, init3, init4},\n"
18881                "     {init1, init2, init3, init4}}\n"
18882                "};",
18883                Style);
18884   Style.ColumnLimit = 100;
18885   EXPECT_EQ(
18886       "test demo[] = {\n"
18887       "    {56,    23,\n"
18888       "     \"hello world i am a very long line that really, in any just world"
18889       ", ought to be split over \"\n"
18890       "     \"multiple lines\"  },\n"
18891       "    {-1, 93463, \"world\"},\n"
18892       "    { 7,     5,    \"!!\"},\n"
18893       "};",
18894       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18895              "that really, in any just world, ought to be split over multiple "
18896              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18897              Style));
18898 
18899   Style = getLLVMStyleWithColumns(50);
18900   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18901   Style.AlignConsecutiveAssignments =
18902       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18903   Style.AlignConsecutiveDeclarations =
18904       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18905   verifyFormat("struct test demo[] = {\n"
18906                "    {56,    23, \"hello\"},\n"
18907                "    {-1, 93463, \"world\"},\n"
18908                "    { 7,     5,    \"!!\"}\n"
18909                "};\n"
18910                "static A x = {\n"
18911                "    {{init1, init2, init3, init4},\n"
18912                "     {init1, init2, init3, init4}}\n"
18913                "};",
18914                Style);
18915   Style.ColumnLimit = 100;
18916   Style.AlignConsecutiveAssignments =
18917       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18918   Style.AlignConsecutiveDeclarations =
18919       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18920   verifyFormat("struct test demo[] = {\n"
18921                "    {56,    23, \"hello\"},\n"
18922                "    {-1, 93463, \"world\"},\n"
18923                "    { 7,     5,    \"!!\"}\n"
18924                "};\n"
18925                "struct test demo[4] = {\n"
18926                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18927                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18928                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18929                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18930                "};\n",
18931                Style);
18932   EXPECT_EQ(
18933       "test demo[] = {\n"
18934       "    {56,\n"
18935       "     \"hello world i am a very long line that really, in any just world"
18936       ", ought to be split over \"\n"
18937       "     \"multiple lines\",    23},\n"
18938       "    {-1,      \"world\", 93463},\n"
18939       "    { 7,         \"!!\",     5},\n"
18940       "};",
18941       format("test demo[] = {{56, \"hello world i am a very long line "
18942              "that really, in any just world, ought to be split over multiple "
18943              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
18944              Style));
18945 }
18946 
18947 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
18948   auto Style = getLLVMStyle();
18949   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18950   /* FIXME: This case gets misformatted.
18951   verifyFormat("auto foo = Items{\n"
18952                "    Section{0, bar(), },\n"
18953                "    Section{1, boo()  }\n"
18954                "};\n",
18955                Style);
18956   */
18957   verifyFormat("auto foo = Items{\n"
18958                "    Section{\n"
18959                "            0, bar(),\n"
18960                "            }\n"
18961                "};\n",
18962                Style);
18963   verifyFormat("struct test demo[] = {\n"
18964                "    {56, 23,    \"hello\"},\n"
18965                "    {-1, 93463, \"world\"},\n"
18966                "    {7,  5,     \"!!\"   }\n"
18967                "};\n",
18968                Style);
18969   verifyFormat("struct test demo[] = {\n"
18970                "    {56, 23,    \"hello\"}, // first line\n"
18971                "    {-1, 93463, \"world\"}, // second line\n"
18972                "    {7,  5,     \"!!\"   }  // third line\n"
18973                "};\n",
18974                Style);
18975   verifyFormat("struct test demo[4] = {\n"
18976                "    {56,  23,    21, \"oh\"      }, // first line\n"
18977                "    {-1,  93463, 22, \"my\"      }, // second line\n"
18978                "    {7,   5,     1,  \"goodness\"}  // third line\n"
18979                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
18980                "};\n",
18981                Style);
18982   verifyFormat("struct test demo[3] = {\n"
18983                "    {56, 23,    \"hello\"},\n"
18984                "    {-1, 93463, \"world\"},\n"
18985                "    {7,  5,     \"!!\"   }\n"
18986                "};\n",
18987                Style);
18988 
18989   verifyFormat("struct test demo[3] = {\n"
18990                "    {int{56}, 23,    \"hello\"},\n"
18991                "    {int{-1}, 93463, \"world\"},\n"
18992                "    {int{7},  5,     \"!!\"   }\n"
18993                "};\n",
18994                Style);
18995   verifyFormat("struct test demo[] = {\n"
18996                "    {56, 23,    \"hello\"},\n"
18997                "    {-1, 93463, \"world\"},\n"
18998                "    {7,  5,     \"!!\"   },\n"
18999                "};\n",
19000                Style);
19001   verifyFormat("test demo[] = {\n"
19002                "    {56, 23,    \"hello\"},\n"
19003                "    {-1, 93463, \"world\"},\n"
19004                "    {7,  5,     \"!!\"   },\n"
19005                "};\n",
19006                Style);
19007   verifyFormat("demo = std::array<struct test, 3>{\n"
19008                "    test{56, 23,    \"hello\"},\n"
19009                "    test{-1, 93463, \"world\"},\n"
19010                "    test{7,  5,     \"!!\"   },\n"
19011                "};\n",
19012                Style);
19013   verifyFormat("test demo[] = {\n"
19014                "    {56, 23,    \"hello\"},\n"
19015                "#if X\n"
19016                "    {-1, 93463, \"world\"},\n"
19017                "#endif\n"
19018                "    {7,  5,     \"!!\"   }\n"
19019                "};\n",
19020                Style);
19021   verifyFormat(
19022       "test demo[] = {\n"
19023       "    {7,  23,\n"
19024       "     \"hello world i am a very long line that really, in any\"\n"
19025       "     \"just world, ought to be split over multiple lines\"},\n"
19026       "    {-1, 93463, \"world\"                                 },\n"
19027       "    {56, 5,     \"!!\"                                    }\n"
19028       "};\n",
19029       Style);
19030 
19031   verifyFormat("return GradForUnaryCwise(g, {\n"
19032                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19033                "\"dy\"}   },\n"
19034                "                                {{\"dx\"},   \"Mul\",  "
19035                "{\"dy\", \"sign\"}},\n"
19036                "});\n",
19037                Style);
19038 
19039   Style.ColumnLimit = 0;
19040   EXPECT_EQ(
19041       "test demo[] = {\n"
19042       "    {56, 23,    \"hello world i am a very long line that really, in any "
19043       "just world, ought to be split over multiple lines\"},\n"
19044       "    {-1, 93463, \"world\"                                               "
19045       "                                                   },\n"
19046       "    {7,  5,     \"!!\"                                                  "
19047       "                                                   },\n"
19048       "};",
19049       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19050              "that really, in any just world, ought to be split over multiple "
19051              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19052              Style));
19053 
19054   Style.ColumnLimit = 80;
19055   verifyFormat("test demo[] = {\n"
19056                "    {56, 23,    /* a comment */ \"hello\"},\n"
19057                "    {-1, 93463, \"world\"                },\n"
19058                "    {7,  5,     \"!!\"                   }\n"
19059                "};\n",
19060                Style);
19061 
19062   verifyFormat("test demo[] = {\n"
19063                "    {56, 23,    \"hello\"                   },\n"
19064                "    {-1, 93463, \"world\" /* comment here */},\n"
19065                "    {7,  5,     \"!!\"                      }\n"
19066                "};\n",
19067                Style);
19068 
19069   verifyFormat("test demo[] = {\n"
19070                "    {56, /* a comment */ 23, \"hello\"},\n"
19071                "    {-1, 93463,              \"world\"},\n"
19072                "    {7,  5,                  \"!!\"   }\n"
19073                "};\n",
19074                Style);
19075 
19076   Style.ColumnLimit = 20;
19077   EXPECT_EQ(
19078       "demo = std::array<\n"
19079       "    struct test, 3>{\n"
19080       "    test{\n"
19081       "         56, 23,\n"
19082       "         \"hello \"\n"
19083       "         \"world i \"\n"
19084       "         \"am a very \"\n"
19085       "         \"long line \"\n"
19086       "         \"that \"\n"
19087       "         \"really, \"\n"
19088       "         \"in any \"\n"
19089       "         \"just \"\n"
19090       "         \"world, \"\n"
19091       "         \"ought to \"\n"
19092       "         \"be split \"\n"
19093       "         \"over \"\n"
19094       "         \"multiple \"\n"
19095       "         \"lines\"},\n"
19096       "    test{-1, 93463,\n"
19097       "         \"world\"},\n"
19098       "    test{7,  5,\n"
19099       "         \"!!\"   },\n"
19100       "};",
19101       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19102              "i am a very long line that really, in any just world, ought "
19103              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19104              "test{7, 5, \"!!\"},};",
19105              Style));
19106 
19107   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19108   Style = getLLVMStyleWithColumns(50);
19109   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19110   verifyFormat("static A x = {\n"
19111                "    {{init1, init2, init3, init4},\n"
19112                "     {init1, init2, init3, init4}}\n"
19113                "};",
19114                Style);
19115   Style.ColumnLimit = 100;
19116   EXPECT_EQ(
19117       "test demo[] = {\n"
19118       "    {56, 23,\n"
19119       "     \"hello world i am a very long line that really, in any just world"
19120       ", ought to be split over \"\n"
19121       "     \"multiple lines\"  },\n"
19122       "    {-1, 93463, \"world\"},\n"
19123       "    {7,  5,     \"!!\"   },\n"
19124       "};",
19125       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19126              "that really, in any just world, ought to be split over multiple "
19127              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19128              Style));
19129 }
19130 
19131 TEST_F(FormatTest, UnderstandsPragmas) {
19132   verifyFormat("#pragma omp reduction(| : var)");
19133   verifyFormat("#pragma omp reduction(+ : var)");
19134 
19135   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19136             "(including parentheses).",
19137             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19138                    "(including parentheses)."));
19139 }
19140 
19141 TEST_F(FormatTest, UnderstandPragmaOption) {
19142   verifyFormat("#pragma option -C -A");
19143 
19144   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19145 }
19146 
19147 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19148   FormatStyle Style = getLLVMStyleWithColumns(20);
19149 
19150   // See PR41213
19151   EXPECT_EQ("/*\n"
19152             " *\t9012345\n"
19153             " * /8901\n"
19154             " */",
19155             format("/*\n"
19156                    " *\t9012345 /8901\n"
19157                    " */",
19158                    Style));
19159   EXPECT_EQ("/*\n"
19160             " *345678\n"
19161             " *\t/8901\n"
19162             " */",
19163             format("/*\n"
19164                    " *345678\t/8901\n"
19165                    " */",
19166                    Style));
19167 
19168   verifyFormat("int a; // the\n"
19169                "       // comment",
19170                Style);
19171   EXPECT_EQ("int a; /* first line\n"
19172             "        * second\n"
19173             "        * line third\n"
19174             "        * line\n"
19175             "        */",
19176             format("int a; /* first line\n"
19177                    "        * second\n"
19178                    "        * line third\n"
19179                    "        * line\n"
19180                    "        */",
19181                    Style));
19182   EXPECT_EQ("int a; // first line\n"
19183             "       // second\n"
19184             "       // line third\n"
19185             "       // line",
19186             format("int a; // first line\n"
19187                    "       // second line\n"
19188                    "       // third line",
19189                    Style));
19190 
19191   Style.PenaltyExcessCharacter = 90;
19192   verifyFormat("int a; // the comment", Style);
19193   EXPECT_EQ("int a; // the comment\n"
19194             "       // aaa",
19195             format("int a; // the comment aaa", Style));
19196   EXPECT_EQ("int a; /* first line\n"
19197             "        * second line\n"
19198             "        * third line\n"
19199             "        */",
19200             format("int a; /* first line\n"
19201                    "        * second line\n"
19202                    "        * third line\n"
19203                    "        */",
19204                    Style));
19205   EXPECT_EQ("int a; // first line\n"
19206             "       // second line\n"
19207             "       // third line",
19208             format("int a; // first line\n"
19209                    "       // second line\n"
19210                    "       // third line",
19211                    Style));
19212   // FIXME: Investigate why this is not getting the same layout as the test
19213   // above.
19214   EXPECT_EQ("int a; /* first line\n"
19215             "        * second line\n"
19216             "        * third line\n"
19217             "        */",
19218             format("int a; /* first line second line third line"
19219                    "\n*/",
19220                    Style));
19221 
19222   EXPECT_EQ("// foo bar baz bazfoo\n"
19223             "// foo bar foo bar\n",
19224             format("// foo bar baz bazfoo\n"
19225                    "// foo bar foo           bar\n",
19226                    Style));
19227   EXPECT_EQ("// foo bar baz bazfoo\n"
19228             "// foo bar foo bar\n",
19229             format("// foo bar baz      bazfoo\n"
19230                    "// foo            bar foo bar\n",
19231                    Style));
19232 
19233   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19234   // next one.
19235   EXPECT_EQ("// foo bar baz bazfoo\n"
19236             "// bar foo bar\n",
19237             format("// foo bar baz      bazfoo bar\n"
19238                    "// foo            bar\n",
19239                    Style));
19240 
19241   EXPECT_EQ("// foo bar baz bazfoo\n"
19242             "// foo bar baz bazfoo\n"
19243             "// bar foo bar\n",
19244             format("// foo bar baz      bazfoo\n"
19245                    "// foo bar baz      bazfoo bar\n"
19246                    "// foo bar\n",
19247                    Style));
19248 
19249   EXPECT_EQ("// foo bar baz bazfoo\n"
19250             "// foo bar baz bazfoo\n"
19251             "// bar foo bar\n",
19252             format("// foo bar baz      bazfoo\n"
19253                    "// foo bar baz      bazfoo bar\n"
19254                    "// foo           bar\n",
19255                    Style));
19256 
19257   // Make sure we do not keep protruding characters if strict mode reflow is
19258   // cheaper than keeping protruding characters.
19259   Style.ColumnLimit = 21;
19260   EXPECT_EQ(
19261       "// foo foo foo foo\n"
19262       "// foo foo foo foo\n"
19263       "// foo foo foo foo\n",
19264       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19265 
19266   EXPECT_EQ("int a = /* long block\n"
19267             "           comment */\n"
19268             "    42;",
19269             format("int a = /* long block comment */ 42;", Style));
19270 }
19271 
19272 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19273   FormatStyle Style = getLLVMStyle();
19274   Style.ColumnLimit = 8;
19275   Style.PenaltyExcessCharacter = 15;
19276   verifyFormat("int foo(\n"
19277                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19278                Style);
19279   Style.PenaltyBreakOpenParenthesis = 200;
19280   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19281             format("int foo(\n"
19282                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19283                    Style));
19284 }
19285 
19286 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19287   FormatStyle Style = getLLVMStyle();
19288   Style.ColumnLimit = 5;
19289   Style.PenaltyExcessCharacter = 150;
19290   verifyFormat("foo((\n"
19291                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19292 
19293                Style);
19294   Style.PenaltyBreakOpenParenthesis = 100000;
19295   EXPECT_EQ("foo((int)\n"
19296             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19297             format("foo((\n"
19298                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19299                    Style));
19300 }
19301 
19302 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19303   FormatStyle Style = getLLVMStyle();
19304   Style.ColumnLimit = 4;
19305   Style.PenaltyExcessCharacter = 100;
19306   verifyFormat("for (\n"
19307                "    int iiiiiiiiiiiiiiiii =\n"
19308                "        0;\n"
19309                "    iiiiiiiiiiiiiiiii <\n"
19310                "    2;\n"
19311                "    iiiiiiiiiiiiiiiii++) {\n"
19312                "}",
19313 
19314                Style);
19315   Style.PenaltyBreakOpenParenthesis = 1250;
19316   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19317             "         0;\n"
19318             "     iiiiiiiiiiiiiiiii <\n"
19319             "     2;\n"
19320             "     iiiiiiiiiiiiiiiii++) {\n"
19321             "}",
19322             format("for (\n"
19323                    "    int iiiiiiiiiiiiiiiii =\n"
19324                    "        0;\n"
19325                    "    iiiiiiiiiiiiiiiii <\n"
19326                    "    2;\n"
19327                    "    iiiiiiiiiiiiiiiii++) {\n"
19328                    "}",
19329                    Style));
19330 }
19331 
19332 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19333   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19334   EXPECT_EQ(Styles[0], Styles[i])                                              \
19335       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19336 
19337 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19338   SmallVector<FormatStyle, 3> Styles;
19339   Styles.resize(3);
19340 
19341   Styles[0] = getLLVMStyle();
19342   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19343   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19344   EXPECT_ALL_STYLES_EQUAL(Styles);
19345 
19346   Styles[0] = getGoogleStyle();
19347   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19348   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19349   EXPECT_ALL_STYLES_EQUAL(Styles);
19350 
19351   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19352   EXPECT_TRUE(
19353       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19354   EXPECT_TRUE(
19355       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19356   EXPECT_ALL_STYLES_EQUAL(Styles);
19357 
19358   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19359   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19360   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19361   EXPECT_ALL_STYLES_EQUAL(Styles);
19362 
19363   Styles[0] = getMozillaStyle();
19364   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19365   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19366   EXPECT_ALL_STYLES_EQUAL(Styles);
19367 
19368   Styles[0] = getWebKitStyle();
19369   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19370   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19371   EXPECT_ALL_STYLES_EQUAL(Styles);
19372 
19373   Styles[0] = getGNUStyle();
19374   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19375   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19376   EXPECT_ALL_STYLES_EQUAL(Styles);
19377 
19378   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19379 }
19380 
19381 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19382   SmallVector<FormatStyle, 8> Styles;
19383   Styles.resize(2);
19384 
19385   Styles[0] = getGoogleStyle();
19386   Styles[1] = getLLVMStyle();
19387   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19388   EXPECT_ALL_STYLES_EQUAL(Styles);
19389 
19390   Styles.resize(5);
19391   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19392   Styles[1] = getLLVMStyle();
19393   Styles[1].Language = FormatStyle::LK_JavaScript;
19394   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19395 
19396   Styles[2] = getLLVMStyle();
19397   Styles[2].Language = FormatStyle::LK_JavaScript;
19398   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19399                                   "BasedOnStyle: Google",
19400                                   &Styles[2])
19401                    .value());
19402 
19403   Styles[3] = getLLVMStyle();
19404   Styles[3].Language = FormatStyle::LK_JavaScript;
19405   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19406                                   "Language: JavaScript",
19407                                   &Styles[3])
19408                    .value());
19409 
19410   Styles[4] = getLLVMStyle();
19411   Styles[4].Language = FormatStyle::LK_JavaScript;
19412   EXPECT_EQ(0, parseConfiguration("---\n"
19413                                   "BasedOnStyle: LLVM\n"
19414                                   "IndentWidth: 123\n"
19415                                   "---\n"
19416                                   "BasedOnStyle: Google\n"
19417                                   "Language: JavaScript",
19418                                   &Styles[4])
19419                    .value());
19420   EXPECT_ALL_STYLES_EQUAL(Styles);
19421 }
19422 
19423 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
19424   Style.FIELD = false;                                                         \
19425   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
19426   EXPECT_TRUE(Style.FIELD);                                                    \
19427   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
19428   EXPECT_FALSE(Style.FIELD);
19429 
19430 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
19431 
19432 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
19433   Style.STRUCT.FIELD = false;                                                  \
19434   EXPECT_EQ(0,                                                                 \
19435             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
19436                 .value());                                                     \
19437   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
19438   EXPECT_EQ(0,                                                                 \
19439             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
19440                 .value());                                                     \
19441   EXPECT_FALSE(Style.STRUCT.FIELD);
19442 
19443 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
19444   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
19445 
19446 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
19447   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
19448   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
19449   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
19450 
19451 TEST_F(FormatTest, ParsesConfigurationBools) {
19452   FormatStyle Style = {};
19453   Style.Language = FormatStyle::LK_Cpp;
19454   CHECK_PARSE_BOOL(AlignTrailingComments);
19455   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
19456   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
19457   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
19458   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
19459   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
19460   CHECK_PARSE_BOOL(BinPackArguments);
19461   CHECK_PARSE_BOOL(BinPackParameters);
19462   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
19463   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
19464   CHECK_PARSE_BOOL(BreakStringLiterals);
19465   CHECK_PARSE_BOOL(CompactNamespaces);
19466   CHECK_PARSE_BOOL(DeriveLineEnding);
19467   CHECK_PARSE_BOOL(DerivePointerAlignment);
19468   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
19469   CHECK_PARSE_BOOL(DisableFormat);
19470   CHECK_PARSE_BOOL(IndentAccessModifiers);
19471   CHECK_PARSE_BOOL(IndentCaseLabels);
19472   CHECK_PARSE_BOOL(IndentCaseBlocks);
19473   CHECK_PARSE_BOOL(IndentGotoLabels);
19474   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
19475   CHECK_PARSE_BOOL(IndentRequiresClause);
19476   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
19477   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
19478   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
19479   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
19480   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
19481   CHECK_PARSE_BOOL(ReflowComments);
19482   CHECK_PARSE_BOOL(RemoveBracesLLVM);
19483   CHECK_PARSE_BOOL(SortUsingDeclarations);
19484   CHECK_PARSE_BOOL(SpacesInParentheses);
19485   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
19486   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
19487   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
19488   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
19489   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
19490   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
19491   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
19492   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
19493   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
19494   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
19495   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
19496   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
19497   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
19498   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
19499   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
19500   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
19501   CHECK_PARSE_BOOL(UseCRLF);
19502 
19503   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
19504   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
19505   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
19506   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
19507   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
19508   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
19509   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
19510   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
19511   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
19512   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
19513   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
19514   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
19515   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
19516   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
19517   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
19518   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
19519   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
19520   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
19521   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
19522   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19523                           AfterFunctionDeclarationName);
19524   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19525                           AfterFunctionDefinitionName);
19526   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
19527   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
19528   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
19529 }
19530 
19531 #undef CHECK_PARSE_BOOL
19532 
19533 TEST_F(FormatTest, ParsesConfiguration) {
19534   FormatStyle Style = {};
19535   Style.Language = FormatStyle::LK_Cpp;
19536   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
19537   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
19538               ConstructorInitializerIndentWidth, 1234u);
19539   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
19540   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
19541   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
19542   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
19543   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
19544               PenaltyBreakBeforeFirstCallParameter, 1234u);
19545   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
19546               PenaltyBreakTemplateDeclaration, 1234u);
19547   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
19548               1234u);
19549   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
19550   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
19551               PenaltyReturnTypeOnItsOwnLine, 1234u);
19552   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
19553               SpacesBeforeTrailingComments, 1234u);
19554   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
19555   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
19556   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
19557 
19558   Style.QualifierAlignment = FormatStyle::QAS_Right;
19559   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
19560               FormatStyle::QAS_Leave);
19561   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
19562               FormatStyle::QAS_Right);
19563   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
19564               FormatStyle::QAS_Left);
19565   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
19566               FormatStyle::QAS_Custom);
19567 
19568   Style.QualifierOrder.clear();
19569   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
19570               std::vector<std::string>({"const", "volatile", "type"}));
19571   Style.QualifierOrder.clear();
19572   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
19573               std::vector<std::string>({"const", "type"}));
19574   Style.QualifierOrder.clear();
19575   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
19576               std::vector<std::string>({"volatile", "type"}));
19577 
19578   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
19579   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
19580               FormatStyle::ACS_None);
19581   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
19582               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
19583   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
19584               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
19585   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
19586               AlignConsecutiveAssignments,
19587               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19588   // For backwards compability, false / true should still parse
19589   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
19590               FormatStyle::ACS_None);
19591   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
19592               FormatStyle::ACS_Consecutive);
19593 
19594   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
19595   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
19596               FormatStyle::ACS_None);
19597   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
19598               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
19599   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
19600               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
19601   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
19602               AlignConsecutiveBitFields,
19603               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19604   // For backwards compability, false / true should still parse
19605   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
19606               FormatStyle::ACS_None);
19607   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
19608               FormatStyle::ACS_Consecutive);
19609 
19610   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
19611   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
19612               FormatStyle::ACS_None);
19613   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
19614               FormatStyle::ACS_Consecutive);
19615   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
19616               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
19617   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
19618               AlignConsecutiveMacros,
19619               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19620   // For backwards compability, false / true should still parse
19621   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
19622               FormatStyle::ACS_None);
19623   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
19624               FormatStyle::ACS_Consecutive);
19625 
19626   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
19627   CHECK_PARSE("AlignConsecutiveDeclarations: None",
19628               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
19629   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
19630               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
19631   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
19632               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
19633   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
19634               AlignConsecutiveDeclarations,
19635               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19636   // For backwards compability, false / true should still parse
19637   CHECK_PARSE("AlignConsecutiveDeclarations: false",
19638               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
19639   CHECK_PARSE("AlignConsecutiveDeclarations: true",
19640               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
19641 
19642   Style.PointerAlignment = FormatStyle::PAS_Middle;
19643   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
19644               FormatStyle::PAS_Left);
19645   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
19646               FormatStyle::PAS_Right);
19647   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
19648               FormatStyle::PAS_Middle);
19649   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
19650   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
19651               FormatStyle::RAS_Pointer);
19652   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
19653               FormatStyle::RAS_Left);
19654   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
19655               FormatStyle::RAS_Right);
19656   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
19657               FormatStyle::RAS_Middle);
19658   // For backward compatibility:
19659   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
19660               FormatStyle::PAS_Left);
19661   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
19662               FormatStyle::PAS_Right);
19663   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
19664               FormatStyle::PAS_Middle);
19665 
19666   Style.Standard = FormatStyle::LS_Auto;
19667   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
19668   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
19669   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
19670   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
19671   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
19672   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
19673   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
19674   // Legacy aliases:
19675   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
19676   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
19677   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
19678   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
19679 
19680   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
19681   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
19682               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
19683   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
19684               FormatStyle::BOS_None);
19685   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
19686               FormatStyle::BOS_All);
19687   // For backward compatibility:
19688   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
19689               FormatStyle::BOS_None);
19690   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
19691               FormatStyle::BOS_All);
19692 
19693   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
19694   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
19695               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
19696   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
19697               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
19698   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
19699               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
19700   // For backward compatibility:
19701   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
19702               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
19703 
19704   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
19705   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
19706               FormatStyle::BILS_AfterComma);
19707   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
19708               FormatStyle::BILS_BeforeComma);
19709   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
19710               FormatStyle::BILS_AfterColon);
19711   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
19712               FormatStyle::BILS_BeforeColon);
19713   // For backward compatibility:
19714   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
19715               FormatStyle::BILS_BeforeComma);
19716 
19717   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19718   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
19719               FormatStyle::PCIS_Never);
19720   CHECK_PARSE("PackConstructorInitializers: BinPack",
19721               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19722   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
19723               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19724   CHECK_PARSE("PackConstructorInitializers: NextLine",
19725               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19726   // For backward compatibility:
19727   CHECK_PARSE("BasedOnStyle: Google\n"
19728               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19729               "AllowAllConstructorInitializersOnNextLine: false",
19730               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19731   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
19732   CHECK_PARSE("BasedOnStyle: Google\n"
19733               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
19734               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19735   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19736               "AllowAllConstructorInitializersOnNextLine: true",
19737               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19738   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19739   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19740               "AllowAllConstructorInitializersOnNextLine: false",
19741               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19742 
19743   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
19744   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
19745               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
19746   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
19747               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
19748   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
19749               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
19750   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
19751               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
19752 
19753   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19754   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
19755               FormatStyle::BAS_Align);
19756   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
19757               FormatStyle::BAS_DontAlign);
19758   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
19759               FormatStyle::BAS_AlwaysBreak);
19760   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
19761               FormatStyle::BAS_BlockIndent);
19762   // For backward compatibility:
19763   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
19764               FormatStyle::BAS_DontAlign);
19765   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
19766               FormatStyle::BAS_Align);
19767 
19768   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
19769   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
19770               FormatStyle::ENAS_DontAlign);
19771   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
19772               FormatStyle::ENAS_Left);
19773   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
19774               FormatStyle::ENAS_Right);
19775   // For backward compatibility:
19776   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
19777               FormatStyle::ENAS_Left);
19778   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
19779               FormatStyle::ENAS_Right);
19780 
19781   Style.AlignOperands = FormatStyle::OAS_Align;
19782   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
19783               FormatStyle::OAS_DontAlign);
19784   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
19785   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
19786               FormatStyle::OAS_AlignAfterOperator);
19787   // For backward compatibility:
19788   CHECK_PARSE("AlignOperands: false", AlignOperands,
19789               FormatStyle::OAS_DontAlign);
19790   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
19791 
19792   Style.UseTab = FormatStyle::UT_ForIndentation;
19793   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
19794   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
19795   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
19796   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
19797               FormatStyle::UT_ForContinuationAndIndentation);
19798   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
19799               FormatStyle::UT_AlignWithSpaces);
19800   // For backward compatibility:
19801   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
19802   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
19803 
19804   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
19805   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
19806               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19807   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
19808               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
19809   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
19810               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19811   // For backward compatibility:
19812   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
19813               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19814   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
19815               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19816 
19817   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
19818   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
19819               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19820   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
19821               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
19822   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
19823               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
19824   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
19825               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19826   // For backward compatibility:
19827   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
19828               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19829   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
19830               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19831 
19832   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
19833   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
19834               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
19835   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
19836               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
19837   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
19838               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
19839   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
19840               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
19841 
19842   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
19843   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
19844               FormatStyle::SBPO_Never);
19845   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
19846               FormatStyle::SBPO_Always);
19847   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
19848               FormatStyle::SBPO_ControlStatements);
19849   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
19850               SpaceBeforeParens,
19851               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19852   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
19853               FormatStyle::SBPO_NonEmptyParentheses);
19854   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
19855               FormatStyle::SBPO_Custom);
19856   // For backward compatibility:
19857   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
19858               FormatStyle::SBPO_Never);
19859   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
19860               FormatStyle::SBPO_ControlStatements);
19861   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
19862               SpaceBeforeParens,
19863               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19864 
19865   Style.ColumnLimit = 123;
19866   FormatStyle BaseStyle = getLLVMStyle();
19867   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
19868   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
19869 
19870   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
19871   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
19872               FormatStyle::BS_Attach);
19873   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
19874               FormatStyle::BS_Linux);
19875   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
19876               FormatStyle::BS_Mozilla);
19877   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
19878               FormatStyle::BS_Stroustrup);
19879   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
19880               FormatStyle::BS_Allman);
19881   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
19882               FormatStyle::BS_Whitesmiths);
19883   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
19884   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
19885               FormatStyle::BS_WebKit);
19886   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
19887               FormatStyle::BS_Custom);
19888 
19889   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
19890   CHECK_PARSE("BraceWrapping:\n"
19891               "  AfterControlStatement: MultiLine",
19892               BraceWrapping.AfterControlStatement,
19893               FormatStyle::BWACS_MultiLine);
19894   CHECK_PARSE("BraceWrapping:\n"
19895               "  AfterControlStatement: Always",
19896               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19897   CHECK_PARSE("BraceWrapping:\n"
19898               "  AfterControlStatement: Never",
19899               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19900   // For backward compatibility:
19901   CHECK_PARSE("BraceWrapping:\n"
19902               "  AfterControlStatement: true",
19903               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19904   CHECK_PARSE("BraceWrapping:\n"
19905               "  AfterControlStatement: false",
19906               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19907 
19908   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
19909   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
19910               FormatStyle::RTBS_None);
19911   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
19912               FormatStyle::RTBS_All);
19913   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
19914               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
19915   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
19916               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
19917   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
19918               AlwaysBreakAfterReturnType,
19919               FormatStyle::RTBS_TopLevelDefinitions);
19920 
19921   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
19922   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
19923               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
19924   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
19925               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19926   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
19927               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19928   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
19929               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19930   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
19931               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19932 
19933   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
19934   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
19935               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
19936   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
19937               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
19938   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
19939               AlwaysBreakAfterDefinitionReturnType,
19940               FormatStyle::DRTBS_TopLevel);
19941 
19942   Style.NamespaceIndentation = FormatStyle::NI_All;
19943   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
19944               FormatStyle::NI_None);
19945   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
19946               FormatStyle::NI_Inner);
19947   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
19948               FormatStyle::NI_All);
19949 
19950   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
19951   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
19952               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19953   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
19954               AllowShortIfStatementsOnASingleLine,
19955               FormatStyle::SIS_WithoutElse);
19956   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
19957               AllowShortIfStatementsOnASingleLine,
19958               FormatStyle::SIS_OnlyFirstIf);
19959   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
19960               AllowShortIfStatementsOnASingleLine,
19961               FormatStyle::SIS_AllIfsAndElse);
19962   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
19963               AllowShortIfStatementsOnASingleLine,
19964               FormatStyle::SIS_OnlyFirstIf);
19965   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
19966               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19967   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
19968               AllowShortIfStatementsOnASingleLine,
19969               FormatStyle::SIS_WithoutElse);
19970 
19971   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
19972   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
19973               FormatStyle::IEBS_AfterExternBlock);
19974   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
19975               FormatStyle::IEBS_Indent);
19976   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
19977               FormatStyle::IEBS_NoIndent);
19978   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
19979               FormatStyle::IEBS_Indent);
19980   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
19981               FormatStyle::IEBS_NoIndent);
19982 
19983   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
19984   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
19985               FormatStyle::BFCS_Both);
19986   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
19987               FormatStyle::BFCS_None);
19988   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
19989               FormatStyle::BFCS_Before);
19990   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
19991               FormatStyle::BFCS_After);
19992 
19993   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
19994   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
19995               FormatStyle::SJSIO_After);
19996   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
19997               FormatStyle::SJSIO_Before);
19998 
19999   // FIXME: This is required because parsing a configuration simply overwrites
20000   // the first N elements of the list instead of resetting it.
20001   Style.ForEachMacros.clear();
20002   std::vector<std::string> BoostForeach;
20003   BoostForeach.push_back("BOOST_FOREACH");
20004   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20005   std::vector<std::string> BoostAndQForeach;
20006   BoostAndQForeach.push_back("BOOST_FOREACH");
20007   BoostAndQForeach.push_back("Q_FOREACH");
20008   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20009               BoostAndQForeach);
20010 
20011   Style.IfMacros.clear();
20012   std::vector<std::string> CustomIfs;
20013   CustomIfs.push_back("MYIF");
20014   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20015 
20016   Style.AttributeMacros.clear();
20017   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20018               std::vector<std::string>{"__capability"});
20019   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20020               std::vector<std::string>({"attr1", "attr2"}));
20021 
20022   Style.StatementAttributeLikeMacros.clear();
20023   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20024               StatementAttributeLikeMacros,
20025               std::vector<std::string>({"emit", "Q_EMIT"}));
20026 
20027   Style.StatementMacros.clear();
20028   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20029               std::vector<std::string>{"QUNUSED"});
20030   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20031               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20032 
20033   Style.NamespaceMacros.clear();
20034   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20035               std::vector<std::string>{"TESTSUITE"});
20036   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20037               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20038 
20039   Style.WhitespaceSensitiveMacros.clear();
20040   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20041               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20042   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20043               WhitespaceSensitiveMacros,
20044               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20045   Style.WhitespaceSensitiveMacros.clear();
20046   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
20047               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20048   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
20049               WhitespaceSensitiveMacros,
20050               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20051 
20052   Style.IncludeStyle.IncludeCategories.clear();
20053   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20054       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20055   CHECK_PARSE("IncludeCategories:\n"
20056               "  - Regex: abc/.*\n"
20057               "    Priority: 2\n"
20058               "  - Regex: .*\n"
20059               "    Priority: 1\n"
20060               "    CaseSensitive: true\n",
20061               IncludeStyle.IncludeCategories, ExpectedCategories);
20062   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20063               "abc$");
20064   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20065               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20066 
20067   Style.SortIncludes = FormatStyle::SI_Never;
20068   CHECK_PARSE("SortIncludes: true", SortIncludes,
20069               FormatStyle::SI_CaseSensitive);
20070   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20071   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20072               FormatStyle::SI_CaseInsensitive);
20073   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20074               FormatStyle::SI_CaseSensitive);
20075   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20076 
20077   Style.RawStringFormats.clear();
20078   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20079       {
20080           FormatStyle::LK_TextProto,
20081           {"pb", "proto"},
20082           {"PARSE_TEXT_PROTO"},
20083           /*CanonicalDelimiter=*/"",
20084           "llvm",
20085       },
20086       {
20087           FormatStyle::LK_Cpp,
20088           {"cc", "cpp"},
20089           {"C_CODEBLOCK", "CPPEVAL"},
20090           /*CanonicalDelimiter=*/"cc",
20091           /*BasedOnStyle=*/"",
20092       },
20093   };
20094 
20095   CHECK_PARSE("RawStringFormats:\n"
20096               "  - Language: TextProto\n"
20097               "    Delimiters:\n"
20098               "      - 'pb'\n"
20099               "      - 'proto'\n"
20100               "    EnclosingFunctions:\n"
20101               "      - 'PARSE_TEXT_PROTO'\n"
20102               "    BasedOnStyle: llvm\n"
20103               "  - Language: Cpp\n"
20104               "    Delimiters:\n"
20105               "      - 'cc'\n"
20106               "      - 'cpp'\n"
20107               "    EnclosingFunctions:\n"
20108               "      - 'C_CODEBLOCK'\n"
20109               "      - 'CPPEVAL'\n"
20110               "    CanonicalDelimiter: 'cc'",
20111               RawStringFormats, ExpectedRawStringFormats);
20112 
20113   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20114               "  Minimum: 0\n"
20115               "  Maximum: 0",
20116               SpacesInLineCommentPrefix.Minimum, 0u);
20117   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20118   Style.SpacesInLineCommentPrefix.Minimum = 1;
20119   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20120               "  Minimum: 2",
20121               SpacesInLineCommentPrefix.Minimum, 0u);
20122   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20123               "  Maximum: -1",
20124               SpacesInLineCommentPrefix.Maximum, -1u);
20125   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20126               "  Minimum: 2",
20127               SpacesInLineCommentPrefix.Minimum, 2u);
20128   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20129               "  Maximum: 1",
20130               SpacesInLineCommentPrefix.Maximum, 1u);
20131   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20132 
20133   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20134   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20135   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20136               FormatStyle::SIAS_Always);
20137   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20138   // For backward compatibility:
20139   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20140   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20141 
20142   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20143               FormatStyle::RCPS_WithPreceding);
20144   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20145               FormatStyle::RCPS_WithFollowing);
20146   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20147               FormatStyle::RCPS_SingleLine);
20148   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20149               FormatStyle::RCPS_OwnLine);
20150 
20151   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20152               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20153   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20154               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20155   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20156               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20157   // For backward compatibility:
20158   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20159               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20160   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20161               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20162 }
20163 
20164 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20165   FormatStyle Style = {};
20166   Style.Language = FormatStyle::LK_Cpp;
20167   CHECK_PARSE("Language: Cpp\n"
20168               "IndentWidth: 12",
20169               IndentWidth, 12u);
20170   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20171                                "IndentWidth: 34",
20172                                &Style),
20173             ParseError::Unsuitable);
20174   FormatStyle BinPackedTCS = {};
20175   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20176   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20177                                "InsertTrailingCommas: Wrapped",
20178                                &BinPackedTCS),
20179             ParseError::BinPackTrailingCommaConflict);
20180   EXPECT_EQ(12u, Style.IndentWidth);
20181   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20182   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20183 
20184   Style.Language = FormatStyle::LK_JavaScript;
20185   CHECK_PARSE("Language: JavaScript\n"
20186               "IndentWidth: 12",
20187               IndentWidth, 12u);
20188   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20189   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20190                                "IndentWidth: 34",
20191                                &Style),
20192             ParseError::Unsuitable);
20193   EXPECT_EQ(23u, Style.IndentWidth);
20194   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20195   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20196 
20197   CHECK_PARSE("BasedOnStyle: LLVM\n"
20198               "IndentWidth: 67",
20199               IndentWidth, 67u);
20200 
20201   CHECK_PARSE("---\n"
20202               "Language: JavaScript\n"
20203               "IndentWidth: 12\n"
20204               "---\n"
20205               "Language: Cpp\n"
20206               "IndentWidth: 34\n"
20207               "...\n",
20208               IndentWidth, 12u);
20209 
20210   Style.Language = FormatStyle::LK_Cpp;
20211   CHECK_PARSE("---\n"
20212               "Language: JavaScript\n"
20213               "IndentWidth: 12\n"
20214               "---\n"
20215               "Language: Cpp\n"
20216               "IndentWidth: 34\n"
20217               "...\n",
20218               IndentWidth, 34u);
20219   CHECK_PARSE("---\n"
20220               "IndentWidth: 78\n"
20221               "---\n"
20222               "Language: JavaScript\n"
20223               "IndentWidth: 56\n"
20224               "...\n",
20225               IndentWidth, 78u);
20226 
20227   Style.ColumnLimit = 123;
20228   Style.IndentWidth = 234;
20229   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20230   Style.TabWidth = 345;
20231   EXPECT_FALSE(parseConfiguration("---\n"
20232                                   "IndentWidth: 456\n"
20233                                   "BreakBeforeBraces: Allman\n"
20234                                   "---\n"
20235                                   "Language: JavaScript\n"
20236                                   "IndentWidth: 111\n"
20237                                   "TabWidth: 111\n"
20238                                   "---\n"
20239                                   "Language: Cpp\n"
20240                                   "BreakBeforeBraces: Stroustrup\n"
20241                                   "TabWidth: 789\n"
20242                                   "...\n",
20243                                   &Style));
20244   EXPECT_EQ(123u, Style.ColumnLimit);
20245   EXPECT_EQ(456u, Style.IndentWidth);
20246   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20247   EXPECT_EQ(789u, Style.TabWidth);
20248 
20249   EXPECT_EQ(parseConfiguration("---\n"
20250                                "Language: JavaScript\n"
20251                                "IndentWidth: 56\n"
20252                                "---\n"
20253                                "IndentWidth: 78\n"
20254                                "...\n",
20255                                &Style),
20256             ParseError::Error);
20257   EXPECT_EQ(parseConfiguration("---\n"
20258                                "Language: JavaScript\n"
20259                                "IndentWidth: 56\n"
20260                                "---\n"
20261                                "Language: JavaScript\n"
20262                                "IndentWidth: 78\n"
20263                                "...\n",
20264                                &Style),
20265             ParseError::Error);
20266 
20267   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20268 }
20269 
20270 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20271   FormatStyle Style = {};
20272   Style.Language = FormatStyle::LK_JavaScript;
20273   Style.BreakBeforeTernaryOperators = true;
20274   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20275   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20276 
20277   Style.BreakBeforeTernaryOperators = true;
20278   EXPECT_EQ(0, parseConfiguration("---\n"
20279                                   "BasedOnStyle: Google\n"
20280                                   "---\n"
20281                                   "Language: JavaScript\n"
20282                                   "IndentWidth: 76\n"
20283                                   "...\n",
20284                                   &Style)
20285                    .value());
20286   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20287   EXPECT_EQ(76u, Style.IndentWidth);
20288   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20289 }
20290 
20291 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20292   FormatStyle Style = getLLVMStyle();
20293   std::string YAML = configurationAsText(Style);
20294   FormatStyle ParsedStyle = {};
20295   ParsedStyle.Language = FormatStyle::LK_Cpp;
20296   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20297   EXPECT_EQ(Style, ParsedStyle);
20298 }
20299 
20300 TEST_F(FormatTest, WorksFor8bitEncodings) {
20301   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20302             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20303             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20304             "\"\xef\xee\xf0\xf3...\"",
20305             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20306                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20307                    "\xef\xee\xf0\xf3...\"",
20308                    getLLVMStyleWithColumns(12)));
20309 }
20310 
20311 TEST_F(FormatTest, HandlesUTF8BOM) {
20312   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20313   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20314             format("\xef\xbb\xbf#include <iostream>"));
20315   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20316             format("\xef\xbb\xbf\n#include <iostream>"));
20317 }
20318 
20319 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20320 #if !defined(_MSC_VER)
20321 
20322 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20323   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20324                getLLVMStyleWithColumns(35));
20325   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20326                getLLVMStyleWithColumns(31));
20327   verifyFormat("// Однажды в студёную зимнюю пору...",
20328                getLLVMStyleWithColumns(36));
20329   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20330   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20331                getLLVMStyleWithColumns(39));
20332   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20333                getLLVMStyleWithColumns(35));
20334 }
20335 
20336 TEST_F(FormatTest, SplitsUTF8Strings) {
20337   // Non-printable characters' width is currently considered to be the length in
20338   // bytes in UTF8. The characters can be displayed in very different manner
20339   // (zero-width, single width with a substitution glyph, expanded to their code
20340   // (e.g. "<8d>"), so there's no single correct way to handle them.
20341   EXPECT_EQ("\"aaaaÄ\"\n"
20342             "\"\xc2\x8d\";",
20343             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20344   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20345             "\"\xc2\x8d\";",
20346             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20347   EXPECT_EQ("\"Однажды, в \"\n"
20348             "\"студёную \"\n"
20349             "\"зимнюю \"\n"
20350             "\"пору,\"",
20351             format("\"Однажды, в студёную зимнюю пору,\"",
20352                    getLLVMStyleWithColumns(13)));
20353   EXPECT_EQ(
20354       "\"一 二 三 \"\n"
20355       "\"四 五六 \"\n"
20356       "\"七 八 九 \"\n"
20357       "\"十\"",
20358       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20359   EXPECT_EQ("\"一\t\"\n"
20360             "\"二 \t\"\n"
20361             "\"三 四 \"\n"
20362             "\"五\t\"\n"
20363             "\"六 \t\"\n"
20364             "\"七 \"\n"
20365             "\"八九十\tqq\"",
20366             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20367                    getLLVMStyleWithColumns(11)));
20368 
20369   // UTF8 character in an escape sequence.
20370   EXPECT_EQ("\"aaaaaa\"\n"
20371             "\"\\\xC2\x8D\"",
20372             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20373 }
20374 
20375 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20376   EXPECT_EQ("const char *sssss =\n"
20377             "    \"一二三四五六七八\\\n"
20378             " 九 十\";",
20379             format("const char *sssss = \"一二三四五六七八\\\n"
20380                    " 九 十\";",
20381                    getLLVMStyleWithColumns(30)));
20382 }
20383 
20384 TEST_F(FormatTest, SplitsUTF8LineComments) {
20385   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20386             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20387   EXPECT_EQ("// Я из лесу\n"
20388             "// вышел; был\n"
20389             "// сильный\n"
20390             "// мороз.",
20391             format("// Я из лесу вышел; был сильный мороз.",
20392                    getLLVMStyleWithColumns(13)));
20393   EXPECT_EQ("// 一二三\n"
20394             "// 四五六七\n"
20395             "// 八  九\n"
20396             "// 十",
20397             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20398 }
20399 
20400 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20401   EXPECT_EQ("/* Гляжу,\n"
20402             " * поднимается\n"
20403             " * медленно в\n"
20404             " * гору\n"
20405             " * Лошадка,\n"
20406             " * везущая\n"
20407             " * хворосту\n"
20408             " * воз. */",
20409             format("/* Гляжу, поднимается медленно в гору\n"
20410                    " * Лошадка, везущая хворосту воз. */",
20411                    getLLVMStyleWithColumns(13)));
20412   EXPECT_EQ(
20413       "/* 一二三\n"
20414       " * 四五六七\n"
20415       " * 八  九\n"
20416       " * 十  */",
20417       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20418   EXPECT_EQ("/* �������� ��������\n"
20419             " * ��������\n"
20420             " * ������-�� */",
20421             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20422 }
20423 
20424 #endif // _MSC_VER
20425 
20426 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
20427   FormatStyle Style = getLLVMStyle();
20428 
20429   Style.ConstructorInitializerIndentWidth = 4;
20430   verifyFormat(
20431       "SomeClass::Constructor()\n"
20432       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20433       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20434       Style);
20435 
20436   Style.ConstructorInitializerIndentWidth = 2;
20437   verifyFormat(
20438       "SomeClass::Constructor()\n"
20439       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20440       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20441       Style);
20442 
20443   Style.ConstructorInitializerIndentWidth = 0;
20444   verifyFormat(
20445       "SomeClass::Constructor()\n"
20446       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20447       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20448       Style);
20449   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20450   verifyFormat(
20451       "SomeLongTemplateVariableName<\n"
20452       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
20453       Style);
20454   verifyFormat("bool smaller = 1 < "
20455                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
20456                "                       "
20457                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
20458                Style);
20459 
20460   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
20461   verifyFormat("SomeClass::Constructor() :\n"
20462                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
20463                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
20464                Style);
20465 }
20466 
20467 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
20468   FormatStyle Style = getLLVMStyle();
20469   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20470   Style.ConstructorInitializerIndentWidth = 4;
20471   verifyFormat("SomeClass::Constructor()\n"
20472                "    : a(a)\n"
20473                "    , b(b)\n"
20474                "    , c(c) {}",
20475                Style);
20476   verifyFormat("SomeClass::Constructor()\n"
20477                "    : a(a) {}",
20478                Style);
20479 
20480   Style.ColumnLimit = 0;
20481   verifyFormat("SomeClass::Constructor()\n"
20482                "    : a(a) {}",
20483                Style);
20484   verifyFormat("SomeClass::Constructor() noexcept\n"
20485                "    : a(a) {}",
20486                Style);
20487   verifyFormat("SomeClass::Constructor()\n"
20488                "    : a(a)\n"
20489                "    , b(b)\n"
20490                "    , c(c) {}",
20491                Style);
20492   verifyFormat("SomeClass::Constructor()\n"
20493                "    : a(a) {\n"
20494                "  foo();\n"
20495                "  bar();\n"
20496                "}",
20497                Style);
20498 
20499   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
20500   verifyFormat("SomeClass::Constructor()\n"
20501                "    : a(a)\n"
20502                "    , b(b)\n"
20503                "    , c(c) {\n}",
20504                Style);
20505   verifyFormat("SomeClass::Constructor()\n"
20506                "    : a(a) {\n}",
20507                Style);
20508 
20509   Style.ColumnLimit = 80;
20510   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
20511   Style.ConstructorInitializerIndentWidth = 2;
20512   verifyFormat("SomeClass::Constructor()\n"
20513                "  : a(a)\n"
20514                "  , b(b)\n"
20515                "  , c(c) {}",
20516                Style);
20517 
20518   Style.ConstructorInitializerIndentWidth = 0;
20519   verifyFormat("SomeClass::Constructor()\n"
20520                ": a(a)\n"
20521                ", b(b)\n"
20522                ", c(c) {}",
20523                Style);
20524 
20525   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20526   Style.ConstructorInitializerIndentWidth = 4;
20527   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
20528   verifyFormat(
20529       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
20530       Style);
20531   verifyFormat(
20532       "SomeClass::Constructor()\n"
20533       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
20534       Style);
20535   Style.ConstructorInitializerIndentWidth = 4;
20536   Style.ColumnLimit = 60;
20537   verifyFormat("SomeClass::Constructor()\n"
20538                "    : aaaaaaaa(aaaaaaaa)\n"
20539                "    , aaaaaaaa(aaaaaaaa)\n"
20540                "    , aaaaaaaa(aaaaaaaa) {}",
20541                Style);
20542 }
20543 
20544 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
20545   FormatStyle Style = getLLVMStyle();
20546   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20547   Style.ConstructorInitializerIndentWidth = 4;
20548   verifyFormat("SomeClass::Constructor()\n"
20549                "    : a{a}\n"
20550                "    , b{b} {}",
20551                Style);
20552   verifyFormat("SomeClass::Constructor()\n"
20553                "    : a{a}\n"
20554                "#if CONDITION\n"
20555                "    , b{b}\n"
20556                "#endif\n"
20557                "{\n}",
20558                Style);
20559   Style.ConstructorInitializerIndentWidth = 2;
20560   verifyFormat("SomeClass::Constructor()\n"
20561                "#if CONDITION\n"
20562                "  : a{a}\n"
20563                "#endif\n"
20564                "  , b{b}\n"
20565                "  , c{c} {\n}",
20566                Style);
20567   Style.ConstructorInitializerIndentWidth = 0;
20568   verifyFormat("SomeClass::Constructor()\n"
20569                ": a{a}\n"
20570                "#ifdef CONDITION\n"
20571                ", b{b}\n"
20572                "#else\n"
20573                ", c{c}\n"
20574                "#endif\n"
20575                ", d{d} {\n}",
20576                Style);
20577   Style.ConstructorInitializerIndentWidth = 4;
20578   verifyFormat("SomeClass::Constructor()\n"
20579                "    : a{a}\n"
20580                "#if WINDOWS\n"
20581                "#if DEBUG\n"
20582                "    , b{0}\n"
20583                "#else\n"
20584                "    , b{1}\n"
20585                "#endif\n"
20586                "#else\n"
20587                "#if DEBUG\n"
20588                "    , b{2}\n"
20589                "#else\n"
20590                "    , b{3}\n"
20591                "#endif\n"
20592                "#endif\n"
20593                "{\n}",
20594                Style);
20595   verifyFormat("SomeClass::Constructor()\n"
20596                "    : a{a}\n"
20597                "#if WINDOWS\n"
20598                "    , b{0}\n"
20599                "#if DEBUG\n"
20600                "    , c{0}\n"
20601                "#else\n"
20602                "    , c{1}\n"
20603                "#endif\n"
20604                "#else\n"
20605                "#if DEBUG\n"
20606                "    , c{2}\n"
20607                "#else\n"
20608                "    , c{3}\n"
20609                "#endif\n"
20610                "    , b{1}\n"
20611                "#endif\n"
20612                "{\n}",
20613                Style);
20614 }
20615 
20616 TEST_F(FormatTest, Destructors) {
20617   verifyFormat("void F(int &i) { i.~int(); }");
20618   verifyFormat("void F(int &i) { i->~int(); }");
20619 }
20620 
20621 TEST_F(FormatTest, FormatsWithWebKitStyle) {
20622   FormatStyle Style = getWebKitStyle();
20623 
20624   // Don't indent in outer namespaces.
20625   verifyFormat("namespace outer {\n"
20626                "int i;\n"
20627                "namespace inner {\n"
20628                "    int i;\n"
20629                "} // namespace inner\n"
20630                "} // namespace outer\n"
20631                "namespace other_outer {\n"
20632                "int i;\n"
20633                "}",
20634                Style);
20635 
20636   // Don't indent case labels.
20637   verifyFormat("switch (variable) {\n"
20638                "case 1:\n"
20639                "case 2:\n"
20640                "    doSomething();\n"
20641                "    break;\n"
20642                "default:\n"
20643                "    ++variable;\n"
20644                "}",
20645                Style);
20646 
20647   // Wrap before binary operators.
20648   EXPECT_EQ("void f()\n"
20649             "{\n"
20650             "    if (aaaaaaaaaaaaaaaa\n"
20651             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
20652             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20653             "        return;\n"
20654             "}",
20655             format("void f() {\n"
20656                    "if (aaaaaaaaaaaaaaaa\n"
20657                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
20658                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20659                    "return;\n"
20660                    "}",
20661                    Style));
20662 
20663   // Allow functions on a single line.
20664   verifyFormat("void f() { return; }", Style);
20665 
20666   // Allow empty blocks on a single line and insert a space in empty blocks.
20667   EXPECT_EQ("void f() { }", format("void f() {}", Style));
20668   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
20669   // However, don't merge non-empty short loops.
20670   EXPECT_EQ("while (true) {\n"
20671             "    continue;\n"
20672             "}",
20673             format("while (true) { continue; }", Style));
20674 
20675   // Constructor initializers are formatted one per line with the "," on the
20676   // new line.
20677   verifyFormat("Constructor()\n"
20678                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
20679                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
20680                "          aaaaaaaaaaaaaa)\n"
20681                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
20682                "{\n"
20683                "}",
20684                Style);
20685   verifyFormat("SomeClass::Constructor()\n"
20686                "    : a(a)\n"
20687                "{\n"
20688                "}",
20689                Style);
20690   EXPECT_EQ("SomeClass::Constructor()\n"
20691             "    : a(a)\n"
20692             "{\n"
20693             "}",
20694             format("SomeClass::Constructor():a(a){}", Style));
20695   verifyFormat("SomeClass::Constructor()\n"
20696                "    : a(a)\n"
20697                "    , b(b)\n"
20698                "    , c(c)\n"
20699                "{\n"
20700                "}",
20701                Style);
20702   verifyFormat("SomeClass::Constructor()\n"
20703                "    : a(a)\n"
20704                "{\n"
20705                "    foo();\n"
20706                "    bar();\n"
20707                "}",
20708                Style);
20709 
20710   // Access specifiers should be aligned left.
20711   verifyFormat("class C {\n"
20712                "public:\n"
20713                "    int i;\n"
20714                "};",
20715                Style);
20716 
20717   // Do not align comments.
20718   verifyFormat("int a; // Do not\n"
20719                "double b; // align comments.",
20720                Style);
20721 
20722   // Do not align operands.
20723   EXPECT_EQ("ASSERT(aaaa\n"
20724             "    || bbbb);",
20725             format("ASSERT ( aaaa\n||bbbb);", Style));
20726 
20727   // Accept input's line breaks.
20728   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
20729             "    || bbbbbbbbbbbbbbb) {\n"
20730             "    i++;\n"
20731             "}",
20732             format("if (aaaaaaaaaaaaaaa\n"
20733                    "|| bbbbbbbbbbbbbbb) { i++; }",
20734                    Style));
20735   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
20736             "    i++;\n"
20737             "}",
20738             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
20739 
20740   // Don't automatically break all macro definitions (llvm.org/PR17842).
20741   verifyFormat("#define aNumber 10", Style);
20742   // However, generally keep the line breaks that the user authored.
20743   EXPECT_EQ("#define aNumber \\\n"
20744             "    10",
20745             format("#define aNumber \\\n"
20746                    " 10",
20747                    Style));
20748 
20749   // Keep empty and one-element array literals on a single line.
20750   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
20751             "                                  copyItems:YES];",
20752             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
20753                    "copyItems:YES];",
20754                    Style));
20755   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
20756             "                                  copyItems:YES];",
20757             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
20758                    "             copyItems:YES];",
20759                    Style));
20760   // FIXME: This does not seem right, there should be more indentation before
20761   // the array literal's entries. Nested blocks have the same problem.
20762   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20763             "    @\"a\",\n"
20764             "    @\"a\"\n"
20765             "]\n"
20766             "                                  copyItems:YES];",
20767             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20768                    "     @\"a\",\n"
20769                    "     @\"a\"\n"
20770                    "     ]\n"
20771                    "       copyItems:YES];",
20772                    Style));
20773   EXPECT_EQ(
20774       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20775       "                                  copyItems:YES];",
20776       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20777              "   copyItems:YES];",
20778              Style));
20779 
20780   verifyFormat("[self.a b:c c:d];", Style);
20781   EXPECT_EQ("[self.a b:c\n"
20782             "        c:d];",
20783             format("[self.a b:c\n"
20784                    "c:d];",
20785                    Style));
20786 }
20787 
20788 TEST_F(FormatTest, FormatsLambdas) {
20789   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
20790   verifyFormat(
20791       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
20792   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
20793   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
20794   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
20795   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
20796   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
20797   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
20798   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
20799   verifyFormat("int x = f(*+[] {});");
20800   verifyFormat("void f() {\n"
20801                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
20802                "}\n");
20803   verifyFormat("void f() {\n"
20804                "  other(x.begin(), //\n"
20805                "        x.end(),   //\n"
20806                "        [&](int, int) { return 1; });\n"
20807                "}\n");
20808   verifyFormat("void f() {\n"
20809                "  other.other.other.other.other(\n"
20810                "      x.begin(), x.end(),\n"
20811                "      [something, rather](int, int, int, int, int, int, int) { "
20812                "return 1; });\n"
20813                "}\n");
20814   verifyFormat(
20815       "void f() {\n"
20816       "  other.other.other.other.other(\n"
20817       "      x.begin(), x.end(),\n"
20818       "      [something, rather](int, int, int, int, int, int, int) {\n"
20819       "        //\n"
20820       "      });\n"
20821       "}\n");
20822   verifyFormat("SomeFunction([]() { // A cool function...\n"
20823                "  return 43;\n"
20824                "});");
20825   EXPECT_EQ("SomeFunction([]() {\n"
20826             "#define A a\n"
20827             "  return 43;\n"
20828             "});",
20829             format("SomeFunction([](){\n"
20830                    "#define A a\n"
20831                    "return 43;\n"
20832                    "});"));
20833   verifyFormat("void f() {\n"
20834                "  SomeFunction([](decltype(x), A *a) {});\n"
20835                "  SomeFunction([](typeof(x), A *a) {});\n"
20836                "  SomeFunction([](_Atomic(x), A *a) {});\n"
20837                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
20838                "}");
20839   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20840                "    [](const aaaaaaaaaa &a) { return a; });");
20841   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
20842                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
20843                "});");
20844   verifyFormat("Constructor()\n"
20845                "    : Field([] { // comment\n"
20846                "        int i;\n"
20847                "      }) {}");
20848   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
20849                "  return some_parameter.size();\n"
20850                "};");
20851   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
20852                "    [](const string &s) { return s; };");
20853   verifyFormat("int i = aaaaaa ? 1 //\n"
20854                "               : [] {\n"
20855                "                   return 2; //\n"
20856                "                 }();");
20857   verifyFormat("llvm::errs() << \"number of twos is \"\n"
20858                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
20859                "                  return x == 2; // force break\n"
20860                "                });");
20861   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20862                "    [=](int iiiiiiiiiiii) {\n"
20863                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
20864                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
20865                "    });",
20866                getLLVMStyleWithColumns(60));
20867 
20868   verifyFormat("SomeFunction({[&] {\n"
20869                "                // comment\n"
20870                "              },\n"
20871                "              [&] {\n"
20872                "                // comment\n"
20873                "              }});");
20874   verifyFormat("SomeFunction({[&] {\n"
20875                "  // comment\n"
20876                "}});");
20877   verifyFormat(
20878       "virtual aaaaaaaaaaaaaaaa(\n"
20879       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
20880       "    aaaaa aaaaaaaaa);");
20881 
20882   // Lambdas with return types.
20883   verifyFormat("int c = []() -> int { return 2; }();\n");
20884   verifyFormat("int c = []() -> int * { return 2; }();\n");
20885   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
20886   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
20887   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
20888   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
20889   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
20890   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
20891   verifyFormat("[a, a]() -> a<1> {};");
20892   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
20893   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
20894   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
20895   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
20896   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
20897   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
20898   verifyFormat("[]() -> foo<!5> { return {}; };");
20899   verifyFormat("[]() -> foo<~5> { return {}; };");
20900   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
20901   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
20902   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
20903   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
20904   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
20905   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
20906   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
20907   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
20908   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
20909   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
20910   verifyFormat("namespace bar {\n"
20911                "// broken:\n"
20912                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
20913                "} // namespace bar");
20914   verifyFormat("namespace bar {\n"
20915                "// broken:\n"
20916                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
20917                "} // namespace bar");
20918   verifyFormat("namespace bar {\n"
20919                "// broken:\n"
20920                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
20921                "} // namespace bar");
20922   verifyFormat("namespace bar {\n"
20923                "// broken:\n"
20924                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
20925                "} // namespace bar");
20926   verifyFormat("namespace bar {\n"
20927                "// broken:\n"
20928                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
20929                "} // namespace bar");
20930   verifyFormat("namespace bar {\n"
20931                "// broken:\n"
20932                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
20933                "} // namespace bar");
20934   verifyFormat("namespace bar {\n"
20935                "// broken:\n"
20936                "auto foo{[]() -> foo<!5> { return {}; }};\n"
20937                "} // namespace bar");
20938   verifyFormat("namespace bar {\n"
20939                "// broken:\n"
20940                "auto foo{[]() -> foo<~5> { return {}; }};\n"
20941                "} // namespace bar");
20942   verifyFormat("namespace bar {\n"
20943                "// broken:\n"
20944                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
20945                "} // namespace bar");
20946   verifyFormat("namespace bar {\n"
20947                "// broken:\n"
20948                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
20949                "} // namespace bar");
20950   verifyFormat("namespace bar {\n"
20951                "// broken:\n"
20952                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
20953                "} // namespace bar");
20954   verifyFormat("namespace bar {\n"
20955                "// broken:\n"
20956                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
20957                "} // namespace bar");
20958   verifyFormat("namespace bar {\n"
20959                "// broken:\n"
20960                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
20961                "} // namespace bar");
20962   verifyFormat("namespace bar {\n"
20963                "// broken:\n"
20964                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
20965                "} // namespace bar");
20966   verifyFormat("namespace bar {\n"
20967                "// broken:\n"
20968                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
20969                "} // namespace bar");
20970   verifyFormat("namespace bar {\n"
20971                "// broken:\n"
20972                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
20973                "} // namespace bar");
20974   verifyFormat("namespace bar {\n"
20975                "// broken:\n"
20976                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
20977                "} // namespace bar");
20978   verifyFormat("namespace bar {\n"
20979                "// broken:\n"
20980                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
20981                "} // namespace bar");
20982   verifyFormat("[]() -> a<1> {};");
20983   verifyFormat("[]() -> a<1> { ; };");
20984   verifyFormat("[]() -> a<1> { ; }();");
20985   verifyFormat("[a, a]() -> a<true> {};");
20986   verifyFormat("[]() -> a<true> {};");
20987   verifyFormat("[]() -> a<true> { ; };");
20988   verifyFormat("[]() -> a<true> { ; }();");
20989   verifyFormat("[a, a]() -> a<false> {};");
20990   verifyFormat("[]() -> a<false> {};");
20991   verifyFormat("[]() -> a<false> { ; };");
20992   verifyFormat("[]() -> a<false> { ; }();");
20993   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
20994   verifyFormat("namespace bar {\n"
20995                "auto foo{[]() -> foo<false> { ; }};\n"
20996                "} // namespace bar");
20997   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
20998                "                   int j) -> int {\n"
20999                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21000                "};");
21001   verifyFormat(
21002       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21003       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21004       "      return aaaaaaaaaaaaaaaaa;\n"
21005       "    });",
21006       getLLVMStyleWithColumns(70));
21007   verifyFormat("[]() //\n"
21008                "    -> int {\n"
21009                "  return 1; //\n"
21010                "};");
21011   verifyFormat("[]() -> Void<T...> {};");
21012   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21013   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21014   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21015   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21016   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21017   verifyFormat("return int{[x = x]() { return x; }()};");
21018 
21019   // Lambdas with explicit template argument lists.
21020   verifyFormat(
21021       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21022   verifyFormat("auto L = []<class T>(T) {\n"
21023                "  {\n"
21024                "    f();\n"
21025                "    g();\n"
21026                "  }\n"
21027                "};\n");
21028   verifyFormat("auto L = []<class... T>(T...) {\n"
21029                "  {\n"
21030                "    f();\n"
21031                "    g();\n"
21032                "  }\n"
21033                "};\n");
21034   verifyFormat("auto L = []<typename... T>(T...) {\n"
21035                "  {\n"
21036                "    f();\n"
21037                "    g();\n"
21038                "  }\n"
21039                "};\n");
21040   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21041                "  {\n"
21042                "    f();\n"
21043                "    g();\n"
21044                "  }\n"
21045                "};\n");
21046   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21047                "  {\n"
21048                "    f();\n"
21049                "    g();\n"
21050                "  }\n"
21051                "};\n");
21052 
21053   // Multiple lambdas in the same parentheses change indentation rules. These
21054   // lambdas are forced to start on new lines.
21055   verifyFormat("SomeFunction(\n"
21056                "    []() {\n"
21057                "      //\n"
21058                "    },\n"
21059                "    []() {\n"
21060                "      //\n"
21061                "    });");
21062 
21063   // A lambda passed as arg0 is always pushed to the next line.
21064   verifyFormat("SomeFunction(\n"
21065                "    [this] {\n"
21066                "      //\n"
21067                "    },\n"
21068                "    1);\n");
21069 
21070   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21071   // the arg0 case above.
21072   auto Style = getGoogleStyle();
21073   Style.BinPackArguments = false;
21074   verifyFormat("SomeFunction(\n"
21075                "    a,\n"
21076                "    [this] {\n"
21077                "      //\n"
21078                "    },\n"
21079                "    b);\n",
21080                Style);
21081   verifyFormat("SomeFunction(\n"
21082                "    a,\n"
21083                "    [this] {\n"
21084                "      //\n"
21085                "    },\n"
21086                "    b);\n");
21087 
21088   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21089   // the BinPackArguments value (as long as the code is wide enough).
21090   verifyFormat(
21091       "something->SomeFunction(\n"
21092       "    a,\n"
21093       "    [this] {\n"
21094       "      "
21095       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21096       "    },\n"
21097       "    b);\n");
21098 
21099   // A multi-line lambda is pulled up as long as the introducer fits on the
21100   // previous line and there are no further args.
21101   verifyFormat("function(1, [this, that] {\n"
21102                "  //\n"
21103                "});\n");
21104   verifyFormat("function([this, that] {\n"
21105                "  //\n"
21106                "});\n");
21107   // FIXME: this format is not ideal and we should consider forcing the first
21108   // arg onto its own line.
21109   verifyFormat("function(a, b, c, //\n"
21110                "         d, [this, that] {\n"
21111                "           //\n"
21112                "         });\n");
21113 
21114   // Multiple lambdas are treated correctly even when there is a short arg0.
21115   verifyFormat("SomeFunction(\n"
21116                "    1,\n"
21117                "    [this] {\n"
21118                "      //\n"
21119                "    },\n"
21120                "    [this] {\n"
21121                "      //\n"
21122                "    },\n"
21123                "    1);\n");
21124 
21125   // More complex introducers.
21126   verifyFormat("return [i, args...] {};");
21127 
21128   // Not lambdas.
21129   verifyFormat("constexpr char hello[]{\"hello\"};");
21130   verifyFormat("double &operator[](int i) { return 0; }\n"
21131                "int i;");
21132   verifyFormat("std::unique_ptr<int[]> foo() {}");
21133   verifyFormat("int i = a[a][a]->f();");
21134   verifyFormat("int i = (*b)[a]->f();");
21135 
21136   // Other corner cases.
21137   verifyFormat("void f() {\n"
21138                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21139                "  );\n"
21140                "}");
21141 
21142   // Lambdas created through weird macros.
21143   verifyFormat("void f() {\n"
21144                "  MACRO((const AA &a) { return 1; });\n"
21145                "  MACRO((AA &a) { return 1; });\n"
21146                "}");
21147 
21148   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21149                "      doo_dah();\n"
21150                "      doo_dah();\n"
21151                "    })) {\n"
21152                "}");
21153   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21154                "                doo_dah();\n"
21155                "                doo_dah();\n"
21156                "              })) {\n"
21157                "}");
21158   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21159                "                doo_dah();\n"
21160                "                doo_dah();\n"
21161                "              })) {\n"
21162                "}");
21163   verifyFormat("auto lambda = []() {\n"
21164                "  int a = 2\n"
21165                "#if A\n"
21166                "          + 2\n"
21167                "#endif\n"
21168                "      ;\n"
21169                "};");
21170 
21171   // Lambdas with complex multiline introducers.
21172   verifyFormat(
21173       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21174       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21175       "        -> ::std::unordered_set<\n"
21176       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21177       "      //\n"
21178       "    });");
21179 
21180   FormatStyle DoNotMerge = getLLVMStyle();
21181   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21182   verifyFormat("auto c = []() {\n"
21183                "  return b;\n"
21184                "};",
21185                "auto c = []() { return b; };", DoNotMerge);
21186   verifyFormat("auto c = []() {\n"
21187                "};",
21188                " auto c = []() {};", DoNotMerge);
21189 
21190   FormatStyle MergeEmptyOnly = getLLVMStyle();
21191   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21192   verifyFormat("auto c = []() {\n"
21193                "  return b;\n"
21194                "};",
21195                "auto c = []() {\n"
21196                "  return b;\n"
21197                " };",
21198                MergeEmptyOnly);
21199   verifyFormat("auto c = []() {};",
21200                "auto c = []() {\n"
21201                "};",
21202                MergeEmptyOnly);
21203 
21204   FormatStyle MergeInline = getLLVMStyle();
21205   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21206   verifyFormat("auto c = []() {\n"
21207                "  return b;\n"
21208                "};",
21209                "auto c = []() { return b; };", MergeInline);
21210   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21211                MergeInline);
21212   verifyFormat("function([]() { return b; }, a)",
21213                "function([]() { return b; }, a)", MergeInline);
21214   verifyFormat("function(a, []() { return b; })",
21215                "function(a, []() { return b; })", MergeInline);
21216 
21217   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21218   // AllowShortLambdasOnASingleLine
21219   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21220   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21221   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21222   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21223       FormatStyle::ShortLambdaStyle::SLS_None;
21224   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21225                "    []()\n"
21226                "    {\n"
21227                "      return 17;\n"
21228                "    });",
21229                LLVMWithBeforeLambdaBody);
21230   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21231                "    []()\n"
21232                "    {\n"
21233                "    });",
21234                LLVMWithBeforeLambdaBody);
21235   verifyFormat("auto fct_SLS_None = []()\n"
21236                "{\n"
21237                "  return 17;\n"
21238                "};",
21239                LLVMWithBeforeLambdaBody);
21240   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21241                "    []()\n"
21242                "    {\n"
21243                "      return Call(\n"
21244                "          []()\n"
21245                "          {\n"
21246                "            return 17;\n"
21247                "          });\n"
21248                "    });",
21249                LLVMWithBeforeLambdaBody);
21250   verifyFormat("void Fct() {\n"
21251                "  return {[]()\n"
21252                "          {\n"
21253                "            return 17;\n"
21254                "          }};\n"
21255                "}",
21256                LLVMWithBeforeLambdaBody);
21257 
21258   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21259       FormatStyle::ShortLambdaStyle::SLS_Empty;
21260   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21261                "    []()\n"
21262                "    {\n"
21263                "      return 17;\n"
21264                "    });",
21265                LLVMWithBeforeLambdaBody);
21266   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21267                LLVMWithBeforeLambdaBody);
21268   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21269                "ongFunctionName_SLS_Empty(\n"
21270                "    []() {});",
21271                LLVMWithBeforeLambdaBody);
21272   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21273                "                                []()\n"
21274                "                                {\n"
21275                "                                  return 17;\n"
21276                "                                });",
21277                LLVMWithBeforeLambdaBody);
21278   verifyFormat("auto fct_SLS_Empty = []()\n"
21279                "{\n"
21280                "  return 17;\n"
21281                "};",
21282                LLVMWithBeforeLambdaBody);
21283   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21284                "    []()\n"
21285                "    {\n"
21286                "      return Call([]() {});\n"
21287                "    });",
21288                LLVMWithBeforeLambdaBody);
21289   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21290                "                           []()\n"
21291                "                           {\n"
21292                "                             return Call([]() {});\n"
21293                "                           });",
21294                LLVMWithBeforeLambdaBody);
21295   verifyFormat(
21296       "FctWithLongLineInLambda_SLS_Empty(\n"
21297       "    []()\n"
21298       "    {\n"
21299       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21300       "                               AndShouldNotBeConsiderAsInline,\n"
21301       "                               LambdaBodyMustBeBreak);\n"
21302       "    });",
21303       LLVMWithBeforeLambdaBody);
21304 
21305   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21306       FormatStyle::ShortLambdaStyle::SLS_Inline;
21307   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21308                LLVMWithBeforeLambdaBody);
21309   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21310                LLVMWithBeforeLambdaBody);
21311   verifyFormat("auto fct_SLS_Inline = []()\n"
21312                "{\n"
21313                "  return 17;\n"
21314                "};",
21315                LLVMWithBeforeLambdaBody);
21316   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21317                "17; }); });",
21318                LLVMWithBeforeLambdaBody);
21319   verifyFormat(
21320       "FctWithLongLineInLambda_SLS_Inline(\n"
21321       "    []()\n"
21322       "    {\n"
21323       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21324       "                               AndShouldNotBeConsiderAsInline,\n"
21325       "                               LambdaBodyMustBeBreak);\n"
21326       "    });",
21327       LLVMWithBeforeLambdaBody);
21328   verifyFormat("FctWithMultipleParams_SLS_Inline("
21329                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21330                "                                 []() { return 17; });",
21331                LLVMWithBeforeLambdaBody);
21332   verifyFormat(
21333       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21334       LLVMWithBeforeLambdaBody);
21335 
21336   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21337       FormatStyle::ShortLambdaStyle::SLS_All;
21338   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21339                LLVMWithBeforeLambdaBody);
21340   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21341                LLVMWithBeforeLambdaBody);
21342   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21343                LLVMWithBeforeLambdaBody);
21344   verifyFormat("FctWithOneParam_SLS_All(\n"
21345                "    []()\n"
21346                "    {\n"
21347                "      // A cool function...\n"
21348                "      return 43;\n"
21349                "    });",
21350                LLVMWithBeforeLambdaBody);
21351   verifyFormat("FctWithMultipleParams_SLS_All("
21352                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21353                "                              []() { return 17; });",
21354                LLVMWithBeforeLambdaBody);
21355   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21356                LLVMWithBeforeLambdaBody);
21357   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21358                LLVMWithBeforeLambdaBody);
21359   verifyFormat(
21360       "FctWithLongLineInLambda_SLS_All(\n"
21361       "    []()\n"
21362       "    {\n"
21363       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21364       "                               AndShouldNotBeConsiderAsInline,\n"
21365       "                               LambdaBodyMustBeBreak);\n"
21366       "    });",
21367       LLVMWithBeforeLambdaBody);
21368   verifyFormat(
21369       "auto fct_SLS_All = []()\n"
21370       "{\n"
21371       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21372       "                           AndShouldNotBeConsiderAsInline,\n"
21373       "                           LambdaBodyMustBeBreak);\n"
21374       "};",
21375       LLVMWithBeforeLambdaBody);
21376   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21377   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21378                LLVMWithBeforeLambdaBody);
21379   verifyFormat(
21380       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21381       "                                FirstParam,\n"
21382       "                                SecondParam,\n"
21383       "                                ThirdParam,\n"
21384       "                                FourthParam);",
21385       LLVMWithBeforeLambdaBody);
21386   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21387                "    []() { return "
21388                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21389                "    FirstParam,\n"
21390                "    SecondParam,\n"
21391                "    ThirdParam,\n"
21392                "    FourthParam);",
21393                LLVMWithBeforeLambdaBody);
21394   verifyFormat(
21395       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21396       "                                SecondParam,\n"
21397       "                                ThirdParam,\n"
21398       "                                FourthParam,\n"
21399       "                                []() { return SomeValueNotSoLong; });",
21400       LLVMWithBeforeLambdaBody);
21401   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21402                "    []()\n"
21403                "    {\n"
21404                "      return "
21405                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21406                "eConsiderAsInline;\n"
21407                "    });",
21408                LLVMWithBeforeLambdaBody);
21409   verifyFormat(
21410       "FctWithLongLineInLambda_SLS_All(\n"
21411       "    []()\n"
21412       "    {\n"
21413       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21414       "                               AndShouldNotBeConsiderAsInline,\n"
21415       "                               LambdaBodyMustBeBreak);\n"
21416       "    });",
21417       LLVMWithBeforeLambdaBody);
21418   verifyFormat("FctWithTwoParams_SLS_All(\n"
21419                "    []()\n"
21420                "    {\n"
21421                "      // A cool function...\n"
21422                "      return 43;\n"
21423                "    },\n"
21424                "    87);",
21425                LLVMWithBeforeLambdaBody);
21426   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
21427                LLVMWithBeforeLambdaBody);
21428   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
21429                LLVMWithBeforeLambdaBody);
21430   verifyFormat(
21431       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
21432       LLVMWithBeforeLambdaBody);
21433   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
21434                "}); }, x);",
21435                LLVMWithBeforeLambdaBody);
21436   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21437                "    []()\n"
21438                "    {\n"
21439                "      // A cool function...\n"
21440                "      return Call([]() { return 17; });\n"
21441                "    });",
21442                LLVMWithBeforeLambdaBody);
21443   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21444                "    []()\n"
21445                "    {\n"
21446                "      return Call(\n"
21447                "          []()\n"
21448                "          {\n"
21449                "            // A cool function...\n"
21450                "            return 17;\n"
21451                "          });\n"
21452                "    });",
21453                LLVMWithBeforeLambdaBody);
21454 
21455   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21456       FormatStyle::ShortLambdaStyle::SLS_None;
21457 
21458   verifyFormat("auto select = [this]() -> const Library::Object *\n"
21459                "{\n"
21460                "  return MyAssignment::SelectFromList(this);\n"
21461                "};\n",
21462                LLVMWithBeforeLambdaBody);
21463 
21464   verifyFormat("auto select = [this]() -> const Library::Object &\n"
21465                "{\n"
21466                "  return MyAssignment::SelectFromList(this);\n"
21467                "};\n",
21468                LLVMWithBeforeLambdaBody);
21469 
21470   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
21471                "{\n"
21472                "  return MyAssignment::SelectFromList(this);\n"
21473                "};\n",
21474                LLVMWithBeforeLambdaBody);
21475 
21476   verifyFormat("namespace test {\n"
21477                "class Test {\n"
21478                "public:\n"
21479                "  Test() = default;\n"
21480                "};\n"
21481                "} // namespace test",
21482                LLVMWithBeforeLambdaBody);
21483 
21484   // Lambdas with different indentation styles.
21485   Style = getLLVMStyleWithColumns(100);
21486   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21487             "  return promise.then(\n"
21488             "      [this, &someVariable, someObject = "
21489             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21490             "        return someObject.startAsyncAction().then(\n"
21491             "            [this, &someVariable](AsyncActionResult result) "
21492             "mutable { result.processMore(); });\n"
21493             "      });\n"
21494             "}\n",
21495             format("SomeResult doSomething(SomeObject promise) {\n"
21496                    "  return promise.then([this, &someVariable, someObject = "
21497                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21498                    "    return someObject.startAsyncAction().then([this, "
21499                    "&someVariable](AsyncActionResult result) mutable {\n"
21500                    "      result.processMore();\n"
21501                    "    });\n"
21502                    "  });\n"
21503                    "}\n",
21504                    Style));
21505   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21506   verifyFormat("test() {\n"
21507                "  ([]() -> {\n"
21508                "    int b = 32;\n"
21509                "    return 3;\n"
21510                "  }).foo();\n"
21511                "}",
21512                Style);
21513   verifyFormat("test() {\n"
21514                "  []() -> {\n"
21515                "    int b = 32;\n"
21516                "    return 3;\n"
21517                "  }\n"
21518                "}",
21519                Style);
21520   verifyFormat("std::sort(v.begin(), v.end(),\n"
21521                "          [](const auto &someLongArgumentName, const auto "
21522                "&someOtherLongArgumentName) {\n"
21523                "  return someLongArgumentName.someMemberVariable < "
21524                "someOtherLongArgumentName.someMemberVariable;\n"
21525                "});",
21526                Style);
21527   verifyFormat("test() {\n"
21528                "  (\n"
21529                "      []() -> {\n"
21530                "        int b = 32;\n"
21531                "        return 3;\n"
21532                "      },\n"
21533                "      foo, bar)\n"
21534                "      .foo();\n"
21535                "}",
21536                Style);
21537   verifyFormat("test() {\n"
21538                "  ([]() -> {\n"
21539                "    int b = 32;\n"
21540                "    return 3;\n"
21541                "  })\n"
21542                "      .foo()\n"
21543                "      .bar();\n"
21544                "}",
21545                Style);
21546   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21547             "  return promise.then(\n"
21548             "      [this, &someVariable, someObject = "
21549             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21550             "    return someObject.startAsyncAction().then(\n"
21551             "        [this, &someVariable](AsyncActionResult result) mutable { "
21552             "result.processMore(); });\n"
21553             "  });\n"
21554             "}\n",
21555             format("SomeResult doSomething(SomeObject promise) {\n"
21556                    "  return promise.then([this, &someVariable, someObject = "
21557                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21558                    "    return someObject.startAsyncAction().then([this, "
21559                    "&someVariable](AsyncActionResult result) mutable {\n"
21560                    "      result.processMore();\n"
21561                    "    });\n"
21562                    "  });\n"
21563                    "}\n",
21564                    Style));
21565   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21566             "  return promise.then([this, &someVariable] {\n"
21567             "    return someObject.startAsyncAction().then(\n"
21568             "        [this, &someVariable](AsyncActionResult result) mutable { "
21569             "result.processMore(); });\n"
21570             "  });\n"
21571             "}\n",
21572             format("SomeResult doSomething(SomeObject promise) {\n"
21573                    "  return promise.then([this, &someVariable] {\n"
21574                    "    return someObject.startAsyncAction().then([this, "
21575                    "&someVariable](AsyncActionResult result) mutable {\n"
21576                    "      result.processMore();\n"
21577                    "    });\n"
21578                    "  });\n"
21579                    "}\n",
21580                    Style));
21581   Style = getGoogleStyle();
21582   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21583   EXPECT_EQ("#define A                                       \\\n"
21584             "  [] {                                          \\\n"
21585             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
21586             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
21587             "      }",
21588             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
21589                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
21590                    Style));
21591   // TODO: The current formatting has a minor issue that's not worth fixing
21592   // right now whereby the closing brace is indented relative to the signature
21593   // instead of being aligned. This only happens with macros.
21594 }
21595 
21596 TEST_F(FormatTest, LambdaWithLineComments) {
21597   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21598   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21599   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21600   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21601       FormatStyle::ShortLambdaStyle::SLS_All;
21602 
21603   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
21604   verifyFormat("auto k = []() // comment\n"
21605                "{ return; }",
21606                LLVMWithBeforeLambdaBody);
21607   verifyFormat("auto k = []() /* comment */ { return; }",
21608                LLVMWithBeforeLambdaBody);
21609   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
21610                LLVMWithBeforeLambdaBody);
21611   verifyFormat("auto k = []() // X\n"
21612                "{ return; }",
21613                LLVMWithBeforeLambdaBody);
21614   verifyFormat(
21615       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
21616       "{ return; }",
21617       LLVMWithBeforeLambdaBody);
21618 }
21619 
21620 TEST_F(FormatTest, EmptyLinesInLambdas) {
21621   verifyFormat("auto lambda = []() {\n"
21622                "  x(); //\n"
21623                "};",
21624                "auto lambda = []() {\n"
21625                "\n"
21626                "  x(); //\n"
21627                "\n"
21628                "};");
21629 }
21630 
21631 TEST_F(FormatTest, FormatsBlocks) {
21632   FormatStyle ShortBlocks = getLLVMStyle();
21633   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21634   verifyFormat("int (^Block)(int, int);", ShortBlocks);
21635   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
21636   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
21637   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
21638   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
21639   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
21640 
21641   verifyFormat("foo(^{ bar(); });", ShortBlocks);
21642   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
21643   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
21644 
21645   verifyFormat("[operation setCompletionBlock:^{\n"
21646                "  [self onOperationDone];\n"
21647                "}];");
21648   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
21649                "  [self onOperationDone];\n"
21650                "}]};");
21651   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
21652                "  f();\n"
21653                "}];");
21654   verifyFormat("int a = [operation block:^int(int *i) {\n"
21655                "  return 1;\n"
21656                "}];");
21657   verifyFormat("[myObject doSomethingWith:arg1\n"
21658                "                      aaa:^int(int *a) {\n"
21659                "                        return 1;\n"
21660                "                      }\n"
21661                "                      bbb:f(a * bbbbbbbb)];");
21662 
21663   verifyFormat("[operation setCompletionBlock:^{\n"
21664                "  [self.delegate newDataAvailable];\n"
21665                "}];",
21666                getLLVMStyleWithColumns(60));
21667   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
21668                "  NSString *path = [self sessionFilePath];\n"
21669                "  if (path) {\n"
21670                "    // ...\n"
21671                "  }\n"
21672                "});");
21673   verifyFormat("[[SessionService sharedService]\n"
21674                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21675                "      if (window) {\n"
21676                "        [self windowDidLoad:window];\n"
21677                "      } else {\n"
21678                "        [self errorLoadingWindow];\n"
21679                "      }\n"
21680                "    }];");
21681   verifyFormat("void (^largeBlock)(void) = ^{\n"
21682                "  // ...\n"
21683                "};\n",
21684                getLLVMStyleWithColumns(40));
21685   verifyFormat("[[SessionService sharedService]\n"
21686                "    loadWindowWithCompletionBlock: //\n"
21687                "        ^(SessionWindow *window) {\n"
21688                "          if (window) {\n"
21689                "            [self windowDidLoad:window];\n"
21690                "          } else {\n"
21691                "            [self errorLoadingWindow];\n"
21692                "          }\n"
21693                "        }];",
21694                getLLVMStyleWithColumns(60));
21695   verifyFormat("[myObject doSomethingWith:arg1\n"
21696                "    firstBlock:^(Foo *a) {\n"
21697                "      // ...\n"
21698                "      int i;\n"
21699                "    }\n"
21700                "    secondBlock:^(Bar *b) {\n"
21701                "      // ...\n"
21702                "      int i;\n"
21703                "    }\n"
21704                "    thirdBlock:^Foo(Bar *b) {\n"
21705                "      // ...\n"
21706                "      int i;\n"
21707                "    }];");
21708   verifyFormat("[myObject doSomethingWith:arg1\n"
21709                "               firstBlock:-1\n"
21710                "              secondBlock:^(Bar *b) {\n"
21711                "                // ...\n"
21712                "                int i;\n"
21713                "              }];");
21714 
21715   verifyFormat("f(^{\n"
21716                "  @autoreleasepool {\n"
21717                "    if (a) {\n"
21718                "      g();\n"
21719                "    }\n"
21720                "  }\n"
21721                "});");
21722   verifyFormat("Block b = ^int *(A *a, B *b) {}");
21723   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
21724                "};");
21725 
21726   FormatStyle FourIndent = getLLVMStyle();
21727   FourIndent.ObjCBlockIndentWidth = 4;
21728   verifyFormat("[operation setCompletionBlock:^{\n"
21729                "    [self onOperationDone];\n"
21730                "}];",
21731                FourIndent);
21732 }
21733 
21734 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
21735   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
21736 
21737   verifyFormat("[[SessionService sharedService] "
21738                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21739                "  if (window) {\n"
21740                "    [self windowDidLoad:window];\n"
21741                "  } else {\n"
21742                "    [self errorLoadingWindow];\n"
21743                "  }\n"
21744                "}];",
21745                ZeroColumn);
21746   EXPECT_EQ("[[SessionService sharedService]\n"
21747             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21748             "      if (window) {\n"
21749             "        [self windowDidLoad:window];\n"
21750             "      } else {\n"
21751             "        [self errorLoadingWindow];\n"
21752             "      }\n"
21753             "    }];",
21754             format("[[SessionService sharedService]\n"
21755                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21756                    "                if (window) {\n"
21757                    "    [self windowDidLoad:window];\n"
21758                    "  } else {\n"
21759                    "    [self errorLoadingWindow];\n"
21760                    "  }\n"
21761                    "}];",
21762                    ZeroColumn));
21763   verifyFormat("[myObject doSomethingWith:arg1\n"
21764                "    firstBlock:^(Foo *a) {\n"
21765                "      // ...\n"
21766                "      int i;\n"
21767                "    }\n"
21768                "    secondBlock:^(Bar *b) {\n"
21769                "      // ...\n"
21770                "      int i;\n"
21771                "    }\n"
21772                "    thirdBlock:^Foo(Bar *b) {\n"
21773                "      // ...\n"
21774                "      int i;\n"
21775                "    }];",
21776                ZeroColumn);
21777   verifyFormat("f(^{\n"
21778                "  @autoreleasepool {\n"
21779                "    if (a) {\n"
21780                "      g();\n"
21781                "    }\n"
21782                "  }\n"
21783                "});",
21784                ZeroColumn);
21785   verifyFormat("void (^largeBlock)(void) = ^{\n"
21786                "  // ...\n"
21787                "};",
21788                ZeroColumn);
21789 
21790   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21791   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
21792             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21793   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
21794   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
21795             "  int i;\n"
21796             "};",
21797             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21798 }
21799 
21800 TEST_F(FormatTest, SupportsCRLF) {
21801   EXPECT_EQ("int a;\r\n"
21802             "int b;\r\n"
21803             "int c;\r\n",
21804             format("int a;\r\n"
21805                    "  int b;\r\n"
21806                    "    int c;\r\n",
21807                    getLLVMStyle()));
21808   EXPECT_EQ("int a;\r\n"
21809             "int b;\r\n"
21810             "int c;\r\n",
21811             format("int a;\r\n"
21812                    "  int b;\n"
21813                    "    int c;\r\n",
21814                    getLLVMStyle()));
21815   EXPECT_EQ("int a;\n"
21816             "int b;\n"
21817             "int c;\n",
21818             format("int a;\r\n"
21819                    "  int b;\n"
21820                    "    int c;\n",
21821                    getLLVMStyle()));
21822   EXPECT_EQ("\"aaaaaaa \"\r\n"
21823             "\"bbbbbbb\";\r\n",
21824             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
21825   EXPECT_EQ("#define A \\\r\n"
21826             "  b;      \\\r\n"
21827             "  c;      \\\r\n"
21828             "  d;\r\n",
21829             format("#define A \\\r\n"
21830                    "  b; \\\r\n"
21831                    "  c; d; \r\n",
21832                    getGoogleStyle()));
21833 
21834   EXPECT_EQ("/*\r\n"
21835             "multi line block comments\r\n"
21836             "should not introduce\r\n"
21837             "an extra carriage return\r\n"
21838             "*/\r\n",
21839             format("/*\r\n"
21840                    "multi line block comments\r\n"
21841                    "should not introduce\r\n"
21842                    "an extra carriage return\r\n"
21843                    "*/\r\n"));
21844   EXPECT_EQ("/*\r\n"
21845             "\r\n"
21846             "*/",
21847             format("/*\r\n"
21848                    "    \r\r\r\n"
21849                    "*/"));
21850 
21851   FormatStyle style = getLLVMStyle();
21852 
21853   style.DeriveLineEnding = true;
21854   style.UseCRLF = false;
21855   EXPECT_EQ("union FooBarBazQux {\n"
21856             "  int foo;\n"
21857             "  int bar;\n"
21858             "  int baz;\n"
21859             "};",
21860             format("union FooBarBazQux {\r\n"
21861                    "  int foo;\n"
21862                    "  int bar;\r\n"
21863                    "  int baz;\n"
21864                    "};",
21865                    style));
21866   style.UseCRLF = true;
21867   EXPECT_EQ("union FooBarBazQux {\r\n"
21868             "  int foo;\r\n"
21869             "  int bar;\r\n"
21870             "  int baz;\r\n"
21871             "};",
21872             format("union FooBarBazQux {\r\n"
21873                    "  int foo;\n"
21874                    "  int bar;\r\n"
21875                    "  int baz;\n"
21876                    "};",
21877                    style));
21878 
21879   style.DeriveLineEnding = false;
21880   style.UseCRLF = false;
21881   EXPECT_EQ("union FooBarBazQux {\n"
21882             "  int foo;\n"
21883             "  int bar;\n"
21884             "  int baz;\n"
21885             "  int qux;\n"
21886             "};",
21887             format("union FooBarBazQux {\r\n"
21888                    "  int foo;\n"
21889                    "  int bar;\r\n"
21890                    "  int baz;\n"
21891                    "  int qux;\r\n"
21892                    "};",
21893                    style));
21894   style.UseCRLF = true;
21895   EXPECT_EQ("union FooBarBazQux {\r\n"
21896             "  int foo;\r\n"
21897             "  int bar;\r\n"
21898             "  int baz;\r\n"
21899             "  int qux;\r\n"
21900             "};",
21901             format("union FooBarBazQux {\r\n"
21902                    "  int foo;\n"
21903                    "  int bar;\r\n"
21904                    "  int baz;\n"
21905                    "  int qux;\n"
21906                    "};",
21907                    style));
21908 
21909   style.DeriveLineEnding = true;
21910   style.UseCRLF = false;
21911   EXPECT_EQ("union FooBarBazQux {\r\n"
21912             "  int foo;\r\n"
21913             "  int bar;\r\n"
21914             "  int baz;\r\n"
21915             "  int qux;\r\n"
21916             "};",
21917             format("union FooBarBazQux {\r\n"
21918                    "  int foo;\n"
21919                    "  int bar;\r\n"
21920                    "  int baz;\n"
21921                    "  int qux;\r\n"
21922                    "};",
21923                    style));
21924   style.UseCRLF = true;
21925   EXPECT_EQ("union FooBarBazQux {\n"
21926             "  int foo;\n"
21927             "  int bar;\n"
21928             "  int baz;\n"
21929             "  int qux;\n"
21930             "};",
21931             format("union FooBarBazQux {\r\n"
21932                    "  int foo;\n"
21933                    "  int bar;\r\n"
21934                    "  int baz;\n"
21935                    "  int qux;\n"
21936                    "};",
21937                    style));
21938 }
21939 
21940 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
21941   verifyFormat("MY_CLASS(C) {\n"
21942                "  int i;\n"
21943                "  int j;\n"
21944                "};");
21945 }
21946 
21947 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
21948   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
21949   TwoIndent.ContinuationIndentWidth = 2;
21950 
21951   EXPECT_EQ("int i =\n"
21952             "  longFunction(\n"
21953             "    arg);",
21954             format("int i = longFunction(arg);", TwoIndent));
21955 
21956   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
21957   SixIndent.ContinuationIndentWidth = 6;
21958 
21959   EXPECT_EQ("int i =\n"
21960             "      longFunction(\n"
21961             "            arg);",
21962             format("int i = longFunction(arg);", SixIndent));
21963 }
21964 
21965 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
21966   FormatStyle Style = getLLVMStyle();
21967   verifyFormat("int Foo::getter(\n"
21968                "    //\n"
21969                ") const {\n"
21970                "  return foo;\n"
21971                "}",
21972                Style);
21973   verifyFormat("void Foo::setter(\n"
21974                "    //\n"
21975                ") {\n"
21976                "  foo = 1;\n"
21977                "}",
21978                Style);
21979 }
21980 
21981 TEST_F(FormatTest, SpacesInAngles) {
21982   FormatStyle Spaces = getLLVMStyle();
21983   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21984 
21985   verifyFormat("vector< ::std::string > x1;", Spaces);
21986   verifyFormat("Foo< int, Bar > x2;", Spaces);
21987   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
21988 
21989   verifyFormat("static_cast< int >(arg);", Spaces);
21990   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
21991   verifyFormat("f< int, float >();", Spaces);
21992   verifyFormat("template <> g() {}", Spaces);
21993   verifyFormat("template < std::vector< int > > f() {}", Spaces);
21994   verifyFormat("std::function< void(int, int) > fct;", Spaces);
21995   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
21996                Spaces);
21997 
21998   Spaces.Standard = FormatStyle::LS_Cpp03;
21999   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22000   verifyFormat("A< A< int > >();", Spaces);
22001 
22002   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22003   verifyFormat("A<A<int> >();", Spaces);
22004 
22005   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22006   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22007                Spaces);
22008   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22009                Spaces);
22010 
22011   verifyFormat("A<A<int> >();", Spaces);
22012   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22013   verifyFormat("A< A< int > >();", Spaces);
22014 
22015   Spaces.Standard = FormatStyle::LS_Cpp11;
22016   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22017   verifyFormat("A< A< int > >();", Spaces);
22018 
22019   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22020   verifyFormat("vector<::std::string> x4;", Spaces);
22021   verifyFormat("vector<int> x5;", Spaces);
22022   verifyFormat("Foo<int, Bar> x6;", Spaces);
22023   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22024 
22025   verifyFormat("A<A<int>>();", Spaces);
22026 
22027   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22028   verifyFormat("vector<::std::string> x4;", Spaces);
22029   verifyFormat("vector< ::std::string > x4;", Spaces);
22030   verifyFormat("vector<int> x5;", Spaces);
22031   verifyFormat("vector< int > x5;", Spaces);
22032   verifyFormat("Foo<int, Bar> x6;", Spaces);
22033   verifyFormat("Foo< int, Bar > x6;", Spaces);
22034   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22035   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22036 
22037   verifyFormat("A<A<int>>();", Spaces);
22038   verifyFormat("A< A< int > >();", Spaces);
22039   verifyFormat("A<A<int > >();", Spaces);
22040   verifyFormat("A< A< int>>();", Spaces);
22041 
22042   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22043   verifyFormat("// clang-format off\n"
22044                "foo<<<1, 1>>>();\n"
22045                "// clang-format on\n",
22046                Spaces);
22047   verifyFormat("// clang-format off\n"
22048                "foo< < <1, 1> > >();\n"
22049                "// clang-format on\n",
22050                Spaces);
22051 }
22052 
22053 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22054   FormatStyle Style = getLLVMStyle();
22055   Style.SpaceAfterTemplateKeyword = false;
22056   verifyFormat("template<int> void foo();", Style);
22057 }
22058 
22059 TEST_F(FormatTest, TripleAngleBrackets) {
22060   verifyFormat("f<<<1, 1>>>();");
22061   verifyFormat("f<<<1, 1, 1, s>>>();");
22062   verifyFormat("f<<<a, b, c, d>>>();");
22063   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22064   verifyFormat("f<param><<<1, 1>>>();");
22065   verifyFormat("f<1><<<1, 1>>>();");
22066   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22067   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22068                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22069   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22070                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22071 }
22072 
22073 TEST_F(FormatTest, MergeLessLessAtEnd) {
22074   verifyFormat("<<");
22075   EXPECT_EQ("< < <", format("\\\n<<<"));
22076   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22077                "aaallvm::outs() <<");
22078   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22079                "aaaallvm::outs()\n    <<");
22080 }
22081 
22082 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22083   std::string code = "#if A\n"
22084                      "#if B\n"
22085                      "a.\n"
22086                      "#endif\n"
22087                      "    a = 1;\n"
22088                      "#else\n"
22089                      "#endif\n"
22090                      "#if C\n"
22091                      "#else\n"
22092                      "#endif\n";
22093   EXPECT_EQ(code, format(code));
22094 }
22095 
22096 TEST_F(FormatTest, HandleConflictMarkers) {
22097   // Git/SVN conflict markers.
22098   EXPECT_EQ("int a;\n"
22099             "void f() {\n"
22100             "  callme(some(parameter1,\n"
22101             "<<<<<<< text by the vcs\n"
22102             "              parameter2),\n"
22103             "||||||| text by the vcs\n"
22104             "              parameter2),\n"
22105             "         parameter3,\n"
22106             "======= text by the vcs\n"
22107             "              parameter2, parameter3),\n"
22108             ">>>>>>> text by the vcs\n"
22109             "         otherparameter);\n",
22110             format("int a;\n"
22111                    "void f() {\n"
22112                    "  callme(some(parameter1,\n"
22113                    "<<<<<<< text by the vcs\n"
22114                    "  parameter2),\n"
22115                    "||||||| text by the vcs\n"
22116                    "  parameter2),\n"
22117                    "  parameter3,\n"
22118                    "======= text by the vcs\n"
22119                    "  parameter2,\n"
22120                    "  parameter3),\n"
22121                    ">>>>>>> text by the vcs\n"
22122                    "  otherparameter);\n"));
22123 
22124   // Perforce markers.
22125   EXPECT_EQ("void f() {\n"
22126             "  function(\n"
22127             ">>>> text by the vcs\n"
22128             "      parameter,\n"
22129             "==== text by the vcs\n"
22130             "      parameter,\n"
22131             "==== text by the vcs\n"
22132             "      parameter,\n"
22133             "<<<< text by the vcs\n"
22134             "      parameter);\n",
22135             format("void f() {\n"
22136                    "  function(\n"
22137                    ">>>> text by the vcs\n"
22138                    "  parameter,\n"
22139                    "==== text by the vcs\n"
22140                    "  parameter,\n"
22141                    "==== text by the vcs\n"
22142                    "  parameter,\n"
22143                    "<<<< text by the vcs\n"
22144                    "  parameter);\n"));
22145 
22146   EXPECT_EQ("<<<<<<<\n"
22147             "|||||||\n"
22148             "=======\n"
22149             ">>>>>>>",
22150             format("<<<<<<<\n"
22151                    "|||||||\n"
22152                    "=======\n"
22153                    ">>>>>>>"));
22154 
22155   EXPECT_EQ("<<<<<<<\n"
22156             "|||||||\n"
22157             "int i;\n"
22158             "=======\n"
22159             ">>>>>>>",
22160             format("<<<<<<<\n"
22161                    "|||||||\n"
22162                    "int i;\n"
22163                    "=======\n"
22164                    ">>>>>>>"));
22165 
22166   // FIXME: Handle parsing of macros around conflict markers correctly:
22167   EXPECT_EQ("#define Macro \\\n"
22168             "<<<<<<<\n"
22169             "Something \\\n"
22170             "|||||||\n"
22171             "Else \\\n"
22172             "=======\n"
22173             "Other \\\n"
22174             ">>>>>>>\n"
22175             "    End int i;\n",
22176             format("#define Macro \\\n"
22177                    "<<<<<<<\n"
22178                    "  Something \\\n"
22179                    "|||||||\n"
22180                    "  Else \\\n"
22181                    "=======\n"
22182                    "  Other \\\n"
22183                    ">>>>>>>\n"
22184                    "  End\n"
22185                    "int i;\n"));
22186 
22187   verifyFormat(R"(====
22188 #ifdef A
22189 a
22190 #else
22191 b
22192 #endif
22193 )");
22194 }
22195 
22196 TEST_F(FormatTest, DisableRegions) {
22197   EXPECT_EQ("int i;\n"
22198             "// clang-format off\n"
22199             "  int j;\n"
22200             "// clang-format on\n"
22201             "int k;",
22202             format(" int  i;\n"
22203                    "   // clang-format off\n"
22204                    "  int j;\n"
22205                    " // clang-format on\n"
22206                    "   int   k;"));
22207   EXPECT_EQ("int i;\n"
22208             "/* clang-format off */\n"
22209             "  int j;\n"
22210             "/* clang-format on */\n"
22211             "int k;",
22212             format(" int  i;\n"
22213                    "   /* clang-format off */\n"
22214                    "  int j;\n"
22215                    " /* clang-format on */\n"
22216                    "   int   k;"));
22217 
22218   // Don't reflow comments within disabled regions.
22219   EXPECT_EQ("// clang-format off\n"
22220             "// long long long long long long line\n"
22221             "/* clang-format on */\n"
22222             "/* long long long\n"
22223             " * long long long\n"
22224             " * line */\n"
22225             "int i;\n"
22226             "/* clang-format off */\n"
22227             "/* long long long long long long line */\n",
22228             format("// clang-format off\n"
22229                    "// long long long long long long line\n"
22230                    "/* clang-format on */\n"
22231                    "/* long long long long long long line */\n"
22232                    "int i;\n"
22233                    "/* clang-format off */\n"
22234                    "/* long long long long long long line */\n",
22235                    getLLVMStyleWithColumns(20)));
22236 }
22237 
22238 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22239   format("? ) =");
22240   verifyNoCrash("#define a\\\n /**/}");
22241 }
22242 
22243 TEST_F(FormatTest, FormatsTableGenCode) {
22244   FormatStyle Style = getLLVMStyle();
22245   Style.Language = FormatStyle::LK_TableGen;
22246   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22247 }
22248 
22249 TEST_F(FormatTest, ArrayOfTemplates) {
22250   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22251             format("auto a = new unique_ptr<int > [ 10];"));
22252 
22253   FormatStyle Spaces = getLLVMStyle();
22254   Spaces.SpacesInSquareBrackets = true;
22255   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22256             format("auto a = new unique_ptr<int > [10];", Spaces));
22257 }
22258 
22259 TEST_F(FormatTest, ArrayAsTemplateType) {
22260   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22261             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22262 
22263   FormatStyle Spaces = getLLVMStyle();
22264   Spaces.SpacesInSquareBrackets = true;
22265   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22266             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22267 }
22268 
22269 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22270 
22271 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22272   llvm::vfs::InMemoryFileSystem FS;
22273   auto Style1 = getStyle("file", "", "Google", "", &FS);
22274   ASSERT_TRUE((bool)Style1);
22275   ASSERT_EQ(*Style1, getGoogleStyle());
22276 }
22277 
22278 TEST(FormatStyle, GetStyleOfFile) {
22279   llvm::vfs::InMemoryFileSystem FS;
22280   // Test 1: format file in the same directory.
22281   ASSERT_TRUE(
22282       FS.addFile("/a/.clang-format", 0,
22283                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22284   ASSERT_TRUE(
22285       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22286   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22287   ASSERT_TRUE((bool)Style1);
22288   ASSERT_EQ(*Style1, getLLVMStyle());
22289 
22290   // Test 2.1: fallback to default.
22291   ASSERT_TRUE(
22292       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22293   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22294   ASSERT_TRUE((bool)Style2);
22295   ASSERT_EQ(*Style2, getMozillaStyle());
22296 
22297   // Test 2.2: no format on 'none' fallback style.
22298   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22299   ASSERT_TRUE((bool)Style2);
22300   ASSERT_EQ(*Style2, getNoStyle());
22301 
22302   // Test 2.3: format if config is found with no based style while fallback is
22303   // 'none'.
22304   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22305                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22306   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22307   ASSERT_TRUE((bool)Style2);
22308   ASSERT_EQ(*Style2, getLLVMStyle());
22309 
22310   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22311   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22312   ASSERT_TRUE((bool)Style2);
22313   ASSERT_EQ(*Style2, getLLVMStyle());
22314 
22315   // Test 3: format file in parent directory.
22316   ASSERT_TRUE(
22317       FS.addFile("/c/.clang-format", 0,
22318                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22319   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22320                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22321   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22322   ASSERT_TRUE((bool)Style3);
22323   ASSERT_EQ(*Style3, getGoogleStyle());
22324 
22325   // Test 4: error on invalid fallback style
22326   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22327   ASSERT_FALSE((bool)Style4);
22328   llvm::consumeError(Style4.takeError());
22329 
22330   // Test 5: error on invalid yaml on command line
22331   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22332   ASSERT_FALSE((bool)Style5);
22333   llvm::consumeError(Style5.takeError());
22334 
22335   // Test 6: error on invalid style
22336   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22337   ASSERT_FALSE((bool)Style6);
22338   llvm::consumeError(Style6.takeError());
22339 
22340   // Test 7: found config file, error on parsing it
22341   ASSERT_TRUE(
22342       FS.addFile("/d/.clang-format", 0,
22343                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22344                                                   "InvalidKey: InvalidValue")));
22345   ASSERT_TRUE(
22346       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22347   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22348   ASSERT_FALSE((bool)Style7a);
22349   llvm::consumeError(Style7a.takeError());
22350 
22351   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22352   ASSERT_TRUE((bool)Style7b);
22353 
22354   // Test 8: inferred per-language defaults apply.
22355   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22356   ASSERT_TRUE((bool)StyleTd);
22357   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22358 
22359   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22360   // fallback style.
22361   ASSERT_TRUE(FS.addFile(
22362       "/e/sub/.clang-format", 0,
22363       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22364                                        "ColumnLimit: 20")));
22365   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22366                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22367   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22368   ASSERT_TRUE(static_cast<bool>(Style9));
22369   ASSERT_EQ(*Style9, [] {
22370     auto Style = getNoStyle();
22371     Style.ColumnLimit = 20;
22372     return Style;
22373   }());
22374 
22375   // Test 9.1.2: propagate more than one level with no parent file.
22376   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22377                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22378   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22379                          llvm::MemoryBuffer::getMemBuffer(
22380                              "BasedOnStyle: InheritParentConfig\n"
22381                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22382   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22383 
22384   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22385   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22386   ASSERT_TRUE(static_cast<bool>(Style9));
22387   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22388     auto Style = getNoStyle();
22389     Style.ColumnLimit = 20;
22390     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22391     return Style;
22392   }());
22393 
22394   // Test 9.2: with LLVM fallback style
22395   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22396   ASSERT_TRUE(static_cast<bool>(Style9));
22397   ASSERT_EQ(*Style9, [] {
22398     auto Style = getLLVMStyle();
22399     Style.ColumnLimit = 20;
22400     return Style;
22401   }());
22402 
22403   // Test 9.3: with a parent file
22404   ASSERT_TRUE(
22405       FS.addFile("/e/.clang-format", 0,
22406                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
22407                                                   "UseTab: Always")));
22408   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22409   ASSERT_TRUE(static_cast<bool>(Style9));
22410   ASSERT_EQ(*Style9, [] {
22411     auto Style = getGoogleStyle();
22412     Style.ColumnLimit = 20;
22413     Style.UseTab = FormatStyle::UT_Always;
22414     return Style;
22415   }());
22416 
22417   // Test 9.4: propagate more than one level with a parent file.
22418   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
22419     auto Style = getGoogleStyle();
22420     Style.ColumnLimit = 20;
22421     Style.UseTab = FormatStyle::UT_Always;
22422     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22423     return Style;
22424   }();
22425 
22426   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22427   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22428   ASSERT_TRUE(static_cast<bool>(Style9));
22429   ASSERT_EQ(*Style9, SubSubStyle);
22430 
22431   // Test 9.5: use InheritParentConfig as style name
22432   Style9 =
22433       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
22434   ASSERT_TRUE(static_cast<bool>(Style9));
22435   ASSERT_EQ(*Style9, SubSubStyle);
22436 
22437   // Test 9.6: use command line style with inheritance
22438   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
22439                     "none", "", &FS);
22440   ASSERT_TRUE(static_cast<bool>(Style9));
22441   ASSERT_EQ(*Style9, SubSubStyle);
22442 
22443   // Test 9.7: use command line style with inheritance and own config
22444   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
22445                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
22446                     "/e/sub/code.cpp", "none", "", &FS);
22447   ASSERT_TRUE(static_cast<bool>(Style9));
22448   ASSERT_EQ(*Style9, SubSubStyle);
22449 
22450   // Test 9.8: use inheritance from a file without BasedOnStyle
22451   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
22452                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
22453   ASSERT_TRUE(
22454       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
22455                  llvm::MemoryBuffer::getMemBuffer(
22456                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
22457   // Make sure we do not use the fallback style
22458   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
22459   ASSERT_TRUE(static_cast<bool>(Style9));
22460   ASSERT_EQ(*Style9, [] {
22461     auto Style = getLLVMStyle();
22462     Style.ColumnLimit = 123;
22463     return Style;
22464   }());
22465 
22466   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
22467   ASSERT_TRUE(static_cast<bool>(Style9));
22468   ASSERT_EQ(*Style9, [] {
22469     auto Style = getLLVMStyle();
22470     Style.ColumnLimit = 123;
22471     Style.IndentWidth = 7;
22472     return Style;
22473   }());
22474 
22475   // Test 9.9: use inheritance from a specific config file.
22476   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
22477                     "none", "", &FS);
22478   ASSERT_TRUE(static_cast<bool>(Style9));
22479   ASSERT_EQ(*Style9, SubSubStyle);
22480 }
22481 
22482 TEST(FormatStyle, GetStyleOfSpecificFile) {
22483   llvm::vfs::InMemoryFileSystem FS;
22484   // Specify absolute path to a format file in a parent directory.
22485   ASSERT_TRUE(
22486       FS.addFile("/e/.clang-format", 0,
22487                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22488   ASSERT_TRUE(
22489       FS.addFile("/e/explicit.clang-format", 0,
22490                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22491   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
22492                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22493   auto Style = getStyle("file:/e/explicit.clang-format",
22494                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22495   ASSERT_TRUE(static_cast<bool>(Style));
22496   ASSERT_EQ(*Style, getGoogleStyle());
22497 
22498   // Specify relative path to a format file.
22499   ASSERT_TRUE(
22500       FS.addFile("../../e/explicit.clang-format", 0,
22501                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22502   Style = getStyle("file:../../e/explicit.clang-format",
22503                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22504   ASSERT_TRUE(static_cast<bool>(Style));
22505   ASSERT_EQ(*Style, getGoogleStyle());
22506 
22507   // Specify path to a format file that does not exist.
22508   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
22509                    "LLVM", "", &FS);
22510   ASSERT_FALSE(static_cast<bool>(Style));
22511   llvm::consumeError(Style.takeError());
22512 
22513   // Specify path to a file on the filesystem.
22514   SmallString<128> FormatFilePath;
22515   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
22516       "FormatFileTest", "tpl", FormatFilePath);
22517   EXPECT_FALSE((bool)ECF);
22518   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
22519   EXPECT_FALSE((bool)ECF);
22520   FormatFileTest << "BasedOnStyle: Google\n";
22521   FormatFileTest.close();
22522 
22523   SmallString<128> TestFilePath;
22524   std::error_code ECT =
22525       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
22526   EXPECT_FALSE((bool)ECT);
22527   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
22528   CodeFileTest << "int i;\n";
22529   CodeFileTest.close();
22530 
22531   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
22532   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
22533 
22534   llvm::sys::fs::remove(FormatFilePath.c_str());
22535   llvm::sys::fs::remove(TestFilePath.c_str());
22536   ASSERT_TRUE(static_cast<bool>(Style));
22537   ASSERT_EQ(*Style, getGoogleStyle());
22538 }
22539 
22540 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
22541   // Column limit is 20.
22542   std::string Code = "Type *a =\n"
22543                      "    new Type();\n"
22544                      "g(iiiii, 0, jjjjj,\n"
22545                      "  0, kkkkk, 0, mm);\n"
22546                      "int  bad     = format   ;";
22547   std::string Expected = "auto a = new Type();\n"
22548                          "g(iiiii, nullptr,\n"
22549                          "  jjjjj, nullptr,\n"
22550                          "  kkkkk, nullptr,\n"
22551                          "  mm);\n"
22552                          "int  bad     = format   ;";
22553   FileID ID = Context.createInMemoryFile("format.cpp", Code);
22554   tooling::Replacements Replaces = toReplacements(
22555       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
22556                             "auto "),
22557        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
22558                             "nullptr"),
22559        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
22560                             "nullptr"),
22561        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
22562                             "nullptr")});
22563 
22564   FormatStyle Style = getLLVMStyle();
22565   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
22566   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22567   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22568       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22569   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22570   EXPECT_TRUE(static_cast<bool>(Result));
22571   EXPECT_EQ(Expected, *Result);
22572 }
22573 
22574 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
22575   std::string Code = "#include \"a.h\"\n"
22576                      "#include \"c.h\"\n"
22577                      "\n"
22578                      "int main() {\n"
22579                      "  return 0;\n"
22580                      "}";
22581   std::string Expected = "#include \"a.h\"\n"
22582                          "#include \"b.h\"\n"
22583                          "#include \"c.h\"\n"
22584                          "\n"
22585                          "int main() {\n"
22586                          "  return 0;\n"
22587                          "}";
22588   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
22589   tooling::Replacements Replaces = toReplacements(
22590       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
22591                             "#include \"b.h\"\n")});
22592 
22593   FormatStyle Style = getLLVMStyle();
22594   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
22595   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22596   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22597       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22598   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22599   EXPECT_TRUE(static_cast<bool>(Result));
22600   EXPECT_EQ(Expected, *Result);
22601 }
22602 
22603 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
22604   EXPECT_EQ("using std::cin;\n"
22605             "using std::cout;",
22606             format("using std::cout;\n"
22607                    "using std::cin;",
22608                    getGoogleStyle()));
22609 }
22610 
22611 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
22612   FormatStyle Style = getLLVMStyle();
22613   Style.Standard = FormatStyle::LS_Cpp03;
22614   // cpp03 recognize this string as identifier u8 and literal character 'a'
22615   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
22616 }
22617 
22618 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
22619   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
22620   // all modes, including C++11, C++14 and C++17
22621   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
22622 }
22623 
22624 TEST_F(FormatTest, DoNotFormatLikelyXml) {
22625   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
22626   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
22627 }
22628 
22629 TEST_F(FormatTest, StructuredBindings) {
22630   // Structured bindings is a C++17 feature.
22631   // all modes, including C++11, C++14 and C++17
22632   verifyFormat("auto [a, b] = f();");
22633   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
22634   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
22635   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
22636   EXPECT_EQ("auto const volatile [a, b] = f();",
22637             format("auto  const   volatile[a, b] = f();"));
22638   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
22639   EXPECT_EQ("auto &[a, b, c] = f();",
22640             format("auto   &[  a  ,  b,c   ] = f();"));
22641   EXPECT_EQ("auto &&[a, b, c] = f();",
22642             format("auto   &&[  a  ,  b,c   ] = f();"));
22643   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
22644   EXPECT_EQ("auto const volatile &&[a, b] = f();",
22645             format("auto  const  volatile  &&[a, b] = f();"));
22646   EXPECT_EQ("auto const &&[a, b] = f();",
22647             format("auto  const   &&  [a, b] = f();"));
22648   EXPECT_EQ("const auto &[a, b] = f();",
22649             format("const  auto  &  [a, b] = f();"));
22650   EXPECT_EQ("const auto volatile &&[a, b] = f();",
22651             format("const  auto   volatile  &&[a, b] = f();"));
22652   EXPECT_EQ("volatile const auto &&[a, b] = f();",
22653             format("volatile  const  auto   &&[a, b] = f();"));
22654   EXPECT_EQ("const auto &&[a, b] = f();",
22655             format("const  auto  &&  [a, b] = f();"));
22656 
22657   // Make sure we don't mistake structured bindings for lambdas.
22658   FormatStyle PointerMiddle = getLLVMStyle();
22659   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
22660   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
22661   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
22662   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
22663   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
22664   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
22665   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
22666   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
22667   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
22668   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
22669   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
22670   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
22671   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
22672 
22673   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
22674             format("for (const auto   &&   [a, b] : some_range) {\n}"));
22675   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
22676             format("for (const auto   &   [a, b] : some_range) {\n}"));
22677   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
22678             format("for (const auto[a, b] : some_range) {\n}"));
22679   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
22680   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
22681   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
22682   EXPECT_EQ("auto const &[x, y](expr);",
22683             format("auto  const  &  [x,y]  (expr);"));
22684   EXPECT_EQ("auto const &&[x, y](expr);",
22685             format("auto  const  &&  [x,y]  (expr);"));
22686   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
22687   EXPECT_EQ("auto const &[x, y]{expr};",
22688             format("auto  const  &  [x,y]  {expr};"));
22689   EXPECT_EQ("auto const &&[x, y]{expr};",
22690             format("auto  const  &&  [x,y]  {expr};"));
22691 
22692   FormatStyle Spaces = getLLVMStyle();
22693   Spaces.SpacesInSquareBrackets = true;
22694   verifyFormat("auto [ a, b ] = f();", Spaces);
22695   verifyFormat("auto &&[ a, b ] = f();", Spaces);
22696   verifyFormat("auto &[ a, b ] = f();", Spaces);
22697   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
22698   verifyFormat("auto const &[ a, b ] = f();", Spaces);
22699 }
22700 
22701 TEST_F(FormatTest, FileAndCode) {
22702   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
22703   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
22704   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
22705   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
22706   EXPECT_EQ(FormatStyle::LK_ObjC,
22707             guessLanguage("foo.h", "@interface Foo\n@end\n"));
22708   EXPECT_EQ(
22709       FormatStyle::LK_ObjC,
22710       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
22711   EXPECT_EQ(FormatStyle::LK_ObjC,
22712             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
22713   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
22714   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
22715   EXPECT_EQ(FormatStyle::LK_ObjC,
22716             guessLanguage("foo", "@interface Foo\n@end\n"));
22717   EXPECT_EQ(FormatStyle::LK_ObjC,
22718             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
22719   EXPECT_EQ(
22720       FormatStyle::LK_ObjC,
22721       guessLanguage("foo.h",
22722                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
22723   EXPECT_EQ(
22724       FormatStyle::LK_Cpp,
22725       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
22726 }
22727 
22728 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
22729   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
22730   EXPECT_EQ(FormatStyle::LK_ObjC,
22731             guessLanguage("foo.h", "array[[calculator getIndex]];"));
22732   EXPECT_EQ(FormatStyle::LK_Cpp,
22733             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
22734   EXPECT_EQ(
22735       FormatStyle::LK_Cpp,
22736       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
22737   EXPECT_EQ(FormatStyle::LK_ObjC,
22738             guessLanguage("foo.h", "[[noreturn foo] bar];"));
22739   EXPECT_EQ(FormatStyle::LK_Cpp,
22740             guessLanguage("foo.h", "[[clang::fallthrough]];"));
22741   EXPECT_EQ(FormatStyle::LK_ObjC,
22742             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
22743   EXPECT_EQ(FormatStyle::LK_Cpp,
22744             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
22745   EXPECT_EQ(FormatStyle::LK_Cpp,
22746             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
22747   EXPECT_EQ(FormatStyle::LK_ObjC,
22748             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
22749   EXPECT_EQ(FormatStyle::LK_Cpp,
22750             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
22751   EXPECT_EQ(
22752       FormatStyle::LK_Cpp,
22753       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
22754   EXPECT_EQ(
22755       FormatStyle::LK_Cpp,
22756       guessLanguage("foo.h",
22757                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
22758   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
22759 }
22760 
22761 TEST_F(FormatTest, GuessLanguageWithCaret) {
22762   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
22763   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
22764   EXPECT_EQ(FormatStyle::LK_ObjC,
22765             guessLanguage("foo.h", "int(^)(char, float);"));
22766   EXPECT_EQ(FormatStyle::LK_ObjC,
22767             guessLanguage("foo.h", "int(^foo)(char, float);"));
22768   EXPECT_EQ(FormatStyle::LK_ObjC,
22769             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
22770   EXPECT_EQ(FormatStyle::LK_ObjC,
22771             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
22772   EXPECT_EQ(
22773       FormatStyle::LK_ObjC,
22774       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
22775 }
22776 
22777 TEST_F(FormatTest, GuessLanguageWithPragmas) {
22778   EXPECT_EQ(FormatStyle::LK_Cpp,
22779             guessLanguage("foo.h", "__pragma(warning(disable:))"));
22780   EXPECT_EQ(FormatStyle::LK_Cpp,
22781             guessLanguage("foo.h", "#pragma(warning(disable:))"));
22782   EXPECT_EQ(FormatStyle::LK_Cpp,
22783             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
22784 }
22785 
22786 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
22787   // ASM symbolic names are identifiers that must be surrounded by [] without
22788   // space in between:
22789   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
22790 
22791   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
22792   verifyFormat(R"(//
22793 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
22794 )");
22795 
22796   // A list of several ASM symbolic names.
22797   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
22798 
22799   // ASM symbolic names in inline ASM with inputs and outputs.
22800   verifyFormat(R"(//
22801 asm("cmoveq %1, %2, %[result]"
22802     : [result] "=r"(result)
22803     : "r"(test), "r"(new), "[result]"(old));
22804 )");
22805 
22806   // ASM symbolic names in inline ASM with no outputs.
22807   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
22808 }
22809 
22810 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
22811   EXPECT_EQ(FormatStyle::LK_Cpp,
22812             guessLanguage("foo.h", "void f() {\n"
22813                                    "  asm (\"mov %[e], %[d]\"\n"
22814                                    "     : [d] \"=rm\" (d)\n"
22815                                    "       [e] \"rm\" (*e));\n"
22816                                    "}"));
22817   EXPECT_EQ(FormatStyle::LK_Cpp,
22818             guessLanguage("foo.h", "void f() {\n"
22819                                    "  _asm (\"mov %[e], %[d]\"\n"
22820                                    "     : [d] \"=rm\" (d)\n"
22821                                    "       [e] \"rm\" (*e));\n"
22822                                    "}"));
22823   EXPECT_EQ(FormatStyle::LK_Cpp,
22824             guessLanguage("foo.h", "void f() {\n"
22825                                    "  __asm (\"mov %[e], %[d]\"\n"
22826                                    "     : [d] \"=rm\" (d)\n"
22827                                    "       [e] \"rm\" (*e));\n"
22828                                    "}"));
22829   EXPECT_EQ(FormatStyle::LK_Cpp,
22830             guessLanguage("foo.h", "void f() {\n"
22831                                    "  __asm__ (\"mov %[e], %[d]\"\n"
22832                                    "     : [d] \"=rm\" (d)\n"
22833                                    "       [e] \"rm\" (*e));\n"
22834                                    "}"));
22835   EXPECT_EQ(FormatStyle::LK_Cpp,
22836             guessLanguage("foo.h", "void f() {\n"
22837                                    "  asm (\"mov %[e], %[d]\"\n"
22838                                    "     : [d] \"=rm\" (d),\n"
22839                                    "       [e] \"rm\" (*e));\n"
22840                                    "}"));
22841   EXPECT_EQ(FormatStyle::LK_Cpp,
22842             guessLanguage("foo.h", "void f() {\n"
22843                                    "  asm volatile (\"mov %[e], %[d]\"\n"
22844                                    "     : [d] \"=rm\" (d)\n"
22845                                    "       [e] \"rm\" (*e));\n"
22846                                    "}"));
22847 }
22848 
22849 TEST_F(FormatTest, GuessLanguageWithChildLines) {
22850   EXPECT_EQ(FormatStyle::LK_Cpp,
22851             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
22852   EXPECT_EQ(FormatStyle::LK_ObjC,
22853             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
22854   EXPECT_EQ(
22855       FormatStyle::LK_Cpp,
22856       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
22857   EXPECT_EQ(
22858       FormatStyle::LK_ObjC,
22859       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
22860 }
22861 
22862 TEST_F(FormatTest, TypenameMacros) {
22863   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
22864 
22865   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
22866   FormatStyle Google = getGoogleStyleWithColumns(0);
22867   Google.TypenameMacros = TypenameMacros;
22868   verifyFormat("struct foo {\n"
22869                "  int bar;\n"
22870                "  TAILQ_ENTRY(a) bleh;\n"
22871                "};",
22872                Google);
22873 
22874   FormatStyle Macros = getLLVMStyle();
22875   Macros.TypenameMacros = TypenameMacros;
22876 
22877   verifyFormat("STACK_OF(int) a;", Macros);
22878   verifyFormat("STACK_OF(int) *a;", Macros);
22879   verifyFormat("STACK_OF(int const *) *a;", Macros);
22880   verifyFormat("STACK_OF(int *const) *a;", Macros);
22881   verifyFormat("STACK_OF(int, string) a;", Macros);
22882   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
22883   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
22884   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
22885   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
22886   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
22887   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
22888 
22889   Macros.PointerAlignment = FormatStyle::PAS_Left;
22890   verifyFormat("STACK_OF(int)* a;", Macros);
22891   verifyFormat("STACK_OF(int*)* a;", Macros);
22892   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
22893   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
22894   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
22895 }
22896 
22897 TEST_F(FormatTest, AtomicQualifier) {
22898   // Check that we treate _Atomic as a type and not a function call
22899   FormatStyle Google = getGoogleStyleWithColumns(0);
22900   verifyFormat("struct foo {\n"
22901                "  int a1;\n"
22902                "  _Atomic(a) a2;\n"
22903                "  _Atomic(_Atomic(int) *const) a3;\n"
22904                "};",
22905                Google);
22906   verifyFormat("_Atomic(uint64_t) a;");
22907   verifyFormat("_Atomic(uint64_t) *a;");
22908   verifyFormat("_Atomic(uint64_t const *) *a;");
22909   verifyFormat("_Atomic(uint64_t *const) *a;");
22910   verifyFormat("_Atomic(const uint64_t *) *a;");
22911   verifyFormat("_Atomic(uint64_t) a;");
22912   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
22913   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
22914   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
22915   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
22916 
22917   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
22918   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
22919   FormatStyle Style = getLLVMStyle();
22920   Style.PointerAlignment = FormatStyle::PAS_Left;
22921   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
22922   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
22923   verifyFormat("_Atomic(int)* a;", Style);
22924   verifyFormat("_Atomic(int*)* a;", Style);
22925   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
22926 
22927   Style.SpacesInCStyleCastParentheses = true;
22928   Style.SpacesInParentheses = false;
22929   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
22930   Style.SpacesInCStyleCastParentheses = false;
22931   Style.SpacesInParentheses = true;
22932   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
22933   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
22934 }
22935 
22936 TEST_F(FormatTest, AmbersandInLamda) {
22937   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
22938   FormatStyle AlignStyle = getLLVMStyle();
22939   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
22940   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22941   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
22942   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22943 }
22944 
22945 TEST_F(FormatTest, SpacesInConditionalStatement) {
22946   FormatStyle Spaces = getLLVMStyle();
22947   Spaces.IfMacros.clear();
22948   Spaces.IfMacros.push_back("MYIF");
22949   Spaces.SpacesInConditionalStatement = true;
22950   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
22951   verifyFormat("if ( !a )\n  return;", Spaces);
22952   verifyFormat("if ( a )\n  return;", Spaces);
22953   verifyFormat("if constexpr ( a )\n  return;", Spaces);
22954   verifyFormat("MYIF ( a )\n  return;", Spaces);
22955   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
22956   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
22957   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
22958   verifyFormat("while ( a )\n  return;", Spaces);
22959   verifyFormat("while ( (a && b) )\n  return;", Spaces);
22960   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
22961   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
22962   // Check that space on the left of "::" is inserted as expected at beginning
22963   // of condition.
22964   verifyFormat("while ( ::func() )\n  return;", Spaces);
22965 
22966   // Check impact of ControlStatementsExceptControlMacros is honored.
22967   Spaces.SpaceBeforeParens =
22968       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
22969   verifyFormat("MYIF( a )\n  return;", Spaces);
22970   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
22971   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
22972 }
22973 
22974 TEST_F(FormatTest, AlternativeOperators) {
22975   // Test case for ensuring alternate operators are not
22976   // combined with their right most neighbour.
22977   verifyFormat("int a and b;");
22978   verifyFormat("int a and_eq b;");
22979   verifyFormat("int a bitand b;");
22980   verifyFormat("int a bitor b;");
22981   verifyFormat("int a compl b;");
22982   verifyFormat("int a not b;");
22983   verifyFormat("int a not_eq b;");
22984   verifyFormat("int a or b;");
22985   verifyFormat("int a xor b;");
22986   verifyFormat("int a xor_eq b;");
22987   verifyFormat("return this not_eq bitand other;");
22988   verifyFormat("bool operator not_eq(const X bitand other)");
22989 
22990   verifyFormat("int a and 5;");
22991   verifyFormat("int a and_eq 5;");
22992   verifyFormat("int a bitand 5;");
22993   verifyFormat("int a bitor 5;");
22994   verifyFormat("int a compl 5;");
22995   verifyFormat("int a not 5;");
22996   verifyFormat("int a not_eq 5;");
22997   verifyFormat("int a or 5;");
22998   verifyFormat("int a xor 5;");
22999   verifyFormat("int a xor_eq 5;");
23000 
23001   verifyFormat("int a compl(5);");
23002   verifyFormat("int a not(5);");
23003 
23004   /* FIXME handle alternate tokens
23005    * https://en.cppreference.com/w/cpp/language/operator_alternative
23006   // alternative tokens
23007   verifyFormat("compl foo();");     //  ~foo();
23008   verifyFormat("foo() <%%>;");      // foo();
23009   verifyFormat("void foo() <%%>;"); // void foo(){}
23010   verifyFormat("int a <:1:>;");     // int a[1];[
23011   verifyFormat("%:define ABC abc"); // #define ABC abc
23012   verifyFormat("%:%:");             // ##
23013   */
23014 }
23015 
23016 TEST_F(FormatTest, STLWhileNotDefineChed) {
23017   verifyFormat("#if defined(while)\n"
23018                "#define while EMIT WARNING C4005\n"
23019                "#endif // while");
23020 }
23021 
23022 TEST_F(FormatTest, OperatorSpacing) {
23023   FormatStyle Style = getLLVMStyle();
23024   Style.PointerAlignment = FormatStyle::PAS_Right;
23025   verifyFormat("Foo::operator*();", Style);
23026   verifyFormat("Foo::operator void *();", Style);
23027   verifyFormat("Foo::operator void **();", Style);
23028   verifyFormat("Foo::operator void *&();", Style);
23029   verifyFormat("Foo::operator void *&&();", Style);
23030   verifyFormat("Foo::operator void const *();", Style);
23031   verifyFormat("Foo::operator void const **();", Style);
23032   verifyFormat("Foo::operator void const *&();", Style);
23033   verifyFormat("Foo::operator void const *&&();", Style);
23034   verifyFormat("Foo::operator()(void *);", Style);
23035   verifyFormat("Foo::operator*(void *);", Style);
23036   verifyFormat("Foo::operator*();", Style);
23037   verifyFormat("Foo::operator**();", Style);
23038   verifyFormat("Foo::operator&();", Style);
23039   verifyFormat("Foo::operator<int> *();", Style);
23040   verifyFormat("Foo::operator<Foo> *();", Style);
23041   verifyFormat("Foo::operator<int> **();", Style);
23042   verifyFormat("Foo::operator<Foo> **();", Style);
23043   verifyFormat("Foo::operator<int> &();", Style);
23044   verifyFormat("Foo::operator<Foo> &();", Style);
23045   verifyFormat("Foo::operator<int> &&();", Style);
23046   verifyFormat("Foo::operator<Foo> &&();", Style);
23047   verifyFormat("Foo::operator<int> *&();", Style);
23048   verifyFormat("Foo::operator<Foo> *&();", Style);
23049   verifyFormat("Foo::operator<int> *&&();", Style);
23050   verifyFormat("Foo::operator<Foo> *&&();", Style);
23051   verifyFormat("operator*(int (*)(), class Foo);", Style);
23052 
23053   verifyFormat("Foo::operator&();", Style);
23054   verifyFormat("Foo::operator void &();", Style);
23055   verifyFormat("Foo::operator void const &();", Style);
23056   verifyFormat("Foo::operator()(void &);", Style);
23057   verifyFormat("Foo::operator&(void &);", Style);
23058   verifyFormat("Foo::operator&();", Style);
23059   verifyFormat("operator&(int (&)(), class Foo);", Style);
23060   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23061 
23062   verifyFormat("Foo::operator&&();", Style);
23063   verifyFormat("Foo::operator**();", Style);
23064   verifyFormat("Foo::operator void &&();", Style);
23065   verifyFormat("Foo::operator void const &&();", Style);
23066   verifyFormat("Foo::operator()(void &&);", Style);
23067   verifyFormat("Foo::operator&&(void &&);", Style);
23068   verifyFormat("Foo::operator&&();", Style);
23069   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23070   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23071   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23072                Style);
23073   verifyFormat("operator void **()", Style);
23074   verifyFormat("operator const FooRight<Object> &()", Style);
23075   verifyFormat("operator const FooRight<Object> *()", Style);
23076   verifyFormat("operator const FooRight<Object> **()", Style);
23077   verifyFormat("operator const FooRight<Object> *&()", Style);
23078   verifyFormat("operator const FooRight<Object> *&&()", Style);
23079 
23080   Style.PointerAlignment = FormatStyle::PAS_Left;
23081   verifyFormat("Foo::operator*();", Style);
23082   verifyFormat("Foo::operator**();", Style);
23083   verifyFormat("Foo::operator void*();", Style);
23084   verifyFormat("Foo::operator void**();", Style);
23085   verifyFormat("Foo::operator void*&();", Style);
23086   verifyFormat("Foo::operator void*&&();", Style);
23087   verifyFormat("Foo::operator void const*();", Style);
23088   verifyFormat("Foo::operator void const**();", Style);
23089   verifyFormat("Foo::operator void const*&();", Style);
23090   verifyFormat("Foo::operator void const*&&();", Style);
23091   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23092   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23093   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23094   verifyFormat("Foo::operator()(void*);", Style);
23095   verifyFormat("Foo::operator*(void*);", Style);
23096   verifyFormat("Foo::operator*();", Style);
23097   verifyFormat("Foo::operator<int>*();", Style);
23098   verifyFormat("Foo::operator<Foo>*();", Style);
23099   verifyFormat("Foo::operator<int>**();", Style);
23100   verifyFormat("Foo::operator<Foo>**();", Style);
23101   verifyFormat("Foo::operator<Foo>*&();", Style);
23102   verifyFormat("Foo::operator<int>&();", Style);
23103   verifyFormat("Foo::operator<Foo>&();", Style);
23104   verifyFormat("Foo::operator<int>&&();", Style);
23105   verifyFormat("Foo::operator<Foo>&&();", Style);
23106   verifyFormat("Foo::operator<int>*&();", Style);
23107   verifyFormat("Foo::operator<Foo>*&();", Style);
23108   verifyFormat("operator*(int (*)(), class Foo);", Style);
23109 
23110   verifyFormat("Foo::operator&();", Style);
23111   verifyFormat("Foo::operator void&();", Style);
23112   verifyFormat("Foo::operator void const&();", Style);
23113   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23114   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23115   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
23116   verifyFormat("Foo::operator()(void&);", Style);
23117   verifyFormat("Foo::operator&(void&);", Style);
23118   verifyFormat("Foo::operator&();", Style);
23119   verifyFormat("operator&(int (&)(), class Foo);", Style);
23120   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23121   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23122 
23123   verifyFormat("Foo::operator&&();", Style);
23124   verifyFormat("Foo::operator void&&();", Style);
23125   verifyFormat("Foo::operator void const&&();", Style);
23126   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23127   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23128   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23129   verifyFormat("Foo::operator()(void&&);", Style);
23130   verifyFormat("Foo::operator&&(void&&);", Style);
23131   verifyFormat("Foo::operator&&();", Style);
23132   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23133   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23134   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23135                Style);
23136   verifyFormat("operator void**()", Style);
23137   verifyFormat("operator const FooLeft<Object>&()", Style);
23138   verifyFormat("operator const FooLeft<Object>*()", Style);
23139   verifyFormat("operator const FooLeft<Object>**()", Style);
23140   verifyFormat("operator const FooLeft<Object>*&()", Style);
23141   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23142 
23143   // PR45107
23144   verifyFormat("operator Vector<String>&();", Style);
23145   verifyFormat("operator const Vector<String>&();", Style);
23146   verifyFormat("operator foo::Bar*();", Style);
23147   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23148   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23149                Style);
23150 
23151   Style.PointerAlignment = FormatStyle::PAS_Middle;
23152   verifyFormat("Foo::operator*();", Style);
23153   verifyFormat("Foo::operator void *();", Style);
23154   verifyFormat("Foo::operator()(void *);", Style);
23155   verifyFormat("Foo::operator*(void *);", Style);
23156   verifyFormat("Foo::operator*();", Style);
23157   verifyFormat("operator*(int (*)(), class Foo);", Style);
23158 
23159   verifyFormat("Foo::operator&();", Style);
23160   verifyFormat("Foo::operator void &();", Style);
23161   verifyFormat("Foo::operator void const &();", Style);
23162   verifyFormat("Foo::operator()(void &);", Style);
23163   verifyFormat("Foo::operator&(void &);", Style);
23164   verifyFormat("Foo::operator&();", Style);
23165   verifyFormat("operator&(int (&)(), class Foo);", Style);
23166 
23167   verifyFormat("Foo::operator&&();", Style);
23168   verifyFormat("Foo::operator void &&();", Style);
23169   verifyFormat("Foo::operator void const &&();", Style);
23170   verifyFormat("Foo::operator()(void &&);", Style);
23171   verifyFormat("Foo::operator&&(void &&);", Style);
23172   verifyFormat("Foo::operator&&();", Style);
23173   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23174 }
23175 
23176 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23177   FormatStyle Style = getLLVMStyle();
23178   // PR46157
23179   verifyFormat("foo(operator+, -42);", Style);
23180   verifyFormat("foo(operator++, -42);", Style);
23181   verifyFormat("foo(operator--, -42);", Style);
23182   verifyFormat("foo(-42, operator--);", Style);
23183   verifyFormat("foo(-42, operator, );", Style);
23184   verifyFormat("foo(operator, , -42);", Style);
23185 }
23186 
23187 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23188   FormatStyle Style = getLLVMStyle();
23189   Style.WhitespaceSensitiveMacros.push_back("FOO");
23190 
23191   // Don't use the helpers here, since 'mess up' will change the whitespace
23192   // and these are all whitespace sensitive by definition
23193   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23194             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23195   EXPECT_EQ(
23196       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23197       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23198   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23199             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23200   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23201             "       Still=Intentional);",
23202             format("FOO(String-ized&Messy+But,: :\n"
23203                    "       Still=Intentional);",
23204                    Style));
23205   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
23206   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
23207             "       Still=Intentional);",
23208             format("FOO(String-ized=&Messy+But,: :\n"
23209                    "       Still=Intentional);",
23210                    Style));
23211 
23212   Style.ColumnLimit = 21;
23213   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23214             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23215 }
23216 
23217 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23218   // These tests are not in NamespaceFixer because that doesn't
23219   // test its interaction with line wrapping
23220   FormatStyle Style = getLLVMStyleWithColumns(80);
23221   verifyFormat("namespace {\n"
23222                "int i;\n"
23223                "int j;\n"
23224                "} // namespace",
23225                Style);
23226 
23227   verifyFormat("namespace AAA {\n"
23228                "int i;\n"
23229                "int j;\n"
23230                "} // namespace AAA",
23231                Style);
23232 
23233   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23234             "int i;\n"
23235             "int j;\n"
23236             "} // namespace Averyveryveryverylongnamespace",
23237             format("namespace Averyveryveryverylongnamespace {\n"
23238                    "int i;\n"
23239                    "int j;\n"
23240                    "}",
23241                    Style));
23242 
23243   EXPECT_EQ(
23244       "namespace "
23245       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23246       "    went::mad::now {\n"
23247       "int i;\n"
23248       "int j;\n"
23249       "} // namespace\n"
23250       "  // "
23251       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23252       "went::mad::now",
23253       format("namespace "
23254              "would::it::save::you::a::lot::of::time::if_::i::"
23255              "just::gave::up::and_::went::mad::now {\n"
23256              "int i;\n"
23257              "int j;\n"
23258              "}",
23259              Style));
23260 
23261   // This used to duplicate the comment again and again on subsequent runs
23262   EXPECT_EQ(
23263       "namespace "
23264       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23265       "    went::mad::now {\n"
23266       "int i;\n"
23267       "int j;\n"
23268       "} // namespace\n"
23269       "  // "
23270       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23271       "went::mad::now",
23272       format("namespace "
23273              "would::it::save::you::a::lot::of::time::if_::i::"
23274              "just::gave::up::and_::went::mad::now {\n"
23275              "int i;\n"
23276              "int j;\n"
23277              "} // namespace\n"
23278              "  // "
23279              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23280              "and_::went::mad::now",
23281              Style));
23282 }
23283 
23284 TEST_F(FormatTest, LikelyUnlikely) {
23285   FormatStyle Style = getLLVMStyle();
23286 
23287   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23288                "  return 29;\n"
23289                "}",
23290                Style);
23291 
23292   verifyFormat("if (argc > 5) [[likely]] {\n"
23293                "  return 29;\n"
23294                "}",
23295                Style);
23296 
23297   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23298                "  return 29;\n"
23299                "} else [[likely]] {\n"
23300                "  return 42;\n"
23301                "}\n",
23302                Style);
23303 
23304   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23305                "  return 29;\n"
23306                "} else if (argc > 10) [[likely]] {\n"
23307                "  return 99;\n"
23308                "} else {\n"
23309                "  return 42;\n"
23310                "}\n",
23311                Style);
23312 
23313   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23314                "  return 29;\n"
23315                "}",
23316                Style);
23317 
23318   verifyFormat("if (argc > 5) [[unlikely]]\n"
23319                "  return 29;\n",
23320                Style);
23321   verifyFormat("if (argc > 5) [[likely]]\n"
23322                "  return 29;\n",
23323                Style);
23324 
23325   Style.AttributeMacros.push_back("UNLIKELY");
23326   Style.AttributeMacros.push_back("LIKELY");
23327   verifyFormat("if (argc > 5) UNLIKELY\n"
23328                "  return 29;\n",
23329                Style);
23330 
23331   verifyFormat("if (argc > 5) UNLIKELY {\n"
23332                "  return 29;\n"
23333                "}",
23334                Style);
23335   verifyFormat("if (argc > 5) UNLIKELY {\n"
23336                "  return 29;\n"
23337                "} else [[likely]] {\n"
23338                "  return 42;\n"
23339                "}\n",
23340                Style);
23341   verifyFormat("if (argc > 5) UNLIKELY {\n"
23342                "  return 29;\n"
23343                "} else LIKELY {\n"
23344                "  return 42;\n"
23345                "}\n",
23346                Style);
23347   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23348                "  return 29;\n"
23349                "} else LIKELY {\n"
23350                "  return 42;\n"
23351                "}\n",
23352                Style);
23353 }
23354 
23355 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23356   verifyFormat("Constructor()\n"
23357                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23358                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
23359                "aaaaaaaaaaaaaaaaaat))");
23360   verifyFormat("Constructor()\n"
23361                "    : aaaaaaaaaaaaa(aaaaaa), "
23362                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
23363 
23364   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
23365   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
23366   verifyFormat("Constructor()\n"
23367                "    : aaaaaa(aaaaaa),\n"
23368                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23369                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
23370                StyleWithWhitespacePenalty);
23371   verifyFormat("Constructor()\n"
23372                "    : aaaaaaaaaaaaa(aaaaaa), "
23373                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
23374                StyleWithWhitespacePenalty);
23375 }
23376 
23377 TEST_F(FormatTest, LLVMDefaultStyle) {
23378   FormatStyle Style = getLLVMStyle();
23379   verifyFormat("extern \"C\" {\n"
23380                "int foo();\n"
23381                "}",
23382                Style);
23383 }
23384 TEST_F(FormatTest, GNUDefaultStyle) {
23385   FormatStyle Style = getGNUStyle();
23386   verifyFormat("extern \"C\"\n"
23387                "{\n"
23388                "  int foo ();\n"
23389                "}",
23390                Style);
23391 }
23392 TEST_F(FormatTest, MozillaDefaultStyle) {
23393   FormatStyle Style = getMozillaStyle();
23394   verifyFormat("extern \"C\"\n"
23395                "{\n"
23396                "  int foo();\n"
23397                "}",
23398                Style);
23399 }
23400 TEST_F(FormatTest, GoogleDefaultStyle) {
23401   FormatStyle Style = getGoogleStyle();
23402   verifyFormat("extern \"C\" {\n"
23403                "int foo();\n"
23404                "}",
23405                Style);
23406 }
23407 TEST_F(FormatTest, ChromiumDefaultStyle) {
23408   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
23409   verifyFormat("extern \"C\" {\n"
23410                "int foo();\n"
23411                "}",
23412                Style);
23413 }
23414 TEST_F(FormatTest, MicrosoftDefaultStyle) {
23415   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
23416   verifyFormat("extern \"C\"\n"
23417                "{\n"
23418                "    int foo();\n"
23419                "}",
23420                Style);
23421 }
23422 TEST_F(FormatTest, WebKitDefaultStyle) {
23423   FormatStyle Style = getWebKitStyle();
23424   verifyFormat("extern \"C\" {\n"
23425                "int foo();\n"
23426                "}",
23427                Style);
23428 }
23429 
23430 TEST_F(FormatTest, Concepts) {
23431   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
23432             FormatStyle::BBCDS_Always);
23433   verifyFormat("template <typename T>\n"
23434                "concept True = true;");
23435 
23436   verifyFormat("template <typename T>\n"
23437                "concept C = ((false || foo()) && C2<T>) ||\n"
23438                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
23439                getLLVMStyleWithColumns(60));
23440 
23441   verifyFormat("template <typename T>\n"
23442                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
23443                "sizeof(T) <= 8;");
23444 
23445   verifyFormat("template <typename T>\n"
23446                "concept DelayedCheck = true && requires(T t) {\n"
23447                "                                 t.bar();\n"
23448                "                                 t.baz();\n"
23449                "                               } && sizeof(T) <= 8;");
23450 
23451   verifyFormat("template <typename T>\n"
23452                "concept DelayedCheck = true && requires(T t) { // Comment\n"
23453                "                                 t.bar();\n"
23454                "                                 t.baz();\n"
23455                "                               } && sizeof(T) <= 8;");
23456 
23457   verifyFormat("template <typename T>\n"
23458                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
23459                "sizeof(T) <= 8;");
23460 
23461   verifyFormat("template <typename T>\n"
23462                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
23463                "&& sizeof(T) <= 8;");
23464 
23465   verifyFormat(
23466       "template <typename T>\n"
23467       "concept DelayedCheck = static_cast<bool>(0) ||\n"
23468       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23469 
23470   verifyFormat("template <typename T>\n"
23471                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
23472                "&& sizeof(T) <= 8;");
23473 
23474   verifyFormat(
23475       "template <typename T>\n"
23476       "concept DelayedCheck = (bool)(0) ||\n"
23477       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23478 
23479   verifyFormat("template <typename T>\n"
23480                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
23481                "&& sizeof(T) <= 8;");
23482 
23483   verifyFormat("template <typename T>\n"
23484                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
23485                "sizeof(T) <= 8;");
23486 
23487   verifyFormat("template <typename T>\n"
23488                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
23489                "               requires(T t) {\n"
23490                "                 t.bar();\n"
23491                "                 t.baz();\n"
23492                "               } && sizeof(T) <= 8 && !(4 < 3);",
23493                getLLVMStyleWithColumns(60));
23494 
23495   verifyFormat("template <typename T>\n"
23496                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
23497 
23498   verifyFormat("template <typename T>\n"
23499                "concept C = foo();");
23500 
23501   verifyFormat("template <typename T>\n"
23502                "concept C = foo(T());");
23503 
23504   verifyFormat("template <typename T>\n"
23505                "concept C = foo(T{});");
23506 
23507   verifyFormat("template <typename T>\n"
23508                "concept Size = V<sizeof(T)>::Value > 5;");
23509 
23510   verifyFormat("template <typename T>\n"
23511                "concept True = S<T>::Value;");
23512 
23513   verifyFormat(
23514       "template <typename T>\n"
23515       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
23516       "            sizeof(T) <= 8;");
23517 
23518   // FIXME: This is misformatted because the fake l paren starts at bool, not at
23519   // the lambda l square.
23520   verifyFormat("template <typename T>\n"
23521                "concept C = [] -> bool { return true; }() && requires(T t) { "
23522                "t.bar(); } &&\n"
23523                "                      sizeof(T) <= 8;");
23524 
23525   verifyFormat(
23526       "template <typename T>\n"
23527       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
23528       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23529 
23530   verifyFormat("template <typename T>\n"
23531                "concept C = decltype([]() { return std::true_type{}; "
23532                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
23533                getLLVMStyleWithColumns(120));
23534 
23535   verifyFormat("template <typename T>\n"
23536                "concept C = decltype([]() -> std::true_type { return {}; "
23537                "}())::value &&\n"
23538                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23539 
23540   verifyFormat("template <typename T>\n"
23541                "concept C = true;\n"
23542                "Foo Bar;");
23543 
23544   verifyFormat("template <typename T>\n"
23545                "concept Hashable = requires(T a) {\n"
23546                "                     { std::hash<T>{}(a) } -> "
23547                "std::convertible_to<std::size_t>;\n"
23548                "                   };");
23549 
23550   verifyFormat(
23551       "template <typename T>\n"
23552       "concept EqualityComparable = requires(T a, T b) {\n"
23553       "                               { a == b } -> std::same_as<bool>;\n"
23554       "                             };");
23555 
23556   verifyFormat(
23557       "template <typename T>\n"
23558       "concept EqualityComparable = requires(T a, T b) {\n"
23559       "                               { a == b } -> std::same_as<bool>;\n"
23560       "                               { a != b } -> std::same_as<bool>;\n"
23561       "                             };");
23562 
23563   verifyFormat("template <typename T>\n"
23564                "concept WeakEqualityComparable = requires(T a, T b) {\n"
23565                "                                   { a == b };\n"
23566                "                                   { a != b };\n"
23567                "                                 };");
23568 
23569   verifyFormat("template <typename T>\n"
23570                "concept HasSizeT = requires { typename T::size_t; };");
23571 
23572   verifyFormat("template <typename T>\n"
23573                "concept Semiregular =\n"
23574                "    DefaultConstructible<T> && CopyConstructible<T> && "
23575                "CopyAssignable<T> &&\n"
23576                "    requires(T a, std::size_t n) {\n"
23577                "      requires Same<T *, decltype(&a)>;\n"
23578                "      { a.~T() } noexcept;\n"
23579                "      requires Same<T *, decltype(new T)>;\n"
23580                "      requires Same<T *, decltype(new T[n])>;\n"
23581                "      { delete new T; };\n"
23582                "      { delete new T[n]; };\n"
23583                "    };");
23584 
23585   verifyFormat("template <typename T>\n"
23586                "concept Semiregular =\n"
23587                "    requires(T a, std::size_t n) {\n"
23588                "      requires Same<T *, decltype(&a)>;\n"
23589                "      { a.~T() } noexcept;\n"
23590                "      requires Same<T *, decltype(new T)>;\n"
23591                "      requires Same<T *, decltype(new T[n])>;\n"
23592                "      { delete new T; };\n"
23593                "      { delete new T[n]; };\n"
23594                "      { new T } -> std::same_as<T *>;\n"
23595                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
23596                "CopyAssignable<T>;");
23597 
23598   verifyFormat(
23599       "template <typename T>\n"
23600       "concept Semiregular =\n"
23601       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
23602       "                                 requires Same<T *, decltype(&a)>;\n"
23603       "                                 { a.~T() } noexcept;\n"
23604       "                                 requires Same<T *, decltype(new T)>;\n"
23605       "                                 requires Same<T *, decltype(new "
23606       "T[n])>;\n"
23607       "                                 { delete new T; };\n"
23608       "                                 { delete new T[n]; };\n"
23609       "                               } && CopyConstructible<T> && "
23610       "CopyAssignable<T>;");
23611 
23612   verifyFormat("template <typename T>\n"
23613                "concept Two = requires(T t) {\n"
23614                "                { t.foo() } -> std::same_as<Bar>;\n"
23615                "              } && requires(T &&t) {\n"
23616                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
23617                "                   };");
23618 
23619   verifyFormat(
23620       "template <typename T>\n"
23621       "concept C = requires(T x) {\n"
23622       "              { *x } -> std::convertible_to<typename T::inner>;\n"
23623       "              { x + 1 } noexcept -> std::same_as<int>;\n"
23624       "              { x * 1 } -> std::convertible_to<T>;\n"
23625       "            };");
23626 
23627   verifyFormat(
23628       "template <typename T, typename U = T>\n"
23629       "concept Swappable = requires(T &&t, U &&u) {\n"
23630       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
23631       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
23632       "                    };");
23633 
23634   verifyFormat("template <typename T, typename U>\n"
23635                "concept Common = requires(T &&t, U &&u) {\n"
23636                "                   typename CommonType<T, U>;\n"
23637                "                   { CommonType<T, U>(std::forward<T>(t)) };\n"
23638                "                 };");
23639 
23640   verifyFormat("template <typename T, typename U>\n"
23641                "concept Common = requires(T &&t, U &&u) {\n"
23642                "                   typename CommonType<T, U>;\n"
23643                "                   { CommonType<T, U>{std::forward<T>(t)} };\n"
23644                "                 };");
23645 
23646   verifyFormat(
23647       "template <typename T>\n"
23648       "concept C = requires(T t) {\n"
23649       "              requires Bar<T> && Foo<T>;\n"
23650       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
23651       "            };");
23652 
23653   verifyFormat("template <typename T>\n"
23654                "concept HasFoo = requires(T t) {\n"
23655                "                   { t.foo() };\n"
23656                "                   t.foo();\n"
23657                "                 };\n"
23658                "template <typename T>\n"
23659                "concept HasBar = requires(T t) {\n"
23660                "                   { t.bar() };\n"
23661                "                   t.bar();\n"
23662                "                 };");
23663 
23664   verifyFormat("template <typename T>\n"
23665                "concept Large = sizeof(T) > 10;");
23666 
23667   verifyFormat("template <typename T, typename U>\n"
23668                "concept FooableWith = requires(T t, U u) {\n"
23669                "                        typename T::foo_type;\n"
23670                "                        { t.foo(u) } -> typename T::foo_type;\n"
23671                "                        t++;\n"
23672                "                      };\n"
23673                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
23674 
23675   verifyFormat("template <typename T>\n"
23676                "concept Context = is_specialization_of_v<context, T>;");
23677 
23678   verifyFormat("template <typename T>\n"
23679                "concept Node = std::is_object_v<T>;");
23680 
23681   auto Style = getLLVMStyle();
23682   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
23683 
23684   verifyFormat(
23685       "template <typename T>\n"
23686       "concept C = requires(T t) {\n"
23687       "              requires Bar<T> && Foo<T>;\n"
23688       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
23689       "            };",
23690       Style);
23691 
23692   verifyFormat("template <typename T>\n"
23693                "concept HasFoo = requires(T t) {\n"
23694                "                   { t.foo() };\n"
23695                "                   t.foo();\n"
23696                "                 };\n"
23697                "template <typename T>\n"
23698                "concept HasBar = requires(T t) {\n"
23699                "                   { t.bar() };\n"
23700                "                   t.bar();\n"
23701                "                 };",
23702                Style);
23703 
23704   verifyFormat("template <typename T> concept True = true;", Style);
23705 
23706   verifyFormat("template <typename T>\n"
23707                "concept C = decltype([]() -> std::true_type { return {}; "
23708                "}())::value &&\n"
23709                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
23710                Style);
23711 
23712   verifyFormat("template <typename T>\n"
23713                "concept Semiregular =\n"
23714                "    DefaultConstructible<T> && CopyConstructible<T> && "
23715                "CopyAssignable<T> &&\n"
23716                "    requires(T a, std::size_t n) {\n"
23717                "      requires Same<T *, decltype(&a)>;\n"
23718                "      { a.~T() } noexcept;\n"
23719                "      requires Same<T *, decltype(new T)>;\n"
23720                "      requires Same<T *, decltype(new T[n])>;\n"
23721                "      { delete new T; };\n"
23722                "      { delete new T[n]; };\n"
23723                "    };",
23724                Style);
23725 
23726   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
23727 
23728   verifyFormat("template <typename T> concept C =\n"
23729                "    requires(T t) {\n"
23730                "      requires Bar<T> && Foo<T>;\n"
23731                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
23732                "    };",
23733                Style);
23734 
23735   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
23736                "                                         { t.foo() };\n"
23737                "                                         t.foo();\n"
23738                "                                       };\n"
23739                "template <typename T> concept HasBar = requires(T t) {\n"
23740                "                                         { t.bar() };\n"
23741                "                                         t.bar();\n"
23742                "                                       };",
23743                Style);
23744 
23745   verifyFormat("template <typename T> concept True = true;", Style);
23746 
23747   verifyFormat(
23748       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
23749       "                                    return {};\n"
23750       "                                  }())::value\n"
23751       "                                  && requires(T t) { t.bar(); } &&\n"
23752       "                                  sizeof(T) <= 8;",
23753       Style);
23754 
23755   verifyFormat("template <typename T> concept Semiregular =\n"
23756                "    DefaultConstructible<T> && CopyConstructible<T> && "
23757                "CopyAssignable<T> &&\n"
23758                "    requires(T a, std::size_t n) {\n"
23759                "      requires Same<T *, decltype(&a)>;\n"
23760                "      { a.~T() } noexcept;\n"
23761                "      requires Same<T *, decltype(new T)>;\n"
23762                "      requires Same<T *, decltype(new T[n])>;\n"
23763                "      { delete new T; };\n"
23764                "      { delete new T[n]; };\n"
23765                "    };",
23766                Style);
23767 
23768   // The following tests are invalid C++, we just want to make sure we don't
23769   // assert.
23770   verifyFormat("template <typename T>\n"
23771                "concept C = requires C2<T>;");
23772 
23773   verifyFormat("template <typename T>\n"
23774                "concept C = 5 + 4;");
23775 
23776   verifyFormat("template <typename T>\n"
23777                "concept C =\n"
23778                "class X;");
23779 
23780   verifyFormat("template <typename T>\n"
23781                "concept C = [] && true;");
23782 
23783   verifyFormat("template <typename T>\n"
23784                "concept C = [] && requires(T t) { typename T::size_type; };");
23785 }
23786 
23787 TEST_F(FormatTest, RequiresClauses) {
23788   auto Style = getLLVMStyle();
23789   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
23790   EXPECT_EQ(Style.IndentRequiresClause, true);
23791 
23792   verifyFormat("template <typename T>\n"
23793                "  requires(Foo<T> && std::trait<T>)\n"
23794                "struct Bar;",
23795                Style);
23796 
23797   verifyFormat("template <typename T>\n"
23798                "  requires(Foo<T> && std::trait<T>)\n"
23799                "class Bar {\n"
23800                "public:\n"
23801                "  Bar(T t);\n"
23802                "  bool baz();\n"
23803                "};",
23804                Style);
23805 
23806   verifyFormat(
23807       "template <typename T>\n"
23808       "  requires requires(T &&t) {\n"
23809       "             typename T::I;\n"
23810       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
23811       "           }\n"
23812       "Bar(T) -> Bar<typename T::I>;",
23813       Style);
23814 
23815   verifyFormat("template <typename T>\n"
23816                "  requires(Foo<T> && std::trait<T>)\n"
23817                "constexpr T MyGlobal;",
23818                Style);
23819 
23820   verifyFormat("template <typename T>\n"
23821                "  requires Foo<T> && requires(T t) {\n"
23822                "                       { t.baz() } -> std::same_as<bool>;\n"
23823                "                       requires std::same_as<T::Factor, int>;\n"
23824                "                     }\n"
23825                "inline int bar(T t) {\n"
23826                "  return t.baz() ? T::Factor : 5;\n"
23827                "}",
23828                Style);
23829 
23830   verifyFormat("template <typename T>\n"
23831                "inline int bar(T t)\n"
23832                "  requires Foo<T> && requires(T t) {\n"
23833                "                       { t.baz() } -> std::same_as<bool>;\n"
23834                "                       requires std::same_as<T::Factor, int>;\n"
23835                "                     }\n"
23836                "{\n"
23837                "  return t.baz() ? T::Factor : 5;\n"
23838                "}",
23839                Style);
23840 
23841   verifyFormat("template <typename T>\n"
23842                "  requires F<T>\n"
23843                "int bar(T t) {\n"
23844                "  return 5;\n"
23845                "}",
23846                Style);
23847 
23848   verifyFormat("template <typename T>\n"
23849                "int bar(T t)\n"
23850                "  requires F<T>\n"
23851                "{\n"
23852                "  return 5;\n"
23853                "}",
23854                Style);
23855 
23856   Style.IndentRequiresClause = false;
23857   verifyFormat("template <typename T>\n"
23858                "requires F<T>\n"
23859                "int bar(T t) {\n"
23860                "  return 5;\n"
23861                "}",
23862                Style);
23863 
23864   verifyFormat("template <typename T>\n"
23865                "int bar(T t)\n"
23866                "requires F<T>\n"
23867                "{\n"
23868                "  return 5;\n"
23869                "}",
23870                Style);
23871 
23872   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
23873   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
23874                "template <typename T> requires Foo<T> void bar() {}\n"
23875                "template <typename T> void bar() requires Foo<T> {}\n"
23876                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
23877                Style);
23878 
23879   auto ColumnStyle = Style;
23880   ColumnStyle.ColumnLimit = 40;
23881   verifyFormat("template <typename AAAAAAA>\n"
23882                "requires Foo<T> struct Bar {};\n"
23883                "template <typename AAAAAAA>\n"
23884                "requires Foo<T> void bar() {}\n"
23885                "template <typename AAAAAAA>\n"
23886                "void bar() requires Foo<T> {}\n"
23887                "template <typename AAAAAAA>\n"
23888                "requires Foo<T> Baz(T) -> Baz<T>;",
23889                ColumnStyle);
23890 
23891   verifyFormat("template <typename T>\n"
23892                "requires Foo<AAAAAAA> struct Bar {};\n"
23893                "template <typename T>\n"
23894                "requires Foo<AAAAAAA> void bar() {}\n"
23895                "template <typename T>\n"
23896                "void bar() requires Foo<AAAAAAA> {}\n"
23897                "template <typename T>\n"
23898                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
23899                ColumnStyle);
23900 
23901   verifyFormat("template <typename AAAAAAA>\n"
23902                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23903                "struct Bar {};\n"
23904                "template <typename AAAAAAA>\n"
23905                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23906                "void bar() {}\n"
23907                "template <typename AAAAAAA>\n"
23908                "void bar()\n"
23909                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
23910                "template <typename AAAAAAA>\n"
23911                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
23912                "template <typename AAAAAAA>\n"
23913                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23914                "Bar(T) -> Bar<T>;",
23915                ColumnStyle);
23916 
23917   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
23918   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
23919 
23920   verifyFormat("template <typename T>\n"
23921                "requires Foo<T> struct Bar {};\n"
23922                "template <typename T>\n"
23923                "requires Foo<T> void bar() {}\n"
23924                "template <typename T>\n"
23925                "void bar()\n"
23926                "requires Foo<T> {}\n"
23927                "template <typename T>\n"
23928                "requires Foo<T> Bar(T) -> Bar<T>;",
23929                Style);
23930 
23931   verifyFormat("template <typename AAAAAAA>\n"
23932                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23933                "struct Bar {};\n"
23934                "template <typename AAAAAAA>\n"
23935                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23936                "void bar() {}\n"
23937                "template <typename AAAAAAA>\n"
23938                "void bar()\n"
23939                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
23940                "template <typename AAAAAAA>\n"
23941                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
23942                "template <typename AAAAAAA>\n"
23943                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23944                "Bar(T) -> Bar<T>;",
23945                ColumnStyle);
23946 
23947   Style.IndentRequiresClause = true;
23948   ColumnStyle.IndentRequiresClause = true;
23949 
23950   verifyFormat("template <typename T>\n"
23951                "  requires Foo<T> struct Bar {};\n"
23952                "template <typename T>\n"
23953                "  requires Foo<T> void bar() {}\n"
23954                "template <typename T>\n"
23955                "void bar()\n"
23956                "  requires Foo<T> {}\n"
23957                "template <typename T>\n"
23958                "  requires Foo<T> Bar(T) -> Bar<T>;",
23959                Style);
23960 
23961   verifyFormat("template <typename AAAAAAA>\n"
23962                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
23963                "struct Bar {};\n"
23964                "template <typename AAAAAAA>\n"
23965                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
23966                "void bar() {}\n"
23967                "template <typename AAAAAAA>\n"
23968                "void bar()\n"
23969                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
23970                "template <typename AAAAAAA>\n"
23971                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
23972                "template <typename AAAAAAA>\n"
23973                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
23974                "Bar(T) -> Bar<T>;",
23975                ColumnStyle);
23976 
23977   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
23978   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
23979 
23980   verifyFormat("template <typename T> requires Foo<T>\n"
23981                "struct Bar {};\n"
23982                "template <typename T> requires Foo<T>\n"
23983                "void bar() {}\n"
23984                "template <typename T>\n"
23985                "void bar() requires Foo<T>\n"
23986                "{}\n"
23987                "template <typename T> requires Foo<T>\n"
23988                "Bar(T) -> Bar<T>;",
23989                Style);
23990 
23991   verifyFormat("template <typename AAAAAAA>\n"
23992                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23993                "struct Bar {};\n"
23994                "template <typename AAAAAAA>\n"
23995                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23996                "void bar() {}\n"
23997                "template <typename AAAAAAA>\n"
23998                "void bar()\n"
23999                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24000                "{}\n"
24001                "template <typename AAAAAAA>\n"
24002                "requires Foo<AAAAAAAA>\n"
24003                "Bar(T) -> Bar<T>;\n"
24004                "template <typename AAAAAAA>\n"
24005                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24006                "Bar(T) -> Bar<T>;",
24007                ColumnStyle);
24008 }
24009 
24010 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24011   FormatStyle Style = getLLVMStyle();
24012   StringRef Source = "void Foo::slot() {\n"
24013                      "  unsigned char MyChar = 'x';\n"
24014                      "  emit signal(MyChar);\n"
24015                      "  Q_EMIT signal(MyChar);\n"
24016                      "}";
24017 
24018   EXPECT_EQ(Source, format(Source, Style));
24019 
24020   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
24021   EXPECT_EQ("void Foo::slot() {\n"
24022             "  unsigned char MyChar = 'x';\n"
24023             "  emit          signal(MyChar);\n"
24024             "  Q_EMIT signal(MyChar);\n"
24025             "}",
24026             format(Source, Style));
24027 
24028   Style.StatementAttributeLikeMacros.push_back("emit");
24029   EXPECT_EQ(Source, format(Source, Style));
24030 
24031   Style.StatementAttributeLikeMacros = {};
24032   EXPECT_EQ("void Foo::slot() {\n"
24033             "  unsigned char MyChar = 'x';\n"
24034             "  emit          signal(MyChar);\n"
24035             "  Q_EMIT        signal(MyChar);\n"
24036             "}",
24037             format(Source, Style));
24038 }
24039 
24040 TEST_F(FormatTest, IndentAccessModifiers) {
24041   FormatStyle Style = getLLVMStyle();
24042   Style.IndentAccessModifiers = true;
24043   // Members are *two* levels below the record;
24044   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24045   verifyFormat("class C {\n"
24046                "    int i;\n"
24047                "};\n",
24048                Style);
24049   verifyFormat("union C {\n"
24050                "    int i;\n"
24051                "    unsigned u;\n"
24052                "};\n",
24053                Style);
24054   // Access modifiers should be indented one level below the record.
24055   verifyFormat("class C {\n"
24056                "  public:\n"
24057                "    int i;\n"
24058                "};\n",
24059                Style);
24060   verifyFormat("struct S {\n"
24061                "  private:\n"
24062                "    class C {\n"
24063                "        int j;\n"
24064                "\n"
24065                "      public:\n"
24066                "        C();\n"
24067                "    };\n"
24068                "\n"
24069                "  public:\n"
24070                "    int i;\n"
24071                "};\n",
24072                Style);
24073   // Enumerations are not records and should be unaffected.
24074   Style.AllowShortEnumsOnASingleLine = false;
24075   verifyFormat("enum class E {\n"
24076                "  A,\n"
24077                "  B\n"
24078                "};\n",
24079                Style);
24080   // Test with a different indentation width;
24081   // also proves that the result is Style.AccessModifierOffset agnostic.
24082   Style.IndentWidth = 3;
24083   verifyFormat("class C {\n"
24084                "   public:\n"
24085                "      int i;\n"
24086                "};\n",
24087                Style);
24088 }
24089 
24090 TEST_F(FormatTest, LimitlessStringsAndComments) {
24091   auto Style = getLLVMStyleWithColumns(0);
24092   constexpr StringRef Code =
24093       "/**\n"
24094       " * This is a multiline comment with quite some long lines, at least for "
24095       "the LLVM Style.\n"
24096       " * We will redo this with strings and line comments. Just to  check if "
24097       "everything is working.\n"
24098       " */\n"
24099       "bool foo() {\n"
24100       "  /* Single line multi line comment. */\n"
24101       "  const std::string String = \"This is a multiline string with quite "
24102       "some long lines, at least for the LLVM Style.\"\n"
24103       "                             \"We already did it with multi line "
24104       "comments, and we will do it with line comments. Just to check if "
24105       "everything is working.\";\n"
24106       "  // This is a line comment (block) with quite some long lines, at "
24107       "least for the LLVM Style.\n"
24108       "  // We already did this with multi line comments and strings. Just to "
24109       "check if everything is working.\n"
24110       "  const std::string SmallString = \"Hello World\";\n"
24111       "  // Small line comment\n"
24112       "  return String.size() > SmallString.size();\n"
24113       "}";
24114   EXPECT_EQ(Code, format(Code, Style));
24115 }
24116 
24117 TEST_F(FormatTest, FormatDecayCopy) {
24118   // error cases from unit tests
24119   verifyFormat("foo(auto())");
24120   verifyFormat("foo(auto{})");
24121   verifyFormat("foo(auto({}))");
24122   verifyFormat("foo(auto{{}})");
24123 
24124   verifyFormat("foo(auto(1))");
24125   verifyFormat("foo(auto{1})");
24126   verifyFormat("foo(new auto(1))");
24127   verifyFormat("foo(new auto{1})");
24128   verifyFormat("decltype(auto(1)) x;");
24129   verifyFormat("decltype(auto{1}) x;");
24130   verifyFormat("auto(x);");
24131   verifyFormat("auto{x};");
24132   verifyFormat("new auto{x};");
24133   verifyFormat("auto{x} = y;");
24134   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24135                                 // the user's own fault
24136   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24137                                          // clearly the user's own fault
24138   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24139 }
24140 
24141 TEST_F(FormatTest, Cpp20ModulesSupport) {
24142   FormatStyle Style = getLLVMStyle();
24143   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24144   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24145 
24146   verifyFormat("export import foo;", Style);
24147   verifyFormat("export import foo:bar;", Style);
24148   verifyFormat("export import foo.bar;", Style);
24149   verifyFormat("export import foo.bar:baz;", Style);
24150   verifyFormat("export import :bar;", Style);
24151   verifyFormat("export module foo:bar;", Style);
24152   verifyFormat("export module foo;", Style);
24153   verifyFormat("export module foo.bar;", Style);
24154   verifyFormat("export module foo.bar:baz;", Style);
24155   verifyFormat("export import <string_view>;", Style);
24156 
24157   verifyFormat("export type_name var;", Style);
24158   verifyFormat("template <class T> export using A = B<T>;", Style);
24159   verifyFormat("export using A = B;", Style);
24160   verifyFormat("export int func() {\n"
24161                "  foo();\n"
24162                "}",
24163                Style);
24164   verifyFormat("export struct {\n"
24165                "  int foo;\n"
24166                "};",
24167                Style);
24168   verifyFormat("export {\n"
24169                "  int foo;\n"
24170                "};",
24171                Style);
24172   verifyFormat("export export char const *hello() { return \"hello\"; }");
24173 
24174   verifyFormat("import bar;", Style);
24175   verifyFormat("import foo.bar;", Style);
24176   verifyFormat("import foo:bar;", Style);
24177   verifyFormat("import :bar;", Style);
24178   verifyFormat("import <ctime>;", Style);
24179   verifyFormat("import \"header\";", Style);
24180 
24181   verifyFormat("module foo;", Style);
24182   verifyFormat("module foo:bar;", Style);
24183   verifyFormat("module foo.bar;", Style);
24184   verifyFormat("module;", Style);
24185 
24186   verifyFormat("export namespace hi {\n"
24187                "const char *sayhi();\n"
24188                "}",
24189                Style);
24190 
24191   verifyFormat("module :private;", Style);
24192   verifyFormat("import <foo/bar.h>;", Style);
24193   verifyFormat("import foo...bar;", Style);
24194   verifyFormat("import ..........;", Style);
24195   verifyFormat("module foo:private;", Style);
24196   verifyFormat("import a", Style);
24197   verifyFormat("module a", Style);
24198   verifyFormat("export import a", Style);
24199   verifyFormat("export module a", Style);
24200 
24201   verifyFormat("import", Style);
24202   verifyFormat("module", Style);
24203   verifyFormat("export", Style);
24204 }
24205 
24206 TEST_F(FormatTest, CoroutineForCoawait) {
24207   FormatStyle Style = getLLVMStyle();
24208   verifyFormat("for co_await (auto x : range())\n  ;");
24209   verifyFormat("for (auto i : arr) {\n"
24210                "}",
24211                Style);
24212   verifyFormat("for co_await (auto i : arr) {\n"
24213                "}",
24214                Style);
24215   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24216                "}",
24217                Style);
24218 }
24219 
24220 TEST_F(FormatTest, CoroutineCoAwait) {
24221   verifyFormat("int x = co_await foo();");
24222   verifyFormat("int x = (co_await foo());");
24223   verifyFormat("co_await (42);");
24224   verifyFormat("void operator co_await(int);");
24225   verifyFormat("void operator co_await(a);");
24226   verifyFormat("co_await a;");
24227   verifyFormat("co_await missing_await_resume{};");
24228   verifyFormat("co_await a; // comment");
24229   verifyFormat("void test0() { co_await a; }");
24230   verifyFormat("co_await co_await co_await foo();");
24231   verifyFormat("co_await foo().bar();");
24232   verifyFormat("co_await [this]() -> Task { co_return x; }");
24233   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24234                "foo(); }(x, y);");
24235 
24236   FormatStyle Style = getLLVMStyleWithColumns(40);
24237   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24238                "  co_return co_await foo();\n"
24239                "}(x, y);",
24240                Style);
24241   verifyFormat("co_await;");
24242 }
24243 
24244 TEST_F(FormatTest, CoroutineCoYield) {
24245   verifyFormat("int x = co_yield foo();");
24246   verifyFormat("int x = (co_yield foo());");
24247   verifyFormat("co_yield (42);");
24248   verifyFormat("co_yield {42};");
24249   verifyFormat("co_yield 42;");
24250   verifyFormat("co_yield n++;");
24251   verifyFormat("co_yield ++n;");
24252   verifyFormat("co_yield;");
24253 }
24254 
24255 TEST_F(FormatTest, CoroutineCoReturn) {
24256   verifyFormat("co_return (42);");
24257   verifyFormat("co_return;");
24258   verifyFormat("co_return {};");
24259   verifyFormat("co_return x;");
24260   verifyFormat("co_return co_await foo();");
24261   verifyFormat("co_return co_yield foo();");
24262 }
24263 
24264 TEST_F(FormatTest, EmptyShortBlock) {
24265   auto Style = getLLVMStyle();
24266   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24267 
24268   verifyFormat("try {\n"
24269                "  doA();\n"
24270                "} catch (Exception &e) {\n"
24271                "  e.printStackTrace();\n"
24272                "}\n",
24273                Style);
24274 
24275   verifyFormat("try {\n"
24276                "  doA();\n"
24277                "} catch (Exception &e) {}\n",
24278                Style);
24279 }
24280 
24281 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
24282   auto Style = getLLVMStyle();
24283 
24284   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
24285   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
24286   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
24287   verifyFormat("struct Y<[] { return 0; }> {};", Style);
24288 
24289   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
24290   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
24291 }
24292 
24293 TEST_F(FormatTest, RemoveBraces) {
24294   FormatStyle Style = getLLVMStyle();
24295   Style.RemoveBracesLLVM = true;
24296 
24297   // The following eight test cases are fully-braced versions of the examples at
24298   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
24299   // statement-bodies-of-if-else-loop-statements".
24300 
24301   // 1. Omit the braces, since the body is simple and clearly associated with
24302   // the if.
24303   verifyFormat("if (isa<FunctionDecl>(D))\n"
24304                "  handleFunctionDecl(D);\n"
24305                "else if (isa<VarDecl>(D))\n"
24306                "  handleVarDecl(D);",
24307                "if (isa<FunctionDecl>(D)) {\n"
24308                "  handleFunctionDecl(D);\n"
24309                "} else if (isa<VarDecl>(D)) {\n"
24310                "  handleVarDecl(D);\n"
24311                "}",
24312                Style);
24313 
24314   // 2. Here we document the condition itself and not the body.
24315   verifyFormat("if (isa<VarDecl>(D)) {\n"
24316                "  // It is necessary that we explain the situation with this\n"
24317                "  // surprisingly long comment, so it would be unclear\n"
24318                "  // without the braces whether the following statement is in\n"
24319                "  // the scope of the `if`.\n"
24320                "  // Because the condition is documented, we can't really\n"
24321                "  // hoist this comment that applies to the body above the\n"
24322                "  // if.\n"
24323                "  handleOtherDecl(D);\n"
24324                "}",
24325                Style);
24326 
24327   // 3. Use braces on the outer `if` to avoid a potential dangling else
24328   // situation.
24329   verifyFormat("if (isa<VarDecl>(D)) {\n"
24330                "  for (auto *A : D.attrs())\n"
24331                "    if (shouldProcessAttr(A))\n"
24332                "      handleAttr(A);\n"
24333                "}",
24334                "if (isa<VarDecl>(D)) {\n"
24335                "  for (auto *A : D.attrs()) {\n"
24336                "    if (shouldProcessAttr(A)) {\n"
24337                "      handleAttr(A);\n"
24338                "    }\n"
24339                "  }\n"
24340                "}",
24341                Style);
24342 
24343   // 4. Use braces for the `if` block to keep it uniform with the else block.
24344   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24345                "  handleFunctionDecl(D);\n"
24346                "} else {\n"
24347                "  // In this else case, it is necessary that we explain the\n"
24348                "  // situation with this surprisingly long comment, so it\n"
24349                "  // would be unclear without the braces whether the\n"
24350                "  // following statement is in the scope of the `if`.\n"
24351                "  handleOtherDecl(D);\n"
24352                "}",
24353                Style);
24354 
24355   // 5. This should also omit braces.  The `for` loop contains only a single
24356   // statement, so it shouldn't have braces.  The `if` also only contains a
24357   // single simple statement (the for loop), so it also should omit braces.
24358   verifyFormat("if (isa<FunctionDecl>(D))\n"
24359                "  for (auto *A : D.attrs())\n"
24360                "    handleAttr(A);",
24361                "if (isa<FunctionDecl>(D)) {\n"
24362                "  for (auto *A : D.attrs()) {\n"
24363                "    handleAttr(A);\n"
24364                "  }\n"
24365                "}",
24366                Style);
24367 
24368   // 6. Use braces for the outer `if` since the nested `for` is braced.
24369   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24370                "  for (auto *A : D.attrs()) {\n"
24371                "    // In this for loop body, it is necessary that we explain\n"
24372                "    // the situation with this surprisingly long comment,\n"
24373                "    // forcing braces on the `for` block.\n"
24374                "    handleAttr(A);\n"
24375                "  }\n"
24376                "}",
24377                Style);
24378 
24379   // 7. Use braces on the outer block because there are more than two levels of
24380   // nesting.
24381   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24382                "  for (auto *A : D.attrs())\n"
24383                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
24384                "      handleAttrOnDecl(D, A, i);\n"
24385                "}",
24386                "if (isa<FunctionDecl>(D)) {\n"
24387                "  for (auto *A : D.attrs()) {\n"
24388                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
24389                "      handleAttrOnDecl(D, A, i);\n"
24390                "    }\n"
24391                "  }\n"
24392                "}",
24393                Style);
24394 
24395   // 8. Use braces on the outer block because of a nested `if`, otherwise the
24396   // compiler would warn: `add explicit braces to avoid dangling else`
24397   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
24398                "  if (shouldProcess(D))\n"
24399                "    handleVarDecl(D);\n"
24400                "  else\n"
24401                "    markAsIgnored(D);\n"
24402                "}",
24403                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
24404                "  if (shouldProcess(D)) {\n"
24405                "    handleVarDecl(D);\n"
24406                "  } else {\n"
24407                "    markAsIgnored(D);\n"
24408                "  }\n"
24409                "}",
24410                Style);
24411 
24412   verifyFormat("if (a)\n"
24413                "  b; // comment\n"
24414                "else if (c)\n"
24415                "  d; /* comment */\n"
24416                "else\n"
24417                "  e;",
24418                "if (a) {\n"
24419                "  b; // comment\n"
24420                "} else if (c) {\n"
24421                "  d; /* comment */\n"
24422                "} else {\n"
24423                "  e;\n"
24424                "}",
24425                Style);
24426 
24427   verifyFormat("if (a) {\n"
24428                "  b;\n"
24429                "  c;\n"
24430                "} else if (d) {\n"
24431                "  e;\n"
24432                "}",
24433                Style);
24434 
24435   verifyFormat("if (a) {\n"
24436                "#undef NDEBUG\n"
24437                "  b;\n"
24438                "} else {\n"
24439                "  c;\n"
24440                "}",
24441                Style);
24442 
24443   verifyFormat("if (a) {\n"
24444                "  // comment\n"
24445                "} else if (b) {\n"
24446                "  c;\n"
24447                "}",
24448                Style);
24449 
24450   verifyFormat("if (a) {\n"
24451                "  b;\n"
24452                "} else {\n"
24453                "  { c; }\n"
24454                "}",
24455                Style);
24456 
24457   verifyFormat("if (a) {\n"
24458                "  if (b) // comment\n"
24459                "    c;\n"
24460                "} else if (d) {\n"
24461                "  e;\n"
24462                "}",
24463                "if (a) {\n"
24464                "  if (b) { // comment\n"
24465                "    c;\n"
24466                "  }\n"
24467                "} else if (d) {\n"
24468                "  e;\n"
24469                "}",
24470                Style);
24471 
24472   verifyFormat("if (a) {\n"
24473                "  if (b) {\n"
24474                "    c;\n"
24475                "    // comment\n"
24476                "  } else if (d) {\n"
24477                "    e;\n"
24478                "  }\n"
24479                "}",
24480                Style);
24481 
24482   verifyFormat("if (a) {\n"
24483                "  if (b)\n"
24484                "    c;\n"
24485                "}",
24486                "if (a) {\n"
24487                "  if (b) {\n"
24488                "    c;\n"
24489                "  }\n"
24490                "}",
24491                Style);
24492 
24493   verifyFormat("if (a)\n"
24494                "  if (b)\n"
24495                "    c;\n"
24496                "  else\n"
24497                "    d;\n"
24498                "else\n"
24499                "  e;",
24500                "if (a) {\n"
24501                "  if (b) {\n"
24502                "    c;\n"
24503                "  } else {\n"
24504                "    d;\n"
24505                "  }\n"
24506                "} else {\n"
24507                "  e;\n"
24508                "}",
24509                Style);
24510 
24511   verifyFormat("if (a) {\n"
24512                "  // comment\n"
24513                "  if (b)\n"
24514                "    c;\n"
24515                "  else if (d)\n"
24516                "    e;\n"
24517                "} else {\n"
24518                "  g;\n"
24519                "}",
24520                "if (a) {\n"
24521                "  // comment\n"
24522                "  if (b) {\n"
24523                "    c;\n"
24524                "  } else if (d) {\n"
24525                "    e;\n"
24526                "  }\n"
24527                "} else {\n"
24528                "  g;\n"
24529                "}",
24530                Style);
24531 
24532   verifyFormat("if (a)\n"
24533                "  b;\n"
24534                "else if (c)\n"
24535                "  d;\n"
24536                "else\n"
24537                "  e;",
24538                "if (a) {\n"
24539                "  b;\n"
24540                "} else {\n"
24541                "  if (c) {\n"
24542                "    d;\n"
24543                "  } else {\n"
24544                "    e;\n"
24545                "  }\n"
24546                "}",
24547                Style);
24548 
24549   verifyFormat("if (a) {\n"
24550                "  if (b)\n"
24551                "    c;\n"
24552                "  else if (d)\n"
24553                "    e;\n"
24554                "} else {\n"
24555                "  g;\n"
24556                "}",
24557                "if (a) {\n"
24558                "  if (b)\n"
24559                "    c;\n"
24560                "  else {\n"
24561                "    if (d)\n"
24562                "      e;\n"
24563                "  }\n"
24564                "} else {\n"
24565                "  g;\n"
24566                "}",
24567                Style);
24568 
24569   verifyFormat("if (a)\n"
24570                "  b;\n"
24571                "else if (c)\n"
24572                "  while (d)\n"
24573                "    e;\n"
24574                "// comment",
24575                "if (a)\n"
24576                "{\n"
24577                "  b;\n"
24578                "} else if (c) {\n"
24579                "  while (d) {\n"
24580                "    e;\n"
24581                "  }\n"
24582                "}\n"
24583                "// comment",
24584                Style);
24585 
24586   verifyFormat("if (a) {\n"
24587                "  b;\n"
24588                "} else if (c) {\n"
24589                "  d;\n"
24590                "} else {\n"
24591                "  e;\n"
24592                "  g;\n"
24593                "}",
24594                Style);
24595 
24596   verifyFormat("if (a) {\n"
24597                "  b;\n"
24598                "} else if (c) {\n"
24599                "  d;\n"
24600                "} else {\n"
24601                "  e;\n"
24602                "} // comment",
24603                Style);
24604 
24605   verifyFormat("int abs = [](int i) {\n"
24606                "  if (i >= 0)\n"
24607                "    return i;\n"
24608                "  return -i;\n"
24609                "};",
24610                "int abs = [](int i) {\n"
24611                "  if (i >= 0) {\n"
24612                "    return i;\n"
24613                "  }\n"
24614                "  return -i;\n"
24615                "};",
24616                Style);
24617 
24618   // FIXME: See https://github.com/llvm/llvm-project/issues/53543.
24619 #if 0
24620   Style.ColumnLimit = 65;
24621 
24622   verifyFormat("if (condition) {\n"
24623                "  ff(Indices,\n"
24624                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
24625                "} else {\n"
24626                "  ff(Indices,\n"
24627                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
24628                "}",
24629                Style);
24630 
24631   Style.ColumnLimit = 20;
24632 
24633   verifyFormat("if (a) {\n"
24634                "  b = c + // 1 -\n"
24635                "      d;\n"
24636                "}",
24637                Style);
24638 
24639   verifyFormat("if (a) {\n"
24640                "  b = c >= 0 ? d\n"
24641                "             : e;\n"
24642                "}",
24643                "if (a) {\n"
24644                "  b = c >= 0 ? d : e;\n"
24645                "}",
24646                Style);
24647 #endif
24648 
24649   Style.ColumnLimit = 20;
24650 
24651   verifyFormat("if (a)\n"
24652                "  b = c > 0 ? d : e;",
24653                "if (a) {\n"
24654                "  b = c > 0 ? d : e;\n"
24655                "}",
24656                Style);
24657 
24658   Style.ColumnLimit = 0;
24659 
24660   verifyFormat("if (a)\n"
24661                "  b234567890223456789032345678904234567890 = "
24662                "c234567890223456789032345678904234567890;",
24663                "if (a) {\n"
24664                "  b234567890223456789032345678904234567890 = "
24665                "c234567890223456789032345678904234567890;\n"
24666                "}",
24667                Style);
24668 }
24669 
24670 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
24671   auto Style = getLLVMStyle();
24672 
24673   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
24674                     "void functionDecl(int a, int b, int c);";
24675 
24676   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
24677                      "paramF, paramG, paramH, paramI);\n"
24678                      "void functionDecl(int argumentA, int argumentB, int "
24679                      "argumentC, int argumentD, int argumentE);";
24680 
24681   verifyFormat(Short, Style);
24682 
24683   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
24684                       "paramF, paramG, paramH,\n"
24685                       "             paramI);\n"
24686                       "void functionDecl(int argumentA, int argumentB, int "
24687                       "argumentC, int argumentD,\n"
24688                       "                  int argumentE);";
24689 
24690   verifyFormat(NoBreak, Medium, Style);
24691   verifyFormat(NoBreak,
24692                "functionCall(\n"
24693                "    paramA,\n"
24694                "    paramB,\n"
24695                "    paramC,\n"
24696                "    paramD,\n"
24697                "    paramE,\n"
24698                "    paramF,\n"
24699                "    paramG,\n"
24700                "    paramH,\n"
24701                "    paramI\n"
24702                ");\n"
24703                "void functionDecl(\n"
24704                "    int argumentA,\n"
24705                "    int argumentB,\n"
24706                "    int argumentC,\n"
24707                "    int argumentD,\n"
24708                "    int argumentE\n"
24709                ");",
24710                Style);
24711 
24712   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
24713                "                  nestedLongFunctionCall(argument1, "
24714                "argument2, argument3,\n"
24715                "                                         argument4, "
24716                "argument5));",
24717                Style);
24718 
24719   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
24720 
24721   verifyFormat(Short, Style);
24722   verifyFormat(
24723       "functionCall(\n"
24724       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
24725       "paramI\n"
24726       ");\n"
24727       "void functionDecl(\n"
24728       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
24729       "argumentE\n"
24730       ");",
24731       Medium, Style);
24732 
24733   Style.AllowAllArgumentsOnNextLine = false;
24734   Style.AllowAllParametersOfDeclarationOnNextLine = false;
24735 
24736   verifyFormat(Short, Style);
24737   verifyFormat(
24738       "functionCall(\n"
24739       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
24740       "paramI\n"
24741       ");\n"
24742       "void functionDecl(\n"
24743       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
24744       "argumentE\n"
24745       ");",
24746       Medium, Style);
24747 
24748   Style.BinPackArguments = false;
24749   Style.BinPackParameters = false;
24750 
24751   verifyFormat(Short, Style);
24752 
24753   verifyFormat("functionCall(\n"
24754                "    paramA,\n"
24755                "    paramB,\n"
24756                "    paramC,\n"
24757                "    paramD,\n"
24758                "    paramE,\n"
24759                "    paramF,\n"
24760                "    paramG,\n"
24761                "    paramH,\n"
24762                "    paramI\n"
24763                ");\n"
24764                "void functionDecl(\n"
24765                "    int argumentA,\n"
24766                "    int argumentB,\n"
24767                "    int argumentC,\n"
24768                "    int argumentD,\n"
24769                "    int argumentE\n"
24770                ");",
24771                Medium, Style);
24772 
24773   verifyFormat("outerFunctionCall(\n"
24774                "    nestedFunctionCall(argument1),\n"
24775                "    nestedLongFunctionCall(\n"
24776                "        argument1,\n"
24777                "        argument2,\n"
24778                "        argument3,\n"
24779                "        argument4,\n"
24780                "        argument5\n"
24781                "    )\n"
24782                ");",
24783                Style);
24784 
24785   verifyFormat("int a = (int)b;", Style);
24786   verifyFormat("int a = (int)b;",
24787                "int a = (\n"
24788                "    int\n"
24789                ") b;",
24790                Style);
24791 
24792   verifyFormat("return (true);", Style);
24793   verifyFormat("return (true);",
24794                "return (\n"
24795                "    true\n"
24796                ");",
24797                Style);
24798 
24799   verifyFormat("void foo();", Style);
24800   verifyFormat("void foo();",
24801                "void foo(\n"
24802                ");",
24803                Style);
24804 
24805   verifyFormat("void foo() {}", Style);
24806   verifyFormat("void foo() {}",
24807                "void foo(\n"
24808                ") {\n"
24809                "}",
24810                Style);
24811 
24812   verifyFormat("auto string = std::string();", Style);
24813   verifyFormat("auto string = std::string();",
24814                "auto string = std::string(\n"
24815                ");",
24816                Style);
24817 
24818   verifyFormat("void (*functionPointer)() = nullptr;", Style);
24819   verifyFormat("void (*functionPointer)() = nullptr;",
24820                "void (\n"
24821                "    *functionPointer\n"
24822                ")\n"
24823                "(\n"
24824                ") = nullptr;",
24825                Style);
24826 }
24827 
24828 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
24829   auto Style = getLLVMStyle();
24830 
24831   verifyFormat("if (foo()) {\n"
24832                "  return;\n"
24833                "}",
24834                Style);
24835 
24836   verifyFormat("if (quitelongarg !=\n"
24837                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
24838                "comment\n"
24839                "  return;\n"
24840                "}",
24841                Style);
24842 
24843   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
24844 
24845   verifyFormat("if (foo()) {\n"
24846                "  return;\n"
24847                "}",
24848                Style);
24849 
24850   verifyFormat("if (quitelongarg !=\n"
24851                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
24852                "comment\n"
24853                "  return;\n"
24854                "}",
24855                Style);
24856 }
24857 
24858 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
24859   auto Style = getLLVMStyle();
24860 
24861   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
24862                "  doSomething();\n"
24863                "}",
24864                Style);
24865 
24866   verifyFormat("for (int myReallyLongCountVariable = 0; "
24867                "myReallyLongCountVariable < count;\n"
24868                "     myReallyLongCountVariable++) {\n"
24869                "  doSomething();\n"
24870                "}",
24871                Style);
24872 
24873   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
24874 
24875   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
24876                "  doSomething();\n"
24877                "}",
24878                Style);
24879 
24880   verifyFormat("for (int myReallyLongCountVariable = 0; "
24881                "myReallyLongCountVariable < count;\n"
24882                "     myReallyLongCountVariable++) {\n"
24883                "  doSomething();\n"
24884                "}",
24885                Style);
24886 }
24887 
24888 TEST_F(FormatTest, UnderstandsDigraphs) {
24889   verifyFormat("int arr<:5:> = {};");
24890   verifyFormat("int arr[5] = <%%>;");
24891   verifyFormat("int arr<:::qualified_variable:> = {};");
24892   verifyFormat("int arr[::qualified_variable] = <%%>;");
24893   verifyFormat("%:include <header>");
24894   verifyFormat("%:define A x##y");
24895   verifyFormat("#define A x%:%:y");
24896 }
24897 
24898 } // namespace
24899 } // namespace format
24900 } // namespace clang
24901