xref: /llvm-project/clang/unittests/Format/FormatTest.cpp (revision 1e512f022ad5c23dc4ef4e663f51d5d0bcbc7c69)
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   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
1524   // Where line-lengths matter, a 2-letter synonym that maintains line length.
1525   // Not IF to avoid any confusion that IF is somehow special.
1526   AllowSimpleBracedStatements.IfMacros.push_back("FI");
1527   AllowSimpleBracedStatements.ColumnLimit = 40;
1528   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1529       FormatStyle::SBS_Always;
1530 
1531   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1532       FormatStyle::SIS_WithoutElse;
1533   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1534 
1535   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1536   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1537   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1538 
1539   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1540   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1541   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1542   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1543   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1544   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1545   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1546   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1547   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1548   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1549   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1550   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1551   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1552   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1553   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1554   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1555   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1556                AllowSimpleBracedStatements);
1557   verifyFormat("if (true) {\n"
1558                "  ffffffffffffffffffffffff();\n"
1559                "}",
1560                AllowSimpleBracedStatements);
1561   verifyFormat("if (true) {\n"
1562                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1563                "}",
1564                AllowSimpleBracedStatements);
1565   verifyFormat("if (true) { //\n"
1566                "  f();\n"
1567                "}",
1568                AllowSimpleBracedStatements);
1569   verifyFormat("if (true) {\n"
1570                "  f();\n"
1571                "  f();\n"
1572                "}",
1573                AllowSimpleBracedStatements);
1574   verifyFormat("if (true) {\n"
1575                "  f();\n"
1576                "} else {\n"
1577                "  f();\n"
1578                "}",
1579                AllowSimpleBracedStatements);
1580   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1581                AllowSimpleBracedStatements);
1582   verifyFormat("MYIF (true) {\n"
1583                "  ffffffffffffffffffffffff();\n"
1584                "}",
1585                AllowSimpleBracedStatements);
1586   verifyFormat("MYIF (true) {\n"
1587                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1588                "}",
1589                AllowSimpleBracedStatements);
1590   verifyFormat("MYIF (true) { //\n"
1591                "  f();\n"
1592                "}",
1593                AllowSimpleBracedStatements);
1594   verifyFormat("MYIF (true) {\n"
1595                "  f();\n"
1596                "  f();\n"
1597                "}",
1598                AllowSimpleBracedStatements);
1599   verifyFormat("MYIF (true) {\n"
1600                "  f();\n"
1601                "} else {\n"
1602                "  f();\n"
1603                "}",
1604                AllowSimpleBracedStatements);
1605 
1606   verifyFormat("struct A2 {\n"
1607                "  int X;\n"
1608                "};",
1609                AllowSimpleBracedStatements);
1610   verifyFormat("typedef struct A2 {\n"
1611                "  int X;\n"
1612                "} A2_t;",
1613                AllowSimpleBracedStatements);
1614   verifyFormat("template <int> struct A2 {\n"
1615                "  struct B {};\n"
1616                "};",
1617                AllowSimpleBracedStatements);
1618 
1619   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1620       FormatStyle::SIS_Never;
1621   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1622   verifyFormat("if (true) {\n"
1623                "  f();\n"
1624                "}",
1625                AllowSimpleBracedStatements);
1626   verifyFormat("if (true) {\n"
1627                "  f();\n"
1628                "} else {\n"
1629                "  f();\n"
1630                "}",
1631                AllowSimpleBracedStatements);
1632   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1633   verifyFormat("MYIF (true) {\n"
1634                "  f();\n"
1635                "}",
1636                AllowSimpleBracedStatements);
1637   verifyFormat("MYIF (true) {\n"
1638                "  f();\n"
1639                "} else {\n"
1640                "  f();\n"
1641                "}",
1642                AllowSimpleBracedStatements);
1643 
1644   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1645   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1646   verifyFormat("while (true) {\n"
1647                "  f();\n"
1648                "}",
1649                AllowSimpleBracedStatements);
1650   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1651   verifyFormat("for (;;) {\n"
1652                "  f();\n"
1653                "}",
1654                AllowSimpleBracedStatements);
1655   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1656   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1657                "  f();\n"
1658                "}",
1659                AllowSimpleBracedStatements);
1660 
1661   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1662       FormatStyle::SIS_WithoutElse;
1663   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1664   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1665       FormatStyle::BWACS_Always;
1666 
1667   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1668   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1669   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1670   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1671   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1672   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1673   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1674   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1675   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1676   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1677   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1678   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1679   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1680   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1681   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1682   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1683   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1684                AllowSimpleBracedStatements);
1685   verifyFormat("if (true)\n"
1686                "{\n"
1687                "  ffffffffffffffffffffffff();\n"
1688                "}",
1689                AllowSimpleBracedStatements);
1690   verifyFormat("if (true)\n"
1691                "{\n"
1692                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1693                "}",
1694                AllowSimpleBracedStatements);
1695   verifyFormat("if (true)\n"
1696                "{ //\n"
1697                "  f();\n"
1698                "}",
1699                AllowSimpleBracedStatements);
1700   verifyFormat("if (true)\n"
1701                "{\n"
1702                "  f();\n"
1703                "  f();\n"
1704                "}",
1705                AllowSimpleBracedStatements);
1706   verifyFormat("if (true)\n"
1707                "{\n"
1708                "  f();\n"
1709                "} else\n"
1710                "{\n"
1711                "  f();\n"
1712                "}",
1713                AllowSimpleBracedStatements);
1714   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1715                AllowSimpleBracedStatements);
1716   verifyFormat("MYIF (true)\n"
1717                "{\n"
1718                "  ffffffffffffffffffffffff();\n"
1719                "}",
1720                AllowSimpleBracedStatements);
1721   verifyFormat("MYIF (true)\n"
1722                "{\n"
1723                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1724                "}",
1725                AllowSimpleBracedStatements);
1726   verifyFormat("MYIF (true)\n"
1727                "{ //\n"
1728                "  f();\n"
1729                "}",
1730                AllowSimpleBracedStatements);
1731   verifyFormat("MYIF (true)\n"
1732                "{\n"
1733                "  f();\n"
1734                "  f();\n"
1735                "}",
1736                AllowSimpleBracedStatements);
1737   verifyFormat("MYIF (true)\n"
1738                "{\n"
1739                "  f();\n"
1740                "} else\n"
1741                "{\n"
1742                "  f();\n"
1743                "}",
1744                AllowSimpleBracedStatements);
1745 
1746   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1747       FormatStyle::SIS_Never;
1748   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1749   verifyFormat("if (true)\n"
1750                "{\n"
1751                "  f();\n"
1752                "}",
1753                AllowSimpleBracedStatements);
1754   verifyFormat("if (true)\n"
1755                "{\n"
1756                "  f();\n"
1757                "} else\n"
1758                "{\n"
1759                "  f();\n"
1760                "}",
1761                AllowSimpleBracedStatements);
1762   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1763   verifyFormat("MYIF (true)\n"
1764                "{\n"
1765                "  f();\n"
1766                "}",
1767                AllowSimpleBracedStatements);
1768   verifyFormat("MYIF (true)\n"
1769                "{\n"
1770                "  f();\n"
1771                "} else\n"
1772                "{\n"
1773                "  f();\n"
1774                "}",
1775                AllowSimpleBracedStatements);
1776 
1777   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1778   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1779   verifyFormat("while (true)\n"
1780                "{\n"
1781                "  f();\n"
1782                "}",
1783                AllowSimpleBracedStatements);
1784   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1785   verifyFormat("for (;;)\n"
1786                "{\n"
1787                "  f();\n"
1788                "}",
1789                AllowSimpleBracedStatements);
1790   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1791   verifyFormat("BOOST_FOREACH (int v, vec)\n"
1792                "{\n"
1793                "  f();\n"
1794                "}",
1795                AllowSimpleBracedStatements);
1796 }
1797 
1798 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1799   FormatStyle Style = getLLVMStyleWithColumns(60);
1800   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1801   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1802   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1803   EXPECT_EQ("#define A                                                  \\\n"
1804             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1805             "  {                                                        \\\n"
1806             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1807             "  }\n"
1808             "X;",
1809             format("#define A \\\n"
1810                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1811                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1812                    "   }\n"
1813                    "X;",
1814                    Style));
1815 }
1816 
1817 TEST_F(FormatTest, ParseIfElse) {
1818   verifyFormat("if (true)\n"
1819                "  if (true)\n"
1820                "    if (true)\n"
1821                "      f();\n"
1822                "    else\n"
1823                "      g();\n"
1824                "  else\n"
1825                "    h();\n"
1826                "else\n"
1827                "  i();");
1828   verifyFormat("if (true)\n"
1829                "  if (true)\n"
1830                "    if (true) {\n"
1831                "      if (true)\n"
1832                "        f();\n"
1833                "    } else {\n"
1834                "      g();\n"
1835                "    }\n"
1836                "  else\n"
1837                "    h();\n"
1838                "else {\n"
1839                "  i();\n"
1840                "}");
1841   verifyFormat("if (true)\n"
1842                "  if constexpr (true)\n"
1843                "    if (true) {\n"
1844                "      if constexpr (true)\n"
1845                "        f();\n"
1846                "    } else {\n"
1847                "      g();\n"
1848                "    }\n"
1849                "  else\n"
1850                "    h();\n"
1851                "else {\n"
1852                "  i();\n"
1853                "}");
1854   verifyFormat("if (true)\n"
1855                "  if CONSTEXPR (true)\n"
1856                "    if (true) {\n"
1857                "      if CONSTEXPR (true)\n"
1858                "        f();\n"
1859                "    } else {\n"
1860                "      g();\n"
1861                "    }\n"
1862                "  else\n"
1863                "    h();\n"
1864                "else {\n"
1865                "  i();\n"
1866                "}");
1867   verifyFormat("void f() {\n"
1868                "  if (a) {\n"
1869                "  } else {\n"
1870                "  }\n"
1871                "}");
1872 }
1873 
1874 TEST_F(FormatTest, ElseIf) {
1875   verifyFormat("if (a) {\n} else if (b) {\n}");
1876   verifyFormat("if (a)\n"
1877                "  f();\n"
1878                "else if (b)\n"
1879                "  g();\n"
1880                "else\n"
1881                "  h();");
1882   verifyFormat("if (a)\n"
1883                "  f();\n"
1884                "else // comment\n"
1885                "  if (b) {\n"
1886                "    g();\n"
1887                "    h();\n"
1888                "  }");
1889   verifyFormat("if constexpr (a)\n"
1890                "  f();\n"
1891                "else if constexpr (b)\n"
1892                "  g();\n"
1893                "else\n"
1894                "  h();");
1895   verifyFormat("if CONSTEXPR (a)\n"
1896                "  f();\n"
1897                "else if CONSTEXPR (b)\n"
1898                "  g();\n"
1899                "else\n"
1900                "  h();");
1901   verifyFormat("if (a) {\n"
1902                "  f();\n"
1903                "}\n"
1904                "// or else ..\n"
1905                "else {\n"
1906                "  g()\n"
1907                "}");
1908 
1909   verifyFormat("if (a) {\n"
1910                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1911                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1912                "}");
1913   verifyFormat("if (a) {\n"
1914                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1915                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1916                "}");
1917   verifyFormat("if (a) {\n"
1918                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1919                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1920                "}");
1921   verifyFormat("if (a) {\n"
1922                "} else if (\n"
1923                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1924                "}",
1925                getLLVMStyleWithColumns(62));
1926   verifyFormat("if (a) {\n"
1927                "} else if constexpr (\n"
1928                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1929                "}",
1930                getLLVMStyleWithColumns(62));
1931   verifyFormat("if (a) {\n"
1932                "} else if CONSTEXPR (\n"
1933                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1934                "}",
1935                getLLVMStyleWithColumns(62));
1936 }
1937 
1938 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
1939   FormatStyle Style = getLLVMStyle();
1940   // Check first the default LLVM style
1941   // Style.PointerAlignment = FormatStyle::PAS_Right;
1942   // Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1943   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
1944   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
1945   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
1946   verifyFormat("int *f1(int &a) const &;", Style);
1947   verifyFormat("int *f1(int &a) const & = 0;", Style);
1948   verifyFormat("int *a = f1();", Style);
1949   verifyFormat("int &b = f2();", Style);
1950   verifyFormat("int &&c = f3();", Style);
1951   verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
1952   verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
1953   verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
1954   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
1955   verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
1956   verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
1957   verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
1958   verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
1959   verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
1960   verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
1961   verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
1962   verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
1963   verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
1964   verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
1965   verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
1966   verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
1967 
1968   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1969   verifyFormat("Const unsigned int *c;\n"
1970                "const unsigned int *d;\n"
1971                "Const unsigned int &e;\n"
1972                "const unsigned int &f;\n"
1973                "const unsigned    &&g;\n"
1974                "Const unsigned      h;",
1975                Style);
1976 
1977   Style.PointerAlignment = FormatStyle::PAS_Left;
1978   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1979   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
1980   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
1981   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
1982   verifyFormat("int* f1(int& a) const& = 0;", Style);
1983   verifyFormat("int* a = f1();", Style);
1984   verifyFormat("int& b = f2();", Style);
1985   verifyFormat("int&& c = f3();", Style);
1986   verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
1987   verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
1988   verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
1989   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
1990   verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
1991   verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
1992   verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
1993   verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
1994   verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
1995   verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
1996   verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
1997   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
1998   verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
1999   verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
2000   verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
2001   verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
2002   verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
2003   verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
2004 
2005   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2006   verifyFormat("Const unsigned int* c;\n"
2007                "const unsigned int* d;\n"
2008                "Const unsigned int& e;\n"
2009                "const unsigned int& f;\n"
2010                "const unsigned&&    g;\n"
2011                "Const unsigned      h;",
2012                Style);
2013 
2014   Style.PointerAlignment = FormatStyle::PAS_Right;
2015   Style.ReferenceAlignment = FormatStyle::RAS_Left;
2016   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
2017   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
2018   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
2019   verifyFormat("int *a = f1();", Style);
2020   verifyFormat("int& b = f2();", Style);
2021   verifyFormat("int&& c = f3();", Style);
2022   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2023   verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2024   verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
2025 
2026   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2027   verifyFormat("Const unsigned int *c;\n"
2028                "const unsigned int *d;\n"
2029                "Const unsigned int& e;\n"
2030                "const unsigned int& f;\n"
2031                "const unsigned      g;\n"
2032                "Const unsigned      h;",
2033                Style);
2034 
2035   Style.PointerAlignment = FormatStyle::PAS_Left;
2036   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
2037   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
2038   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
2039   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
2040   verifyFormat("int* a = f1();", Style);
2041   verifyFormat("int & b = f2();", Style);
2042   verifyFormat("int && c = f3();", Style);
2043   verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
2044   verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
2045   verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
2046   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2047   verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
2048   verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
2049   verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
2050   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2051   verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
2052   verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
2053   verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
2054   verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
2055   verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
2056   verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
2057 
2058   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2059   verifyFormat("Const unsigned int*  c;\n"
2060                "const unsigned int*  d;\n"
2061                "Const unsigned int & e;\n"
2062                "const unsigned int & f;\n"
2063                "const unsigned &&    g;\n"
2064                "Const unsigned       h;",
2065                Style);
2066 
2067   Style.PointerAlignment = FormatStyle::PAS_Middle;
2068   Style.ReferenceAlignment = FormatStyle::RAS_Right;
2069   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
2070   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
2071   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
2072   verifyFormat("int * a = f1();", Style);
2073   verifyFormat("int &b = f2();", Style);
2074   verifyFormat("int &&c = f3();", Style);
2075   verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2076   verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2077   verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
2078 
2079   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2080   // specifically handled
2081   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2082 }
2083 
2084 TEST_F(FormatTest, FormatsForLoop) {
2085   verifyFormat(
2086       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2087       "     ++VeryVeryLongLoopVariable)\n"
2088       "  ;");
2089   verifyFormat("for (;;)\n"
2090                "  f();");
2091   verifyFormat("for (;;) {\n}");
2092   verifyFormat("for (;;) {\n"
2093                "  f();\n"
2094                "}");
2095   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2096 
2097   verifyFormat(
2098       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2099       "                                          E = UnwrappedLines.end();\n"
2100       "     I != E; ++I) {\n}");
2101 
2102   verifyFormat(
2103       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2104       "     ++IIIII) {\n}");
2105   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2106                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2107                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2108   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2109                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2110                "         E = FD->getDeclsInPrototypeScope().end();\n"
2111                "     I != E; ++I) {\n}");
2112   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2113                "         I = Container.begin(),\n"
2114                "         E = Container.end();\n"
2115                "     I != E; ++I) {\n}",
2116                getLLVMStyleWithColumns(76));
2117 
2118   verifyFormat(
2119       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2120       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2121       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2122       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2123       "     ++aaaaaaaaaaa) {\n}");
2124   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2125                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2126                "     ++i) {\n}");
2127   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2128                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2129                "}");
2130   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2131                "         aaaaaaaaaa);\n"
2132                "     iter; ++iter) {\n"
2133                "}");
2134   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2135                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2136                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2137                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2138 
2139   // These should not be formatted as Objective-C for-in loops.
2140   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2141   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2142   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2143   verifyFormat(
2144       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2145 
2146   FormatStyle NoBinPacking = getLLVMStyle();
2147   NoBinPacking.BinPackParameters = false;
2148   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2149                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2150                "                                           aaaaaaaaaaaaaaaa,\n"
2151                "                                           aaaaaaaaaaaaaaaa,\n"
2152                "                                           aaaaaaaaaaaaaaaa);\n"
2153                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2154                "}",
2155                NoBinPacking);
2156   verifyFormat(
2157       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2158       "                                          E = UnwrappedLines.end();\n"
2159       "     I != E;\n"
2160       "     ++I) {\n}",
2161       NoBinPacking);
2162 
2163   FormatStyle AlignLeft = getLLVMStyle();
2164   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2165   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2166 }
2167 
2168 TEST_F(FormatTest, RangeBasedForLoops) {
2169   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2170                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2171   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2172                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2173   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2174                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2175   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2176                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2177 }
2178 
2179 TEST_F(FormatTest, ForEachLoops) {
2180   FormatStyle Style = getLLVMStyle();
2181   EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2182   EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
2183   verifyFormat("void f() {\n"
2184                "  for (;;) {\n"
2185                "  }\n"
2186                "  foreach (Item *item, itemlist) {\n"
2187                "  }\n"
2188                "  Q_FOREACH (Item *item, itemlist) {\n"
2189                "  }\n"
2190                "  BOOST_FOREACH (Item *item, itemlist) {\n"
2191                "  }\n"
2192                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2193                "}",
2194                Style);
2195   verifyFormat("void f() {\n"
2196                "  for (;;)\n"
2197                "    int j = 1;\n"
2198                "  Q_FOREACH (int v, vec)\n"
2199                "    v *= 2;\n"
2200                "  for (;;) {\n"
2201                "    int j = 1;\n"
2202                "  }\n"
2203                "  Q_FOREACH (int v, vec) {\n"
2204                "    v *= 2;\n"
2205                "  }\n"
2206                "}",
2207                Style);
2208 
2209   FormatStyle ShortBlocks = getLLVMStyle();
2210   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2211   EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
2212   verifyFormat("void f() {\n"
2213                "  for (;;)\n"
2214                "    int j = 1;\n"
2215                "  Q_FOREACH (int &v, vec)\n"
2216                "    v *= 2;\n"
2217                "  for (;;) {\n"
2218                "    int j = 1;\n"
2219                "  }\n"
2220                "  Q_FOREACH (int &v, vec) {\n"
2221                "    int j = 1;\n"
2222                "  }\n"
2223                "}",
2224                ShortBlocks);
2225 
2226   FormatStyle ShortLoops = getLLVMStyle();
2227   ShortLoops.AllowShortLoopsOnASingleLine = true;
2228   EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2229   verifyFormat("void f() {\n"
2230                "  for (;;) int j = 1;\n"
2231                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2232                "  for (;;) {\n"
2233                "    int j = 1;\n"
2234                "  }\n"
2235                "  Q_FOREACH (int &v, vec) {\n"
2236                "    int j = 1;\n"
2237                "  }\n"
2238                "}",
2239                ShortLoops);
2240 
2241   FormatStyle ShortBlocksAndLoops = getLLVMStyle();
2242   ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2243   ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true;
2244   verifyFormat("void f() {\n"
2245                "  for (;;) int j = 1;\n"
2246                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2247                "  for (;;) { int j = 1; }\n"
2248                "  Q_FOREACH (int &v, vec) { int j = 1; }\n"
2249                "}",
2250                ShortBlocksAndLoops);
2251 
2252   Style.SpaceBeforeParens =
2253       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2254   verifyFormat("void f() {\n"
2255                "  for (;;) {\n"
2256                "  }\n"
2257                "  foreach(Item *item, itemlist) {\n"
2258                "  }\n"
2259                "  Q_FOREACH(Item *item, itemlist) {\n"
2260                "  }\n"
2261                "  BOOST_FOREACH(Item *item, itemlist) {\n"
2262                "  }\n"
2263                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2264                "}",
2265                Style);
2266 
2267   // As function-like macros.
2268   verifyFormat("#define foreach(x, y)\n"
2269                "#define Q_FOREACH(x, y)\n"
2270                "#define BOOST_FOREACH(x, y)\n"
2271                "#define UNKNOWN_FOREACH(x, y)\n");
2272 
2273   // Not as function-like macros.
2274   verifyFormat("#define foreach (x, y)\n"
2275                "#define Q_FOREACH (x, y)\n"
2276                "#define BOOST_FOREACH (x, y)\n"
2277                "#define UNKNOWN_FOREACH (x, y)\n");
2278 
2279   // handle microsoft non standard extension
2280   verifyFormat("for each (char c in x->MyStringProperty)");
2281 }
2282 
2283 TEST_F(FormatTest, FormatsWhileLoop) {
2284   verifyFormat("while (true) {\n}");
2285   verifyFormat("while (true)\n"
2286                "  f();");
2287   verifyFormat("while () {\n}");
2288   verifyFormat("while () {\n"
2289                "  f();\n"
2290                "}");
2291 }
2292 
2293 TEST_F(FormatTest, FormatsDoWhile) {
2294   verifyFormat("do {\n"
2295                "  do_something();\n"
2296                "} while (something());");
2297   verifyFormat("do\n"
2298                "  do_something();\n"
2299                "while (something());");
2300 }
2301 
2302 TEST_F(FormatTest, FormatsSwitchStatement) {
2303   verifyFormat("switch (x) {\n"
2304                "case 1:\n"
2305                "  f();\n"
2306                "  break;\n"
2307                "case kFoo:\n"
2308                "case ns::kBar:\n"
2309                "case kBaz:\n"
2310                "  break;\n"
2311                "default:\n"
2312                "  g();\n"
2313                "  break;\n"
2314                "}");
2315   verifyFormat("switch (x) {\n"
2316                "case 1: {\n"
2317                "  f();\n"
2318                "  break;\n"
2319                "}\n"
2320                "case 2: {\n"
2321                "  break;\n"
2322                "}\n"
2323                "}");
2324   verifyFormat("switch (x) {\n"
2325                "case 1: {\n"
2326                "  f();\n"
2327                "  {\n"
2328                "    g();\n"
2329                "    h();\n"
2330                "  }\n"
2331                "  break;\n"
2332                "}\n"
2333                "}");
2334   verifyFormat("switch (x) {\n"
2335                "case 1: {\n"
2336                "  f();\n"
2337                "  if (foo) {\n"
2338                "    g();\n"
2339                "    h();\n"
2340                "  }\n"
2341                "  break;\n"
2342                "}\n"
2343                "}");
2344   verifyFormat("switch (x) {\n"
2345                "case 1: {\n"
2346                "  f();\n"
2347                "  g();\n"
2348                "} break;\n"
2349                "}");
2350   verifyFormat("switch (test)\n"
2351                "  ;");
2352   verifyFormat("switch (x) {\n"
2353                "default: {\n"
2354                "  // Do nothing.\n"
2355                "}\n"
2356                "}");
2357   verifyFormat("switch (x) {\n"
2358                "// comment\n"
2359                "// if 1, do f()\n"
2360                "case 1:\n"
2361                "  f();\n"
2362                "}");
2363   verifyFormat("switch (x) {\n"
2364                "case 1:\n"
2365                "  // Do amazing stuff\n"
2366                "  {\n"
2367                "    f();\n"
2368                "    g();\n"
2369                "  }\n"
2370                "  break;\n"
2371                "}");
2372   verifyFormat("#define A          \\\n"
2373                "  switch (x) {     \\\n"
2374                "  case a:          \\\n"
2375                "    foo = b;       \\\n"
2376                "  }",
2377                getLLVMStyleWithColumns(20));
2378   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2379                "  case OP_name:                        \\\n"
2380                "    return operations::Operation##name\n",
2381                getLLVMStyleWithColumns(40));
2382   verifyFormat("switch (x) {\n"
2383                "case 1:;\n"
2384                "default:;\n"
2385                "  int i;\n"
2386                "}");
2387 
2388   verifyGoogleFormat("switch (x) {\n"
2389                      "  case 1:\n"
2390                      "    f();\n"
2391                      "    break;\n"
2392                      "  case kFoo:\n"
2393                      "  case ns::kBar:\n"
2394                      "  case kBaz:\n"
2395                      "    break;\n"
2396                      "  default:\n"
2397                      "    g();\n"
2398                      "    break;\n"
2399                      "}");
2400   verifyGoogleFormat("switch (x) {\n"
2401                      "  case 1: {\n"
2402                      "    f();\n"
2403                      "    break;\n"
2404                      "  }\n"
2405                      "}");
2406   verifyGoogleFormat("switch (test)\n"
2407                      "  ;");
2408 
2409   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2410                      "  case OP_name:              \\\n"
2411                      "    return operations::Operation##name\n");
2412   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2413                      "  // Get the correction operation class.\n"
2414                      "  switch (OpCode) {\n"
2415                      "    CASE(Add);\n"
2416                      "    CASE(Subtract);\n"
2417                      "    default:\n"
2418                      "      return operations::Unknown;\n"
2419                      "  }\n"
2420                      "#undef OPERATION_CASE\n"
2421                      "}");
2422   verifyFormat("DEBUG({\n"
2423                "  switch (x) {\n"
2424                "  case A:\n"
2425                "    f();\n"
2426                "    break;\n"
2427                "    // fallthrough\n"
2428                "  case B:\n"
2429                "    g();\n"
2430                "    break;\n"
2431                "  }\n"
2432                "});");
2433   EXPECT_EQ("DEBUG({\n"
2434             "  switch (x) {\n"
2435             "  case A:\n"
2436             "    f();\n"
2437             "    break;\n"
2438             "  // On B:\n"
2439             "  case B:\n"
2440             "    g();\n"
2441             "    break;\n"
2442             "  }\n"
2443             "});",
2444             format("DEBUG({\n"
2445                    "  switch (x) {\n"
2446                    "  case A:\n"
2447                    "    f();\n"
2448                    "    break;\n"
2449                    "  // On B:\n"
2450                    "  case B:\n"
2451                    "    g();\n"
2452                    "    break;\n"
2453                    "  }\n"
2454                    "});",
2455                    getLLVMStyle()));
2456   EXPECT_EQ("switch (n) {\n"
2457             "case 0: {\n"
2458             "  return false;\n"
2459             "}\n"
2460             "default: {\n"
2461             "  return true;\n"
2462             "}\n"
2463             "}",
2464             format("switch (n)\n"
2465                    "{\n"
2466                    "case 0: {\n"
2467                    "  return false;\n"
2468                    "}\n"
2469                    "default: {\n"
2470                    "  return true;\n"
2471                    "}\n"
2472                    "}",
2473                    getLLVMStyle()));
2474   verifyFormat("switch (a) {\n"
2475                "case (b):\n"
2476                "  return;\n"
2477                "}");
2478 
2479   verifyFormat("switch (a) {\n"
2480                "case some_namespace::\n"
2481                "    some_constant:\n"
2482                "  return;\n"
2483                "}",
2484                getLLVMStyleWithColumns(34));
2485 
2486   FormatStyle Style = getLLVMStyle();
2487   Style.IndentCaseLabels = true;
2488   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2489   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2490   Style.BraceWrapping.AfterCaseLabel = true;
2491   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2492   EXPECT_EQ("switch (n)\n"
2493             "{\n"
2494             "  case 0:\n"
2495             "  {\n"
2496             "    return false;\n"
2497             "  }\n"
2498             "  default:\n"
2499             "  {\n"
2500             "    return true;\n"
2501             "  }\n"
2502             "}",
2503             format("switch (n) {\n"
2504                    "  case 0: {\n"
2505                    "    return false;\n"
2506                    "  }\n"
2507                    "  default: {\n"
2508                    "    return true;\n"
2509                    "  }\n"
2510                    "}",
2511                    Style));
2512   Style.BraceWrapping.AfterCaseLabel = false;
2513   EXPECT_EQ("switch (n)\n"
2514             "{\n"
2515             "  case 0: {\n"
2516             "    return false;\n"
2517             "  }\n"
2518             "  default: {\n"
2519             "    return true;\n"
2520             "  }\n"
2521             "}",
2522             format("switch (n) {\n"
2523                    "  case 0:\n"
2524                    "  {\n"
2525                    "    return false;\n"
2526                    "  }\n"
2527                    "  default:\n"
2528                    "  {\n"
2529                    "    return true;\n"
2530                    "  }\n"
2531                    "}",
2532                    Style));
2533   Style.IndentCaseLabels = false;
2534   Style.IndentCaseBlocks = true;
2535   EXPECT_EQ("switch (n)\n"
2536             "{\n"
2537             "case 0:\n"
2538             "  {\n"
2539             "    return false;\n"
2540             "  }\n"
2541             "case 1:\n"
2542             "  break;\n"
2543             "default:\n"
2544             "  {\n"
2545             "    return true;\n"
2546             "  }\n"
2547             "}",
2548             format("switch (n) {\n"
2549                    "case 0: {\n"
2550                    "  return false;\n"
2551                    "}\n"
2552                    "case 1:\n"
2553                    "  break;\n"
2554                    "default: {\n"
2555                    "  return true;\n"
2556                    "}\n"
2557                    "}",
2558                    Style));
2559   Style.IndentCaseLabels = true;
2560   Style.IndentCaseBlocks = true;
2561   EXPECT_EQ("switch (n)\n"
2562             "{\n"
2563             "  case 0:\n"
2564             "    {\n"
2565             "      return false;\n"
2566             "    }\n"
2567             "  case 1:\n"
2568             "    break;\n"
2569             "  default:\n"
2570             "    {\n"
2571             "      return true;\n"
2572             "    }\n"
2573             "}",
2574             format("switch (n) {\n"
2575                    "case 0: {\n"
2576                    "  return false;\n"
2577                    "}\n"
2578                    "case 1:\n"
2579                    "  break;\n"
2580                    "default: {\n"
2581                    "  return true;\n"
2582                    "}\n"
2583                    "}",
2584                    Style));
2585 }
2586 
2587 TEST_F(FormatTest, CaseRanges) {
2588   verifyFormat("switch (x) {\n"
2589                "case 'A' ... 'Z':\n"
2590                "case 1 ... 5:\n"
2591                "case a ... b:\n"
2592                "  break;\n"
2593                "}");
2594 }
2595 
2596 TEST_F(FormatTest, ShortEnums) {
2597   FormatStyle Style = getLLVMStyle();
2598   Style.AllowShortEnumsOnASingleLine = true;
2599   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2600   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2601   Style.AllowShortEnumsOnASingleLine = false;
2602   verifyFormat("enum {\n"
2603                "  A,\n"
2604                "  B,\n"
2605                "  C\n"
2606                "} ShortEnum1, ShortEnum2;",
2607                Style);
2608   verifyFormat("typedef enum {\n"
2609                "  A,\n"
2610                "  B,\n"
2611                "  C\n"
2612                "} ShortEnum1, ShortEnum2;",
2613                Style);
2614   verifyFormat("enum {\n"
2615                "  A,\n"
2616                "} ShortEnum1, ShortEnum2;",
2617                Style);
2618   verifyFormat("typedef enum {\n"
2619                "  A,\n"
2620                "} ShortEnum1, ShortEnum2;",
2621                Style);
2622   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2623   Style.BraceWrapping.AfterEnum = true;
2624   verifyFormat("enum\n"
2625                "{\n"
2626                "  A,\n"
2627                "  B,\n"
2628                "  C\n"
2629                "} ShortEnum1, ShortEnum2;",
2630                Style);
2631   verifyFormat("typedef enum\n"
2632                "{\n"
2633                "  A,\n"
2634                "  B,\n"
2635                "  C\n"
2636                "} ShortEnum1, ShortEnum2;",
2637                Style);
2638 }
2639 
2640 TEST_F(FormatTest, ShortCaseLabels) {
2641   FormatStyle Style = getLLVMStyle();
2642   Style.AllowShortCaseLabelsOnASingleLine = true;
2643   verifyFormat("switch (a) {\n"
2644                "case 1: x = 1; break;\n"
2645                "case 2: return;\n"
2646                "case 3:\n"
2647                "case 4:\n"
2648                "case 5: return;\n"
2649                "case 6: // comment\n"
2650                "  return;\n"
2651                "case 7:\n"
2652                "  // comment\n"
2653                "  return;\n"
2654                "case 8:\n"
2655                "  x = 8; // comment\n"
2656                "  break;\n"
2657                "default: y = 1; break;\n"
2658                "}",
2659                Style);
2660   verifyFormat("switch (a) {\n"
2661                "case 0: return; // comment\n"
2662                "case 1: break;  // comment\n"
2663                "case 2: return;\n"
2664                "// comment\n"
2665                "case 3: return;\n"
2666                "// comment 1\n"
2667                "// comment 2\n"
2668                "// comment 3\n"
2669                "case 4: break; /* comment */\n"
2670                "case 5:\n"
2671                "  // comment\n"
2672                "  break;\n"
2673                "case 6: /* comment */ x = 1; break;\n"
2674                "case 7: x = /* comment */ 1; break;\n"
2675                "case 8:\n"
2676                "  x = 1; /* comment */\n"
2677                "  break;\n"
2678                "case 9:\n"
2679                "  break; // comment line 1\n"
2680                "         // comment line 2\n"
2681                "}",
2682                Style);
2683   EXPECT_EQ("switch (a) {\n"
2684             "case 1:\n"
2685             "  x = 8;\n"
2686             "  // fall through\n"
2687             "case 2: x = 8;\n"
2688             "// comment\n"
2689             "case 3:\n"
2690             "  return; /* comment line 1\n"
2691             "           * comment line 2 */\n"
2692             "case 4: i = 8;\n"
2693             "// something else\n"
2694             "#if FOO\n"
2695             "case 5: break;\n"
2696             "#endif\n"
2697             "}",
2698             format("switch (a) {\n"
2699                    "case 1: x = 8;\n"
2700                    "  // fall through\n"
2701                    "case 2:\n"
2702                    "  x = 8;\n"
2703                    "// comment\n"
2704                    "case 3:\n"
2705                    "  return; /* comment line 1\n"
2706                    "           * comment line 2 */\n"
2707                    "case 4:\n"
2708                    "  i = 8;\n"
2709                    "// something else\n"
2710                    "#if FOO\n"
2711                    "case 5: break;\n"
2712                    "#endif\n"
2713                    "}",
2714                    Style));
2715   EXPECT_EQ("switch (a) {\n"
2716             "case 0:\n"
2717             "  return; // long long long long long long long long long long "
2718             "long long comment\n"
2719             "          // line\n"
2720             "}",
2721             format("switch (a) {\n"
2722                    "case 0: return; // long long long long long long long long "
2723                    "long long long long comment line\n"
2724                    "}",
2725                    Style));
2726   EXPECT_EQ("switch (a) {\n"
2727             "case 0:\n"
2728             "  return; /* long long long long long long long long long long "
2729             "long long comment\n"
2730             "             line */\n"
2731             "}",
2732             format("switch (a) {\n"
2733                    "case 0: return; /* long long long long long long long long "
2734                    "long long long long comment line */\n"
2735                    "}",
2736                    Style));
2737   verifyFormat("switch (a) {\n"
2738                "#if FOO\n"
2739                "case 0: return 0;\n"
2740                "#endif\n"
2741                "}",
2742                Style);
2743   verifyFormat("switch (a) {\n"
2744                "case 1: {\n"
2745                "}\n"
2746                "case 2: {\n"
2747                "  return;\n"
2748                "}\n"
2749                "case 3: {\n"
2750                "  x = 1;\n"
2751                "  return;\n"
2752                "}\n"
2753                "case 4:\n"
2754                "  if (x)\n"
2755                "    return;\n"
2756                "}",
2757                Style);
2758   Style.ColumnLimit = 21;
2759   verifyFormat("switch (a) {\n"
2760                "case 1: x = 1; break;\n"
2761                "case 2: return;\n"
2762                "case 3:\n"
2763                "case 4:\n"
2764                "case 5: return;\n"
2765                "default:\n"
2766                "  y = 1;\n"
2767                "  break;\n"
2768                "}",
2769                Style);
2770   Style.ColumnLimit = 80;
2771   Style.AllowShortCaseLabelsOnASingleLine = false;
2772   Style.IndentCaseLabels = true;
2773   EXPECT_EQ("switch (n) {\n"
2774             "  default /*comments*/:\n"
2775             "    return true;\n"
2776             "  case 0:\n"
2777             "    return false;\n"
2778             "}",
2779             format("switch (n) {\n"
2780                    "default/*comments*/:\n"
2781                    "  return true;\n"
2782                    "case 0:\n"
2783                    "  return false;\n"
2784                    "}",
2785                    Style));
2786   Style.AllowShortCaseLabelsOnASingleLine = true;
2787   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2788   Style.BraceWrapping.AfterCaseLabel = true;
2789   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2790   EXPECT_EQ("switch (n)\n"
2791             "{\n"
2792             "  case 0:\n"
2793             "  {\n"
2794             "    return false;\n"
2795             "  }\n"
2796             "  default:\n"
2797             "  {\n"
2798             "    return true;\n"
2799             "  }\n"
2800             "}",
2801             format("switch (n) {\n"
2802                    "  case 0: {\n"
2803                    "    return false;\n"
2804                    "  }\n"
2805                    "  default:\n"
2806                    "  {\n"
2807                    "    return true;\n"
2808                    "  }\n"
2809                    "}",
2810                    Style));
2811 }
2812 
2813 TEST_F(FormatTest, FormatsLabels) {
2814   verifyFormat("void f() {\n"
2815                "  some_code();\n"
2816                "test_label:\n"
2817                "  some_other_code();\n"
2818                "  {\n"
2819                "    some_more_code();\n"
2820                "  another_label:\n"
2821                "    some_more_code();\n"
2822                "  }\n"
2823                "}");
2824   verifyFormat("{\n"
2825                "  some_code();\n"
2826                "test_label:\n"
2827                "  some_other_code();\n"
2828                "}");
2829   verifyFormat("{\n"
2830                "  some_code();\n"
2831                "test_label:;\n"
2832                "  int i = 0;\n"
2833                "}");
2834   FormatStyle Style = getLLVMStyle();
2835   Style.IndentGotoLabels = false;
2836   verifyFormat("void f() {\n"
2837                "  some_code();\n"
2838                "test_label:\n"
2839                "  some_other_code();\n"
2840                "  {\n"
2841                "    some_more_code();\n"
2842                "another_label:\n"
2843                "    some_more_code();\n"
2844                "  }\n"
2845                "}",
2846                Style);
2847   verifyFormat("{\n"
2848                "  some_code();\n"
2849                "test_label:\n"
2850                "  some_other_code();\n"
2851                "}",
2852                Style);
2853   verifyFormat("{\n"
2854                "  some_code();\n"
2855                "test_label:;\n"
2856                "  int i = 0;\n"
2857                "}");
2858 }
2859 
2860 TEST_F(FormatTest, MultiLineControlStatements) {
2861   FormatStyle Style = getLLVMStyleWithColumns(20);
2862   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2863   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2864   // Short lines should keep opening brace on same line.
2865   EXPECT_EQ("if (foo) {\n"
2866             "  bar();\n"
2867             "}",
2868             format("if(foo){bar();}", Style));
2869   EXPECT_EQ("if (foo) {\n"
2870             "  bar();\n"
2871             "} else {\n"
2872             "  baz();\n"
2873             "}",
2874             format("if(foo){bar();}else{baz();}", Style));
2875   EXPECT_EQ("if (foo && bar) {\n"
2876             "  baz();\n"
2877             "}",
2878             format("if(foo&&bar){baz();}", Style));
2879   EXPECT_EQ("if (foo) {\n"
2880             "  bar();\n"
2881             "} else if (baz) {\n"
2882             "  quux();\n"
2883             "}",
2884             format("if(foo){bar();}else if(baz){quux();}", Style));
2885   EXPECT_EQ(
2886       "if (foo) {\n"
2887       "  bar();\n"
2888       "} else if (baz) {\n"
2889       "  quux();\n"
2890       "} else {\n"
2891       "  foobar();\n"
2892       "}",
2893       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
2894   EXPECT_EQ("for (;;) {\n"
2895             "  foo();\n"
2896             "}",
2897             format("for(;;){foo();}"));
2898   EXPECT_EQ("while (1) {\n"
2899             "  foo();\n"
2900             "}",
2901             format("while(1){foo();}", Style));
2902   EXPECT_EQ("switch (foo) {\n"
2903             "case bar:\n"
2904             "  return;\n"
2905             "}",
2906             format("switch(foo){case bar:return;}", Style));
2907   EXPECT_EQ("try {\n"
2908             "  foo();\n"
2909             "} catch (...) {\n"
2910             "  bar();\n"
2911             "}",
2912             format("try{foo();}catch(...){bar();}", Style));
2913   EXPECT_EQ("do {\n"
2914             "  foo();\n"
2915             "} while (bar &&\n"
2916             "         baz);",
2917             format("do{foo();}while(bar&&baz);", Style));
2918   // Long lines should put opening brace on new line.
2919   EXPECT_EQ("if (foo && bar &&\n"
2920             "    baz)\n"
2921             "{\n"
2922             "  quux();\n"
2923             "}",
2924             format("if(foo&&bar&&baz){quux();}", Style));
2925   EXPECT_EQ("if (foo && bar &&\n"
2926             "    baz)\n"
2927             "{\n"
2928             "  quux();\n"
2929             "}",
2930             format("if (foo && bar &&\n"
2931                    "    baz) {\n"
2932                    "  quux();\n"
2933                    "}",
2934                    Style));
2935   EXPECT_EQ("if (foo) {\n"
2936             "  bar();\n"
2937             "} else if (baz ||\n"
2938             "           quux)\n"
2939             "{\n"
2940             "  foobar();\n"
2941             "}",
2942             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
2943   EXPECT_EQ(
2944       "if (foo) {\n"
2945       "  bar();\n"
2946       "} else if (baz ||\n"
2947       "           quux)\n"
2948       "{\n"
2949       "  foobar();\n"
2950       "} else {\n"
2951       "  barbaz();\n"
2952       "}",
2953       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2954              Style));
2955   EXPECT_EQ("for (int i = 0;\n"
2956             "     i < 10; ++i)\n"
2957             "{\n"
2958             "  foo();\n"
2959             "}",
2960             format("for(int i=0;i<10;++i){foo();}", Style));
2961   EXPECT_EQ("foreach (int i,\n"
2962             "         list)\n"
2963             "{\n"
2964             "  foo();\n"
2965             "}",
2966             format("foreach(int i, list){foo();}", Style));
2967   Style.ColumnLimit =
2968       40; // to concentrate at brace wrapping, not line wrap due to column limit
2969   EXPECT_EQ("foreach (int i, list) {\n"
2970             "  foo();\n"
2971             "}",
2972             format("foreach(int i, list){foo();}", Style));
2973   Style.ColumnLimit =
2974       20; // to concentrate at brace wrapping, not line wrap due to column limit
2975   EXPECT_EQ("while (foo || bar ||\n"
2976             "       baz)\n"
2977             "{\n"
2978             "  quux();\n"
2979             "}",
2980             format("while(foo||bar||baz){quux();}", Style));
2981   EXPECT_EQ("switch (\n"
2982             "    foo = barbaz)\n"
2983             "{\n"
2984             "case quux:\n"
2985             "  return;\n"
2986             "}",
2987             format("switch(foo=barbaz){case quux:return;}", Style));
2988   EXPECT_EQ("try {\n"
2989             "  foo();\n"
2990             "} catch (\n"
2991             "    Exception &bar)\n"
2992             "{\n"
2993             "  baz();\n"
2994             "}",
2995             format("try{foo();}catch(Exception&bar){baz();}", Style));
2996   Style.ColumnLimit =
2997       40; // to concentrate at brace wrapping, not line wrap due to column limit
2998   EXPECT_EQ("try {\n"
2999             "  foo();\n"
3000             "} catch (Exception &bar) {\n"
3001             "  baz();\n"
3002             "}",
3003             format("try{foo();}catch(Exception&bar){baz();}", Style));
3004   Style.ColumnLimit =
3005       20; // to concentrate at brace wrapping, not line wrap due to column limit
3006 
3007   Style.BraceWrapping.BeforeElse = true;
3008   EXPECT_EQ(
3009       "if (foo) {\n"
3010       "  bar();\n"
3011       "}\n"
3012       "else if (baz ||\n"
3013       "         quux)\n"
3014       "{\n"
3015       "  foobar();\n"
3016       "}\n"
3017       "else {\n"
3018       "  barbaz();\n"
3019       "}",
3020       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3021              Style));
3022 
3023   Style.BraceWrapping.BeforeCatch = true;
3024   EXPECT_EQ("try {\n"
3025             "  foo();\n"
3026             "}\n"
3027             "catch (...) {\n"
3028             "  baz();\n"
3029             "}",
3030             format("try{foo();}catch(...){baz();}", Style));
3031 
3032   Style.BraceWrapping.AfterFunction = true;
3033   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3034   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
3035   Style.ColumnLimit = 80;
3036   verifyFormat("void shortfunction() { bar(); }", Style);
3037 
3038   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
3039   verifyFormat("void shortfunction()\n"
3040                "{\n"
3041                "  bar();\n"
3042                "}",
3043                Style);
3044 }
3045 
3046 TEST_F(FormatTest, BeforeWhile) {
3047   FormatStyle Style = getLLVMStyle();
3048   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3049 
3050   verifyFormat("do {\n"
3051                "  foo();\n"
3052                "} while (1);",
3053                Style);
3054   Style.BraceWrapping.BeforeWhile = true;
3055   verifyFormat("do {\n"
3056                "  foo();\n"
3057                "}\n"
3058                "while (1);",
3059                Style);
3060 }
3061 
3062 //===----------------------------------------------------------------------===//
3063 // Tests for classes, namespaces, etc.
3064 //===----------------------------------------------------------------------===//
3065 
3066 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
3067   verifyFormat("class A {};");
3068 }
3069 
3070 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
3071   verifyFormat("class A {\n"
3072                "public:\n"
3073                "public: // comment\n"
3074                "protected:\n"
3075                "private:\n"
3076                "  void f() {}\n"
3077                "};");
3078   verifyFormat("export class A {\n"
3079                "public:\n"
3080                "public: // comment\n"
3081                "protected:\n"
3082                "private:\n"
3083                "  void f() {}\n"
3084                "};");
3085   verifyGoogleFormat("class A {\n"
3086                      " public:\n"
3087                      " protected:\n"
3088                      " private:\n"
3089                      "  void f() {}\n"
3090                      "};");
3091   verifyGoogleFormat("export class A {\n"
3092                      " public:\n"
3093                      " protected:\n"
3094                      " private:\n"
3095                      "  void f() {}\n"
3096                      "};");
3097   verifyFormat("class A {\n"
3098                "public slots:\n"
3099                "  void f1() {}\n"
3100                "public Q_SLOTS:\n"
3101                "  void f2() {}\n"
3102                "protected slots:\n"
3103                "  void f3() {}\n"
3104                "protected Q_SLOTS:\n"
3105                "  void f4() {}\n"
3106                "private slots:\n"
3107                "  void f5() {}\n"
3108                "private Q_SLOTS:\n"
3109                "  void f6() {}\n"
3110                "signals:\n"
3111                "  void g1();\n"
3112                "Q_SIGNALS:\n"
3113                "  void g2();\n"
3114                "};");
3115 
3116   // Don't interpret 'signals' the wrong way.
3117   verifyFormat("signals.set();");
3118   verifyFormat("for (Signals signals : f()) {\n}");
3119   verifyFormat("{\n"
3120                "  signals.set(); // This needs indentation.\n"
3121                "}");
3122   verifyFormat("void f() {\n"
3123                "label:\n"
3124                "  signals.baz();\n"
3125                "}");
3126 }
3127 
3128 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3129   EXPECT_EQ("class A {\n"
3130             "public:\n"
3131             "  void f();\n"
3132             "\n"
3133             "private:\n"
3134             "  void g() {}\n"
3135             "  // test\n"
3136             "protected:\n"
3137             "  int h;\n"
3138             "};",
3139             format("class A {\n"
3140                    "public:\n"
3141                    "void f();\n"
3142                    "private:\n"
3143                    "void g() {}\n"
3144                    "// test\n"
3145                    "protected:\n"
3146                    "int h;\n"
3147                    "};"));
3148   EXPECT_EQ("class A {\n"
3149             "protected:\n"
3150             "public:\n"
3151             "  void f();\n"
3152             "};",
3153             format("class A {\n"
3154                    "protected:\n"
3155                    "\n"
3156                    "public:\n"
3157                    "\n"
3158                    "  void f();\n"
3159                    "};"));
3160 
3161   // Even ensure proper spacing inside macros.
3162   EXPECT_EQ("#define B     \\\n"
3163             "  class A {   \\\n"
3164             "   protected: \\\n"
3165             "   public:    \\\n"
3166             "    void f(); \\\n"
3167             "  };",
3168             format("#define B     \\\n"
3169                    "  class A {   \\\n"
3170                    "   protected: \\\n"
3171                    "              \\\n"
3172                    "   public:    \\\n"
3173                    "              \\\n"
3174                    "    void f(); \\\n"
3175                    "  };",
3176                    getGoogleStyle()));
3177   // But don't remove empty lines after macros ending in access specifiers.
3178   EXPECT_EQ("#define A private:\n"
3179             "\n"
3180             "int i;",
3181             format("#define A         private:\n"
3182                    "\n"
3183                    "int              i;"));
3184 }
3185 
3186 TEST_F(FormatTest, FormatsClasses) {
3187   verifyFormat("class A : public B {};");
3188   verifyFormat("class A : public ::B {};");
3189 
3190   verifyFormat(
3191       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3192       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3193   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3194                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3195                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3196   verifyFormat(
3197       "class A : public B, public C, public D, public E, public F {};");
3198   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3199                "                     public C,\n"
3200                "                     public D,\n"
3201                "                     public E,\n"
3202                "                     public F,\n"
3203                "                     public G {};");
3204 
3205   verifyFormat("class\n"
3206                "    ReallyReallyLongClassName {\n"
3207                "  int i;\n"
3208                "};",
3209                getLLVMStyleWithColumns(32));
3210   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3211                "                           aaaaaaaaaaaaaaaa> {};");
3212   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3213                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3214                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3215   verifyFormat("template <class R, class C>\n"
3216                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3217                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3218   verifyFormat("class ::A::B {};");
3219 }
3220 
3221 TEST_F(FormatTest, BreakInheritanceStyle) {
3222   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3223   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3224       FormatStyle::BILS_BeforeComma;
3225   verifyFormat("class MyClass : public X {};",
3226                StyleWithInheritanceBreakBeforeComma);
3227   verifyFormat("class MyClass\n"
3228                "    : public X\n"
3229                "    , public Y {};",
3230                StyleWithInheritanceBreakBeforeComma);
3231   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3232                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3233                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3234                StyleWithInheritanceBreakBeforeComma);
3235   verifyFormat("struct aaaaaaaaaaaaa\n"
3236                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3237                "          aaaaaaaaaaaaaaaa> {};",
3238                StyleWithInheritanceBreakBeforeComma);
3239 
3240   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3241   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3242       FormatStyle::BILS_AfterColon;
3243   verifyFormat("class MyClass : public X {};",
3244                StyleWithInheritanceBreakAfterColon);
3245   verifyFormat("class MyClass : public X, public Y {};",
3246                StyleWithInheritanceBreakAfterColon);
3247   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3248                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3249                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3250                StyleWithInheritanceBreakAfterColon);
3251   verifyFormat("struct aaaaaaaaaaaaa :\n"
3252                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3253                "        aaaaaaaaaaaaaaaa> {};",
3254                StyleWithInheritanceBreakAfterColon);
3255 
3256   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3257   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3258       FormatStyle::BILS_AfterComma;
3259   verifyFormat("class MyClass : public X {};",
3260                StyleWithInheritanceBreakAfterComma);
3261   verifyFormat("class MyClass : public X,\n"
3262                "                public Y {};",
3263                StyleWithInheritanceBreakAfterComma);
3264   verifyFormat(
3265       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3266       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3267       "{};",
3268       StyleWithInheritanceBreakAfterComma);
3269   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3270                "                           aaaaaaaaaaaaaaaa> {};",
3271                StyleWithInheritanceBreakAfterComma);
3272   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3273                "    : public OnceBreak,\n"
3274                "      public AlwaysBreak,\n"
3275                "      EvenBasesFitInOneLine {};",
3276                StyleWithInheritanceBreakAfterComma);
3277 }
3278 
3279 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
3280   verifyFormat("class A {\n} a, b;");
3281   verifyFormat("struct A {\n} a, b;");
3282   verifyFormat("union A {\n} a;");
3283 }
3284 
3285 TEST_F(FormatTest, FormatsEnum) {
3286   verifyFormat("enum {\n"
3287                "  Zero,\n"
3288                "  One = 1,\n"
3289                "  Two = One + 1,\n"
3290                "  Three = (One + Two),\n"
3291                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3292                "  Five = (One, Two, Three, Four, 5)\n"
3293                "};");
3294   verifyGoogleFormat("enum {\n"
3295                      "  Zero,\n"
3296                      "  One = 1,\n"
3297                      "  Two = One + 1,\n"
3298                      "  Three = (One + Two),\n"
3299                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3300                      "  Five = (One, Two, Three, Four, 5)\n"
3301                      "};");
3302   verifyFormat("enum Enum {};");
3303   verifyFormat("enum {};");
3304   verifyFormat("enum X E {} d;");
3305   verifyFormat("enum __attribute__((...)) E {} d;");
3306   verifyFormat("enum __declspec__((...)) E {} d;");
3307   verifyFormat("enum {\n"
3308                "  Bar = Foo<int, int>::value\n"
3309                "};",
3310                getLLVMStyleWithColumns(30));
3311 
3312   verifyFormat("enum ShortEnum { A, B, C };");
3313   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3314 
3315   EXPECT_EQ("enum KeepEmptyLines {\n"
3316             "  ONE,\n"
3317             "\n"
3318             "  TWO,\n"
3319             "\n"
3320             "  THREE\n"
3321             "}",
3322             format("enum KeepEmptyLines {\n"
3323                    "  ONE,\n"
3324                    "\n"
3325                    "  TWO,\n"
3326                    "\n"
3327                    "\n"
3328                    "  THREE\n"
3329                    "}"));
3330   verifyFormat("enum E { // comment\n"
3331                "  ONE,\n"
3332                "  TWO\n"
3333                "};\n"
3334                "int i;");
3335 
3336   FormatStyle EightIndent = getLLVMStyle();
3337   EightIndent.IndentWidth = 8;
3338   verifyFormat("enum {\n"
3339                "        VOID,\n"
3340                "        CHAR,\n"
3341                "        SHORT,\n"
3342                "        INT,\n"
3343                "        LONG,\n"
3344                "        SIGNED,\n"
3345                "        UNSIGNED,\n"
3346                "        BOOL,\n"
3347                "        FLOAT,\n"
3348                "        DOUBLE,\n"
3349                "        COMPLEX\n"
3350                "};",
3351                EightIndent);
3352 
3353   // Not enums.
3354   verifyFormat("enum X f() {\n"
3355                "  a();\n"
3356                "  return 42;\n"
3357                "}");
3358   verifyFormat("enum X Type::f() {\n"
3359                "  a();\n"
3360                "  return 42;\n"
3361                "}");
3362   verifyFormat("enum ::X f() {\n"
3363                "  a();\n"
3364                "  return 42;\n"
3365                "}");
3366   verifyFormat("enum ns::X f() {\n"
3367                "  a();\n"
3368                "  return 42;\n"
3369                "}");
3370 }
3371 
3372 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3373   verifyFormat("enum Type {\n"
3374                "  One = 0; // These semicolons should be commas.\n"
3375                "  Two = 1;\n"
3376                "};");
3377   verifyFormat("namespace n {\n"
3378                "enum Type {\n"
3379                "  One,\n"
3380                "  Two, // missing };\n"
3381                "  int i;\n"
3382                "}\n"
3383                "void g() {}");
3384 }
3385 
3386 TEST_F(FormatTest, FormatsEnumStruct) {
3387   verifyFormat("enum struct {\n"
3388                "  Zero,\n"
3389                "  One = 1,\n"
3390                "  Two = One + 1,\n"
3391                "  Three = (One + Two),\n"
3392                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3393                "  Five = (One, Two, Three, Four, 5)\n"
3394                "};");
3395   verifyFormat("enum struct Enum {};");
3396   verifyFormat("enum struct {};");
3397   verifyFormat("enum struct X E {} d;");
3398   verifyFormat("enum struct __attribute__((...)) E {} d;");
3399   verifyFormat("enum struct __declspec__((...)) E {} d;");
3400   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3401 }
3402 
3403 TEST_F(FormatTest, FormatsEnumClass) {
3404   verifyFormat("enum class {\n"
3405                "  Zero,\n"
3406                "  One = 1,\n"
3407                "  Two = One + 1,\n"
3408                "  Three = (One + Two),\n"
3409                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3410                "  Five = (One, Two, Three, Four, 5)\n"
3411                "};");
3412   verifyFormat("enum class Enum {};");
3413   verifyFormat("enum class {};");
3414   verifyFormat("enum class X E {} d;");
3415   verifyFormat("enum class __attribute__((...)) E {} d;");
3416   verifyFormat("enum class __declspec__((...)) E {} d;");
3417   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3418 }
3419 
3420 TEST_F(FormatTest, FormatsEnumTypes) {
3421   verifyFormat("enum X : int {\n"
3422                "  A, // Force multiple lines.\n"
3423                "  B\n"
3424                "};");
3425   verifyFormat("enum X : int { A, B };");
3426   verifyFormat("enum X : std::uint32_t { A, B };");
3427 }
3428 
3429 TEST_F(FormatTest, FormatsTypedefEnum) {
3430   FormatStyle Style = getLLVMStyleWithColumns(40);
3431   verifyFormat("typedef enum {} EmptyEnum;");
3432   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3433   verifyFormat("typedef enum {\n"
3434                "  ZERO = 0,\n"
3435                "  ONE = 1,\n"
3436                "  TWO = 2,\n"
3437                "  THREE = 3\n"
3438                "} LongEnum;",
3439                Style);
3440   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3441   Style.BraceWrapping.AfterEnum = true;
3442   verifyFormat("typedef enum {} EmptyEnum;");
3443   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3444   verifyFormat("typedef enum\n"
3445                "{\n"
3446                "  ZERO = 0,\n"
3447                "  ONE = 1,\n"
3448                "  TWO = 2,\n"
3449                "  THREE = 3\n"
3450                "} LongEnum;",
3451                Style);
3452 }
3453 
3454 TEST_F(FormatTest, FormatsNSEnums) {
3455   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3456   verifyGoogleFormat(
3457       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3458   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3459                      "  // Information about someDecentlyLongValue.\n"
3460                      "  someDecentlyLongValue,\n"
3461                      "  // Information about anotherDecentlyLongValue.\n"
3462                      "  anotherDecentlyLongValue,\n"
3463                      "  // Information about aThirdDecentlyLongValue.\n"
3464                      "  aThirdDecentlyLongValue\n"
3465                      "};");
3466   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3467                      "  // Information about someDecentlyLongValue.\n"
3468                      "  someDecentlyLongValue,\n"
3469                      "  // Information about anotherDecentlyLongValue.\n"
3470                      "  anotherDecentlyLongValue,\n"
3471                      "  // Information about aThirdDecentlyLongValue.\n"
3472                      "  aThirdDecentlyLongValue\n"
3473                      "};");
3474   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3475                      "  a = 1,\n"
3476                      "  b = 2,\n"
3477                      "  c = 3,\n"
3478                      "};");
3479   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3480                      "  a = 1,\n"
3481                      "  b = 2,\n"
3482                      "  c = 3,\n"
3483                      "};");
3484   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3485                      "  a = 1,\n"
3486                      "  b = 2,\n"
3487                      "  c = 3,\n"
3488                      "};");
3489   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3490                      "  a = 1,\n"
3491                      "  b = 2,\n"
3492                      "  c = 3,\n"
3493                      "};");
3494 }
3495 
3496 TEST_F(FormatTest, FormatsBitfields) {
3497   verifyFormat("struct Bitfields {\n"
3498                "  unsigned sClass : 8;\n"
3499                "  unsigned ValueKind : 2;\n"
3500                "};");
3501   verifyFormat("struct A {\n"
3502                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3503                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3504                "};");
3505   verifyFormat("struct MyStruct {\n"
3506                "  uchar data;\n"
3507                "  uchar : 8;\n"
3508                "  uchar : 8;\n"
3509                "  uchar other;\n"
3510                "};");
3511   FormatStyle Style = getLLVMStyle();
3512   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3513   verifyFormat("struct Bitfields {\n"
3514                "  unsigned sClass:8;\n"
3515                "  unsigned ValueKind:2;\n"
3516                "  uchar other;\n"
3517                "};",
3518                Style);
3519   verifyFormat("struct A {\n"
3520                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3521                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3522                "};",
3523                Style);
3524   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3525   verifyFormat("struct Bitfields {\n"
3526                "  unsigned sClass :8;\n"
3527                "  unsigned ValueKind :2;\n"
3528                "  uchar other;\n"
3529                "};",
3530                Style);
3531   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3532   verifyFormat("struct Bitfields {\n"
3533                "  unsigned sClass: 8;\n"
3534                "  unsigned ValueKind: 2;\n"
3535                "  uchar other;\n"
3536                "};",
3537                Style);
3538 }
3539 
3540 TEST_F(FormatTest, FormatsNamespaces) {
3541   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3542   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3543 
3544   verifyFormat("namespace some_namespace {\n"
3545                "class A {};\n"
3546                "void f() { f(); }\n"
3547                "}",
3548                LLVMWithNoNamespaceFix);
3549   verifyFormat("namespace N::inline D {\n"
3550                "class A {};\n"
3551                "void f() { f(); }\n"
3552                "}",
3553                LLVMWithNoNamespaceFix);
3554   verifyFormat("namespace N::inline D::E {\n"
3555                "class A {};\n"
3556                "void f() { f(); }\n"
3557                "}",
3558                LLVMWithNoNamespaceFix);
3559   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3560                "class A {};\n"
3561                "void f() { f(); }\n"
3562                "}",
3563                LLVMWithNoNamespaceFix);
3564   verifyFormat("/* something */ namespace some_namespace {\n"
3565                "class A {};\n"
3566                "void f() { f(); }\n"
3567                "}",
3568                LLVMWithNoNamespaceFix);
3569   verifyFormat("namespace {\n"
3570                "class A {};\n"
3571                "void f() { f(); }\n"
3572                "}",
3573                LLVMWithNoNamespaceFix);
3574   verifyFormat("/* something */ namespace {\n"
3575                "class A {};\n"
3576                "void f() { f(); }\n"
3577                "}",
3578                LLVMWithNoNamespaceFix);
3579   verifyFormat("inline namespace X {\n"
3580                "class A {};\n"
3581                "void f() { f(); }\n"
3582                "}",
3583                LLVMWithNoNamespaceFix);
3584   verifyFormat("/* something */ inline namespace X {\n"
3585                "class A {};\n"
3586                "void f() { f(); }\n"
3587                "}",
3588                LLVMWithNoNamespaceFix);
3589   verifyFormat("export namespace X {\n"
3590                "class A {};\n"
3591                "void f() { f(); }\n"
3592                "}",
3593                LLVMWithNoNamespaceFix);
3594   verifyFormat("using namespace some_namespace;\n"
3595                "class A {};\n"
3596                "void f() { f(); }",
3597                LLVMWithNoNamespaceFix);
3598 
3599   // This code is more common than we thought; if we
3600   // layout this correctly the semicolon will go into
3601   // its own line, which is undesirable.
3602   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3603   verifyFormat("namespace {\n"
3604                "class A {};\n"
3605                "};",
3606                LLVMWithNoNamespaceFix);
3607 
3608   verifyFormat("namespace {\n"
3609                "int SomeVariable = 0; // comment\n"
3610                "} // namespace",
3611                LLVMWithNoNamespaceFix);
3612   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3613             "#define HEADER_GUARD\n"
3614             "namespace my_namespace {\n"
3615             "int i;\n"
3616             "} // my_namespace\n"
3617             "#endif // HEADER_GUARD",
3618             format("#ifndef HEADER_GUARD\n"
3619                    " #define HEADER_GUARD\n"
3620                    "   namespace my_namespace {\n"
3621                    "int i;\n"
3622                    "}    // my_namespace\n"
3623                    "#endif    // HEADER_GUARD",
3624                    LLVMWithNoNamespaceFix));
3625 
3626   EXPECT_EQ("namespace A::B {\n"
3627             "class C {};\n"
3628             "}",
3629             format("namespace A::B {\n"
3630                    "class C {};\n"
3631                    "}",
3632                    LLVMWithNoNamespaceFix));
3633 
3634   FormatStyle Style = getLLVMStyle();
3635   Style.NamespaceIndentation = FormatStyle::NI_All;
3636   EXPECT_EQ("namespace out {\n"
3637             "  int i;\n"
3638             "  namespace in {\n"
3639             "    int i;\n"
3640             "  } // namespace in\n"
3641             "} // namespace out",
3642             format("namespace out {\n"
3643                    "int i;\n"
3644                    "namespace in {\n"
3645                    "int i;\n"
3646                    "} // namespace in\n"
3647                    "} // namespace out",
3648                    Style));
3649 
3650   FormatStyle ShortInlineFunctions = getLLVMStyle();
3651   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3652   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3653       FormatStyle::SFS_Inline;
3654   verifyFormat("namespace {\n"
3655                "  void f() {\n"
3656                "    return;\n"
3657                "  }\n"
3658                "} // namespace\n",
3659                ShortInlineFunctions);
3660   verifyFormat("namespace {\n"
3661                "  int some_int;\n"
3662                "  void f() {\n"
3663                "    return;\n"
3664                "  }\n"
3665                "} // namespace\n",
3666                ShortInlineFunctions);
3667   verifyFormat("namespace interface {\n"
3668                "  void f() {\n"
3669                "    return;\n"
3670                "  }\n"
3671                "} // namespace interface\n",
3672                ShortInlineFunctions);
3673   verifyFormat("namespace {\n"
3674                "  class X {\n"
3675                "    void f() { return; }\n"
3676                "  };\n"
3677                "} // namespace\n",
3678                ShortInlineFunctions);
3679   verifyFormat("namespace {\n"
3680                "  struct X {\n"
3681                "    void f() { return; }\n"
3682                "  };\n"
3683                "} // namespace\n",
3684                ShortInlineFunctions);
3685   verifyFormat("namespace {\n"
3686                "  union X {\n"
3687                "    void f() { return; }\n"
3688                "  };\n"
3689                "} // namespace\n",
3690                ShortInlineFunctions);
3691   verifyFormat("extern \"C\" {\n"
3692                "void f() {\n"
3693                "  return;\n"
3694                "}\n"
3695                "} // namespace\n",
3696                ShortInlineFunctions);
3697   verifyFormat("namespace {\n"
3698                "  class X {\n"
3699                "    void f() { return; }\n"
3700                "  } x;\n"
3701                "} // namespace\n",
3702                ShortInlineFunctions);
3703   verifyFormat("namespace {\n"
3704                "  [[nodiscard]] class X {\n"
3705                "    void f() { return; }\n"
3706                "  };\n"
3707                "} // namespace\n",
3708                ShortInlineFunctions);
3709   verifyFormat("namespace {\n"
3710                "  static class X {\n"
3711                "    void f() { return; }\n"
3712                "  } x;\n"
3713                "} // namespace\n",
3714                ShortInlineFunctions);
3715   verifyFormat("namespace {\n"
3716                "  constexpr class X {\n"
3717                "    void f() { return; }\n"
3718                "  } x;\n"
3719                "} // namespace\n",
3720                ShortInlineFunctions);
3721 
3722   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
3723   verifyFormat("extern \"C\" {\n"
3724                "  void f() {\n"
3725                "    return;\n"
3726                "  }\n"
3727                "} // namespace\n",
3728                ShortInlineFunctions);
3729 
3730   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3731   EXPECT_EQ("namespace out {\n"
3732             "int i;\n"
3733             "namespace in {\n"
3734             "  int i;\n"
3735             "} // namespace in\n"
3736             "} // namespace out",
3737             format("namespace out {\n"
3738                    "int i;\n"
3739                    "namespace in {\n"
3740                    "int i;\n"
3741                    "} // namespace in\n"
3742                    "} // namespace out",
3743                    Style));
3744 
3745   Style.NamespaceIndentation = FormatStyle::NI_None;
3746   verifyFormat("template <class T>\n"
3747                "concept a_concept = X<>;\n"
3748                "namespace B {\n"
3749                "struct b_struct {};\n"
3750                "} // namespace B\n",
3751                Style);
3752   verifyFormat("template <int I> constexpr void foo requires(I == 42) {}\n"
3753                "namespace ns {\n"
3754                "void foo() {}\n"
3755                "} // namespace ns\n",
3756                Style);
3757 }
3758 
3759 TEST_F(FormatTest, NamespaceMacros) {
3760   FormatStyle Style = getLLVMStyle();
3761   Style.NamespaceMacros.push_back("TESTSUITE");
3762 
3763   verifyFormat("TESTSUITE(A) {\n"
3764                "int foo();\n"
3765                "} // TESTSUITE(A)",
3766                Style);
3767 
3768   verifyFormat("TESTSUITE(A, B) {\n"
3769                "int foo();\n"
3770                "} // TESTSUITE(A)",
3771                Style);
3772 
3773   // Properly indent according to NamespaceIndentation style
3774   Style.NamespaceIndentation = FormatStyle::NI_All;
3775   verifyFormat("TESTSUITE(A) {\n"
3776                "  int foo();\n"
3777                "} // TESTSUITE(A)",
3778                Style);
3779   verifyFormat("TESTSUITE(A) {\n"
3780                "  namespace B {\n"
3781                "    int foo();\n"
3782                "  } // namespace B\n"
3783                "} // TESTSUITE(A)",
3784                Style);
3785   verifyFormat("namespace A {\n"
3786                "  TESTSUITE(B) {\n"
3787                "    int foo();\n"
3788                "  } // TESTSUITE(B)\n"
3789                "} // namespace A",
3790                Style);
3791 
3792   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3793   verifyFormat("TESTSUITE(A) {\n"
3794                "TESTSUITE(B) {\n"
3795                "  int foo();\n"
3796                "} // TESTSUITE(B)\n"
3797                "} // TESTSUITE(A)",
3798                Style);
3799   verifyFormat("TESTSUITE(A) {\n"
3800                "namespace B {\n"
3801                "  int foo();\n"
3802                "} // namespace B\n"
3803                "} // TESTSUITE(A)",
3804                Style);
3805   verifyFormat("namespace A {\n"
3806                "TESTSUITE(B) {\n"
3807                "  int foo();\n"
3808                "} // TESTSUITE(B)\n"
3809                "} // namespace A",
3810                Style);
3811 
3812   // Properly merge namespace-macros blocks in CompactNamespaces mode
3813   Style.NamespaceIndentation = FormatStyle::NI_None;
3814   Style.CompactNamespaces = true;
3815   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
3816                "}} // TESTSUITE(A::B)",
3817                Style);
3818 
3819   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3820             "}} // TESTSUITE(out::in)",
3821             format("TESTSUITE(out) {\n"
3822                    "TESTSUITE(in) {\n"
3823                    "} // TESTSUITE(in)\n"
3824                    "} // TESTSUITE(out)",
3825                    Style));
3826 
3827   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3828             "}} // TESTSUITE(out::in)",
3829             format("TESTSUITE(out) {\n"
3830                    "TESTSUITE(in) {\n"
3831                    "} // TESTSUITE(in)\n"
3832                    "} // TESTSUITE(out)",
3833                    Style));
3834 
3835   // Do not merge different namespaces/macros
3836   EXPECT_EQ("namespace out {\n"
3837             "TESTSUITE(in) {\n"
3838             "} // TESTSUITE(in)\n"
3839             "} // namespace out",
3840             format("namespace out {\n"
3841                    "TESTSUITE(in) {\n"
3842                    "} // TESTSUITE(in)\n"
3843                    "} // namespace out",
3844                    Style));
3845   EXPECT_EQ("TESTSUITE(out) {\n"
3846             "namespace in {\n"
3847             "} // namespace in\n"
3848             "} // TESTSUITE(out)",
3849             format("TESTSUITE(out) {\n"
3850                    "namespace in {\n"
3851                    "} // namespace in\n"
3852                    "} // TESTSUITE(out)",
3853                    Style));
3854   Style.NamespaceMacros.push_back("FOOBAR");
3855   EXPECT_EQ("TESTSUITE(out) {\n"
3856             "FOOBAR(in) {\n"
3857             "} // FOOBAR(in)\n"
3858             "} // TESTSUITE(out)",
3859             format("TESTSUITE(out) {\n"
3860                    "FOOBAR(in) {\n"
3861                    "} // FOOBAR(in)\n"
3862                    "} // TESTSUITE(out)",
3863                    Style));
3864 }
3865 
3866 TEST_F(FormatTest, FormatsCompactNamespaces) {
3867   FormatStyle Style = getLLVMStyle();
3868   Style.CompactNamespaces = true;
3869   Style.NamespaceMacros.push_back("TESTSUITE");
3870 
3871   verifyFormat("namespace A { namespace B {\n"
3872                "}} // namespace A::B",
3873                Style);
3874 
3875   EXPECT_EQ("namespace out { namespace in {\n"
3876             "}} // namespace out::in",
3877             format("namespace out {\n"
3878                    "namespace in {\n"
3879                    "} // namespace in\n"
3880                    "} // namespace out",
3881                    Style));
3882 
3883   // Only namespaces which have both consecutive opening and end get compacted
3884   EXPECT_EQ("namespace out {\n"
3885             "namespace in1 {\n"
3886             "} // namespace in1\n"
3887             "namespace in2 {\n"
3888             "} // namespace in2\n"
3889             "} // namespace out",
3890             format("namespace out {\n"
3891                    "namespace in1 {\n"
3892                    "} // namespace in1\n"
3893                    "namespace in2 {\n"
3894                    "} // namespace in2\n"
3895                    "} // namespace out",
3896                    Style));
3897 
3898   EXPECT_EQ("namespace out {\n"
3899             "int i;\n"
3900             "namespace in {\n"
3901             "int j;\n"
3902             "} // namespace in\n"
3903             "int k;\n"
3904             "} // namespace out",
3905             format("namespace out { int i;\n"
3906                    "namespace in { int j; } // namespace in\n"
3907                    "int k; } // namespace out",
3908                    Style));
3909 
3910   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
3911             "}}} // namespace A::B::C\n",
3912             format("namespace A { namespace B {\n"
3913                    "namespace C {\n"
3914                    "}} // namespace B::C\n"
3915                    "} // namespace A\n",
3916                    Style));
3917 
3918   Style.ColumnLimit = 40;
3919   EXPECT_EQ("namespace aaaaaaaaaa {\n"
3920             "namespace bbbbbbbbbb {\n"
3921             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
3922             format("namespace aaaaaaaaaa {\n"
3923                    "namespace bbbbbbbbbb {\n"
3924                    "} // namespace bbbbbbbbbb\n"
3925                    "} // namespace aaaaaaaaaa",
3926                    Style));
3927 
3928   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
3929             "namespace cccccc {\n"
3930             "}}} // namespace aaaaaa::bbbbbb::cccccc",
3931             format("namespace aaaaaa {\n"
3932                    "namespace bbbbbb {\n"
3933                    "namespace cccccc {\n"
3934                    "} // namespace cccccc\n"
3935                    "} // namespace bbbbbb\n"
3936                    "} // namespace aaaaaa",
3937                    Style));
3938   Style.ColumnLimit = 80;
3939 
3940   // Extra semicolon after 'inner' closing brace prevents merging
3941   EXPECT_EQ("namespace out { namespace in {\n"
3942             "}; } // namespace out::in",
3943             format("namespace out {\n"
3944                    "namespace in {\n"
3945                    "}; // namespace in\n"
3946                    "} // namespace out",
3947                    Style));
3948 
3949   // Extra semicolon after 'outer' closing brace is conserved
3950   EXPECT_EQ("namespace out { namespace in {\n"
3951             "}}; // namespace out::in",
3952             format("namespace out {\n"
3953                    "namespace in {\n"
3954                    "} // namespace in\n"
3955                    "}; // namespace out",
3956                    Style));
3957 
3958   Style.NamespaceIndentation = FormatStyle::NI_All;
3959   EXPECT_EQ("namespace out { namespace in {\n"
3960             "  int i;\n"
3961             "}} // namespace out::in",
3962             format("namespace out {\n"
3963                    "namespace in {\n"
3964                    "int i;\n"
3965                    "} // namespace in\n"
3966                    "} // namespace out",
3967                    Style));
3968   EXPECT_EQ("namespace out { namespace mid {\n"
3969             "  namespace in {\n"
3970             "    int j;\n"
3971             "  } // namespace in\n"
3972             "  int k;\n"
3973             "}} // namespace out::mid",
3974             format("namespace out { namespace mid {\n"
3975                    "namespace in { int j; } // namespace in\n"
3976                    "int k; }} // namespace out::mid",
3977                    Style));
3978 
3979   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3980   EXPECT_EQ("namespace out { namespace in {\n"
3981             "  int i;\n"
3982             "}} // namespace out::in",
3983             format("namespace out {\n"
3984                    "namespace in {\n"
3985                    "int i;\n"
3986                    "} // namespace in\n"
3987                    "} // namespace out",
3988                    Style));
3989   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
3990             "  int i;\n"
3991             "}}} // namespace out::mid::in",
3992             format("namespace out {\n"
3993                    "namespace mid {\n"
3994                    "namespace in {\n"
3995                    "int i;\n"
3996                    "} // namespace in\n"
3997                    "} // namespace mid\n"
3998                    "} // namespace out",
3999                    Style));
4000 
4001   Style.CompactNamespaces = true;
4002   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
4003   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4004   Style.BraceWrapping.BeforeLambdaBody = true;
4005   verifyFormat("namespace out { namespace in {\n"
4006                "}} // namespace out::in",
4007                Style);
4008   EXPECT_EQ("namespace out { namespace in {\n"
4009             "}} // namespace out::in",
4010             format("namespace out {\n"
4011                    "namespace in {\n"
4012                    "} // namespace in\n"
4013                    "} // namespace out",
4014                    Style));
4015 }
4016 
4017 TEST_F(FormatTest, FormatsExternC) {
4018   verifyFormat("extern \"C\" {\nint a;");
4019   verifyFormat("extern \"C\" {}");
4020   verifyFormat("extern \"C\" {\n"
4021                "int foo();\n"
4022                "}");
4023   verifyFormat("extern \"C\" int foo() {}");
4024   verifyFormat("extern \"C\" int foo();");
4025   verifyFormat("extern \"C\" int foo() {\n"
4026                "  int i = 42;\n"
4027                "  return i;\n"
4028                "}");
4029 
4030   FormatStyle Style = getLLVMStyle();
4031   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4032   Style.BraceWrapping.AfterFunction = true;
4033   verifyFormat("extern \"C\" int foo() {}", Style);
4034   verifyFormat("extern \"C\" int foo();", Style);
4035   verifyFormat("extern \"C\" int foo()\n"
4036                "{\n"
4037                "  int i = 42;\n"
4038                "  return i;\n"
4039                "}",
4040                Style);
4041 
4042   Style.BraceWrapping.AfterExternBlock = true;
4043   Style.BraceWrapping.SplitEmptyRecord = false;
4044   verifyFormat("extern \"C\"\n"
4045                "{}",
4046                Style);
4047   verifyFormat("extern \"C\"\n"
4048                "{\n"
4049                "  int foo();\n"
4050                "}",
4051                Style);
4052 }
4053 
4054 TEST_F(FormatTest, IndentExternBlockStyle) {
4055   FormatStyle Style = getLLVMStyle();
4056   Style.IndentWidth = 2;
4057 
4058   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4059   verifyFormat("extern \"C\" { /*9*/\n"
4060                "}",
4061                Style);
4062   verifyFormat("extern \"C\" {\n"
4063                "  int foo10();\n"
4064                "}",
4065                Style);
4066 
4067   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4068   verifyFormat("extern \"C\" { /*11*/\n"
4069                "}",
4070                Style);
4071   verifyFormat("extern \"C\" {\n"
4072                "int foo12();\n"
4073                "}",
4074                Style);
4075 
4076   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4077   Style.BraceWrapping.AfterExternBlock = true;
4078   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4079   verifyFormat("extern \"C\"\n"
4080                "{ /*13*/\n"
4081                "}",
4082                Style);
4083   verifyFormat("extern \"C\"\n{\n"
4084                "  int foo14();\n"
4085                "}",
4086                Style);
4087 
4088   Style.BraceWrapping.AfterExternBlock = false;
4089   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4090   verifyFormat("extern \"C\" { /*15*/\n"
4091                "}",
4092                Style);
4093   verifyFormat("extern \"C\" {\n"
4094                "int foo16();\n"
4095                "}",
4096                Style);
4097 
4098   Style.BraceWrapping.AfterExternBlock = true;
4099   verifyFormat("extern \"C\"\n"
4100                "{ /*13*/\n"
4101                "}",
4102                Style);
4103   verifyFormat("extern \"C\"\n"
4104                "{\n"
4105                "int foo14();\n"
4106                "}",
4107                Style);
4108 
4109   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4110   verifyFormat("extern \"C\"\n"
4111                "{ /*13*/\n"
4112                "}",
4113                Style);
4114   verifyFormat("extern \"C\"\n"
4115                "{\n"
4116                "  int foo14();\n"
4117                "}",
4118                Style);
4119 }
4120 
4121 TEST_F(FormatTest, FormatsInlineASM) {
4122   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4123   verifyFormat("asm(\"nop\" ::: \"memory\");");
4124   verifyFormat(
4125       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4126       "    \"cpuid\\n\\t\"\n"
4127       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4128       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4129       "    : \"a\"(value));");
4130   EXPECT_EQ(
4131       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4132       "  __asm {\n"
4133       "        mov     edx,[that] // vtable in edx\n"
4134       "        mov     eax,methodIndex\n"
4135       "        call    [edx][eax*4] // stdcall\n"
4136       "  }\n"
4137       "}",
4138       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4139              "    __asm {\n"
4140              "        mov     edx,[that] // vtable in edx\n"
4141              "        mov     eax,methodIndex\n"
4142              "        call    [edx][eax*4] // stdcall\n"
4143              "    }\n"
4144              "}"));
4145   EXPECT_EQ("_asm {\n"
4146             "  xor eax, eax;\n"
4147             "  cpuid;\n"
4148             "}",
4149             format("_asm {\n"
4150                    "  xor eax, eax;\n"
4151                    "  cpuid;\n"
4152                    "}"));
4153   verifyFormat("void function() {\n"
4154                "  // comment\n"
4155                "  asm(\"\");\n"
4156                "}");
4157   EXPECT_EQ("__asm {\n"
4158             "}\n"
4159             "int i;",
4160             format("__asm   {\n"
4161                    "}\n"
4162                    "int   i;"));
4163 }
4164 
4165 TEST_F(FormatTest, FormatTryCatch) {
4166   verifyFormat("try {\n"
4167                "  throw a * b;\n"
4168                "} catch (int a) {\n"
4169                "  // Do nothing.\n"
4170                "} catch (...) {\n"
4171                "  exit(42);\n"
4172                "}");
4173 
4174   // Function-level try statements.
4175   verifyFormat("int f() try { return 4; } catch (...) {\n"
4176                "  return 5;\n"
4177                "}");
4178   verifyFormat("class A {\n"
4179                "  int a;\n"
4180                "  A() try : a(0) {\n"
4181                "  } catch (...) {\n"
4182                "    throw;\n"
4183                "  }\n"
4184                "};\n");
4185   verifyFormat("class A {\n"
4186                "  int a;\n"
4187                "  A() try : a(0), b{1} {\n"
4188                "  } catch (...) {\n"
4189                "    throw;\n"
4190                "  }\n"
4191                "};\n");
4192   verifyFormat("class A {\n"
4193                "  int a;\n"
4194                "  A() try : a(0), b{1}, c{2} {\n"
4195                "  } catch (...) {\n"
4196                "    throw;\n"
4197                "  }\n"
4198                "};\n");
4199   verifyFormat("class A {\n"
4200                "  int a;\n"
4201                "  A() try : a(0), b{1}, c{2} {\n"
4202                "    { // New scope.\n"
4203                "    }\n"
4204                "  } catch (...) {\n"
4205                "    throw;\n"
4206                "  }\n"
4207                "};\n");
4208 
4209   // Incomplete try-catch blocks.
4210   verifyIncompleteFormat("try {} catch (");
4211 }
4212 
4213 TEST_F(FormatTest, FormatTryAsAVariable) {
4214   verifyFormat("int try;");
4215   verifyFormat("int try, size;");
4216   verifyFormat("try = foo();");
4217   verifyFormat("if (try < size) {\n  return true;\n}");
4218 
4219   verifyFormat("int catch;");
4220   verifyFormat("int catch, size;");
4221   verifyFormat("catch = foo();");
4222   verifyFormat("if (catch < size) {\n  return true;\n}");
4223 
4224   FormatStyle Style = getLLVMStyle();
4225   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4226   Style.BraceWrapping.AfterFunction = true;
4227   Style.BraceWrapping.BeforeCatch = true;
4228   verifyFormat("try {\n"
4229                "  int bar = 1;\n"
4230                "}\n"
4231                "catch (...) {\n"
4232                "  int bar = 1;\n"
4233                "}",
4234                Style);
4235   verifyFormat("#if NO_EX\n"
4236                "try\n"
4237                "#endif\n"
4238                "{\n"
4239                "}\n"
4240                "#if NO_EX\n"
4241                "catch (...) {\n"
4242                "}",
4243                Style);
4244   verifyFormat("try /* abc */ {\n"
4245                "  int bar = 1;\n"
4246                "}\n"
4247                "catch (...) {\n"
4248                "  int bar = 1;\n"
4249                "}",
4250                Style);
4251   verifyFormat("try\n"
4252                "// abc\n"
4253                "{\n"
4254                "  int bar = 1;\n"
4255                "}\n"
4256                "catch (...) {\n"
4257                "  int bar = 1;\n"
4258                "}",
4259                Style);
4260 }
4261 
4262 TEST_F(FormatTest, FormatSEHTryCatch) {
4263   verifyFormat("__try {\n"
4264                "  int a = b * c;\n"
4265                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4266                "  // Do nothing.\n"
4267                "}");
4268 
4269   verifyFormat("__try {\n"
4270                "  int a = b * c;\n"
4271                "} __finally {\n"
4272                "  // Do nothing.\n"
4273                "}");
4274 
4275   verifyFormat("DEBUG({\n"
4276                "  __try {\n"
4277                "  } __finally {\n"
4278                "  }\n"
4279                "});\n");
4280 }
4281 
4282 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4283   verifyFormat("try {\n"
4284                "  f();\n"
4285                "} catch {\n"
4286                "  g();\n"
4287                "}");
4288   verifyFormat("try {\n"
4289                "  f();\n"
4290                "} catch (A a) MACRO(x) {\n"
4291                "  g();\n"
4292                "} catch (B b) MACRO(x) {\n"
4293                "  g();\n"
4294                "}");
4295 }
4296 
4297 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4298   FormatStyle Style = getLLVMStyle();
4299   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4300                           FormatStyle::BS_WebKit}) {
4301     Style.BreakBeforeBraces = BraceStyle;
4302     verifyFormat("try {\n"
4303                  "  // something\n"
4304                  "} catch (...) {\n"
4305                  "  // something\n"
4306                  "}",
4307                  Style);
4308   }
4309   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4310   verifyFormat("try {\n"
4311                "  // something\n"
4312                "}\n"
4313                "catch (...) {\n"
4314                "  // something\n"
4315                "}",
4316                Style);
4317   verifyFormat("__try {\n"
4318                "  // something\n"
4319                "}\n"
4320                "__finally {\n"
4321                "  // something\n"
4322                "}",
4323                Style);
4324   verifyFormat("@try {\n"
4325                "  // something\n"
4326                "}\n"
4327                "@finally {\n"
4328                "  // something\n"
4329                "}",
4330                Style);
4331   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4332   verifyFormat("try\n"
4333                "{\n"
4334                "  // something\n"
4335                "}\n"
4336                "catch (...)\n"
4337                "{\n"
4338                "  // something\n"
4339                "}",
4340                Style);
4341   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4342   verifyFormat("try\n"
4343                "  {\n"
4344                "  // something white\n"
4345                "  }\n"
4346                "catch (...)\n"
4347                "  {\n"
4348                "  // something white\n"
4349                "  }",
4350                Style);
4351   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4352   verifyFormat("try\n"
4353                "  {\n"
4354                "    // something\n"
4355                "  }\n"
4356                "catch (...)\n"
4357                "  {\n"
4358                "    // something\n"
4359                "  }",
4360                Style);
4361   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4362   Style.BraceWrapping.BeforeCatch = true;
4363   verifyFormat("try {\n"
4364                "  // something\n"
4365                "}\n"
4366                "catch (...) {\n"
4367                "  // something\n"
4368                "}",
4369                Style);
4370 }
4371 
4372 TEST_F(FormatTest, StaticInitializers) {
4373   verifyFormat("static SomeClass SC = {1, 'a'};");
4374 
4375   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4376                "    100000000, "
4377                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4378 
4379   // Here, everything other than the "}" would fit on a line.
4380   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4381                "    10000000000000000000000000};");
4382   EXPECT_EQ("S s = {a,\n"
4383             "\n"
4384             "       b};",
4385             format("S s = {\n"
4386                    "  a,\n"
4387                    "\n"
4388                    "  b\n"
4389                    "};"));
4390 
4391   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4392   // line. However, the formatting looks a bit off and this probably doesn't
4393   // happen often in practice.
4394   verifyFormat("static int Variable[1] = {\n"
4395                "    {1000000000000000000000000000000000000}};",
4396                getLLVMStyleWithColumns(40));
4397 }
4398 
4399 TEST_F(FormatTest, DesignatedInitializers) {
4400   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4401   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4402                "                    .bbbbbbbbbb = 2,\n"
4403                "                    .cccccccccc = 3,\n"
4404                "                    .dddddddddd = 4,\n"
4405                "                    .eeeeeeeeee = 5};");
4406   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4407                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4408                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4409                "    .ccccccccccccccccccccccccccc = 3,\n"
4410                "    .ddddddddddddddddddddddddddd = 4,\n"
4411                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4412 
4413   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4414 
4415   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4416   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4417                "                    [2] = bbbbbbbbbb,\n"
4418                "                    [3] = cccccccccc,\n"
4419                "                    [4] = dddddddddd,\n"
4420                "                    [5] = eeeeeeeeee};");
4421   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4422                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4423                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4424                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4425                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4426                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4427 }
4428 
4429 TEST_F(FormatTest, NestedStaticInitializers) {
4430   verifyFormat("static A x = {{{}}};\n");
4431   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4432                "               {init1, init2, init3, init4}}};",
4433                getLLVMStyleWithColumns(50));
4434 
4435   verifyFormat("somes Status::global_reps[3] = {\n"
4436                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4437                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4438                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4439                getLLVMStyleWithColumns(60));
4440   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4441                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4442                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4443                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4444   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4445                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4446                "rect.fTop}};");
4447 
4448   verifyFormat(
4449       "SomeArrayOfSomeType a = {\n"
4450       "    {{1, 2, 3},\n"
4451       "     {1, 2, 3},\n"
4452       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4453       "      333333333333333333333333333333},\n"
4454       "     {1, 2, 3},\n"
4455       "     {1, 2, 3}}};");
4456   verifyFormat(
4457       "SomeArrayOfSomeType a = {\n"
4458       "    {{1, 2, 3}},\n"
4459       "    {{1, 2, 3}},\n"
4460       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4461       "      333333333333333333333333333333}},\n"
4462       "    {{1, 2, 3}},\n"
4463       "    {{1, 2, 3}}};");
4464 
4465   verifyFormat("struct {\n"
4466                "  unsigned bit;\n"
4467                "  const char *const name;\n"
4468                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4469                "                 {kOsWin, \"Windows\"},\n"
4470                "                 {kOsLinux, \"Linux\"},\n"
4471                "                 {kOsCrOS, \"Chrome OS\"}};");
4472   verifyFormat("struct {\n"
4473                "  unsigned bit;\n"
4474                "  const char *const name;\n"
4475                "} kBitsToOs[] = {\n"
4476                "    {kOsMac, \"Mac\"},\n"
4477                "    {kOsWin, \"Windows\"},\n"
4478                "    {kOsLinux, \"Linux\"},\n"
4479                "    {kOsCrOS, \"Chrome OS\"},\n"
4480                "};");
4481 }
4482 
4483 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4484   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4485                "                      \\\n"
4486                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4487 }
4488 
4489 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4490   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4491                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4492 
4493   // Do break defaulted and deleted functions.
4494   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4495                "    default;",
4496                getLLVMStyleWithColumns(40));
4497   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4498                "    delete;",
4499                getLLVMStyleWithColumns(40));
4500 }
4501 
4502 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4503   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4504                getLLVMStyleWithColumns(40));
4505   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4506                getLLVMStyleWithColumns(40));
4507   EXPECT_EQ("#define Q                              \\\n"
4508             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4509             "  \"aaaaaaaa.cpp\"",
4510             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4511                    getLLVMStyleWithColumns(40)));
4512 }
4513 
4514 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4515   EXPECT_EQ("# 123 \"A string literal\"",
4516             format("   #     123    \"A string literal\""));
4517 }
4518 
4519 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4520   EXPECT_EQ("#;", format("#;"));
4521   verifyFormat("#\n;\n;\n;");
4522 }
4523 
4524 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4525   EXPECT_EQ("#line 42 \"test\"\n",
4526             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4527   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4528                                     getLLVMStyleWithColumns(12)));
4529 }
4530 
4531 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4532   EXPECT_EQ("#line 42 \"test\"",
4533             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4534   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4535 }
4536 
4537 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4538   verifyFormat("#define A \\x20");
4539   verifyFormat("#define A \\ x20");
4540   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4541   verifyFormat("#define A ''");
4542   verifyFormat("#define A ''qqq");
4543   verifyFormat("#define A `qqq");
4544   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4545   EXPECT_EQ("const char *c = STRINGIFY(\n"
4546             "\\na : b);",
4547             format("const char * c = STRINGIFY(\n"
4548                    "\\na : b);"));
4549 
4550   verifyFormat("a\r\\");
4551   verifyFormat("a\v\\");
4552   verifyFormat("a\f\\");
4553 }
4554 
4555 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4556   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4557   style.IndentWidth = 4;
4558   style.PPIndentWidth = 1;
4559 
4560   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4561   verifyFormat("#ifdef __linux__\n"
4562                "void foo() {\n"
4563                "    int x = 0;\n"
4564                "}\n"
4565                "#define FOO\n"
4566                "#endif\n"
4567                "void bar() {\n"
4568                "    int y = 0;\n"
4569                "}\n",
4570                style);
4571 
4572   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4573   verifyFormat("#ifdef __linux__\n"
4574                "void foo() {\n"
4575                "    int x = 0;\n"
4576                "}\n"
4577                "# define FOO foo\n"
4578                "#endif\n"
4579                "void bar() {\n"
4580                "    int y = 0;\n"
4581                "}\n",
4582                style);
4583 
4584   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4585   verifyFormat("#ifdef __linux__\n"
4586                "void foo() {\n"
4587                "    int x = 0;\n"
4588                "}\n"
4589                " #define FOO foo\n"
4590                "#endif\n"
4591                "void bar() {\n"
4592                "    int y = 0;\n"
4593                "}\n",
4594                style);
4595 }
4596 
4597 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4598   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4599   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4600   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4601   // FIXME: We never break before the macro name.
4602   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4603 
4604   verifyFormat("#define A A\n#define A A");
4605   verifyFormat("#define A(X) A\n#define A A");
4606 
4607   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4608   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4609 }
4610 
4611 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4612   EXPECT_EQ("// somecomment\n"
4613             "#include \"a.h\"\n"
4614             "#define A(  \\\n"
4615             "    A, B)\n"
4616             "#include \"b.h\"\n"
4617             "// somecomment\n",
4618             format("  // somecomment\n"
4619                    "  #include \"a.h\"\n"
4620                    "#define A(A,\\\n"
4621                    "    B)\n"
4622                    "    #include \"b.h\"\n"
4623                    " // somecomment\n",
4624                    getLLVMStyleWithColumns(13)));
4625 }
4626 
4627 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4628 
4629 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4630   EXPECT_EQ("#define A    \\\n"
4631             "  c;         \\\n"
4632             "  e;\n"
4633             "f;",
4634             format("#define A c; e;\n"
4635                    "f;",
4636                    getLLVMStyleWithColumns(14)));
4637 }
4638 
4639 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4640 
4641 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4642   EXPECT_EQ("int x,\n"
4643             "#define A\n"
4644             "    y;",
4645             format("int x,\n#define A\ny;"));
4646 }
4647 
4648 TEST_F(FormatTest, HashInMacroDefinition) {
4649   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4650   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4651   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4652   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4653   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4654   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4655   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4656   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4657   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4658   verifyFormat("#define A  \\\n"
4659                "  {        \\\n"
4660                "    f(#c); \\\n"
4661                "  }",
4662                getLLVMStyleWithColumns(11));
4663 
4664   verifyFormat("#define A(X)         \\\n"
4665                "  void function##X()",
4666                getLLVMStyleWithColumns(22));
4667 
4668   verifyFormat("#define A(a, b, c)   \\\n"
4669                "  void a##b##c()",
4670                getLLVMStyleWithColumns(22));
4671 
4672   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4673 }
4674 
4675 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4676   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4677   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4678 
4679   FormatStyle Style = getLLVMStyle();
4680   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4681   verifyFormat("#define true ((foo)1)", Style);
4682   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4683   verifyFormat("#define false((foo)0)", Style);
4684 }
4685 
4686 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4687   EXPECT_EQ("#define A b;", format("#define A \\\n"
4688                                    "          \\\n"
4689                                    "  b;",
4690                                    getLLVMStyleWithColumns(25)));
4691   EXPECT_EQ("#define A \\\n"
4692             "          \\\n"
4693             "  a;      \\\n"
4694             "  b;",
4695             format("#define A \\\n"
4696                    "          \\\n"
4697                    "  a;      \\\n"
4698                    "  b;",
4699                    getLLVMStyleWithColumns(11)));
4700   EXPECT_EQ("#define A \\\n"
4701             "  a;      \\\n"
4702             "          \\\n"
4703             "  b;",
4704             format("#define A \\\n"
4705                    "  a;      \\\n"
4706                    "          \\\n"
4707                    "  b;",
4708                    getLLVMStyleWithColumns(11)));
4709 }
4710 
4711 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
4712   verifyIncompleteFormat("#define A :");
4713   verifyFormat("#define SOMECASES  \\\n"
4714                "  case 1:          \\\n"
4715                "  case 2\n",
4716                getLLVMStyleWithColumns(20));
4717   verifyFormat("#define MACRO(a) \\\n"
4718                "  if (a)         \\\n"
4719                "    f();         \\\n"
4720                "  else           \\\n"
4721                "    g()",
4722                getLLVMStyleWithColumns(18));
4723   verifyFormat("#define A template <typename T>");
4724   verifyIncompleteFormat("#define STR(x) #x\n"
4725                          "f(STR(this_is_a_string_literal{));");
4726   verifyFormat("#pragma omp threadprivate( \\\n"
4727                "    y)), // expected-warning",
4728                getLLVMStyleWithColumns(28));
4729   verifyFormat("#d, = };");
4730   verifyFormat("#if \"a");
4731   verifyIncompleteFormat("({\n"
4732                          "#define b     \\\n"
4733                          "  }           \\\n"
4734                          "  a\n"
4735                          "a",
4736                          getLLVMStyleWithColumns(15));
4737   verifyFormat("#define A     \\\n"
4738                "  {           \\\n"
4739                "    {\n"
4740                "#define B     \\\n"
4741                "  }           \\\n"
4742                "  }",
4743                getLLVMStyleWithColumns(15));
4744   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
4745   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
4746   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
4747   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
4748 }
4749 
4750 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
4751   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
4752   EXPECT_EQ("class A : public QObject {\n"
4753             "  Q_OBJECT\n"
4754             "\n"
4755             "  A() {}\n"
4756             "};",
4757             format("class A  :  public QObject {\n"
4758                    "     Q_OBJECT\n"
4759                    "\n"
4760                    "  A() {\n}\n"
4761                    "}  ;"));
4762   EXPECT_EQ("MACRO\n"
4763             "/*static*/ int i;",
4764             format("MACRO\n"
4765                    " /*static*/ int   i;"));
4766   EXPECT_EQ("SOME_MACRO\n"
4767             "namespace {\n"
4768             "void f();\n"
4769             "} // namespace",
4770             format("SOME_MACRO\n"
4771                    "  namespace    {\n"
4772                    "void   f(  );\n"
4773                    "} // namespace"));
4774   // Only if the identifier contains at least 5 characters.
4775   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
4776   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
4777   // Only if everything is upper case.
4778   EXPECT_EQ("class A : public QObject {\n"
4779             "  Q_Object A() {}\n"
4780             "};",
4781             format("class A  :  public QObject {\n"
4782                    "     Q_Object\n"
4783                    "  A() {\n}\n"
4784                    "}  ;"));
4785 
4786   // Only if the next line can actually start an unwrapped line.
4787   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
4788             format("SOME_WEIRD_LOG_MACRO\n"
4789                    "<< SomeThing;"));
4790 
4791   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
4792                "(n, buffers))\n",
4793                getChromiumStyle(FormatStyle::LK_Cpp));
4794 
4795   // See PR41483
4796   EXPECT_EQ("/**/ FOO(a)\n"
4797             "FOO(b)",
4798             format("/**/ FOO(a)\n"
4799                    "FOO(b)"));
4800 }
4801 
4802 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
4803   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4804             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4805             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4806             "class X {};\n"
4807             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4808             "int *createScopDetectionPass() { return 0; }",
4809             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4810                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4811                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4812                    "  class X {};\n"
4813                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4814                    "  int *createScopDetectionPass() { return 0; }"));
4815   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
4816   // braces, so that inner block is indented one level more.
4817   EXPECT_EQ("int q() {\n"
4818             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4819             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4820             "  IPC_END_MESSAGE_MAP()\n"
4821             "}",
4822             format("int q() {\n"
4823                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4824                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4825                    "  IPC_END_MESSAGE_MAP()\n"
4826                    "}"));
4827 
4828   // Same inside macros.
4829   EXPECT_EQ("#define LIST(L) \\\n"
4830             "  L(A)          \\\n"
4831             "  L(B)          \\\n"
4832             "  L(C)",
4833             format("#define LIST(L) \\\n"
4834                    "  L(A) \\\n"
4835                    "  L(B) \\\n"
4836                    "  L(C)",
4837                    getGoogleStyle()));
4838 
4839   // These must not be recognized as macros.
4840   EXPECT_EQ("int q() {\n"
4841             "  f(x);\n"
4842             "  f(x) {}\n"
4843             "  f(x)->g();\n"
4844             "  f(x)->*g();\n"
4845             "  f(x).g();\n"
4846             "  f(x) = x;\n"
4847             "  f(x) += x;\n"
4848             "  f(x) -= x;\n"
4849             "  f(x) *= x;\n"
4850             "  f(x) /= x;\n"
4851             "  f(x) %= x;\n"
4852             "  f(x) &= x;\n"
4853             "  f(x) |= x;\n"
4854             "  f(x) ^= x;\n"
4855             "  f(x) >>= x;\n"
4856             "  f(x) <<= x;\n"
4857             "  f(x)[y].z();\n"
4858             "  LOG(INFO) << x;\n"
4859             "  ifstream(x) >> x;\n"
4860             "}\n",
4861             format("int q() {\n"
4862                    "  f(x)\n;\n"
4863                    "  f(x)\n {}\n"
4864                    "  f(x)\n->g();\n"
4865                    "  f(x)\n->*g();\n"
4866                    "  f(x)\n.g();\n"
4867                    "  f(x)\n = x;\n"
4868                    "  f(x)\n += x;\n"
4869                    "  f(x)\n -= x;\n"
4870                    "  f(x)\n *= x;\n"
4871                    "  f(x)\n /= x;\n"
4872                    "  f(x)\n %= x;\n"
4873                    "  f(x)\n &= x;\n"
4874                    "  f(x)\n |= x;\n"
4875                    "  f(x)\n ^= x;\n"
4876                    "  f(x)\n >>= x;\n"
4877                    "  f(x)\n <<= x;\n"
4878                    "  f(x)\n[y].z();\n"
4879                    "  LOG(INFO)\n << x;\n"
4880                    "  ifstream(x)\n >> x;\n"
4881                    "}\n"));
4882   EXPECT_EQ("int q() {\n"
4883             "  F(x)\n"
4884             "  if (1) {\n"
4885             "  }\n"
4886             "  F(x)\n"
4887             "  while (1) {\n"
4888             "  }\n"
4889             "  F(x)\n"
4890             "  G(x);\n"
4891             "  F(x)\n"
4892             "  try {\n"
4893             "    Q();\n"
4894             "  } catch (...) {\n"
4895             "  }\n"
4896             "}\n",
4897             format("int q() {\n"
4898                    "F(x)\n"
4899                    "if (1) {}\n"
4900                    "F(x)\n"
4901                    "while (1) {}\n"
4902                    "F(x)\n"
4903                    "G(x);\n"
4904                    "F(x)\n"
4905                    "try { Q(); } catch (...) {}\n"
4906                    "}\n"));
4907   EXPECT_EQ("class A {\n"
4908             "  A() : t(0) {}\n"
4909             "  A(int i) noexcept() : {}\n"
4910             "  A(X x)\n" // FIXME: function-level try blocks are broken.
4911             "  try : t(0) {\n"
4912             "  } catch (...) {\n"
4913             "  }\n"
4914             "};",
4915             format("class A {\n"
4916                    "  A()\n : t(0) {}\n"
4917                    "  A(int i)\n noexcept() : {}\n"
4918                    "  A(X x)\n"
4919                    "  try : t(0) {} catch (...) {}\n"
4920                    "};"));
4921   FormatStyle Style = getLLVMStyle();
4922   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4923   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
4924   Style.BraceWrapping.AfterFunction = true;
4925   EXPECT_EQ("void f()\n"
4926             "try\n"
4927             "{\n"
4928             "}",
4929             format("void f() try {\n"
4930                    "}",
4931                    Style));
4932   EXPECT_EQ("class SomeClass {\n"
4933             "public:\n"
4934             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4935             "};",
4936             format("class SomeClass {\n"
4937                    "public:\n"
4938                    "  SomeClass()\n"
4939                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4940                    "};"));
4941   EXPECT_EQ("class SomeClass {\n"
4942             "public:\n"
4943             "  SomeClass()\n"
4944             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4945             "};",
4946             format("class SomeClass {\n"
4947                    "public:\n"
4948                    "  SomeClass()\n"
4949                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4950                    "};",
4951                    getLLVMStyleWithColumns(40)));
4952 
4953   verifyFormat("MACRO(>)");
4954 
4955   // Some macros contain an implicit semicolon.
4956   Style = getLLVMStyle();
4957   Style.StatementMacros.push_back("FOO");
4958   verifyFormat("FOO(a) int b = 0;");
4959   verifyFormat("FOO(a)\n"
4960                "int b = 0;",
4961                Style);
4962   verifyFormat("FOO(a);\n"
4963                "int b = 0;",
4964                Style);
4965   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
4966                "int b = 0;",
4967                Style);
4968   verifyFormat("FOO()\n"
4969                "int b = 0;",
4970                Style);
4971   verifyFormat("FOO\n"
4972                "int b = 0;",
4973                Style);
4974   verifyFormat("void f() {\n"
4975                "  FOO(a)\n"
4976                "  return a;\n"
4977                "}",
4978                Style);
4979   verifyFormat("FOO(a)\n"
4980                "FOO(b)",
4981                Style);
4982   verifyFormat("int a = 0;\n"
4983                "FOO(b)\n"
4984                "int c = 0;",
4985                Style);
4986   verifyFormat("int a = 0;\n"
4987                "int x = FOO(a)\n"
4988                "int b = 0;",
4989                Style);
4990   verifyFormat("void foo(int a) { FOO(a) }\n"
4991                "uint32_t bar() {}",
4992                Style);
4993 }
4994 
4995 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
4996   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
4997 
4998   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
4999                ZeroColumn);
5000 }
5001 
5002 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5003   verifyFormat("#define A \\\n"
5004                "  f({     \\\n"
5005                "    g();  \\\n"
5006                "  });",
5007                getLLVMStyleWithColumns(11));
5008 }
5009 
5010 TEST_F(FormatTest, IndentPreprocessorDirectives) {
5011   FormatStyle Style = getLLVMStyleWithColumns(40);
5012   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
5013   verifyFormat("#ifdef _WIN32\n"
5014                "#define A 0\n"
5015                "#ifdef VAR2\n"
5016                "#define B 1\n"
5017                "#include <someheader.h>\n"
5018                "#define MACRO                          \\\n"
5019                "  some_very_long_func_aaaaaaaaaa();\n"
5020                "#endif\n"
5021                "#else\n"
5022                "#define A 1\n"
5023                "#endif",
5024                Style);
5025   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
5026   verifyFormat("#ifdef _WIN32\n"
5027                "#  define A 0\n"
5028                "#  ifdef VAR2\n"
5029                "#    define B 1\n"
5030                "#    include <someheader.h>\n"
5031                "#    define MACRO                      \\\n"
5032                "      some_very_long_func_aaaaaaaaaa();\n"
5033                "#  endif\n"
5034                "#else\n"
5035                "#  define A 1\n"
5036                "#endif",
5037                Style);
5038   verifyFormat("#if A\n"
5039                "#  define MACRO                        \\\n"
5040                "    void a(int x) {                    \\\n"
5041                "      b();                             \\\n"
5042                "      c();                             \\\n"
5043                "      d();                             \\\n"
5044                "      e();                             \\\n"
5045                "      f();                             \\\n"
5046                "    }\n"
5047                "#endif",
5048                Style);
5049   // Comments before include guard.
5050   verifyFormat("// file comment\n"
5051                "// file comment\n"
5052                "#ifndef HEADER_H\n"
5053                "#define HEADER_H\n"
5054                "code();\n"
5055                "#endif",
5056                Style);
5057   // Test with include guards.
5058   verifyFormat("#ifndef HEADER_H\n"
5059                "#define HEADER_H\n"
5060                "code();\n"
5061                "#endif",
5062                Style);
5063   // Include guards must have a #define with the same variable immediately
5064   // after #ifndef.
5065   verifyFormat("#ifndef NOT_GUARD\n"
5066                "#  define FOO\n"
5067                "code();\n"
5068                "#endif",
5069                Style);
5070 
5071   // Include guards must cover the entire file.
5072   verifyFormat("code();\n"
5073                "code();\n"
5074                "#ifndef NOT_GUARD\n"
5075                "#  define NOT_GUARD\n"
5076                "code();\n"
5077                "#endif",
5078                Style);
5079   verifyFormat("#ifndef NOT_GUARD\n"
5080                "#  define NOT_GUARD\n"
5081                "code();\n"
5082                "#endif\n"
5083                "code();",
5084                Style);
5085   // Test with trailing blank lines.
5086   verifyFormat("#ifndef HEADER_H\n"
5087                "#define HEADER_H\n"
5088                "code();\n"
5089                "#endif\n",
5090                Style);
5091   // Include guards don't have #else.
5092   verifyFormat("#ifndef NOT_GUARD\n"
5093                "#  define NOT_GUARD\n"
5094                "code();\n"
5095                "#else\n"
5096                "#endif",
5097                Style);
5098   verifyFormat("#ifndef NOT_GUARD\n"
5099                "#  define NOT_GUARD\n"
5100                "code();\n"
5101                "#elif FOO\n"
5102                "#endif",
5103                Style);
5104   // Non-identifier #define after potential include guard.
5105   verifyFormat("#ifndef FOO\n"
5106                "#  define 1\n"
5107                "#endif\n",
5108                Style);
5109   // #if closes past last non-preprocessor line.
5110   verifyFormat("#ifndef FOO\n"
5111                "#define FOO\n"
5112                "#if 1\n"
5113                "int i;\n"
5114                "#  define A 0\n"
5115                "#endif\n"
5116                "#endif\n",
5117                Style);
5118   // Don't crash if there is an #elif directive without a condition.
5119   verifyFormat("#if 1\n"
5120                "int x;\n"
5121                "#elif\n"
5122                "int y;\n"
5123                "#else\n"
5124                "int z;\n"
5125                "#endif",
5126                Style);
5127   // FIXME: This doesn't handle the case where there's code between the
5128   // #ifndef and #define but all other conditions hold. This is because when
5129   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5130   // previous code line yet, so we can't detect it.
5131   EXPECT_EQ("#ifndef NOT_GUARD\n"
5132             "code();\n"
5133             "#define NOT_GUARD\n"
5134             "code();\n"
5135             "#endif",
5136             format("#ifndef NOT_GUARD\n"
5137                    "code();\n"
5138                    "#  define NOT_GUARD\n"
5139                    "code();\n"
5140                    "#endif",
5141                    Style));
5142   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5143   // be outside an include guard. Examples are #pragma once and
5144   // #pragma GCC diagnostic, or anything else that does not change the meaning
5145   // of the file if it's included multiple times.
5146   EXPECT_EQ("#ifdef WIN32\n"
5147             "#  pragma once\n"
5148             "#endif\n"
5149             "#ifndef HEADER_H\n"
5150             "#  define HEADER_H\n"
5151             "code();\n"
5152             "#endif",
5153             format("#ifdef WIN32\n"
5154                    "#  pragma once\n"
5155                    "#endif\n"
5156                    "#ifndef HEADER_H\n"
5157                    "#define HEADER_H\n"
5158                    "code();\n"
5159                    "#endif",
5160                    Style));
5161   // FIXME: This does not detect when there is a single non-preprocessor line
5162   // in front of an include-guard-like structure where other conditions hold
5163   // because ScopedLineState hides the line.
5164   EXPECT_EQ("code();\n"
5165             "#ifndef HEADER_H\n"
5166             "#define HEADER_H\n"
5167             "code();\n"
5168             "#endif",
5169             format("code();\n"
5170                    "#ifndef HEADER_H\n"
5171                    "#  define HEADER_H\n"
5172                    "code();\n"
5173                    "#endif",
5174                    Style));
5175   // Keep comments aligned with #, otherwise indent comments normally. These
5176   // tests cannot use verifyFormat because messUp manipulates leading
5177   // whitespace.
5178   {
5179     const char *Expected = ""
5180                            "void f() {\n"
5181                            "#if 1\n"
5182                            "// Preprocessor aligned.\n"
5183                            "#  define A 0\n"
5184                            "  // Code. Separated by blank line.\n"
5185                            "\n"
5186                            "#  define B 0\n"
5187                            "  // Code. Not aligned with #\n"
5188                            "#  define C 0\n"
5189                            "#endif";
5190     const char *ToFormat = ""
5191                            "void f() {\n"
5192                            "#if 1\n"
5193                            "// Preprocessor aligned.\n"
5194                            "#  define A 0\n"
5195                            "// Code. Separated by blank line.\n"
5196                            "\n"
5197                            "#  define B 0\n"
5198                            "   // Code. Not aligned with #\n"
5199                            "#  define C 0\n"
5200                            "#endif";
5201     EXPECT_EQ(Expected, format(ToFormat, Style));
5202     EXPECT_EQ(Expected, format(Expected, Style));
5203   }
5204   // Keep block quotes aligned.
5205   {
5206     const char *Expected = ""
5207                            "void f() {\n"
5208                            "#if 1\n"
5209                            "/* Preprocessor aligned. */\n"
5210                            "#  define A 0\n"
5211                            "  /* Code. Separated by blank line. */\n"
5212                            "\n"
5213                            "#  define B 0\n"
5214                            "  /* Code. Not aligned with # */\n"
5215                            "#  define C 0\n"
5216                            "#endif";
5217     const char *ToFormat = ""
5218                            "void f() {\n"
5219                            "#if 1\n"
5220                            "/* Preprocessor aligned. */\n"
5221                            "#  define A 0\n"
5222                            "/* Code. Separated by blank line. */\n"
5223                            "\n"
5224                            "#  define B 0\n"
5225                            "   /* Code. Not aligned with # */\n"
5226                            "#  define C 0\n"
5227                            "#endif";
5228     EXPECT_EQ(Expected, format(ToFormat, Style));
5229     EXPECT_EQ(Expected, format(Expected, Style));
5230   }
5231   // Keep comments aligned with un-indented directives.
5232   {
5233     const char *Expected = ""
5234                            "void f() {\n"
5235                            "// Preprocessor aligned.\n"
5236                            "#define A 0\n"
5237                            "  // Code. Separated by blank line.\n"
5238                            "\n"
5239                            "#define B 0\n"
5240                            "  // Code. Not aligned with #\n"
5241                            "#define C 0\n";
5242     const char *ToFormat = ""
5243                            "void f() {\n"
5244                            "// Preprocessor aligned.\n"
5245                            "#define A 0\n"
5246                            "// Code. Separated by blank line.\n"
5247                            "\n"
5248                            "#define B 0\n"
5249                            "   // Code. Not aligned with #\n"
5250                            "#define C 0\n";
5251     EXPECT_EQ(Expected, format(ToFormat, Style));
5252     EXPECT_EQ(Expected, format(Expected, Style));
5253   }
5254   // Test AfterHash with tabs.
5255   {
5256     FormatStyle Tabbed = Style;
5257     Tabbed.UseTab = FormatStyle::UT_Always;
5258     Tabbed.IndentWidth = 8;
5259     Tabbed.TabWidth = 8;
5260     verifyFormat("#ifdef _WIN32\n"
5261                  "#\tdefine A 0\n"
5262                  "#\tifdef VAR2\n"
5263                  "#\t\tdefine B 1\n"
5264                  "#\t\tinclude <someheader.h>\n"
5265                  "#\t\tdefine MACRO          \\\n"
5266                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5267                  "#\tendif\n"
5268                  "#else\n"
5269                  "#\tdefine A 1\n"
5270                  "#endif",
5271                  Tabbed);
5272   }
5273 
5274   // Regression test: Multiline-macro inside include guards.
5275   verifyFormat("#ifndef HEADER_H\n"
5276                "#define HEADER_H\n"
5277                "#define A()        \\\n"
5278                "  int i;           \\\n"
5279                "  int j;\n"
5280                "#endif // HEADER_H",
5281                getLLVMStyleWithColumns(20));
5282 
5283   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5284   // Basic before hash indent tests
5285   verifyFormat("#ifdef _WIN32\n"
5286                "  #define A 0\n"
5287                "  #ifdef VAR2\n"
5288                "    #define B 1\n"
5289                "    #include <someheader.h>\n"
5290                "    #define MACRO                      \\\n"
5291                "      some_very_long_func_aaaaaaaaaa();\n"
5292                "  #endif\n"
5293                "#else\n"
5294                "  #define A 1\n"
5295                "#endif",
5296                Style);
5297   verifyFormat("#if A\n"
5298                "  #define MACRO                        \\\n"
5299                "    void a(int x) {                    \\\n"
5300                "      b();                             \\\n"
5301                "      c();                             \\\n"
5302                "      d();                             \\\n"
5303                "      e();                             \\\n"
5304                "      f();                             \\\n"
5305                "    }\n"
5306                "#endif",
5307                Style);
5308   // Keep comments aligned with indented directives. These
5309   // tests cannot use verifyFormat because messUp manipulates leading
5310   // whitespace.
5311   {
5312     const char *Expected = "void f() {\n"
5313                            "// Aligned to preprocessor.\n"
5314                            "#if 1\n"
5315                            "  // Aligned to code.\n"
5316                            "  int a;\n"
5317                            "  #if 1\n"
5318                            "    // Aligned to preprocessor.\n"
5319                            "    #define A 0\n"
5320                            "  // Aligned to code.\n"
5321                            "  int b;\n"
5322                            "  #endif\n"
5323                            "#endif\n"
5324                            "}";
5325     const char *ToFormat = "void f() {\n"
5326                            "// Aligned to preprocessor.\n"
5327                            "#if 1\n"
5328                            "// Aligned to code.\n"
5329                            "int a;\n"
5330                            "#if 1\n"
5331                            "// Aligned to preprocessor.\n"
5332                            "#define A 0\n"
5333                            "// Aligned to code.\n"
5334                            "int b;\n"
5335                            "#endif\n"
5336                            "#endif\n"
5337                            "}";
5338     EXPECT_EQ(Expected, format(ToFormat, Style));
5339     EXPECT_EQ(Expected, format(Expected, Style));
5340   }
5341   {
5342     const char *Expected = "void f() {\n"
5343                            "/* Aligned to preprocessor. */\n"
5344                            "#if 1\n"
5345                            "  /* Aligned to code. */\n"
5346                            "  int a;\n"
5347                            "  #if 1\n"
5348                            "    /* Aligned to preprocessor. */\n"
5349                            "    #define A 0\n"
5350                            "  /* Aligned to code. */\n"
5351                            "  int b;\n"
5352                            "  #endif\n"
5353                            "#endif\n"
5354                            "}";
5355     const char *ToFormat = "void f() {\n"
5356                            "/* Aligned to preprocessor. */\n"
5357                            "#if 1\n"
5358                            "/* Aligned to code. */\n"
5359                            "int a;\n"
5360                            "#if 1\n"
5361                            "/* Aligned to preprocessor. */\n"
5362                            "#define A 0\n"
5363                            "/* Aligned to code. */\n"
5364                            "int b;\n"
5365                            "#endif\n"
5366                            "#endif\n"
5367                            "}";
5368     EXPECT_EQ(Expected, format(ToFormat, Style));
5369     EXPECT_EQ(Expected, format(Expected, Style));
5370   }
5371 
5372   // Test single comment before preprocessor
5373   verifyFormat("// Comment\n"
5374                "\n"
5375                "#if 1\n"
5376                "#endif",
5377                Style);
5378 }
5379 
5380 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5381   verifyFormat("{\n  { a #c; }\n}");
5382 }
5383 
5384 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5385   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5386             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5387   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5388             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5389 }
5390 
5391 TEST_F(FormatTest, EscapedNewlines) {
5392   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5393   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5394             format("#define A \\\nint i;\\\n  int j;", Narrow));
5395   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5396   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5397   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5398   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5399 
5400   FormatStyle AlignLeft = getLLVMStyle();
5401   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5402   EXPECT_EQ("#define MACRO(x) \\\n"
5403             "private:         \\\n"
5404             "  int x(int a);\n",
5405             format("#define MACRO(x) \\\n"
5406                    "private:         \\\n"
5407                    "  int x(int a);\n",
5408                    AlignLeft));
5409 
5410   // CRLF line endings
5411   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5412             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5413   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5414   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5415   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5416   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5417   EXPECT_EQ("#define MACRO(x) \\\r\n"
5418             "private:         \\\r\n"
5419             "  int x(int a);\r\n",
5420             format("#define MACRO(x) \\\r\n"
5421                    "private:         \\\r\n"
5422                    "  int x(int a);\r\n",
5423                    AlignLeft));
5424 
5425   FormatStyle DontAlign = getLLVMStyle();
5426   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5427   DontAlign.MaxEmptyLinesToKeep = 3;
5428   // FIXME: can't use verifyFormat here because the newline before
5429   // "public:" is not inserted the first time it's reformatted
5430   EXPECT_EQ("#define A \\\n"
5431             "  class Foo { \\\n"
5432             "    void bar(); \\\n"
5433             "\\\n"
5434             "\\\n"
5435             "\\\n"
5436             "  public: \\\n"
5437             "    void baz(); \\\n"
5438             "  };",
5439             format("#define A \\\n"
5440                    "  class Foo { \\\n"
5441                    "    void bar(); \\\n"
5442                    "\\\n"
5443                    "\\\n"
5444                    "\\\n"
5445                    "  public: \\\n"
5446                    "    void baz(); \\\n"
5447                    "  };",
5448                    DontAlign));
5449 }
5450 
5451 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5452   verifyFormat("#define A \\\n"
5453                "  int v(  \\\n"
5454                "      a); \\\n"
5455                "  int i;",
5456                getLLVMStyleWithColumns(11));
5457 }
5458 
5459 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5460   EXPECT_EQ(
5461       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5462       "                      \\\n"
5463       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5464       "\n"
5465       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5466       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5467       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5468              "\\\n"
5469              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5470              "  \n"
5471              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5472              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5473 }
5474 
5475 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5476   EXPECT_EQ("int\n"
5477             "#define A\n"
5478             "    a;",
5479             format("int\n#define A\na;"));
5480   verifyFormat("functionCallTo(\n"
5481                "    someOtherFunction(\n"
5482                "        withSomeParameters, whichInSequence,\n"
5483                "        areLongerThanALine(andAnotherCall,\n"
5484                "#define A B\n"
5485                "                           withMoreParamters,\n"
5486                "                           whichStronglyInfluenceTheLayout),\n"
5487                "        andMoreParameters),\n"
5488                "    trailing);",
5489                getLLVMStyleWithColumns(69));
5490   verifyFormat("Foo::Foo()\n"
5491                "#ifdef BAR\n"
5492                "    : baz(0)\n"
5493                "#endif\n"
5494                "{\n"
5495                "}");
5496   verifyFormat("void f() {\n"
5497                "  if (true)\n"
5498                "#ifdef A\n"
5499                "    f(42);\n"
5500                "  x();\n"
5501                "#else\n"
5502                "    g();\n"
5503                "  x();\n"
5504                "#endif\n"
5505                "}");
5506   verifyFormat("void f(param1, param2,\n"
5507                "       param3,\n"
5508                "#ifdef A\n"
5509                "       param4(param5,\n"
5510                "#ifdef A1\n"
5511                "              param6,\n"
5512                "#ifdef A2\n"
5513                "              param7),\n"
5514                "#else\n"
5515                "              param8),\n"
5516                "       param9,\n"
5517                "#endif\n"
5518                "       param10,\n"
5519                "#endif\n"
5520                "       param11)\n"
5521                "#else\n"
5522                "       param12)\n"
5523                "#endif\n"
5524                "{\n"
5525                "  x();\n"
5526                "}",
5527                getLLVMStyleWithColumns(28));
5528   verifyFormat("#if 1\n"
5529                "int i;");
5530   verifyFormat("#if 1\n"
5531                "#endif\n"
5532                "#if 1\n"
5533                "#else\n"
5534                "#endif\n");
5535   verifyFormat("DEBUG({\n"
5536                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5537                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5538                "});\n"
5539                "#if a\n"
5540                "#else\n"
5541                "#endif");
5542 
5543   verifyIncompleteFormat("void f(\n"
5544                          "#if A\n"
5545                          ");\n"
5546                          "#else\n"
5547                          "#endif");
5548 }
5549 
5550 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5551   verifyFormat("#endif\n"
5552                "#if B");
5553 }
5554 
5555 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5556   FormatStyle SingleLine = getLLVMStyle();
5557   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5558   verifyFormat("#if 0\n"
5559                "#elif 1\n"
5560                "#endif\n"
5561                "void foo() {\n"
5562                "  if (test) foo2();\n"
5563                "}",
5564                SingleLine);
5565 }
5566 
5567 TEST_F(FormatTest, LayoutBlockInsideParens) {
5568   verifyFormat("functionCall({ int i; });");
5569   verifyFormat("functionCall({\n"
5570                "  int i;\n"
5571                "  int j;\n"
5572                "});");
5573   verifyFormat("functionCall(\n"
5574                "    {\n"
5575                "      int i;\n"
5576                "      int j;\n"
5577                "    },\n"
5578                "    aaaa, bbbb, cccc);");
5579   verifyFormat("functionA(functionB({\n"
5580                "            int i;\n"
5581                "            int j;\n"
5582                "          }),\n"
5583                "          aaaa, bbbb, cccc);");
5584   verifyFormat("functionCall(\n"
5585                "    {\n"
5586                "      int i;\n"
5587                "      int j;\n"
5588                "    },\n"
5589                "    aaaa, bbbb, // comment\n"
5590                "    cccc);");
5591   verifyFormat("functionA(functionB({\n"
5592                "            int i;\n"
5593                "            int j;\n"
5594                "          }),\n"
5595                "          aaaa, bbbb, // comment\n"
5596                "          cccc);");
5597   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5598   verifyFormat("functionCall(aaaa, bbbb, {\n"
5599                "  int i;\n"
5600                "  int j;\n"
5601                "});");
5602   verifyFormat(
5603       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5604       "    {\n"
5605       "      int i; // break\n"
5606       "    },\n"
5607       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5608       "                                     ccccccccccccccccc));");
5609   verifyFormat("DEBUG({\n"
5610                "  if (a)\n"
5611                "    f();\n"
5612                "});");
5613 }
5614 
5615 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5616   EXPECT_EQ("SOME_MACRO { int i; }\n"
5617             "int i;",
5618             format("  SOME_MACRO  {int i;}  int i;"));
5619 }
5620 
5621 TEST_F(FormatTest, LayoutNestedBlocks) {
5622   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5623                "  struct s {\n"
5624                "    int i;\n"
5625                "  };\n"
5626                "  s kBitsToOs[] = {{10}};\n"
5627                "  for (int i = 0; i < 10; ++i)\n"
5628                "    return;\n"
5629                "}");
5630   verifyFormat("call(parameter, {\n"
5631                "  something();\n"
5632                "  // Comment using all columns.\n"
5633                "  somethingelse();\n"
5634                "});",
5635                getLLVMStyleWithColumns(40));
5636   verifyFormat("DEBUG( //\n"
5637                "    { f(); }, a);");
5638   verifyFormat("DEBUG( //\n"
5639                "    {\n"
5640                "      f(); //\n"
5641                "    },\n"
5642                "    a);");
5643 
5644   EXPECT_EQ("call(parameter, {\n"
5645             "  something();\n"
5646             "  // Comment too\n"
5647             "  // looooooooooong.\n"
5648             "  somethingElse();\n"
5649             "});",
5650             format("call(parameter, {\n"
5651                    "  something();\n"
5652                    "  // Comment too looooooooooong.\n"
5653                    "  somethingElse();\n"
5654                    "});",
5655                    getLLVMStyleWithColumns(29)));
5656   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5657   EXPECT_EQ("DEBUG({ // comment\n"
5658             "  int i;\n"
5659             "});",
5660             format("DEBUG({ // comment\n"
5661                    "int  i;\n"
5662                    "});"));
5663   EXPECT_EQ("DEBUG({\n"
5664             "  int i;\n"
5665             "\n"
5666             "  // comment\n"
5667             "  int j;\n"
5668             "});",
5669             format("DEBUG({\n"
5670                    "  int  i;\n"
5671                    "\n"
5672                    "  // comment\n"
5673                    "  int  j;\n"
5674                    "});"));
5675 
5676   verifyFormat("DEBUG({\n"
5677                "  if (a)\n"
5678                "    return;\n"
5679                "});");
5680   verifyGoogleFormat("DEBUG({\n"
5681                      "  if (a) return;\n"
5682                      "});");
5683   FormatStyle Style = getGoogleStyle();
5684   Style.ColumnLimit = 45;
5685   verifyFormat("Debug(\n"
5686                "    aaaaa,\n"
5687                "    {\n"
5688                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5689                "    },\n"
5690                "    a);",
5691                Style);
5692 
5693   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5694 
5695   verifyNoCrash("^{v^{a}}");
5696 }
5697 
5698 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
5699   EXPECT_EQ("#define MACRO()                     \\\n"
5700             "  Debug(aaa, /* force line break */ \\\n"
5701             "        {                           \\\n"
5702             "          int i;                    \\\n"
5703             "          int j;                    \\\n"
5704             "        })",
5705             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
5706                    "          {  int   i;  int  j;   })",
5707                    getGoogleStyle()));
5708 
5709   EXPECT_EQ("#define A                                       \\\n"
5710             "  [] {                                          \\\n"
5711             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
5712             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
5713             "  }",
5714             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
5715                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
5716                    getGoogleStyle()));
5717 }
5718 
5719 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
5720   EXPECT_EQ("{}", format("{}"));
5721   verifyFormat("enum E {};");
5722   verifyFormat("enum E {}");
5723   FormatStyle Style = getLLVMStyle();
5724   Style.SpaceInEmptyBlock = true;
5725   EXPECT_EQ("void f() { }", format("void f() {}", Style));
5726   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
5727   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
5728   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5729   Style.BraceWrapping.BeforeElse = false;
5730   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5731   verifyFormat("if (a)\n"
5732                "{\n"
5733                "} else if (b)\n"
5734                "{\n"
5735                "} else\n"
5736                "{ }",
5737                Style);
5738   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
5739   verifyFormat("if (a) {\n"
5740                "} else if (b) {\n"
5741                "} else {\n"
5742                "}",
5743                Style);
5744   Style.BraceWrapping.BeforeElse = true;
5745   verifyFormat("if (a) { }\n"
5746                "else if (b) { }\n"
5747                "else { }",
5748                Style);
5749 }
5750 
5751 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
5752   FormatStyle Style = getLLVMStyle();
5753   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
5754   Style.MacroBlockEnd = "^[A-Z_]+_END$";
5755   verifyFormat("FOO_BEGIN\n"
5756                "  FOO_ENTRY\n"
5757                "FOO_END",
5758                Style);
5759   verifyFormat("FOO_BEGIN\n"
5760                "  NESTED_FOO_BEGIN\n"
5761                "    NESTED_FOO_ENTRY\n"
5762                "  NESTED_FOO_END\n"
5763                "FOO_END",
5764                Style);
5765   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
5766                "  int x;\n"
5767                "  x = 1;\n"
5768                "FOO_END(Baz)",
5769                Style);
5770 }
5771 
5772 //===----------------------------------------------------------------------===//
5773 // Line break tests.
5774 //===----------------------------------------------------------------------===//
5775 
5776 TEST_F(FormatTest, PreventConfusingIndents) {
5777   verifyFormat(
5778       "void f() {\n"
5779       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
5780       "                         parameter, parameter, parameter)),\n"
5781       "                     SecondLongCall(parameter));\n"
5782       "}");
5783   verifyFormat(
5784       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5785       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5786       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5787       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
5788   verifyFormat(
5789       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5790       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
5791       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5792       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
5793   verifyFormat(
5794       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5795       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
5796       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
5797       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
5798   verifyFormat("int a = bbbb && ccc &&\n"
5799                "        fffff(\n"
5800                "#define A Just forcing a new line\n"
5801                "            ddd);");
5802 }
5803 
5804 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
5805   verifyFormat(
5806       "bool aaaaaaa =\n"
5807       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
5808       "    bbbbbbbb();");
5809   verifyFormat(
5810       "bool aaaaaaa =\n"
5811       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
5812       "    bbbbbbbb();");
5813 
5814   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5815                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
5816                "    ccccccccc == ddddddddddd;");
5817   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5818                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
5819                "    ccccccccc == ddddddddddd;");
5820   verifyFormat(
5821       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
5822       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
5823       "    ccccccccc == ddddddddddd;");
5824 
5825   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5826                "                 aaaaaa) &&\n"
5827                "         bbbbbb && cccccc;");
5828   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5829                "                 aaaaaa) >>\n"
5830                "         bbbbbb;");
5831   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
5832                "    SourceMgr.getSpellingColumnNumber(\n"
5833                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
5834                "    1);");
5835 
5836   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5837                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
5838                "    cccccc) {\n}");
5839   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5840                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5841                "              cccccc) {\n}");
5842   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5843                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5844                "              cccccc) {\n}");
5845   verifyFormat("b = a &&\n"
5846                "    // Comment\n"
5847                "    b.c && d;");
5848 
5849   // If the LHS of a comparison is not a binary expression itself, the
5850   // additional linebreak confuses many people.
5851   verifyFormat(
5852       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5853       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
5854       "}");
5855   verifyFormat(
5856       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5857       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5858       "}");
5859   verifyFormat(
5860       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
5861       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5862       "}");
5863   verifyFormat(
5864       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5865       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
5866       "}");
5867   // Even explicit parentheses stress the precedence enough to make the
5868   // additional break unnecessary.
5869   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5870                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5871                "}");
5872   // This cases is borderline, but with the indentation it is still readable.
5873   verifyFormat(
5874       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5875       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5876       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
5877       "}",
5878       getLLVMStyleWithColumns(75));
5879 
5880   // If the LHS is a binary expression, we should still use the additional break
5881   // as otherwise the formatting hides the operator precedence.
5882   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5883                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5884                "    5) {\n"
5885                "}");
5886   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5887                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
5888                "    5) {\n"
5889                "}");
5890 
5891   FormatStyle OnePerLine = getLLVMStyle();
5892   OnePerLine.BinPackParameters = false;
5893   verifyFormat(
5894       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5895       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5896       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
5897       OnePerLine);
5898 
5899   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
5900                "                .aaa(aaaaaaaaaaaaa) *\n"
5901                "            aaaaaaa +\n"
5902                "        aaaaaaa;",
5903                getLLVMStyleWithColumns(40));
5904 }
5905 
5906 TEST_F(FormatTest, ExpressionIndentation) {
5907   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5908                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5909                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5910                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5911                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
5912                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
5913                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5914                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
5915                "                 ccccccccccccccccccccccccccccccccccccccccc;");
5916   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5917                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5918                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5919                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5920   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5921                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5922                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5923                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5924   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5925                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5926                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5927                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5928   verifyFormat("if () {\n"
5929                "} else if (aaaaa && bbbbb > // break\n"
5930                "                        ccccc) {\n"
5931                "}");
5932   verifyFormat("if () {\n"
5933                "} else if constexpr (aaaaa && bbbbb > // break\n"
5934                "                                  ccccc) {\n"
5935                "}");
5936   verifyFormat("if () {\n"
5937                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
5938                "                                  ccccc) {\n"
5939                "}");
5940   verifyFormat("if () {\n"
5941                "} else if (aaaaa &&\n"
5942                "           bbbbb > // break\n"
5943                "               ccccc &&\n"
5944                "           ddddd) {\n"
5945                "}");
5946 
5947   // Presence of a trailing comment used to change indentation of b.
5948   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
5949                "       b;\n"
5950                "return aaaaaaaaaaaaaaaaaaa +\n"
5951                "       b; //",
5952                getLLVMStyleWithColumns(30));
5953 }
5954 
5955 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
5956   // Not sure what the best system is here. Like this, the LHS can be found
5957   // immediately above an operator (everything with the same or a higher
5958   // indent). The RHS is aligned right of the operator and so compasses
5959   // everything until something with the same indent as the operator is found.
5960   // FIXME: Is this a good system?
5961   FormatStyle Style = getLLVMStyle();
5962   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5963   verifyFormat(
5964       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5965       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5966       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5967       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5968       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5969       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5970       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5971       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5972       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
5973       Style);
5974   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5975                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5976                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5977                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5978                Style);
5979   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5980                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5981                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5982                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5983                Style);
5984   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5985                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5986                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5987                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5988                Style);
5989   verifyFormat("if () {\n"
5990                "} else if (aaaaa\n"
5991                "           && bbbbb // break\n"
5992                "                  > ccccc) {\n"
5993                "}",
5994                Style);
5995   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5996                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5997                Style);
5998   verifyFormat("return (a)\n"
5999                "       // comment\n"
6000                "       + b;",
6001                Style);
6002   verifyFormat(
6003       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6004       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6005       "             + cc;",
6006       Style);
6007 
6008   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6009                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6010                Style);
6011 
6012   // Forced by comments.
6013   verifyFormat(
6014       "unsigned ContentSize =\n"
6015       "    sizeof(int16_t)   // DWARF ARange version number\n"
6016       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6017       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6018       "    + sizeof(int8_t); // Segment Size (in bytes)");
6019 
6020   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6021                "       == boost::fusion::at_c<1>(iiii).second;",
6022                Style);
6023 
6024   Style.ColumnLimit = 60;
6025   verifyFormat("zzzzzzzzzz\n"
6026                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6027                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6028                Style);
6029 
6030   Style.ColumnLimit = 80;
6031   Style.IndentWidth = 4;
6032   Style.TabWidth = 4;
6033   Style.UseTab = FormatStyle::UT_Always;
6034   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6035   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6036   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
6037             "\t&& (someOtherLongishConditionPart1\n"
6038             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
6039             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
6040                    "(someOtherLongishConditionPart1 || "
6041                    "someOtherEvenLongerNestedConditionPart2);",
6042                    Style));
6043 }
6044 
6045 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
6046   FormatStyle Style = getLLVMStyle();
6047   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6048   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
6049 
6050   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6051                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6052                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6053                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6054                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6055                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6056                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6057                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6058                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
6059                Style);
6060   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6061                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6062                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6063                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6064                Style);
6065   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6066                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6067                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6068                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6069                Style);
6070   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6071                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6072                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6073                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6074                Style);
6075   verifyFormat("if () {\n"
6076                "} else if (aaaaa\n"
6077                "           && bbbbb // break\n"
6078                "                  > ccccc) {\n"
6079                "}",
6080                Style);
6081   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6082                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6083                Style);
6084   verifyFormat("return (a)\n"
6085                "     // comment\n"
6086                "     + b;",
6087                Style);
6088   verifyFormat(
6089       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6090       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6091       "           + cc;",
6092       Style);
6093   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6094                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6095                "                        : 3333333333333333;",
6096                Style);
6097   verifyFormat(
6098       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6099       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6100       "                                             : eeeeeeeeeeeeeeeeee)\n"
6101       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6102       "                        : 3333333333333333;",
6103       Style);
6104   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6105                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6106                Style);
6107 
6108   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6109                "    == boost::fusion::at_c<1>(iiii).second;",
6110                Style);
6111 
6112   Style.ColumnLimit = 60;
6113   verifyFormat("zzzzzzzzzzzzz\n"
6114                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6115                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6116                Style);
6117 
6118   // Forced by comments.
6119   Style.ColumnLimit = 80;
6120   verifyFormat(
6121       "unsigned ContentSize\n"
6122       "    = sizeof(int16_t) // DWARF ARange version number\n"
6123       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6124       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6125       "    + sizeof(int8_t); // Segment Size (in bytes)",
6126       Style);
6127 
6128   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6129   verifyFormat(
6130       "unsigned ContentSize =\n"
6131       "    sizeof(int16_t)   // DWARF ARange version number\n"
6132       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6133       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6134       "    + sizeof(int8_t); // Segment Size (in bytes)",
6135       Style);
6136 
6137   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6138   verifyFormat(
6139       "unsigned ContentSize =\n"
6140       "    sizeof(int16_t)   // DWARF ARange version number\n"
6141       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6142       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6143       "    + sizeof(int8_t); // Segment Size (in bytes)",
6144       Style);
6145 }
6146 
6147 TEST_F(FormatTest, EnforcedOperatorWraps) {
6148   // Here we'd like to wrap after the || operators, but a comment is forcing an
6149   // earlier wrap.
6150   verifyFormat("bool x = aaaaa //\n"
6151                "         || bbbbb\n"
6152                "         //\n"
6153                "         || cccc;");
6154 }
6155 
6156 TEST_F(FormatTest, NoOperandAlignment) {
6157   FormatStyle Style = getLLVMStyle();
6158   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6159   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6160                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6161                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6162                Style);
6163   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6164   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6165                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6166                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6167                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6168                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6169                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6170                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6171                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6172                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6173                Style);
6174 
6175   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6176                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6177                "    + cc;",
6178                Style);
6179   verifyFormat("int a = aa\n"
6180                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6181                "        * cccccccccccccccccccccccccccccccccccc;\n",
6182                Style);
6183 
6184   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6185   verifyFormat("return (a > b\n"
6186                "    // comment1\n"
6187                "    // comment2\n"
6188                "    || c);",
6189                Style);
6190 }
6191 
6192 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6193   FormatStyle Style = getLLVMStyle();
6194   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6195   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6196                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6197                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6198                Style);
6199 }
6200 
6201 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6202   FormatStyle Style = getLLVMStyleWithColumns(40);
6203   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6204   Style.BinPackArguments = false;
6205   verifyFormat("void test() {\n"
6206                "  someFunction(\n"
6207                "      this + argument + is + quite\n"
6208                "      + long + so + it + gets + wrapped\n"
6209                "      + but + remains + bin - packed);\n"
6210                "}",
6211                Style);
6212   verifyFormat("void test() {\n"
6213                "  someFunction(arg1,\n"
6214                "               this + argument + is\n"
6215                "                   + quite + long + so\n"
6216                "                   + it + gets + wrapped\n"
6217                "                   + but + remains + bin\n"
6218                "                   - packed,\n"
6219                "               arg3);\n"
6220                "}",
6221                Style);
6222   verifyFormat("void test() {\n"
6223                "  someFunction(\n"
6224                "      arg1,\n"
6225                "      this + argument + has\n"
6226                "          + anotherFunc(nested,\n"
6227                "                        calls + whose\n"
6228                "                            + arguments\n"
6229                "                            + are + also\n"
6230                "                            + wrapped,\n"
6231                "                        in + addition)\n"
6232                "          + to + being + bin - packed,\n"
6233                "      arg3);\n"
6234                "}",
6235                Style);
6236 
6237   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6238   verifyFormat("void test() {\n"
6239                "  someFunction(\n"
6240                "      arg1,\n"
6241                "      this + argument + has +\n"
6242                "          anotherFunc(nested,\n"
6243                "                      calls + whose +\n"
6244                "                          arguments +\n"
6245                "                          are + also +\n"
6246                "                          wrapped,\n"
6247                "                      in + addition) +\n"
6248                "          to + being + bin - packed,\n"
6249                "      arg3);\n"
6250                "}",
6251                Style);
6252 }
6253 
6254 TEST_F(FormatTest, ConstructorInitializers) {
6255   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6256   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6257                getLLVMStyleWithColumns(45));
6258   verifyFormat("Constructor()\n"
6259                "    : Inttializer(FitsOnTheLine) {}",
6260                getLLVMStyleWithColumns(44));
6261   verifyFormat("Constructor()\n"
6262                "    : Inttializer(FitsOnTheLine) {}",
6263                getLLVMStyleWithColumns(43));
6264 
6265   verifyFormat("template <typename T>\n"
6266                "Constructor() : Initializer(FitsOnTheLine) {}",
6267                getLLVMStyleWithColumns(45));
6268 
6269   verifyFormat(
6270       "SomeClass::Constructor()\n"
6271       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6272 
6273   verifyFormat(
6274       "SomeClass::Constructor()\n"
6275       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6276       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6277   verifyFormat(
6278       "SomeClass::Constructor()\n"
6279       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6280       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6281   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6282                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6283                "    : aaaaaaaaaa(aaaaaa) {}");
6284 
6285   verifyFormat("Constructor()\n"
6286                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6287                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6288                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6289                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6290 
6291   verifyFormat("Constructor()\n"
6292                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6293                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6294 
6295   verifyFormat("Constructor(int Parameter = 0)\n"
6296                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6297                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6298   verifyFormat("Constructor()\n"
6299                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6300                "}",
6301                getLLVMStyleWithColumns(60));
6302   verifyFormat("Constructor()\n"
6303                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6304                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6305 
6306   // Here a line could be saved by splitting the second initializer onto two
6307   // lines, but that is not desirable.
6308   verifyFormat("Constructor()\n"
6309                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6310                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6311                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6312 
6313   FormatStyle OnePerLine = getLLVMStyle();
6314   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6315   verifyFormat("MyClass::MyClass()\n"
6316                "    : a(a),\n"
6317                "      b(b),\n"
6318                "      c(c) {}",
6319                OnePerLine);
6320   verifyFormat("MyClass::MyClass()\n"
6321                "    : a(a), // comment\n"
6322                "      b(b),\n"
6323                "      c(c) {}",
6324                OnePerLine);
6325   verifyFormat("MyClass::MyClass(int a)\n"
6326                "    : b(a),      // comment\n"
6327                "      c(a + 1) { // lined up\n"
6328                "}",
6329                OnePerLine);
6330   verifyFormat("Constructor()\n"
6331                "    : a(b, b, b) {}",
6332                OnePerLine);
6333   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6334   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6335   verifyFormat("SomeClass::Constructor()\n"
6336                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6337                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6338                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6339                OnePerLine);
6340   verifyFormat("SomeClass::Constructor()\n"
6341                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6342                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6343                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6344                OnePerLine);
6345   verifyFormat("MyClass::MyClass(int var)\n"
6346                "    : some_var_(var),            // 4 space indent\n"
6347                "      some_other_var_(var + 1) { // lined up\n"
6348                "}",
6349                OnePerLine);
6350   verifyFormat("Constructor()\n"
6351                "    : aaaaa(aaaaaa),\n"
6352                "      aaaaa(aaaaaa),\n"
6353                "      aaaaa(aaaaaa),\n"
6354                "      aaaaa(aaaaaa),\n"
6355                "      aaaaa(aaaaaa) {}",
6356                OnePerLine);
6357   verifyFormat("Constructor()\n"
6358                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6359                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6360                OnePerLine);
6361   OnePerLine.BinPackParameters = false;
6362   verifyFormat(
6363       "Constructor()\n"
6364       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6365       "          aaaaaaaaaaa().aaa(),\n"
6366       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6367       OnePerLine);
6368   OnePerLine.ColumnLimit = 60;
6369   verifyFormat("Constructor()\n"
6370                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6371                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6372                OnePerLine);
6373 
6374   EXPECT_EQ("Constructor()\n"
6375             "    : // Comment forcing unwanted break.\n"
6376             "      aaaa(aaaa) {}",
6377             format("Constructor() :\n"
6378                    "    // Comment forcing unwanted break.\n"
6379                    "    aaaa(aaaa) {}"));
6380 }
6381 
6382 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6383   FormatStyle Style = getLLVMStyleWithColumns(60);
6384   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6385   Style.BinPackParameters = false;
6386 
6387   for (int i = 0; i < 4; ++i) {
6388     // Test all combinations of parameters that should not have an effect.
6389     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6390     Style.AllowAllArgumentsOnNextLine = i & 2;
6391 
6392     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6393     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6394     verifyFormat("Constructor()\n"
6395                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6396                  Style);
6397     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6398 
6399     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6400     verifyFormat("Constructor()\n"
6401                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6402                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6403                  Style);
6404     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6405 
6406     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6407     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6408     verifyFormat("Constructor()\n"
6409                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6410                  Style);
6411 
6412     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6413     verifyFormat("Constructor()\n"
6414                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6415                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6416                  Style);
6417 
6418     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6419     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6420     verifyFormat("Constructor() :\n"
6421                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6422                  Style);
6423 
6424     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6425     verifyFormat("Constructor() :\n"
6426                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6427                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6428                  Style);
6429   }
6430 
6431   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6432   // AllowAllConstructorInitializersOnNextLine in all
6433   // BreakConstructorInitializers modes
6434   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6435   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6436   verifyFormat("SomeClassWithALongName::Constructor(\n"
6437                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6438                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6439                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6440                Style);
6441 
6442   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6443   verifyFormat("SomeClassWithALongName::Constructor(\n"
6444                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6445                "    int bbbbbbbbbbbbb,\n"
6446                "    int cccccccccccccccc)\n"
6447                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6448                Style);
6449 
6450   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6451   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6452   verifyFormat("SomeClassWithALongName::Constructor(\n"
6453                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6454                "    int bbbbbbbbbbbbb)\n"
6455                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6456                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6457                Style);
6458 
6459   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6460 
6461   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6462   verifyFormat("SomeClassWithALongName::Constructor(\n"
6463                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6464                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6465                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6466                Style);
6467 
6468   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6469   verifyFormat("SomeClassWithALongName::Constructor(\n"
6470                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6471                "    int bbbbbbbbbbbbb,\n"
6472                "    int cccccccccccccccc)\n"
6473                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6474                Style);
6475 
6476   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6477   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6478   verifyFormat("SomeClassWithALongName::Constructor(\n"
6479                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6480                "    int bbbbbbbbbbbbb)\n"
6481                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6482                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6483                Style);
6484 
6485   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6486   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6487   verifyFormat("SomeClassWithALongName::Constructor(\n"
6488                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6489                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6490                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6491                Style);
6492 
6493   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6494   verifyFormat("SomeClassWithALongName::Constructor(\n"
6495                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6496                "    int bbbbbbbbbbbbb,\n"
6497                "    int cccccccccccccccc) :\n"
6498                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6499                Style);
6500 
6501   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6502   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6503   verifyFormat("SomeClassWithALongName::Constructor(\n"
6504                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6505                "    int bbbbbbbbbbbbb) :\n"
6506                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6507                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6508                Style);
6509 }
6510 
6511 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6512   FormatStyle Style = getLLVMStyleWithColumns(60);
6513   Style.BinPackArguments = false;
6514   for (int i = 0; i < 4; ++i) {
6515     // Test all combinations of parameters that should not have an effect.
6516     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6517     Style.PackConstructorInitializers =
6518         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6519 
6520     Style.AllowAllArgumentsOnNextLine = true;
6521     verifyFormat("void foo() {\n"
6522                  "  FunctionCallWithReallyLongName(\n"
6523                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6524                  "}",
6525                  Style);
6526     Style.AllowAllArgumentsOnNextLine = false;
6527     verifyFormat("void foo() {\n"
6528                  "  FunctionCallWithReallyLongName(\n"
6529                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6530                  "      bbbbbbbbbbbb);\n"
6531                  "}",
6532                  Style);
6533 
6534     Style.AllowAllArgumentsOnNextLine = true;
6535     verifyFormat("void foo() {\n"
6536                  "  auto VariableWithReallyLongName = {\n"
6537                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6538                  "}",
6539                  Style);
6540     Style.AllowAllArgumentsOnNextLine = false;
6541     verifyFormat("void foo() {\n"
6542                  "  auto VariableWithReallyLongName = {\n"
6543                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6544                  "      bbbbbbbbbbbb};\n"
6545                  "}",
6546                  Style);
6547   }
6548 
6549   // This parameter should not affect declarations.
6550   Style.BinPackParameters = false;
6551   Style.AllowAllArgumentsOnNextLine = false;
6552   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6553   verifyFormat("void FunctionCallWithReallyLongName(\n"
6554                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6555                Style);
6556   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6557   verifyFormat("void FunctionCallWithReallyLongName(\n"
6558                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6559                "    int bbbbbbbbbbbb);",
6560                Style);
6561 }
6562 
6563 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6564   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6565   // and BAS_Align.
6566   FormatStyle Style = getLLVMStyleWithColumns(35);
6567   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6568                     "void functionDecl(int A, int B, int C);";
6569   Style.AllowAllArgumentsOnNextLine = false;
6570   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6571   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6572                       "    paramC);\n"
6573                       "void functionDecl(int A, int B,\n"
6574                       "    int C);"),
6575             format(Input, Style));
6576   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6577   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6578                       "             paramC);\n"
6579                       "void functionDecl(int A, int B,\n"
6580                       "                  int C);"),
6581             format(Input, Style));
6582   // However, BAS_AlwaysBreak should take precedence over
6583   // AllowAllArgumentsOnNextLine.
6584   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6585   EXPECT_EQ(StringRef("functionCall(\n"
6586                       "    paramA, paramB, paramC);\n"
6587                       "void functionDecl(\n"
6588                       "    int A, int B, int C);"),
6589             format(Input, Style));
6590 
6591   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6592   // first argument.
6593   Style.AllowAllArgumentsOnNextLine = true;
6594   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6595   EXPECT_EQ(StringRef("functionCall(\n"
6596                       "    paramA, paramB, paramC);\n"
6597                       "void functionDecl(\n"
6598                       "    int A, int B, int C);"),
6599             format(Input, Style));
6600   // It wouldn't fit on one line with aligned parameters so this setting
6601   // doesn't change anything for BAS_Align.
6602   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6603   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6604                       "             paramC);\n"
6605                       "void functionDecl(int A, int B,\n"
6606                       "                  int C);"),
6607             format(Input, Style));
6608   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6609   EXPECT_EQ(StringRef("functionCall(\n"
6610                       "    paramA, paramB, paramC);\n"
6611                       "void functionDecl(\n"
6612                       "    int A, int B, int C);"),
6613             format(Input, Style));
6614 }
6615 
6616 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6617   FormatStyle Style = getLLVMStyle();
6618   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6619 
6620   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6621   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6622                getStyleWithColumns(Style, 45));
6623   verifyFormat("Constructor() :\n"
6624                "    Initializer(FitsOnTheLine) {}",
6625                getStyleWithColumns(Style, 44));
6626   verifyFormat("Constructor() :\n"
6627                "    Initializer(FitsOnTheLine) {}",
6628                getStyleWithColumns(Style, 43));
6629 
6630   verifyFormat("template <typename T>\n"
6631                "Constructor() : Initializer(FitsOnTheLine) {}",
6632                getStyleWithColumns(Style, 50));
6633   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6634   verifyFormat(
6635       "SomeClass::Constructor() :\n"
6636       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6637       Style);
6638 
6639   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6640   verifyFormat(
6641       "SomeClass::Constructor() :\n"
6642       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6643       Style);
6644 
6645   verifyFormat(
6646       "SomeClass::Constructor() :\n"
6647       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6648       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6649       Style);
6650   verifyFormat(
6651       "SomeClass::Constructor() :\n"
6652       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6653       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6654       Style);
6655   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6656                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6657                "    aaaaaaaaaa(aaaaaa) {}",
6658                Style);
6659 
6660   verifyFormat("Constructor() :\n"
6661                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6662                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6663                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6664                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
6665                Style);
6666 
6667   verifyFormat("Constructor() :\n"
6668                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6669                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6670                Style);
6671 
6672   verifyFormat("Constructor(int Parameter = 0) :\n"
6673                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6674                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
6675                Style);
6676   verifyFormat("Constructor() :\n"
6677                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6678                "}",
6679                getStyleWithColumns(Style, 60));
6680   verifyFormat("Constructor() :\n"
6681                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6682                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
6683                Style);
6684 
6685   // Here a line could be saved by splitting the second initializer onto two
6686   // lines, but that is not desirable.
6687   verifyFormat("Constructor() :\n"
6688                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6689                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
6690                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6691                Style);
6692 
6693   FormatStyle OnePerLine = Style;
6694   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6695   verifyFormat("SomeClass::Constructor() :\n"
6696                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6697                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6698                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6699                OnePerLine);
6700   verifyFormat("SomeClass::Constructor() :\n"
6701                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6702                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6703                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6704                OnePerLine);
6705   verifyFormat("MyClass::MyClass(int var) :\n"
6706                "    some_var_(var),            // 4 space indent\n"
6707                "    some_other_var_(var + 1) { // lined up\n"
6708                "}",
6709                OnePerLine);
6710   verifyFormat("Constructor() :\n"
6711                "    aaaaa(aaaaaa),\n"
6712                "    aaaaa(aaaaaa),\n"
6713                "    aaaaa(aaaaaa),\n"
6714                "    aaaaa(aaaaaa),\n"
6715                "    aaaaa(aaaaaa) {}",
6716                OnePerLine);
6717   verifyFormat("Constructor() :\n"
6718                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6719                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
6720                OnePerLine);
6721   OnePerLine.BinPackParameters = false;
6722   verifyFormat("Constructor() :\n"
6723                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6724                "        aaaaaaaaaaa().aaa(),\n"
6725                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6726                OnePerLine);
6727   OnePerLine.ColumnLimit = 60;
6728   verifyFormat("Constructor() :\n"
6729                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6730                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6731                OnePerLine);
6732 
6733   EXPECT_EQ("Constructor() :\n"
6734             "    // Comment forcing unwanted break.\n"
6735             "    aaaa(aaaa) {}",
6736             format("Constructor() :\n"
6737                    "    // Comment forcing unwanted break.\n"
6738                    "    aaaa(aaaa) {}",
6739                    Style));
6740 
6741   Style.ColumnLimit = 0;
6742   verifyFormat("SomeClass::Constructor() :\n"
6743                "    a(a) {}",
6744                Style);
6745   verifyFormat("SomeClass::Constructor() noexcept :\n"
6746                "    a(a) {}",
6747                Style);
6748   verifyFormat("SomeClass::Constructor() :\n"
6749                "    a(a), b(b), c(c) {}",
6750                Style);
6751   verifyFormat("SomeClass::Constructor() :\n"
6752                "    a(a) {\n"
6753                "  foo();\n"
6754                "  bar();\n"
6755                "}",
6756                Style);
6757 
6758   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6759   verifyFormat("SomeClass::Constructor() :\n"
6760                "    a(a), b(b), c(c) {\n"
6761                "}",
6762                Style);
6763   verifyFormat("SomeClass::Constructor() :\n"
6764                "    a(a) {\n"
6765                "}",
6766                Style);
6767 
6768   Style.ColumnLimit = 80;
6769   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
6770   Style.ConstructorInitializerIndentWidth = 2;
6771   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
6772   verifyFormat("SomeClass::Constructor() :\n"
6773                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6774                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
6775                Style);
6776 
6777   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
6778   // well
6779   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
6780   verifyFormat(
6781       "class SomeClass\n"
6782       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6783       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6784       Style);
6785   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
6786   verifyFormat(
6787       "class SomeClass\n"
6788       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6789       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6790       Style);
6791   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
6792   verifyFormat(
6793       "class SomeClass :\n"
6794       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6795       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6796       Style);
6797   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
6798   verifyFormat(
6799       "class SomeClass\n"
6800       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6801       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6802       Style);
6803 }
6804 
6805 #ifndef EXPENSIVE_CHECKS
6806 // Expensive checks enables libstdc++ checking which includes validating the
6807 // state of ranges used in std::priority_queue - this blows out the
6808 // runtime/scalability of the function and makes this test unacceptably slow.
6809 TEST_F(FormatTest, MemoizationTests) {
6810   // This breaks if the memoization lookup does not take \c Indent and
6811   // \c LastSpace into account.
6812   verifyFormat(
6813       "extern CFRunLoopTimerRef\n"
6814       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
6815       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
6816       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
6817       "                     CFRunLoopTimerContext *context) {}");
6818 
6819   // Deep nesting somewhat works around our memoization.
6820   verifyFormat(
6821       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6822       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6823       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6824       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6825       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
6826       getLLVMStyleWithColumns(65));
6827   verifyFormat(
6828       "aaaaa(\n"
6829       "    aaaaa,\n"
6830       "    aaaaa(\n"
6831       "        aaaaa,\n"
6832       "        aaaaa(\n"
6833       "            aaaaa,\n"
6834       "            aaaaa(\n"
6835       "                aaaaa,\n"
6836       "                aaaaa(\n"
6837       "                    aaaaa,\n"
6838       "                    aaaaa(\n"
6839       "                        aaaaa,\n"
6840       "                        aaaaa(\n"
6841       "                            aaaaa,\n"
6842       "                            aaaaa(\n"
6843       "                                aaaaa,\n"
6844       "                                aaaaa(\n"
6845       "                                    aaaaa,\n"
6846       "                                    aaaaa(\n"
6847       "                                        aaaaa,\n"
6848       "                                        aaaaa(\n"
6849       "                                            aaaaa,\n"
6850       "                                            aaaaa(\n"
6851       "                                                aaaaa,\n"
6852       "                                                aaaaa))))))))))));",
6853       getLLVMStyleWithColumns(65));
6854   verifyFormat(
6855       "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"
6856       "                                  a),\n"
6857       "                                a),\n"
6858       "                              a),\n"
6859       "                            a),\n"
6860       "                          a),\n"
6861       "                        a),\n"
6862       "                      a),\n"
6863       "                    a),\n"
6864       "                  a),\n"
6865       "                a),\n"
6866       "              a),\n"
6867       "            a),\n"
6868       "          a),\n"
6869       "        a),\n"
6870       "      a),\n"
6871       "    a),\n"
6872       "  a)",
6873       getLLVMStyleWithColumns(65));
6874 
6875   // This test takes VERY long when memoization is broken.
6876   FormatStyle OnePerLine = getLLVMStyle();
6877   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6878   OnePerLine.BinPackParameters = false;
6879   std::string input = "Constructor()\n"
6880                       "    : aaaa(a,\n";
6881   for (unsigned i = 0, e = 80; i != e; ++i) {
6882     input += "           a,\n";
6883   }
6884   input += "           a) {}";
6885   verifyFormat(input, OnePerLine);
6886 }
6887 #endif
6888 
6889 TEST_F(FormatTest, BreaksAsHighAsPossible) {
6890   verifyFormat(
6891       "void f() {\n"
6892       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
6893       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
6894       "    f();\n"
6895       "}");
6896   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
6897                "    Intervals[i - 1].getRange().getLast()) {\n}");
6898 }
6899 
6900 TEST_F(FormatTest, BreaksFunctionDeclarations) {
6901   // Principially, we break function declarations in a certain order:
6902   // 1) break amongst arguments.
6903   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
6904                "                              Cccccccccccccc cccccccccccccc);");
6905   verifyFormat("template <class TemplateIt>\n"
6906                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
6907                "                            TemplateIt *stop) {}");
6908 
6909   // 2) break after return type.
6910   verifyFormat(
6911       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6912       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
6913       getGoogleStyle());
6914 
6915   // 3) break after (.
6916   verifyFormat(
6917       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
6918       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
6919       getGoogleStyle());
6920 
6921   // 4) break before after nested name specifiers.
6922   verifyFormat(
6923       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6924       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
6925       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
6926       getGoogleStyle());
6927 
6928   // However, there are exceptions, if a sufficient amount of lines can be
6929   // saved.
6930   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
6931   // more adjusting.
6932   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6933                "                                  Cccccccccccccc cccccccccc,\n"
6934                "                                  Cccccccccccccc cccccccccc,\n"
6935                "                                  Cccccccccccccc cccccccccc,\n"
6936                "                                  Cccccccccccccc cccccccccc);");
6937   verifyFormat(
6938       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6939       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6940       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6941       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
6942       getGoogleStyle());
6943   verifyFormat(
6944       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6945       "                                          Cccccccccccccc cccccccccc,\n"
6946       "                                          Cccccccccccccc cccccccccc,\n"
6947       "                                          Cccccccccccccc cccccccccc,\n"
6948       "                                          Cccccccccccccc cccccccccc,\n"
6949       "                                          Cccccccccccccc cccccccccc,\n"
6950       "                                          Cccccccccccccc cccccccccc);");
6951   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6952                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6953                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6954                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6955                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
6956 
6957   // Break after multi-line parameters.
6958   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6959                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6960                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6961                "    bbbb bbbb);");
6962   verifyFormat("void SomeLoooooooooooongFunction(\n"
6963                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
6964                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6965                "    int bbbbbbbbbbbbb);");
6966 
6967   // Treat overloaded operators like other functions.
6968   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6969                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
6970   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6971                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
6972   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6973                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
6974   verifyGoogleFormat(
6975       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
6976       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6977   verifyGoogleFormat(
6978       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
6979       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6980   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6981                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6982   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
6983                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6984   verifyGoogleFormat(
6985       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
6986       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6987       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
6988   verifyGoogleFormat("template <typename T>\n"
6989                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6990                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
6991                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
6992 
6993   FormatStyle Style = getLLVMStyle();
6994   Style.PointerAlignment = FormatStyle::PAS_Left;
6995   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6996                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
6997                Style);
6998   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
6999                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7000                Style);
7001 }
7002 
7003 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
7004   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
7005   // Prefer keeping `::` followed by `operator` together.
7006   EXPECT_EQ("const aaaa::bbbbbbb &\n"
7007             "ccccccccc::operator++() {\n"
7008             "  stuff();\n"
7009             "}",
7010             format("const aaaa::bbbbbbb\n"
7011                    "&ccccccccc::operator++() { stuff(); }",
7012                    getLLVMStyleWithColumns(40)));
7013 }
7014 
7015 TEST_F(FormatTest, TrailingReturnType) {
7016   verifyFormat("auto foo() -> int;\n");
7017   // correct trailing return type spacing
7018   verifyFormat("auto operator->() -> int;\n");
7019   verifyFormat("auto operator++(int) -> int;\n");
7020 
7021   verifyFormat("struct S {\n"
7022                "  auto bar() const -> int;\n"
7023                "};");
7024   verifyFormat("template <size_t Order, typename T>\n"
7025                "auto load_img(const std::string &filename)\n"
7026                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
7027   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
7028                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
7029   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
7030   verifyFormat("template <typename T>\n"
7031                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
7032                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
7033 
7034   // Not trailing return types.
7035   verifyFormat("void f() { auto a = b->c(); }");
7036   verifyFormat("auto a = p->foo();");
7037   verifyFormat("int a = p->foo();");
7038   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
7039 }
7040 
7041 TEST_F(FormatTest, DeductionGuides) {
7042   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
7043   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
7044   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
7045   verifyFormat(
7046       "template <class... T>\n"
7047       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
7048   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
7049   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
7050   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
7051   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
7052   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
7053   verifyFormat("template <class T> x() -> x<1>;");
7054   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
7055 
7056   // Ensure not deduction guides.
7057   verifyFormat("c()->f<int>();");
7058   verifyFormat("x()->foo<1>;");
7059   verifyFormat("x = p->foo<3>();");
7060   verifyFormat("x()->x<1>();");
7061   verifyFormat("x()->x<1>;");
7062 }
7063 
7064 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
7065   // Avoid breaking before trailing 'const' or other trailing annotations, if
7066   // they are not function-like.
7067   FormatStyle Style = getGoogleStyleWithColumns(47);
7068   verifyFormat("void someLongFunction(\n"
7069                "    int someLoooooooooooooongParameter) const {\n}",
7070                getLLVMStyleWithColumns(47));
7071   verifyFormat("LoooooongReturnType\n"
7072                "someLoooooooongFunction() const {}",
7073                getLLVMStyleWithColumns(47));
7074   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
7075                "    const {}",
7076                Style);
7077   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7078                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
7079   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7080                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
7081   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7082                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
7083   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
7084                "                   aaaaaaaaaaa aaaaa) const override;");
7085   verifyGoogleFormat(
7086       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7087       "    const override;");
7088 
7089   // Even if the first parameter has to be wrapped.
7090   verifyFormat("void someLongFunction(\n"
7091                "    int someLongParameter) const {}",
7092                getLLVMStyleWithColumns(46));
7093   verifyFormat("void someLongFunction(\n"
7094                "    int someLongParameter) const {}",
7095                Style);
7096   verifyFormat("void someLongFunction(\n"
7097                "    int someLongParameter) override {}",
7098                Style);
7099   verifyFormat("void someLongFunction(\n"
7100                "    int someLongParameter) OVERRIDE {}",
7101                Style);
7102   verifyFormat("void someLongFunction(\n"
7103                "    int someLongParameter) final {}",
7104                Style);
7105   verifyFormat("void someLongFunction(\n"
7106                "    int someLongParameter) FINAL {}",
7107                Style);
7108   verifyFormat("void someLongFunction(\n"
7109                "    int parameter) const override {}",
7110                Style);
7111 
7112   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
7113   verifyFormat("void someLongFunction(\n"
7114                "    int someLongParameter) const\n"
7115                "{\n"
7116                "}",
7117                Style);
7118 
7119   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
7120   verifyFormat("void someLongFunction(\n"
7121                "    int someLongParameter) const\n"
7122                "  {\n"
7123                "  }",
7124                Style);
7125 
7126   // Unless these are unknown annotations.
7127   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
7128                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7129                "    LONG_AND_UGLY_ANNOTATION;");
7130 
7131   // Breaking before function-like trailing annotations is fine to keep them
7132   // close to their arguments.
7133   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7134                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7135   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7136                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7137   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7138                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
7139   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
7140                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
7141   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
7142 
7143   verifyFormat(
7144       "void aaaaaaaaaaaaaaaaaa()\n"
7145       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
7146       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
7147   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7148                "    __attribute__((unused));");
7149   verifyGoogleFormat(
7150       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7151       "    GUARDED_BY(aaaaaaaaaaaa);");
7152   verifyGoogleFormat(
7153       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7154       "    GUARDED_BY(aaaaaaaaaaaa);");
7155   verifyGoogleFormat(
7156       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7157       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7158   verifyGoogleFormat(
7159       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7160       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
7161 }
7162 
7163 TEST_F(FormatTest, FunctionAnnotations) {
7164   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7165                "int OldFunction(const string &parameter) {}");
7166   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7167                "string OldFunction(const string &parameter) {}");
7168   verifyFormat("template <typename T>\n"
7169                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7170                "string OldFunction(const string &parameter) {}");
7171 
7172   // Not function annotations.
7173   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7174                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
7175   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
7176                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
7177   verifyFormat("MACRO(abc).function() // wrap\n"
7178                "    << abc;");
7179   verifyFormat("MACRO(abc)->function() // wrap\n"
7180                "    << abc;");
7181   verifyFormat("MACRO(abc)::function() // wrap\n"
7182                "    << abc;");
7183 }
7184 
7185 TEST_F(FormatTest, BreaksDesireably) {
7186   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7187                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7188                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
7189   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7190                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
7191                "}");
7192 
7193   verifyFormat(
7194       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7195       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7196 
7197   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7198                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7199                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7200 
7201   verifyFormat(
7202       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7203       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7204       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7205       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7206       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7207 
7208   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7209                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7210 
7211   verifyFormat(
7212       "void f() {\n"
7213       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7214       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7215       "}");
7216   verifyFormat(
7217       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7218       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7219   verifyFormat(
7220       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7221       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7222   verifyFormat(
7223       "aaaaaa(aaa,\n"
7224       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7225       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7226       "       aaaa);");
7227   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7228                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7229                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7230 
7231   // Indent consistently independent of call expression and unary operator.
7232   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7233                "    dddddddddddddddddddddddddddddd));");
7234   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7235                "    dddddddddddddddddddddddddddddd));");
7236   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7237                "    dddddddddddddddddddddddddddddd));");
7238 
7239   // This test case breaks on an incorrect memoization, i.e. an optimization not
7240   // taking into account the StopAt value.
7241   verifyFormat(
7242       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7243       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7244       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7245       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7246 
7247   verifyFormat("{\n  {\n    {\n"
7248                "      Annotation.SpaceRequiredBefore =\n"
7249                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7250                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7251                "    }\n  }\n}");
7252 
7253   // Break on an outer level if there was a break on an inner level.
7254   EXPECT_EQ("f(g(h(a, // comment\n"
7255             "      b, c),\n"
7256             "    d, e),\n"
7257             "  x, y);",
7258             format("f(g(h(a, // comment\n"
7259                    "    b, c), d, e), x, y);"));
7260 
7261   // Prefer breaking similar line breaks.
7262   verifyFormat(
7263       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7264       "                             NSTrackingMouseEnteredAndExited |\n"
7265       "                             NSTrackingActiveAlways;");
7266 }
7267 
7268 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7269   FormatStyle NoBinPacking = getGoogleStyle();
7270   NoBinPacking.BinPackParameters = false;
7271   NoBinPacking.BinPackArguments = true;
7272   verifyFormat("void f() {\n"
7273                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7274                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7275                "}",
7276                NoBinPacking);
7277   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7278                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7279                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7280                NoBinPacking);
7281 
7282   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7283   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7284                "                        vector<int> bbbbbbbbbbbbbbb);",
7285                NoBinPacking);
7286   // FIXME: This behavior difference is probably not wanted. However, currently
7287   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7288   // template arguments from BreakBeforeParameter being set because of the
7289   // one-per-line formatting.
7290   verifyFormat(
7291       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7292       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7293       NoBinPacking);
7294   verifyFormat(
7295       "void fffffffffff(\n"
7296       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7297       "        aaaaaaaaaa);");
7298 }
7299 
7300 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7301   FormatStyle NoBinPacking = getGoogleStyle();
7302   NoBinPacking.BinPackParameters = false;
7303   NoBinPacking.BinPackArguments = false;
7304   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7305                "  aaaaaaaaaaaaaaaaaaaa,\n"
7306                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7307                NoBinPacking);
7308   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7309                "        aaaaaaaaaaaaa,\n"
7310                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7311                NoBinPacking);
7312   verifyFormat(
7313       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7314       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7315       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7316       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7317       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7318       NoBinPacking);
7319   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7320                "    .aaaaaaaaaaaaaaaaaa();",
7321                NoBinPacking);
7322   verifyFormat("void f() {\n"
7323                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7324                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7325                "}",
7326                NoBinPacking);
7327 
7328   verifyFormat(
7329       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7330       "             aaaaaaaaaaaa,\n"
7331       "             aaaaaaaaaaaa);",
7332       NoBinPacking);
7333   verifyFormat(
7334       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7335       "                               ddddddddddddddddddddddddddddd),\n"
7336       "             test);",
7337       NoBinPacking);
7338 
7339   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7340                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7341                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7342                "    aaaaaaaaaaaaaaaaaa;",
7343                NoBinPacking);
7344   verifyFormat("a(\"a\"\n"
7345                "  \"a\",\n"
7346                "  a);");
7347 
7348   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7349   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7350                "                aaaaaaaaa,\n"
7351                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7352                NoBinPacking);
7353   verifyFormat(
7354       "void f() {\n"
7355       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7356       "      .aaaaaaa();\n"
7357       "}",
7358       NoBinPacking);
7359   verifyFormat(
7360       "template <class SomeType, class SomeOtherType>\n"
7361       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7362       NoBinPacking);
7363 }
7364 
7365 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7366   FormatStyle Style = getLLVMStyleWithColumns(15);
7367   Style.ExperimentalAutoDetectBinPacking = true;
7368   EXPECT_EQ("aaa(aaaa,\n"
7369             "    aaaa,\n"
7370             "    aaaa);\n"
7371             "aaa(aaaa,\n"
7372             "    aaaa,\n"
7373             "    aaaa);",
7374             format("aaa(aaaa,\n" // one-per-line
7375                    "  aaaa,\n"
7376                    "    aaaa  );\n"
7377                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7378                    Style));
7379   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7380             "    aaaa);\n"
7381             "aaa(aaaa, aaaa,\n"
7382             "    aaaa);",
7383             format("aaa(aaaa,  aaaa,\n" // bin-packed
7384                    "    aaaa  );\n"
7385                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7386                    Style));
7387 }
7388 
7389 TEST_F(FormatTest, FormatsBuilderPattern) {
7390   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7391                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7392                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7393                "    .StartsWith(\".init\", ORDER_INIT)\n"
7394                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7395                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7396                "    .Default(ORDER_TEXT);\n");
7397 
7398   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7399                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7400   verifyFormat("aaaaaaa->aaaaaaa\n"
7401                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7402                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7403                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7404   verifyFormat(
7405       "aaaaaaa->aaaaaaa\n"
7406       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7407       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7408   verifyFormat(
7409       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7410       "    aaaaaaaaaaaaaa);");
7411   verifyFormat(
7412       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7413       "    aaaaaa->aaaaaaaaaaaa()\n"
7414       "        ->aaaaaaaaaaaaaaaa(\n"
7415       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7416       "        ->aaaaaaaaaaaaaaaaa();");
7417   verifyGoogleFormat(
7418       "void f() {\n"
7419       "  someo->Add((new util::filetools::Handler(dir))\n"
7420       "                 ->OnEvent1(NewPermanentCallback(\n"
7421       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7422       "                 ->OnEvent2(NewPermanentCallback(\n"
7423       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7424       "                 ->OnEvent3(NewPermanentCallback(\n"
7425       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7426       "                 ->OnEvent5(NewPermanentCallback(\n"
7427       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7428       "                 ->OnEvent6(NewPermanentCallback(\n"
7429       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7430       "}");
7431 
7432   verifyFormat(
7433       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7434   verifyFormat("aaaaaaaaaaaaaaa()\n"
7435                "    .aaaaaaaaaaaaaaa()\n"
7436                "    .aaaaaaaaaaaaaaa()\n"
7437                "    .aaaaaaaaaaaaaaa()\n"
7438                "    .aaaaaaaaaaaaaaa();");
7439   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7440                "    .aaaaaaaaaaaaaaa()\n"
7441                "    .aaaaaaaaaaaaaaa()\n"
7442                "    .aaaaaaaaaaaaaaa();");
7443   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7444                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7445                "    .aaaaaaaaaaaaaaa();");
7446   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7447                "    ->aaaaaaaaaaaaaae(0)\n"
7448                "    ->aaaaaaaaaaaaaaa();");
7449 
7450   // Don't linewrap after very short segments.
7451   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7452                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7453                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7454   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7455                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7456                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7457   verifyFormat("aaa()\n"
7458                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7459                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7460                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7461 
7462   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7463                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7464                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7465   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7466                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7467                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7468 
7469   // Prefer not to break after empty parentheses.
7470   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7471                "    First->LastNewlineOffset);");
7472 
7473   // Prefer not to create "hanging" indents.
7474   verifyFormat(
7475       "return !soooooooooooooome_map\n"
7476       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7477       "            .second;");
7478   verifyFormat(
7479       "return aaaaaaaaaaaaaaaa\n"
7480       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7481       "    .aaaa(aaaaaaaaaaaaaa);");
7482   // No hanging indent here.
7483   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7484                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7485   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7486                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7487   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7488                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7489                getLLVMStyleWithColumns(60));
7490   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7491                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7492                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7493                getLLVMStyleWithColumns(59));
7494   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7495                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7496                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7497 
7498   // Dont break if only closing statements before member call
7499   verifyFormat("test() {\n"
7500                "  ([]() -> {\n"
7501                "    int b = 32;\n"
7502                "    return 3;\n"
7503                "  }).foo();\n"
7504                "}");
7505   verifyFormat("test() {\n"
7506                "  (\n"
7507                "      []() -> {\n"
7508                "        int b = 32;\n"
7509                "        return 3;\n"
7510                "      },\n"
7511                "      foo, bar)\n"
7512                "      .foo();\n"
7513                "}");
7514   verifyFormat("test() {\n"
7515                "  ([]() -> {\n"
7516                "    int b = 32;\n"
7517                "    return 3;\n"
7518                "  })\n"
7519                "      .foo()\n"
7520                "      .bar();\n"
7521                "}");
7522   verifyFormat("test() {\n"
7523                "  ([]() -> {\n"
7524                "    int b = 32;\n"
7525                "    return 3;\n"
7526                "  })\n"
7527                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7528                "           \"bbbb\");\n"
7529                "}",
7530                getLLVMStyleWithColumns(30));
7531 }
7532 
7533 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7534   verifyFormat(
7535       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7536       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7537   verifyFormat(
7538       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7539       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7540 
7541   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7542                "    ccccccccccccccccccccccccc) {\n}");
7543   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7544                "    ccccccccccccccccccccccccc) {\n}");
7545 
7546   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7547                "    ccccccccccccccccccccccccc) {\n}");
7548   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7549                "    ccccccccccccccccccccccccc) {\n}");
7550 
7551   verifyFormat(
7552       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7553       "    ccccccccccccccccccccccccc) {\n}");
7554   verifyFormat(
7555       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7556       "    ccccccccccccccccccccccccc) {\n}");
7557 
7558   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7559                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7560                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7561                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7562   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7563                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7564                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7565                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7566 
7567   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7568                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7569                "    aaaaaaaaaaaaaaa != aa) {\n}");
7570   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7571                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7572                "    aaaaaaaaaaaaaaa != aa) {\n}");
7573 }
7574 
7575 TEST_F(FormatTest, BreaksAfterAssignments) {
7576   verifyFormat(
7577       "unsigned Cost =\n"
7578       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7579       "                        SI->getPointerAddressSpaceee());\n");
7580   verifyFormat(
7581       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7582       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7583 
7584   verifyFormat(
7585       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7586       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7587   verifyFormat("unsigned OriginalStartColumn =\n"
7588                "    SourceMgr.getSpellingColumnNumber(\n"
7589                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7590                "    1;");
7591 }
7592 
7593 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7594   FormatStyle Style = getLLVMStyle();
7595   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7596                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7597                Style);
7598 
7599   Style.PenaltyBreakAssignment = 20;
7600   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7601                "                                 cccccccccccccccccccccccccc;",
7602                Style);
7603 }
7604 
7605 TEST_F(FormatTest, AlignsAfterAssignments) {
7606   verifyFormat(
7607       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7608       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7609   verifyFormat(
7610       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7611       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7612   verifyFormat(
7613       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7614       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7615   verifyFormat(
7616       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7617       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7618   verifyFormat(
7619       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7620       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7621       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7622 }
7623 
7624 TEST_F(FormatTest, AlignsAfterReturn) {
7625   verifyFormat(
7626       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7627       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7628   verifyFormat(
7629       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7630       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7631   verifyFormat(
7632       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7633       "       aaaaaaaaaaaaaaaaaaaaaa();");
7634   verifyFormat(
7635       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7636       "        aaaaaaaaaaaaaaaaaaaaaa());");
7637   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7638                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7639   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7640                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7641                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7642   verifyFormat("return\n"
7643                "    // true if code is one of a or b.\n"
7644                "    code == a || code == b;");
7645 }
7646 
7647 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7648   verifyFormat(
7649       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7650       "                                                aaaaaaaaa aaaaaaa) {}");
7651   verifyFormat(
7652       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7653       "                                               aaaaaaaaaaa aaaaaaaaa);");
7654   verifyFormat(
7655       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7656       "                                             aaaaaaaaaaaaaaaaaaaaa));");
7657   FormatStyle Style = getLLVMStyle();
7658   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7659   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7660                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
7661                Style);
7662   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7663                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
7664                Style);
7665   verifyFormat("SomeLongVariableName->someFunction(\n"
7666                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
7667                Style);
7668   verifyFormat(
7669       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7670       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7671       Style);
7672   verifyFormat(
7673       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7674       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7675       Style);
7676   verifyFormat(
7677       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7678       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7679       Style);
7680 
7681   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
7682                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
7683                "        b));",
7684                Style);
7685 
7686   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7687   Style.BinPackArguments = false;
7688   Style.BinPackParameters = false;
7689   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7690                "    aaaaaaaaaaa aaaaaaaa,\n"
7691                "    aaaaaaaaa aaaaaaa,\n"
7692                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7693                Style);
7694   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7695                "    aaaaaaaaaaa aaaaaaaaa,\n"
7696                "    aaaaaaaaaaa aaaaaaaaa,\n"
7697                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7698                Style);
7699   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
7700                "    aaaaaaaaaaaaaaa,\n"
7701                "    aaaaaaaaaaaaaaaaaaaaa,\n"
7702                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7703                Style);
7704   verifyFormat(
7705       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
7706       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7707       Style);
7708   verifyFormat(
7709       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
7710       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7711       Style);
7712   verifyFormat(
7713       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7714       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7715       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
7716       "    aaaaaaaaaaaaaaaa);",
7717       Style);
7718   verifyFormat(
7719       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7720       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7721       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
7722       "    aaaaaaaaaaaaaaaa);",
7723       Style);
7724 }
7725 
7726 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
7727   FormatStyle Style = getLLVMStyleWithColumns(40);
7728   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7729                "          bbbbbbbbbbbbbbbbbbbbbb);",
7730                Style);
7731   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7732   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7733   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7734                "          bbbbbbbbbbbbbbbbbbbbbb);",
7735                Style);
7736   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7737   Style.AlignOperands = FormatStyle::OAS_Align;
7738   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7739                "          bbbbbbbbbbbbbbbbbbbbbb);",
7740                Style);
7741   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7742   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7743   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7744                "    bbbbbbbbbbbbbbbbbbbbbb);",
7745                Style);
7746 }
7747 
7748 TEST_F(FormatTest, BreaksConditionalExpressions) {
7749   verifyFormat(
7750       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7751       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7752       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7753   verifyFormat(
7754       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7755       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7756       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7757   verifyFormat(
7758       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7759       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7760   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
7761                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7762                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7763   verifyFormat(
7764       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
7765       "                                                    : aaaaaaaaaaaaa);");
7766   verifyFormat(
7767       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7768       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7769       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7770       "                   aaaaaaaaaaaaa);");
7771   verifyFormat(
7772       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7773       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7774       "                   aaaaaaaaaaaaa);");
7775   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7776                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7777                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7778                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7779                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7780   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7781                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7782                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7783                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7784                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7785                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7786                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7787   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7788                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7789                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7790                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7791                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7792   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7793                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7794                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7795   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7796                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7797                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7798                "        : aaaaaaaaaaaaaaaa;");
7799   verifyFormat(
7800       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7801       "    ? aaaaaaaaaaaaaaa\n"
7802       "    : aaaaaaaaaaaaaaa;");
7803   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7804                "          aaaaaaaaa\n"
7805                "      ? b\n"
7806                "      : c);");
7807   verifyFormat("return aaaa == bbbb\n"
7808                "           // comment\n"
7809                "           ? aaaa\n"
7810                "           : bbbb;");
7811   verifyFormat("unsigned Indent =\n"
7812                "    format(TheLine.First,\n"
7813                "           IndentForLevel[TheLine.Level] >= 0\n"
7814                "               ? IndentForLevel[TheLine.Level]\n"
7815                "               : TheLine * 2,\n"
7816                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
7817                getLLVMStyleWithColumns(60));
7818   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7819                "                  ? aaaaaaaaaaaaaaa\n"
7820                "                  : bbbbbbbbbbbbbbb //\n"
7821                "                        ? ccccccccccccccc\n"
7822                "                        : ddddddddddddddd;");
7823   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7824                "                  ? aaaaaaaaaaaaaaa\n"
7825                "                  : (bbbbbbbbbbbbbbb //\n"
7826                "                         ? ccccccccccccccc\n"
7827                "                         : ddddddddddddddd);");
7828   verifyFormat(
7829       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7830       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7831       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
7832       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
7833       "                                      : aaaaaaaaaa;");
7834   verifyFormat(
7835       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7836       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
7837       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7838 
7839   FormatStyle NoBinPacking = getLLVMStyle();
7840   NoBinPacking.BinPackArguments = false;
7841   verifyFormat(
7842       "void f() {\n"
7843       "  g(aaa,\n"
7844       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7845       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7846       "        ? aaaaaaaaaaaaaaa\n"
7847       "        : aaaaaaaaaaaaaaa);\n"
7848       "}",
7849       NoBinPacking);
7850   verifyFormat(
7851       "void f() {\n"
7852       "  g(aaa,\n"
7853       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7854       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7855       "        ?: aaaaaaaaaaaaaaa);\n"
7856       "}",
7857       NoBinPacking);
7858 
7859   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
7860                "             // comment.\n"
7861                "             ccccccccccccccccccccccccccccccccccccccc\n"
7862                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7863                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
7864 
7865   // Assignments in conditional expressions. Apparently not uncommon :-(.
7866   verifyFormat("return a != b\n"
7867                "           // comment\n"
7868                "           ? a = b\n"
7869                "           : a = b;");
7870   verifyFormat("return a != b\n"
7871                "           // comment\n"
7872                "           ? a = a != b\n"
7873                "                     // comment\n"
7874                "                     ? a = b\n"
7875                "                     : a\n"
7876                "           : a;\n");
7877   verifyFormat("return a != b\n"
7878                "           // comment\n"
7879                "           ? a\n"
7880                "           : a = a != b\n"
7881                "                     // comment\n"
7882                "                     ? a = b\n"
7883                "                     : a;");
7884 
7885   // Chained conditionals
7886   FormatStyle Style = getLLVMStyleWithColumns(70);
7887   Style.AlignOperands = FormatStyle::OAS_Align;
7888   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7889                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7890                "                        : 3333333333333333;",
7891                Style);
7892   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7893                "       : bbbbbbbbbb     ? 2222222222222222\n"
7894                "                        : 3333333333333333;",
7895                Style);
7896   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
7897                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
7898                "                          : 3333333333333333;",
7899                Style);
7900   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7901                "       : bbbbbbbbbbbbbb ? 222222\n"
7902                "                        : 333333;",
7903                Style);
7904   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7905                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7906                "       : cccccccccccccc ? 3333333333333333\n"
7907                "                        : 4444444444444444;",
7908                Style);
7909   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
7910                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7911                "                        : 3333333333333333;",
7912                Style);
7913   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7914                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7915                "                        : (aaa ? bbb : ccc);",
7916                Style);
7917   verifyFormat(
7918       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7919       "                                             : cccccccccccccccccc)\n"
7920       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7921       "                        : 3333333333333333;",
7922       Style);
7923   verifyFormat(
7924       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7925       "                                             : cccccccccccccccccc)\n"
7926       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7927       "                        : 3333333333333333;",
7928       Style);
7929   verifyFormat(
7930       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7931       "                                             : dddddddddddddddddd)\n"
7932       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7933       "                        : 3333333333333333;",
7934       Style);
7935   verifyFormat(
7936       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7937       "                                             : dddddddddddddddddd)\n"
7938       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7939       "                        : 3333333333333333;",
7940       Style);
7941   verifyFormat(
7942       "return aaaaaaaaa        ? 1111111111111111\n"
7943       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7944       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7945       "                                             : dddddddddddddddddd)\n",
7946       Style);
7947   verifyFormat(
7948       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7949       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7950       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7951       "                                             : cccccccccccccccccc);",
7952       Style);
7953   verifyFormat(
7954       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7955       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7956       "                                             : eeeeeeeeeeeeeeeeee)\n"
7957       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7958       "                        : 3333333333333333;",
7959       Style);
7960   verifyFormat(
7961       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
7962       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7963       "                                             : eeeeeeeeeeeeeeeeee)\n"
7964       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7965       "                        : 3333333333333333;",
7966       Style);
7967   verifyFormat(
7968       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7969       "                           : cccccccccccc    ? dddddddddddddddddd\n"
7970       "                                             : eeeeeeeeeeeeeeeeee)\n"
7971       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7972       "                        : 3333333333333333;",
7973       Style);
7974   verifyFormat(
7975       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7976       "                                             : cccccccccccccccccc\n"
7977       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7978       "                        : 3333333333333333;",
7979       Style);
7980   verifyFormat(
7981       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7982       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
7983       "                                             : eeeeeeeeeeeeeeeeee\n"
7984       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7985       "                        : 3333333333333333;",
7986       Style);
7987   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
7988                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
7989                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
7990                "                                   : eeeeeeeeeeeeeeeeee)\n"
7991                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7992                "                             : 3333333333333333;",
7993                Style);
7994   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
7995                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7996                "             : cccccccccccccccc ? dddddddddddddddddd\n"
7997                "                                : eeeeeeeeeeeeeeeeee\n"
7998                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7999                "                                 : 3333333333333333;",
8000                Style);
8001 
8002   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8003   Style.BreakBeforeTernaryOperators = false;
8004   // FIXME: Aligning the question marks is weird given DontAlign.
8005   // Consider disabling this alignment in this case. Also check whether this
8006   // will render the adjustment from https://reviews.llvm.org/D82199
8007   // unnecessary.
8008   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
8009                "    bbbb                ? cccccccccccccccccc :\n"
8010                "                          ddddd;\n",
8011                Style);
8012 
8013   EXPECT_EQ(
8014       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8015       "    /*\n"
8016       "     */\n"
8017       "    function() {\n"
8018       "      try {\n"
8019       "        return JJJJJJJJJJJJJJ(\n"
8020       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8021       "      }\n"
8022       "    } :\n"
8023       "    function() {};",
8024       format(
8025           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8026           "     /*\n"
8027           "      */\n"
8028           "     function() {\n"
8029           "      try {\n"
8030           "        return JJJJJJJJJJJJJJ(\n"
8031           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8032           "      }\n"
8033           "    } :\n"
8034           "    function() {};",
8035           getGoogleStyle(FormatStyle::LK_JavaScript)));
8036 }
8037 
8038 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
8039   FormatStyle Style = getLLVMStyleWithColumns(70);
8040   Style.BreakBeforeTernaryOperators = false;
8041   verifyFormat(
8042       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8043       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8044       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8045       Style);
8046   verifyFormat(
8047       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8048       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8049       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8050       Style);
8051   verifyFormat(
8052       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8053       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8054       Style);
8055   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
8056                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8057                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8058                Style);
8059   verifyFormat(
8060       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
8061       "                                                      aaaaaaaaaaaaa);",
8062       Style);
8063   verifyFormat(
8064       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8065       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8066       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8067       "                   aaaaaaaaaaaaa);",
8068       Style);
8069   verifyFormat(
8070       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8071       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8072       "                   aaaaaaaaaaaaa);",
8073       Style);
8074   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8075                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8076                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8077                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8078                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8079                Style);
8080   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8081                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8082                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8083                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8084                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8085                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8086                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8087                Style);
8088   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8089                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
8090                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8091                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8092                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8093                Style);
8094   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8095                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8096                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8097                Style);
8098   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8099                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8100                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8101                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8102                Style);
8103   verifyFormat(
8104       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8105       "    aaaaaaaaaaaaaaa :\n"
8106       "    aaaaaaaaaaaaaaa;",
8107       Style);
8108   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8109                "          aaaaaaaaa ?\n"
8110                "      b :\n"
8111                "      c);",
8112                Style);
8113   verifyFormat("unsigned Indent =\n"
8114                "    format(TheLine.First,\n"
8115                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
8116                "               IndentForLevel[TheLine.Level] :\n"
8117                "               TheLine * 2,\n"
8118                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8119                Style);
8120   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8121                "                  aaaaaaaaaaaaaaa :\n"
8122                "                  bbbbbbbbbbbbbbb ? //\n"
8123                "                      ccccccccccccccc :\n"
8124                "                      ddddddddddddddd;",
8125                Style);
8126   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8127                "                  aaaaaaaaaaaaaaa :\n"
8128                "                  (bbbbbbbbbbbbbbb ? //\n"
8129                "                       ccccccccccccccc :\n"
8130                "                       ddddddddddddddd);",
8131                Style);
8132   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8133                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
8134                "            ccccccccccccccccccccccccccc;",
8135                Style);
8136   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8137                "           aaaaa :\n"
8138                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
8139                Style);
8140 
8141   // Chained conditionals
8142   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8143                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8144                "                          3333333333333333;",
8145                Style);
8146   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8147                "       bbbbbbbbbb       ? 2222222222222222 :\n"
8148                "                          3333333333333333;",
8149                Style);
8150   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
8151                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8152                "                          3333333333333333;",
8153                Style);
8154   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8155                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
8156                "                          333333;",
8157                Style);
8158   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8159                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8160                "       cccccccccccccccc ? 3333333333333333 :\n"
8161                "                          4444444444444444;",
8162                Style);
8163   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
8164                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8165                "                          3333333333333333;",
8166                Style);
8167   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8168                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8169                "                          (aaa ? bbb : ccc);",
8170                Style);
8171   verifyFormat(
8172       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8173       "                                               cccccccccccccccccc) :\n"
8174       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8175       "                          3333333333333333;",
8176       Style);
8177   verifyFormat(
8178       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8179       "                                               cccccccccccccccccc) :\n"
8180       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8181       "                          3333333333333333;",
8182       Style);
8183   verifyFormat(
8184       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8185       "                                               dddddddddddddddddd) :\n"
8186       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8187       "                          3333333333333333;",
8188       Style);
8189   verifyFormat(
8190       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8191       "                                               dddddddddddddddddd) :\n"
8192       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8193       "                          3333333333333333;",
8194       Style);
8195   verifyFormat(
8196       "return aaaaaaaaa        ? 1111111111111111 :\n"
8197       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8198       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8199       "                                               dddddddddddddddddd)\n",
8200       Style);
8201   verifyFormat(
8202       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8203       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8204       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8205       "                                               cccccccccccccccccc);",
8206       Style);
8207   verifyFormat(
8208       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8209       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8210       "                                               eeeeeeeeeeeeeeeeee) :\n"
8211       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8212       "                          3333333333333333;",
8213       Style);
8214   verifyFormat(
8215       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8216       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8217       "                                               eeeeeeeeeeeeeeeeee) :\n"
8218       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8219       "                          3333333333333333;",
8220       Style);
8221   verifyFormat(
8222       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8223       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8224       "                                               eeeeeeeeeeeeeeeeee) :\n"
8225       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8226       "                          3333333333333333;",
8227       Style);
8228   verifyFormat(
8229       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8230       "                                               cccccccccccccccccc :\n"
8231       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8232       "                          3333333333333333;",
8233       Style);
8234   verifyFormat(
8235       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8236       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8237       "                                               eeeeeeeeeeeeeeeeee :\n"
8238       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8239       "                          3333333333333333;",
8240       Style);
8241   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8242                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8243                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8244                "                                 eeeeeeeeeeeeeeeeee) :\n"
8245                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8246                "                               3333333333333333;",
8247                Style);
8248   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8249                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8250                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8251                "                                  eeeeeeeeeeeeeeeeee :\n"
8252                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8253                "                               3333333333333333;",
8254                Style);
8255 }
8256 
8257 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8258   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8259                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8260   verifyFormat("bool a = true, b = false;");
8261 
8262   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8263                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8264                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8265                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8266   verifyFormat(
8267       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8268       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8269       "     d = e && f;");
8270   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8271                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8272   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8273                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8274   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8275                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8276 
8277   FormatStyle Style = getGoogleStyle();
8278   Style.PointerAlignment = FormatStyle::PAS_Left;
8279   Style.DerivePointerAlignment = false;
8280   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8281                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8282                "    *b = bbbbbbbbbbbbbbbbbbb;",
8283                Style);
8284   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8285                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8286                Style);
8287   verifyFormat("vector<int*> a, b;", Style);
8288   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8289 }
8290 
8291 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8292   verifyFormat("arr[foo ? bar : baz];");
8293   verifyFormat("f()[foo ? bar : baz];");
8294   verifyFormat("(a + b)[foo ? bar : baz];");
8295   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8296 }
8297 
8298 TEST_F(FormatTest, AlignsStringLiterals) {
8299   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8300                "                                      \"short literal\");");
8301   verifyFormat(
8302       "looooooooooooooooooooooooongFunction(\n"
8303       "    \"short literal\"\n"
8304       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8305   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8306                "             \" string literals\",\n"
8307                "             and, other, parameters);");
8308   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8309             "      \"5678\";",
8310             format("fun + \"1243\" /* comment */\n"
8311                    "    \"5678\";",
8312                    getLLVMStyleWithColumns(28)));
8313   EXPECT_EQ(
8314       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8315       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8316       "         \"aaaaaaaaaaaaaaaa\";",
8317       format("aaaaaa ="
8318              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8319              "aaaaaaaaaaaaaaaaaaaaa\" "
8320              "\"aaaaaaaaaaaaaaaa\";"));
8321   verifyFormat("a = a + \"a\"\n"
8322                "        \"a\"\n"
8323                "        \"a\";");
8324   verifyFormat("f(\"a\", \"b\"\n"
8325                "       \"c\");");
8326 
8327   verifyFormat(
8328       "#define LL_FORMAT \"ll\"\n"
8329       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8330       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8331 
8332   verifyFormat("#define A(X)          \\\n"
8333                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8334                "  \"ccccc\"",
8335                getLLVMStyleWithColumns(23));
8336   verifyFormat("#define A \"def\"\n"
8337                "f(\"abc\" A \"ghi\"\n"
8338                "  \"jkl\");");
8339 
8340   verifyFormat("f(L\"a\"\n"
8341                "  L\"b\");");
8342   verifyFormat("#define A(X)            \\\n"
8343                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8344                "  L\"ccccc\"",
8345                getLLVMStyleWithColumns(25));
8346 
8347   verifyFormat("f(@\"a\"\n"
8348                "  @\"b\");");
8349   verifyFormat("NSString s = @\"a\"\n"
8350                "             @\"b\"\n"
8351                "             @\"c\";");
8352   verifyFormat("NSString s = @\"a\"\n"
8353                "              \"b\"\n"
8354                "              \"c\";");
8355 }
8356 
8357 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8358   FormatStyle Style = getLLVMStyle();
8359   // No declarations or definitions should be moved to own line.
8360   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8361   verifyFormat("class A {\n"
8362                "  int f() { return 1; }\n"
8363                "  int g();\n"
8364                "};\n"
8365                "int f() { return 1; }\n"
8366                "int g();\n",
8367                Style);
8368 
8369   // All declarations and definitions should have the return type moved to its
8370   // own line.
8371   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8372   Style.TypenameMacros = {"LIST"};
8373   verifyFormat("SomeType\n"
8374                "funcdecl(LIST(uint64_t));",
8375                Style);
8376   verifyFormat("class E {\n"
8377                "  int\n"
8378                "  f() {\n"
8379                "    return 1;\n"
8380                "  }\n"
8381                "  int\n"
8382                "  g();\n"
8383                "};\n"
8384                "int\n"
8385                "f() {\n"
8386                "  return 1;\n"
8387                "}\n"
8388                "int\n"
8389                "g();\n",
8390                Style);
8391 
8392   // Top-level definitions, and no kinds of declarations should have the
8393   // return type moved to its own line.
8394   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8395   verifyFormat("class B {\n"
8396                "  int f() { return 1; }\n"
8397                "  int g();\n"
8398                "};\n"
8399                "int\n"
8400                "f() {\n"
8401                "  return 1;\n"
8402                "}\n"
8403                "int g();\n",
8404                Style);
8405 
8406   // Top-level definitions and declarations should have the return type moved
8407   // to its own line.
8408   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8409   verifyFormat("class C {\n"
8410                "  int f() { return 1; }\n"
8411                "  int g();\n"
8412                "};\n"
8413                "int\n"
8414                "f() {\n"
8415                "  return 1;\n"
8416                "}\n"
8417                "int\n"
8418                "g();\n",
8419                Style);
8420 
8421   // All definitions should have the return type moved to its own line, but no
8422   // kinds of declarations.
8423   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8424   verifyFormat("class D {\n"
8425                "  int\n"
8426                "  f() {\n"
8427                "    return 1;\n"
8428                "  }\n"
8429                "  int g();\n"
8430                "};\n"
8431                "int\n"
8432                "f() {\n"
8433                "  return 1;\n"
8434                "}\n"
8435                "int g();\n",
8436                Style);
8437   verifyFormat("const char *\n"
8438                "f(void) {\n" // Break here.
8439                "  return \"\";\n"
8440                "}\n"
8441                "const char *bar(void);\n", // No break here.
8442                Style);
8443   verifyFormat("template <class T>\n"
8444                "T *\n"
8445                "f(T &c) {\n" // Break here.
8446                "  return NULL;\n"
8447                "}\n"
8448                "template <class T> T *f(T &c);\n", // No break here.
8449                Style);
8450   verifyFormat("class C {\n"
8451                "  int\n"
8452                "  operator+() {\n"
8453                "    return 1;\n"
8454                "  }\n"
8455                "  int\n"
8456                "  operator()() {\n"
8457                "    return 1;\n"
8458                "  }\n"
8459                "};\n",
8460                Style);
8461   verifyFormat("void\n"
8462                "A::operator()() {}\n"
8463                "void\n"
8464                "A::operator>>() {}\n"
8465                "void\n"
8466                "A::operator+() {}\n"
8467                "void\n"
8468                "A::operator*() {}\n"
8469                "void\n"
8470                "A::operator->() {}\n"
8471                "void\n"
8472                "A::operator void *() {}\n"
8473                "void\n"
8474                "A::operator void &() {}\n"
8475                "void\n"
8476                "A::operator void &&() {}\n"
8477                "void\n"
8478                "A::operator char *() {}\n"
8479                "void\n"
8480                "A::operator[]() {}\n"
8481                "void\n"
8482                "A::operator!() {}\n"
8483                "void\n"
8484                "A::operator**() {}\n"
8485                "void\n"
8486                "A::operator<Foo> *() {}\n"
8487                "void\n"
8488                "A::operator<Foo> **() {}\n"
8489                "void\n"
8490                "A::operator<Foo> &() {}\n"
8491                "void\n"
8492                "A::operator void **() {}\n",
8493                Style);
8494   verifyFormat("constexpr auto\n"
8495                "operator()() const -> reference {}\n"
8496                "constexpr auto\n"
8497                "operator>>() const -> reference {}\n"
8498                "constexpr auto\n"
8499                "operator+() const -> reference {}\n"
8500                "constexpr auto\n"
8501                "operator*() const -> reference {}\n"
8502                "constexpr auto\n"
8503                "operator->() const -> reference {}\n"
8504                "constexpr auto\n"
8505                "operator++() const -> reference {}\n"
8506                "constexpr auto\n"
8507                "operator void *() const -> reference {}\n"
8508                "constexpr auto\n"
8509                "operator void **() const -> reference {}\n"
8510                "constexpr auto\n"
8511                "operator void *() const -> reference {}\n"
8512                "constexpr auto\n"
8513                "operator void &() const -> reference {}\n"
8514                "constexpr auto\n"
8515                "operator void &&() const -> reference {}\n"
8516                "constexpr auto\n"
8517                "operator char *() const -> reference {}\n"
8518                "constexpr auto\n"
8519                "operator!() const -> reference {}\n"
8520                "constexpr auto\n"
8521                "operator[]() const -> reference {}\n",
8522                Style);
8523   verifyFormat("void *operator new(std::size_t s);", // No break here.
8524                Style);
8525   verifyFormat("void *\n"
8526                "operator new(std::size_t s) {}",
8527                Style);
8528   verifyFormat("void *\n"
8529                "operator delete[](void *ptr) {}",
8530                Style);
8531   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8532   verifyFormat("const char *\n"
8533                "f(void)\n" // Break here.
8534                "{\n"
8535                "  return \"\";\n"
8536                "}\n"
8537                "const char *bar(void);\n", // No break here.
8538                Style);
8539   verifyFormat("template <class T>\n"
8540                "T *\n"     // Problem here: no line break
8541                "f(T &c)\n" // Break here.
8542                "{\n"
8543                "  return NULL;\n"
8544                "}\n"
8545                "template <class T> T *f(T &c);\n", // No break here.
8546                Style);
8547   verifyFormat("int\n"
8548                "foo(A<bool> a)\n"
8549                "{\n"
8550                "  return a;\n"
8551                "}\n",
8552                Style);
8553   verifyFormat("int\n"
8554                "foo(A<8> a)\n"
8555                "{\n"
8556                "  return a;\n"
8557                "}\n",
8558                Style);
8559   verifyFormat("int\n"
8560                "foo(A<B<bool>, 8> a)\n"
8561                "{\n"
8562                "  return a;\n"
8563                "}\n",
8564                Style);
8565   verifyFormat("int\n"
8566                "foo(A<B<8>, bool> a)\n"
8567                "{\n"
8568                "  return a;\n"
8569                "}\n",
8570                Style);
8571   verifyFormat("int\n"
8572                "foo(A<B<bool>, bool> a)\n"
8573                "{\n"
8574                "  return a;\n"
8575                "}\n",
8576                Style);
8577   verifyFormat("int\n"
8578                "foo(A<B<8>, 8> a)\n"
8579                "{\n"
8580                "  return a;\n"
8581                "}\n",
8582                Style);
8583 
8584   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8585   Style.BraceWrapping.AfterFunction = true;
8586   verifyFormat("int f(i);\n" // No break here.
8587                "int\n"       // Break here.
8588                "f(i)\n"
8589                "{\n"
8590                "  return i + 1;\n"
8591                "}\n"
8592                "int\n" // Break here.
8593                "f(i)\n"
8594                "{\n"
8595                "  return i + 1;\n"
8596                "};",
8597                Style);
8598   verifyFormat("int f(a, b, c);\n" // No break here.
8599                "int\n"             // Break here.
8600                "f(a, b, c)\n"      // Break here.
8601                "short a, b;\n"
8602                "float c;\n"
8603                "{\n"
8604                "  return a + b < c;\n"
8605                "}\n"
8606                "int\n"        // Break here.
8607                "f(a, b, c)\n" // Break here.
8608                "short a, b;\n"
8609                "float c;\n"
8610                "{\n"
8611                "  return a + b < c;\n"
8612                "};",
8613                Style);
8614   verifyFormat("byte *\n" // Break here.
8615                "f(a)\n"   // Break here.
8616                "byte a[];\n"
8617                "{\n"
8618                "  return a;\n"
8619                "}",
8620                Style);
8621   verifyFormat("bool f(int a, int) override;\n"
8622                "Bar g(int a, Bar) final;\n"
8623                "Bar h(a, Bar) final;",
8624                Style);
8625   verifyFormat("int\n"
8626                "f(a)",
8627                Style);
8628   verifyFormat("bool\n"
8629                "f(size_t = 0, bool b = false)\n"
8630                "{\n"
8631                "  return !b;\n"
8632                "}",
8633                Style);
8634 
8635   // The return breaking style doesn't affect:
8636   // * function and object definitions with attribute-like macros
8637   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8638                "    ABSL_GUARDED_BY(mutex) = {};",
8639                getGoogleStyleWithColumns(40));
8640   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8641                "    ABSL_GUARDED_BY(mutex);  // comment",
8642                getGoogleStyleWithColumns(40));
8643   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8644                "    ABSL_GUARDED_BY(mutex1)\n"
8645                "        ABSL_GUARDED_BY(mutex2);",
8646                getGoogleStyleWithColumns(40));
8647   verifyFormat("Tttttt f(int a, int b)\n"
8648                "    ABSL_GUARDED_BY(mutex1)\n"
8649                "        ABSL_GUARDED_BY(mutex2);",
8650                getGoogleStyleWithColumns(40));
8651   // * typedefs
8652   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
8653 
8654   Style = getGNUStyle();
8655 
8656   // Test for comments at the end of function declarations.
8657   verifyFormat("void\n"
8658                "foo (int a, /*abc*/ int b) // def\n"
8659                "{\n"
8660                "}\n",
8661                Style);
8662 
8663   verifyFormat("void\n"
8664                "foo (int a, /* abc */ int b) /* def */\n"
8665                "{\n"
8666                "}\n",
8667                Style);
8668 
8669   // Definitions that should not break after return type
8670   verifyFormat("void foo (int a, int b); // def\n", Style);
8671   verifyFormat("void foo (int a, int b); /* def */\n", Style);
8672   verifyFormat("void foo (int a, int b);\n", Style);
8673 }
8674 
8675 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
8676   FormatStyle NoBreak = getLLVMStyle();
8677   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
8678   FormatStyle Break = getLLVMStyle();
8679   Break.AlwaysBreakBeforeMultilineStrings = true;
8680   verifyFormat("aaaa = \"bbbb\"\n"
8681                "       \"cccc\";",
8682                NoBreak);
8683   verifyFormat("aaaa =\n"
8684                "    \"bbbb\"\n"
8685                "    \"cccc\";",
8686                Break);
8687   verifyFormat("aaaa(\"bbbb\"\n"
8688                "     \"cccc\");",
8689                NoBreak);
8690   verifyFormat("aaaa(\n"
8691                "    \"bbbb\"\n"
8692                "    \"cccc\");",
8693                Break);
8694   verifyFormat("aaaa(qqq, \"bbbb\"\n"
8695                "          \"cccc\");",
8696                NoBreak);
8697   verifyFormat("aaaa(qqq,\n"
8698                "     \"bbbb\"\n"
8699                "     \"cccc\");",
8700                Break);
8701   verifyFormat("aaaa(qqq,\n"
8702                "     L\"bbbb\"\n"
8703                "     L\"cccc\");",
8704                Break);
8705   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
8706                "                      \"bbbb\"));",
8707                Break);
8708   verifyFormat("string s = someFunction(\n"
8709                "    \"abc\"\n"
8710                "    \"abc\");",
8711                Break);
8712 
8713   // As we break before unary operators, breaking right after them is bad.
8714   verifyFormat("string foo = abc ? \"x\"\n"
8715                "                   \"blah blah blah blah blah blah\"\n"
8716                "                 : \"y\";",
8717                Break);
8718 
8719   // Don't break if there is no column gain.
8720   verifyFormat("f(\"aaaa\"\n"
8721                "  \"bbbb\");",
8722                Break);
8723 
8724   // Treat literals with escaped newlines like multi-line string literals.
8725   EXPECT_EQ("x = \"a\\\n"
8726             "b\\\n"
8727             "c\";",
8728             format("x = \"a\\\n"
8729                    "b\\\n"
8730                    "c\";",
8731                    NoBreak));
8732   EXPECT_EQ("xxxx =\n"
8733             "    \"a\\\n"
8734             "b\\\n"
8735             "c\";",
8736             format("xxxx = \"a\\\n"
8737                    "b\\\n"
8738                    "c\";",
8739                    Break));
8740 
8741   EXPECT_EQ("NSString *const kString =\n"
8742             "    @\"aaaa\"\n"
8743             "    @\"bbbb\";",
8744             format("NSString *const kString = @\"aaaa\"\n"
8745                    "@\"bbbb\";",
8746                    Break));
8747 
8748   Break.ColumnLimit = 0;
8749   verifyFormat("const char *hello = \"hello llvm\";", Break);
8750 }
8751 
8752 TEST_F(FormatTest, AlignsPipes) {
8753   verifyFormat(
8754       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8755       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8756       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8757   verifyFormat(
8758       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
8759       "                     << aaaaaaaaaaaaaaaaaaaa;");
8760   verifyFormat(
8761       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8762       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8763   verifyFormat(
8764       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
8765       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8766   verifyFormat(
8767       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
8768       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
8769       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
8770   verifyFormat(
8771       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8772       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8773       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8774   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8775                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8776                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8777                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8778   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
8779                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
8780   verifyFormat(
8781       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8782       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8783   verifyFormat(
8784       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
8785       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
8786 
8787   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
8788                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
8789   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8790                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8791                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
8792                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
8793   verifyFormat("LOG_IF(aaa == //\n"
8794                "       bbb)\n"
8795                "    << a << b;");
8796 
8797   // But sometimes, breaking before the first "<<" is desirable.
8798   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8799                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
8800   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
8801                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8802                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8803   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
8804                "    << BEF << IsTemplate << Description << E->getType();");
8805   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8806                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8807                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8808   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8809                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8810                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8811                "    << aaa;");
8812 
8813   verifyFormat(
8814       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8815       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8816 
8817   // Incomplete string literal.
8818   EXPECT_EQ("llvm::errs() << \"\n"
8819             "             << a;",
8820             format("llvm::errs() << \"\n<<a;"));
8821 
8822   verifyFormat("void f() {\n"
8823                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
8824                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
8825                "}");
8826 
8827   // Handle 'endl'.
8828   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
8829                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8830   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8831 
8832   // Handle '\n'.
8833   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
8834                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8835   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
8836                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
8837   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
8838                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
8839   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8840 }
8841 
8842 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
8843   verifyFormat("return out << \"somepacket = {\\n\"\n"
8844                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
8845                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
8846                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
8847                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
8848                "           << \"}\";");
8849 
8850   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8851                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8852                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
8853   verifyFormat(
8854       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
8855       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
8856       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
8857       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
8858       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
8859   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
8860                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8861   verifyFormat(
8862       "void f() {\n"
8863       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
8864       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
8865       "}");
8866 
8867   // Breaking before the first "<<" is generally not desirable.
8868   verifyFormat(
8869       "llvm::errs()\n"
8870       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8871       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8872       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8873       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8874       getLLVMStyleWithColumns(70));
8875   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8876                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8877                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8878                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8879                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8880                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8881                getLLVMStyleWithColumns(70));
8882 
8883   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8884                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8885                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
8886   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8887                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8888                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
8889   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
8890                "           (aaaa + aaaa);",
8891                getLLVMStyleWithColumns(40));
8892   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
8893                "                  (aaaaaaa + aaaaa));",
8894                getLLVMStyleWithColumns(40));
8895   verifyFormat(
8896       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
8897       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
8898       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
8899 }
8900 
8901 TEST_F(FormatTest, UnderstandsEquals) {
8902   verifyFormat(
8903       "aaaaaaaaaaaaaaaaa =\n"
8904       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8905   verifyFormat(
8906       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8907       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8908   verifyFormat(
8909       "if (a) {\n"
8910       "  f();\n"
8911       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8912       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
8913       "}");
8914 
8915   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8916                "        100000000 + 10000000) {\n}");
8917 }
8918 
8919 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
8920   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8921                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
8922 
8923   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8924                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
8925 
8926   verifyFormat(
8927       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
8928       "                                                          Parameter2);");
8929 
8930   verifyFormat(
8931       "ShortObject->shortFunction(\n"
8932       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
8933       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
8934 
8935   verifyFormat("loooooooooooooongFunction(\n"
8936                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
8937 
8938   verifyFormat(
8939       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
8940       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
8941 
8942   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8943                "    .WillRepeatedly(Return(SomeValue));");
8944   verifyFormat("void f() {\n"
8945                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8946                "      .Times(2)\n"
8947                "      .WillRepeatedly(Return(SomeValue));\n"
8948                "}");
8949   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
8950                "    ccccccccccccccccccccccc);");
8951   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8952                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8953                "          .aaaaa(aaaaa),\n"
8954                "      aaaaaaaaaaaaaaaaaaaaa);");
8955   verifyFormat("void f() {\n"
8956                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8957                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
8958                "}");
8959   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8960                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8961                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8962                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8963                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
8964   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8965                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8966                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8967                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
8968                "}");
8969 
8970   // Here, it is not necessary to wrap at "." or "->".
8971   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
8972                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8973   verifyFormat(
8974       "aaaaaaaaaaa->aaaaaaaaa(\n"
8975       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8976       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
8977 
8978   verifyFormat(
8979       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8980       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
8981   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
8982                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8983   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
8984                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8985 
8986   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8987                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8988                "    .a();");
8989 
8990   FormatStyle NoBinPacking = getLLVMStyle();
8991   NoBinPacking.BinPackParameters = false;
8992   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8993                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8994                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
8995                "                         aaaaaaaaaaaaaaaaaaa,\n"
8996                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8997                NoBinPacking);
8998 
8999   // If there is a subsequent call, change to hanging indentation.
9000   verifyFormat(
9001       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9002       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
9003       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9004   verifyFormat(
9005       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9006       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
9007   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9008                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9009                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9010   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9011                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9012                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9013 }
9014 
9015 TEST_F(FormatTest, WrapsTemplateDeclarations) {
9016   verifyFormat("template <typename T>\n"
9017                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9018   verifyFormat("template <typename T>\n"
9019                "// T should be one of {A, B}.\n"
9020                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9021   verifyFormat(
9022       "template <typename T>\n"
9023       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
9024   verifyFormat("template <typename T>\n"
9025                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
9026                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
9027   verifyFormat(
9028       "template <typename T>\n"
9029       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
9030       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
9031   verifyFormat(
9032       "template <typename T>\n"
9033       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
9034       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
9035       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9036   verifyFormat("template <typename T>\n"
9037                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9038                "    int aaaaaaaaaaaaaaaaaaaaaa);");
9039   verifyFormat(
9040       "template <typename T1, typename T2 = char, typename T3 = char,\n"
9041       "          typename T4 = char>\n"
9042       "void f();");
9043   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
9044                "          template <typename> class cccccccccccccccccccccc,\n"
9045                "          typename ddddddddddddd>\n"
9046                "class C {};");
9047   verifyFormat(
9048       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
9049       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9050 
9051   verifyFormat("void f() {\n"
9052                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
9053                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
9054                "}");
9055 
9056   verifyFormat("template <typename T> class C {};");
9057   verifyFormat("template <typename T> void f();");
9058   verifyFormat("template <typename T> void f() {}");
9059   verifyFormat(
9060       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9061       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9062       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
9063       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9064       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9065       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
9066       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
9067       getLLVMStyleWithColumns(72));
9068   EXPECT_EQ("static_cast<A< //\n"
9069             "    B> *>(\n"
9070             "\n"
9071             ");",
9072             format("static_cast<A<//\n"
9073                    "    B>*>(\n"
9074                    "\n"
9075                    "    );"));
9076   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9077                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
9078 
9079   FormatStyle AlwaysBreak = getLLVMStyle();
9080   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9081   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
9082   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
9083   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
9084   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9085                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9086                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
9087   verifyFormat("template <template <typename> class Fooooooo,\n"
9088                "          template <typename> class Baaaaaaar>\n"
9089                "struct C {};",
9090                AlwaysBreak);
9091   verifyFormat("template <typename T> // T can be A, B or C.\n"
9092                "struct C {};",
9093                AlwaysBreak);
9094   verifyFormat("template <enum E> class A {\n"
9095                "public:\n"
9096                "  E *f();\n"
9097                "};");
9098 
9099   FormatStyle NeverBreak = getLLVMStyle();
9100   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
9101   verifyFormat("template <typename T> class C {};", NeverBreak);
9102   verifyFormat("template <typename T> void f();", NeverBreak);
9103   verifyFormat("template <typename T> void f() {}", NeverBreak);
9104   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9105                "bbbbbbbbbbbbbbbbbbbb) {}",
9106                NeverBreak);
9107   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9108                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9109                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
9110                NeverBreak);
9111   verifyFormat("template <template <typename> class Fooooooo,\n"
9112                "          template <typename> class Baaaaaaar>\n"
9113                "struct C {};",
9114                NeverBreak);
9115   verifyFormat("template <typename T> // T can be A, B or C.\n"
9116                "struct C {};",
9117                NeverBreak);
9118   verifyFormat("template <enum E> class A {\n"
9119                "public:\n"
9120                "  E *f();\n"
9121                "};",
9122                NeverBreak);
9123   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
9124   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9125                "bbbbbbbbbbbbbbbbbbbb) {}",
9126                NeverBreak);
9127 }
9128 
9129 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
9130   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9131   Style.ColumnLimit = 60;
9132   EXPECT_EQ("// Baseline - no comments.\n"
9133             "template <\n"
9134             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9135             "void f() {}",
9136             format("// Baseline - no comments.\n"
9137                    "template <\n"
9138                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9139                    "void f() {}",
9140                    Style));
9141 
9142   EXPECT_EQ("template <\n"
9143             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9144             "void f() {}",
9145             format("template <\n"
9146                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9147                    "void f() {}",
9148                    Style));
9149 
9150   EXPECT_EQ(
9151       "template <\n"
9152       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
9153       "void f() {}",
9154       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
9155              "void f() {}",
9156              Style));
9157 
9158   EXPECT_EQ(
9159       "template <\n"
9160       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9161       "                                               // multiline\n"
9162       "void f() {}",
9163       format("template <\n"
9164              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9165              "                                              // multiline\n"
9166              "void f() {}",
9167              Style));
9168 
9169   EXPECT_EQ(
9170       "template <typename aaaaaaaaaa<\n"
9171       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
9172       "void f() {}",
9173       format(
9174           "template <\n"
9175           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
9176           "void f() {}",
9177           Style));
9178 }
9179 
9180 TEST_F(FormatTest, WrapsTemplateParameters) {
9181   FormatStyle Style = getLLVMStyle();
9182   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9183   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9184   verifyFormat(
9185       "template <typename... a> struct q {};\n"
9186       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9187       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9188       "    y;",
9189       Style);
9190   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9191   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9192   verifyFormat(
9193       "template <typename... a> struct r {};\n"
9194       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9195       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9196       "    y;",
9197       Style);
9198   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9199   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9200   verifyFormat("template <typename... a> struct s {};\n"
9201                "extern s<\n"
9202                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9203                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9204                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9205                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9206                "    y;",
9207                Style);
9208   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9209   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9210   verifyFormat("template <typename... a> struct t {};\n"
9211                "extern t<\n"
9212                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9213                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9214                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9215                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9216                "    y;",
9217                Style);
9218 }
9219 
9220 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9221   verifyFormat(
9222       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9223       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9224   verifyFormat(
9225       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9226       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9227       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9228 
9229   // FIXME: Should we have the extra indent after the second break?
9230   verifyFormat(
9231       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9232       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9233       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9234 
9235   verifyFormat(
9236       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9237       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9238 
9239   // Breaking at nested name specifiers is generally not desirable.
9240   verifyFormat(
9241       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9242       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9243 
9244   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9245                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9246                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9247                "                   aaaaaaaaaaaaaaaaaaaaa);",
9248                getLLVMStyleWithColumns(74));
9249 
9250   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9251                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9252                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9253 }
9254 
9255 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9256   verifyFormat("A<int> a;");
9257   verifyFormat("A<A<A<int>>> a;");
9258   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9259   verifyFormat("bool x = a < 1 || 2 > a;");
9260   verifyFormat("bool x = 5 < f<int>();");
9261   verifyFormat("bool x = f<int>() > 5;");
9262   verifyFormat("bool x = 5 < a<int>::x;");
9263   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9264   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9265 
9266   verifyGoogleFormat("A<A<int>> a;");
9267   verifyGoogleFormat("A<A<A<int>>> a;");
9268   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9269   verifyGoogleFormat("A<A<int> > a;");
9270   verifyGoogleFormat("A<A<A<int> > > a;");
9271   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9272   verifyGoogleFormat("A<::A<int>> a;");
9273   verifyGoogleFormat("A<::A> a;");
9274   verifyGoogleFormat("A< ::A> a;");
9275   verifyGoogleFormat("A< ::A<int> > a;");
9276   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9277   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9278   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9279   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9280   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9281             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9282 
9283   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9284 
9285   // template closer followed by a token that starts with > or =
9286   verifyFormat("bool b = a<1> > 1;");
9287   verifyFormat("bool b = a<1> >= 1;");
9288   verifyFormat("int i = a<1> >> 1;");
9289   FormatStyle Style = getLLVMStyle();
9290   Style.SpaceBeforeAssignmentOperators = false;
9291   verifyFormat("bool b= a<1> == 1;", Style);
9292   verifyFormat("a<int> = 1;", Style);
9293   verifyFormat("a<int> >>= 1;", Style);
9294 
9295   verifyFormat("test < a | b >> c;");
9296   verifyFormat("test<test<a | b>> c;");
9297   verifyFormat("test >> a >> b;");
9298   verifyFormat("test << a >> b;");
9299 
9300   verifyFormat("f<int>();");
9301   verifyFormat("template <typename T> void f() {}");
9302   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9303   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9304                "sizeof(char)>::type>;");
9305   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9306   verifyFormat("f(a.operator()<A>());");
9307   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9308                "      .template operator()<A>());",
9309                getLLVMStyleWithColumns(35));
9310 
9311   // Not template parameters.
9312   verifyFormat("return a < b && c > d;");
9313   verifyFormat("void f() {\n"
9314                "  while (a < b && c > d) {\n"
9315                "  }\n"
9316                "}");
9317   verifyFormat("template <typename... Types>\n"
9318                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9319 
9320   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9321                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9322                getLLVMStyleWithColumns(60));
9323   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9324   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9325   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9326   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9327 }
9328 
9329 TEST_F(FormatTest, UnderstandsShiftOperators) {
9330   verifyFormat("if (i < x >> 1)");
9331   verifyFormat("while (i < x >> 1)");
9332   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9333   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9334   verifyFormat(
9335       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9336   verifyFormat("Foo.call<Bar<Function>>()");
9337   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9338   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9339                "++i, v = v >> 1)");
9340   verifyFormat("if (w<u<v<x>>, 1>::t)");
9341 }
9342 
9343 TEST_F(FormatTest, BitshiftOperatorWidth) {
9344   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9345             "                   bar */",
9346             format("int    a=1<<2;  /* foo\n"
9347                    "                   bar */"));
9348 
9349   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9350             "                     bar */",
9351             format("int  b  =256>>1 ;  /* foo\n"
9352                    "                      bar */"));
9353 }
9354 
9355 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9356   verifyFormat("COMPARE(a, ==, b);");
9357   verifyFormat("auto s = sizeof...(Ts) - 1;");
9358 }
9359 
9360 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9361   verifyFormat("int A::*x;");
9362   verifyFormat("int (S::*func)(void *);");
9363   verifyFormat("void f() { int (S::*func)(void *); }");
9364   verifyFormat("typedef bool *(Class::*Member)() const;");
9365   verifyFormat("void f() {\n"
9366                "  (a->*f)();\n"
9367                "  a->*x;\n"
9368                "  (a.*f)();\n"
9369                "  ((*a).*f)();\n"
9370                "  a.*x;\n"
9371                "}");
9372   verifyFormat("void f() {\n"
9373                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9374                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9375                "}");
9376   verifyFormat(
9377       "(aaaaaaaaaa->*bbbbbbb)(\n"
9378       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9379   FormatStyle Style = getLLVMStyle();
9380   Style.PointerAlignment = FormatStyle::PAS_Left;
9381   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9382 }
9383 
9384 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9385   verifyFormat("int a = -2;");
9386   verifyFormat("f(-1, -2, -3);");
9387   verifyFormat("a[-1] = 5;");
9388   verifyFormat("int a = 5 + -2;");
9389   verifyFormat("if (i == -1) {\n}");
9390   verifyFormat("if (i != -1) {\n}");
9391   verifyFormat("if (i > -1) {\n}");
9392   verifyFormat("if (i < -1) {\n}");
9393   verifyFormat("++(a->f());");
9394   verifyFormat("--(a->f());");
9395   verifyFormat("(a->f())++;");
9396   verifyFormat("a[42]++;");
9397   verifyFormat("if (!(a->f())) {\n}");
9398   verifyFormat("if (!+i) {\n}");
9399   verifyFormat("~&a;");
9400 
9401   verifyFormat("a-- > b;");
9402   verifyFormat("b ? -a : c;");
9403   verifyFormat("n * sizeof char16;");
9404   verifyFormat("n * alignof char16;", getGoogleStyle());
9405   verifyFormat("sizeof(char);");
9406   verifyFormat("alignof(char);", getGoogleStyle());
9407 
9408   verifyFormat("return -1;");
9409   verifyFormat("throw -1;");
9410   verifyFormat("switch (a) {\n"
9411                "case -1:\n"
9412                "  break;\n"
9413                "}");
9414   verifyFormat("#define X -1");
9415   verifyFormat("#define X -kConstant");
9416 
9417   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9418   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9419 
9420   verifyFormat("int a = /* confusing comment */ -1;");
9421   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9422   verifyFormat("int a = i /* confusing comment */++;");
9423 
9424   verifyFormat("co_yield -1;");
9425   verifyFormat("co_return -1;");
9426 
9427   // Check that * is not treated as a binary operator when we set
9428   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9429   FormatStyle PASLeftStyle = getLLVMStyle();
9430   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9431   verifyFormat("co_return *a;", PASLeftStyle);
9432   verifyFormat("co_await *a;", PASLeftStyle);
9433   verifyFormat("co_yield *a", PASLeftStyle);
9434   verifyFormat("return *a;", PASLeftStyle);
9435 }
9436 
9437 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9438   verifyFormat("if (!aaaaaaaaaa( // break\n"
9439                "        aaaaa)) {\n"
9440                "}");
9441   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9442                "    aaaaa));");
9443   verifyFormat("*aaa = aaaaaaa( // break\n"
9444                "    bbbbbb);");
9445 }
9446 
9447 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9448   verifyFormat("bool operator<();");
9449   verifyFormat("bool operator>();");
9450   verifyFormat("bool operator=();");
9451   verifyFormat("bool operator==();");
9452   verifyFormat("bool operator!=();");
9453   verifyFormat("int operator+();");
9454   verifyFormat("int operator++();");
9455   verifyFormat("int operator++(int) volatile noexcept;");
9456   verifyFormat("bool operator,();");
9457   verifyFormat("bool operator();");
9458   verifyFormat("bool operator()();");
9459   verifyFormat("bool operator[]();");
9460   verifyFormat("operator bool();");
9461   verifyFormat("operator int();");
9462   verifyFormat("operator void *();");
9463   verifyFormat("operator SomeType<int>();");
9464   verifyFormat("operator SomeType<int, int>();");
9465   verifyFormat("operator SomeType<SomeType<int>>();");
9466   verifyFormat("void *operator new(std::size_t size);");
9467   verifyFormat("void *operator new[](std::size_t size);");
9468   verifyFormat("void operator delete(void *ptr);");
9469   verifyFormat("void operator delete[](void *ptr);");
9470   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9471                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9472   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9473                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9474 
9475   verifyFormat(
9476       "ostream &operator<<(ostream &OutputStream,\n"
9477       "                    SomeReallyLongType WithSomeReallyLongValue);");
9478   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9479                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9480                "  return left.group < right.group;\n"
9481                "}");
9482   verifyFormat("SomeType &operator=(const SomeType &S);");
9483   verifyFormat("f.template operator()<int>();");
9484 
9485   verifyGoogleFormat("operator void*();");
9486   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9487   verifyGoogleFormat("operator ::A();");
9488 
9489   verifyFormat("using A::operator+;");
9490   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9491                "int i;");
9492 
9493   // Calling an operator as a member function.
9494   verifyFormat("void f() { a.operator*(); }");
9495   verifyFormat("void f() { a.operator*(b & b); }");
9496   verifyFormat("void f() { a->operator&(a * b); }");
9497   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9498   // TODO: Calling an operator as a non-member function is hard to distinguish.
9499   // https://llvm.org/PR50629
9500   // verifyFormat("void f() { operator*(a & a); }");
9501   // verifyFormat("void f() { operator&(a, b * b); }");
9502 
9503   verifyFormat("::operator delete(foo);");
9504   verifyFormat("::operator new(n * sizeof(foo));");
9505   verifyFormat("foo() { ::operator delete(foo); }");
9506   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9507 }
9508 
9509 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9510   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9511   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9512   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9513   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9514   verifyFormat("Deleted &operator=(const Deleted &) &;");
9515   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9516   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9517   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9518   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9519   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9520   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9521   verifyFormat("void Fn(T const &) const &;");
9522   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9523   verifyFormat("template <typename T>\n"
9524                "void F(T) && = delete;",
9525                getGoogleStyle());
9526 
9527   FormatStyle AlignLeft = getLLVMStyle();
9528   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9529   verifyFormat("void A::b() && {}", AlignLeft);
9530   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9531   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9532                AlignLeft);
9533   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9534   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9535   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9536   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9537   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9538   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9539   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9540   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9541 
9542   FormatStyle Spaces = getLLVMStyle();
9543   Spaces.SpacesInCStyleCastParentheses = true;
9544   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9545   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9546   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9547   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9548 
9549   Spaces.SpacesInCStyleCastParentheses = false;
9550   Spaces.SpacesInParentheses = true;
9551   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9552   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9553                Spaces);
9554   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9555   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9556 
9557   FormatStyle BreakTemplate = getLLVMStyle();
9558   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9559 
9560   verifyFormat("struct f {\n"
9561                "  template <class T>\n"
9562                "  int &foo(const std::string &str) &noexcept {}\n"
9563                "};",
9564                BreakTemplate);
9565 
9566   verifyFormat("struct f {\n"
9567                "  template <class T>\n"
9568                "  int &foo(const std::string &str) &&noexcept {}\n"
9569                "};",
9570                BreakTemplate);
9571 
9572   verifyFormat("struct f {\n"
9573                "  template <class T>\n"
9574                "  int &foo(const std::string &str) const &noexcept {}\n"
9575                "};",
9576                BreakTemplate);
9577 
9578   verifyFormat("struct f {\n"
9579                "  template <class T>\n"
9580                "  int &foo(const std::string &str) const &noexcept {}\n"
9581                "};",
9582                BreakTemplate);
9583 
9584   verifyFormat("struct f {\n"
9585                "  template <class T>\n"
9586                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
9587                "};",
9588                BreakTemplate);
9589 
9590   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
9591   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
9592       FormatStyle::BTDS_Yes;
9593   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
9594 
9595   verifyFormat("struct f {\n"
9596                "  template <class T>\n"
9597                "  int& foo(const std::string& str) & noexcept {}\n"
9598                "};",
9599                AlignLeftBreakTemplate);
9600 
9601   verifyFormat("struct f {\n"
9602                "  template <class T>\n"
9603                "  int& foo(const std::string& str) && noexcept {}\n"
9604                "};",
9605                AlignLeftBreakTemplate);
9606 
9607   verifyFormat("struct f {\n"
9608                "  template <class T>\n"
9609                "  int& foo(const std::string& str) const& noexcept {}\n"
9610                "};",
9611                AlignLeftBreakTemplate);
9612 
9613   verifyFormat("struct f {\n"
9614                "  template <class T>\n"
9615                "  int& foo(const std::string& str) const&& noexcept {}\n"
9616                "};",
9617                AlignLeftBreakTemplate);
9618 
9619   verifyFormat("struct f {\n"
9620                "  template <class T>\n"
9621                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
9622                "};",
9623                AlignLeftBreakTemplate);
9624 
9625   // The `&` in `Type&` should not be confused with a trailing `&` of
9626   // DEPRECATED(reason) member function.
9627   verifyFormat("struct f {\n"
9628                "  template <class T>\n"
9629                "  DEPRECATED(reason)\n"
9630                "  Type &foo(arguments) {}\n"
9631                "};",
9632                BreakTemplate);
9633 
9634   verifyFormat("struct f {\n"
9635                "  template <class T>\n"
9636                "  DEPRECATED(reason)\n"
9637                "  Type& foo(arguments) {}\n"
9638                "};",
9639                AlignLeftBreakTemplate);
9640 
9641   verifyFormat("void (*foopt)(int) = &func;");
9642 }
9643 
9644 TEST_F(FormatTest, UnderstandsNewAndDelete) {
9645   verifyFormat("void f() {\n"
9646                "  A *a = new A;\n"
9647                "  A *a = new (placement) A;\n"
9648                "  delete a;\n"
9649                "  delete (A *)a;\n"
9650                "}");
9651   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9652                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9653   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9654                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9655                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9656   verifyFormat("delete[] h->p;");
9657 
9658   verifyFormat("void operator delete(void *foo) ATTRIB;");
9659   verifyFormat("void operator new(void *foo) ATTRIB;");
9660   verifyFormat("void operator delete[](void *foo) ATTRIB;");
9661   verifyFormat("void operator delete(void *ptr) noexcept;");
9662 }
9663 
9664 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
9665   verifyFormat("int *f(int *a) {}");
9666   verifyFormat("int main(int argc, char **argv) {}");
9667   verifyFormat("Test::Test(int b) : a(b * b) {}");
9668   verifyIndependentOfContext("f(a, *a);");
9669   verifyFormat("void g() { f(*a); }");
9670   verifyIndependentOfContext("int a = b * 10;");
9671   verifyIndependentOfContext("int a = 10 * b;");
9672   verifyIndependentOfContext("int a = b * c;");
9673   verifyIndependentOfContext("int a += b * c;");
9674   verifyIndependentOfContext("int a -= b * c;");
9675   verifyIndependentOfContext("int a *= b * c;");
9676   verifyIndependentOfContext("int a /= b * c;");
9677   verifyIndependentOfContext("int a = *b;");
9678   verifyIndependentOfContext("int a = *b * c;");
9679   verifyIndependentOfContext("int a = b * *c;");
9680   verifyIndependentOfContext("int a = b * (10);");
9681   verifyIndependentOfContext("S << b * (10);");
9682   verifyIndependentOfContext("return 10 * b;");
9683   verifyIndependentOfContext("return *b * *c;");
9684   verifyIndependentOfContext("return a & ~b;");
9685   verifyIndependentOfContext("f(b ? *c : *d);");
9686   verifyIndependentOfContext("int a = b ? *c : *d;");
9687   verifyIndependentOfContext("*b = a;");
9688   verifyIndependentOfContext("a * ~b;");
9689   verifyIndependentOfContext("a * !b;");
9690   verifyIndependentOfContext("a * +b;");
9691   verifyIndependentOfContext("a * -b;");
9692   verifyIndependentOfContext("a * ++b;");
9693   verifyIndependentOfContext("a * --b;");
9694   verifyIndependentOfContext("a[4] * b;");
9695   verifyIndependentOfContext("a[a * a] = 1;");
9696   verifyIndependentOfContext("f() * b;");
9697   verifyIndependentOfContext("a * [self dostuff];");
9698   verifyIndependentOfContext("int x = a * (a + b);");
9699   verifyIndependentOfContext("(a *)(a + b);");
9700   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
9701   verifyIndependentOfContext("int *pa = (int *)&a;");
9702   verifyIndependentOfContext("return sizeof(int **);");
9703   verifyIndependentOfContext("return sizeof(int ******);");
9704   verifyIndependentOfContext("return (int **&)a;");
9705   verifyIndependentOfContext("f((*PointerToArray)[10]);");
9706   verifyFormat("void f(Type (*parameter)[10]) {}");
9707   verifyFormat("void f(Type (&parameter)[10]) {}");
9708   verifyGoogleFormat("return sizeof(int**);");
9709   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
9710   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
9711   verifyFormat("auto a = [](int **&, int ***) {};");
9712   verifyFormat("auto PointerBinding = [](const char *S) {};");
9713   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
9714   verifyFormat("[](const decltype(*a) &value) {}");
9715   verifyFormat("[](const typeof(*a) &value) {}");
9716   verifyFormat("[](const _Atomic(a *) &value) {}");
9717   verifyFormat("[](const __underlying_type(a) &value) {}");
9718   verifyFormat("decltype(a * b) F();");
9719   verifyFormat("typeof(a * b) F();");
9720   verifyFormat("#define MACRO() [](A *a) { return 1; }");
9721   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
9722   verifyIndependentOfContext("typedef void (*f)(int *a);");
9723   verifyIndependentOfContext("int i{a * b};");
9724   verifyIndependentOfContext("aaa && aaa->f();");
9725   verifyIndependentOfContext("int x = ~*p;");
9726   verifyFormat("Constructor() : a(a), area(width * height) {}");
9727   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
9728   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
9729   verifyFormat("void f() { f(a, c * d); }");
9730   verifyFormat("void f() { f(new a(), c * d); }");
9731   verifyFormat("void f(const MyOverride &override);");
9732   verifyFormat("void f(const MyFinal &final);");
9733   verifyIndependentOfContext("bool a = f() && override.f();");
9734   verifyIndependentOfContext("bool a = f() && final.f();");
9735 
9736   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
9737 
9738   verifyIndependentOfContext("A<int *> a;");
9739   verifyIndependentOfContext("A<int **> a;");
9740   verifyIndependentOfContext("A<int *, int *> a;");
9741   verifyIndependentOfContext("A<int *[]> a;");
9742   verifyIndependentOfContext(
9743       "const char *const p = reinterpret_cast<const char *const>(q);");
9744   verifyIndependentOfContext("A<int **, int **> a;");
9745   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
9746   verifyFormat("for (char **a = b; *a; ++a) {\n}");
9747   verifyFormat("for (; a && b;) {\n}");
9748   verifyFormat("bool foo = true && [] { return false; }();");
9749 
9750   verifyFormat(
9751       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9752       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9753 
9754   verifyGoogleFormat("int const* a = &b;");
9755   verifyGoogleFormat("**outparam = 1;");
9756   verifyGoogleFormat("*outparam = a * b;");
9757   verifyGoogleFormat("int main(int argc, char** argv) {}");
9758   verifyGoogleFormat("A<int*> a;");
9759   verifyGoogleFormat("A<int**> a;");
9760   verifyGoogleFormat("A<int*, int*> a;");
9761   verifyGoogleFormat("A<int**, int**> a;");
9762   verifyGoogleFormat("f(b ? *c : *d);");
9763   verifyGoogleFormat("int a = b ? *c : *d;");
9764   verifyGoogleFormat("Type* t = **x;");
9765   verifyGoogleFormat("Type* t = *++*x;");
9766   verifyGoogleFormat("*++*x;");
9767   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
9768   verifyGoogleFormat("Type* t = x++ * y;");
9769   verifyGoogleFormat(
9770       "const char* const p = reinterpret_cast<const char* const>(q);");
9771   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
9772   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
9773   verifyGoogleFormat("template <typename T>\n"
9774                      "void f(int i = 0, SomeType** temps = NULL);");
9775 
9776   FormatStyle Left = getLLVMStyle();
9777   Left.PointerAlignment = FormatStyle::PAS_Left;
9778   verifyFormat("x = *a(x) = *a(y);", Left);
9779   verifyFormat("for (;; *a = b) {\n}", Left);
9780   verifyFormat("return *this += 1;", Left);
9781   verifyFormat("throw *x;", Left);
9782   verifyFormat("delete *x;", Left);
9783   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
9784   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
9785   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
9786   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
9787   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
9788   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
9789   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
9790   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
9791   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
9792 
9793   verifyIndependentOfContext("a = *(x + y);");
9794   verifyIndependentOfContext("a = &(x + y);");
9795   verifyIndependentOfContext("*(x + y).call();");
9796   verifyIndependentOfContext("&(x + y)->call();");
9797   verifyFormat("void f() { &(*I).first; }");
9798 
9799   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
9800   verifyFormat("f(* /* confusing comment */ foo);");
9801   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
9802   verifyFormat("void foo(int * // this is the first paramters\n"
9803                "         ,\n"
9804                "         int second);");
9805   verifyFormat("double term = a * // first\n"
9806                "              b;");
9807   verifyFormat(
9808       "int *MyValues = {\n"
9809       "    *A, // Operator detection might be confused by the '{'\n"
9810       "    *BB // Operator detection might be confused by previous comment\n"
9811       "};");
9812 
9813   verifyIndependentOfContext("if (int *a = &b)");
9814   verifyIndependentOfContext("if (int &a = *b)");
9815   verifyIndependentOfContext("if (a & b[i])");
9816   verifyIndependentOfContext("if constexpr (a & b[i])");
9817   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
9818   verifyIndependentOfContext("if (a * (b * c))");
9819   verifyIndependentOfContext("if constexpr (a * (b * c))");
9820   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
9821   verifyIndependentOfContext("if (a::b::c::d & b[i])");
9822   verifyIndependentOfContext("if (*b[i])");
9823   verifyIndependentOfContext("if (int *a = (&b))");
9824   verifyIndependentOfContext("while (int *a = &b)");
9825   verifyIndependentOfContext("while (a * (b * c))");
9826   verifyIndependentOfContext("size = sizeof *a;");
9827   verifyIndependentOfContext("if (a && (b = c))");
9828   verifyFormat("void f() {\n"
9829                "  for (const int &v : Values) {\n"
9830                "  }\n"
9831                "}");
9832   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
9833   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
9834   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
9835 
9836   verifyFormat("#define A (!a * b)");
9837   verifyFormat("#define MACRO     \\\n"
9838                "  int *i = a * b; \\\n"
9839                "  void f(a *b);",
9840                getLLVMStyleWithColumns(19));
9841 
9842   verifyIndependentOfContext("A = new SomeType *[Length];");
9843   verifyIndependentOfContext("A = new SomeType *[Length]();");
9844   verifyIndependentOfContext("T **t = new T *;");
9845   verifyIndependentOfContext("T **t = new T *();");
9846   verifyGoogleFormat("A = new SomeType*[Length]();");
9847   verifyGoogleFormat("A = new SomeType*[Length];");
9848   verifyGoogleFormat("T** t = new T*;");
9849   verifyGoogleFormat("T** t = new T*();");
9850 
9851   verifyFormat("STATIC_ASSERT((a & b) == 0);");
9852   verifyFormat("STATIC_ASSERT(0 == (a & b));");
9853   verifyFormat("template <bool a, bool b> "
9854                "typename t::if<x && y>::type f() {}");
9855   verifyFormat("template <int *y> f() {}");
9856   verifyFormat("vector<int *> v;");
9857   verifyFormat("vector<int *const> v;");
9858   verifyFormat("vector<int *const **const *> v;");
9859   verifyFormat("vector<int *volatile> v;");
9860   verifyFormat("vector<a *_Nonnull> v;");
9861   verifyFormat("vector<a *_Nullable> v;");
9862   verifyFormat("vector<a *_Null_unspecified> v;");
9863   verifyFormat("vector<a *__ptr32> v;");
9864   verifyFormat("vector<a *__ptr64> v;");
9865   verifyFormat("vector<a *__capability> v;");
9866   FormatStyle TypeMacros = getLLVMStyle();
9867   TypeMacros.TypenameMacros = {"LIST"};
9868   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
9869   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
9870   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
9871   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
9872   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
9873 
9874   FormatStyle CustomQualifier = getLLVMStyle();
9875   // Add identifiers that should not be parsed as a qualifier by default.
9876   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9877   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
9878   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
9879   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
9880   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
9881   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
9882   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
9883   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
9884   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
9885   verifyFormat("vector<a * _NotAQualifier> v;");
9886   verifyFormat("vector<a * __not_a_qualifier> v;");
9887   verifyFormat("vector<a * b> v;");
9888   verifyFormat("foo<b && false>();");
9889   verifyFormat("foo<b & 1>();");
9890   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
9891   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
9892   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
9893   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
9894   verifyFormat(
9895       "template <class T, class = typename std::enable_if<\n"
9896       "                       std::is_integral<T>::value &&\n"
9897       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
9898       "void F();",
9899       getLLVMStyleWithColumns(70));
9900   verifyFormat("template <class T,\n"
9901                "          class = typename std::enable_if<\n"
9902                "              std::is_integral<T>::value &&\n"
9903                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
9904                "          class U>\n"
9905                "void F();",
9906                getLLVMStyleWithColumns(70));
9907   verifyFormat(
9908       "template <class T,\n"
9909       "          class = typename ::std::enable_if<\n"
9910       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
9911       "void F();",
9912       getGoogleStyleWithColumns(68));
9913 
9914   verifyIndependentOfContext("MACRO(int *i);");
9915   verifyIndependentOfContext("MACRO(auto *a);");
9916   verifyIndependentOfContext("MACRO(const A *a);");
9917   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
9918   verifyIndependentOfContext("MACRO(decltype(A) *a);");
9919   verifyIndependentOfContext("MACRO(typeof(A) *a);");
9920   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
9921   verifyIndependentOfContext("MACRO(A *const a);");
9922   verifyIndependentOfContext("MACRO(A *restrict a);");
9923   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
9924   verifyIndependentOfContext("MACRO(A *__restrict a);");
9925   verifyIndependentOfContext("MACRO(A *volatile a);");
9926   verifyIndependentOfContext("MACRO(A *__volatile a);");
9927   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
9928   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
9929   verifyIndependentOfContext("MACRO(A *_Nullable a);");
9930   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
9931   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
9932   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
9933   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
9934   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
9935   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
9936   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
9937   verifyIndependentOfContext("MACRO(A *__capability);");
9938   verifyIndependentOfContext("MACRO(A &__capability);");
9939   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
9940   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
9941   // If we add __my_qualifier to AttributeMacros it should always be parsed as
9942   // a type declaration:
9943   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
9944   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
9945   // Also check that TypenameMacros prevents parsing it as multiplication:
9946   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
9947   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
9948 
9949   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
9950   verifyFormat("void f() { f(float{1}, a * a); }");
9951   verifyFormat("void f() { f(float(1), a * a); }");
9952 
9953   verifyFormat("f((void (*)(int))g);");
9954   verifyFormat("f((void (&)(int))g);");
9955   verifyFormat("f((void (^)(int))g);");
9956 
9957   // FIXME: Is there a way to make this work?
9958   // verifyIndependentOfContext("MACRO(A *a);");
9959   verifyFormat("MACRO(A &B);");
9960   verifyFormat("MACRO(A *B);");
9961   verifyFormat("void f() { MACRO(A * B); }");
9962   verifyFormat("void f() { MACRO(A & B); }");
9963 
9964   // This lambda was mis-formatted after D88956 (treating it as a binop):
9965   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
9966   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
9967   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
9968   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
9969 
9970   verifyFormat("DatumHandle const *operator->() const { return input_; }");
9971   verifyFormat("return options != nullptr && operator==(*options);");
9972 
9973   EXPECT_EQ("#define OP(x)                                    \\\n"
9974             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
9975             "    return s << a.DebugString();                 \\\n"
9976             "  }",
9977             format("#define OP(x) \\\n"
9978                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
9979                    "    return s << a.DebugString(); \\\n"
9980                    "  }",
9981                    getLLVMStyleWithColumns(50)));
9982 
9983   // FIXME: We cannot handle this case yet; we might be able to figure out that
9984   // foo<x> d > v; doesn't make sense.
9985   verifyFormat("foo<a<b && c> d> v;");
9986 
9987   FormatStyle PointerMiddle = getLLVMStyle();
9988   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9989   verifyFormat("delete *x;", PointerMiddle);
9990   verifyFormat("int * x;", PointerMiddle);
9991   verifyFormat("int *[] x;", PointerMiddle);
9992   verifyFormat("template <int * y> f() {}", PointerMiddle);
9993   verifyFormat("int * f(int * a) {}", PointerMiddle);
9994   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
9995   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
9996   verifyFormat("A<int *> a;", PointerMiddle);
9997   verifyFormat("A<int **> a;", PointerMiddle);
9998   verifyFormat("A<int *, int *> a;", PointerMiddle);
9999   verifyFormat("A<int *[]> a;", PointerMiddle);
10000   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10001   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10002   verifyFormat("T ** t = new T *;", PointerMiddle);
10003 
10004   // Member function reference qualifiers aren't binary operators.
10005   verifyFormat("string // break\n"
10006                "operator()() & {}");
10007   verifyFormat("string // break\n"
10008                "operator()() && {}");
10009   verifyGoogleFormat("template <typename T>\n"
10010                      "auto x() & -> int {}");
10011 
10012   // Should be binary operators when used as an argument expression (overloaded
10013   // operator invoked as a member function).
10014   verifyFormat("void f() { a.operator()(a * a); }");
10015   verifyFormat("void f() { a->operator()(a & a); }");
10016   verifyFormat("void f() { a.operator()(*a & *a); }");
10017   verifyFormat("void f() { a->operator()(*a * *a); }");
10018 
10019   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10020   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10021 }
10022 
10023 TEST_F(FormatTest, UnderstandsAttributes) {
10024   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10025   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10026                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10027   FormatStyle AfterType = getLLVMStyle();
10028   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10029   verifyFormat("__attribute__((nodebug)) void\n"
10030                "foo() {}\n",
10031                AfterType);
10032   verifyFormat("__unused void\n"
10033                "foo() {}",
10034                AfterType);
10035 
10036   FormatStyle CustomAttrs = getLLVMStyle();
10037   CustomAttrs.AttributeMacros.push_back("__unused");
10038   CustomAttrs.AttributeMacros.push_back("__attr1");
10039   CustomAttrs.AttributeMacros.push_back("__attr2");
10040   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10041   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10042   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10043   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10044   // Check that it is parsed as a multiplication without AttributeMacros and
10045   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10046   verifyFormat("vector<SomeType * __attr1> v;");
10047   verifyFormat("vector<SomeType __attr1 *> v;");
10048   verifyFormat("vector<SomeType __attr1 *const> v;");
10049   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10050   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10051   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10052   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10053   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10054   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10055   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10056   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10057 
10058   // Check that these are not parsed as function declarations:
10059   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10060   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10061   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10062   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10063   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10064   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10065   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10066   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10067   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10068   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10069 }
10070 
10071 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10072   // Check that qualifiers on pointers don't break parsing of casts.
10073   verifyFormat("x = (foo *const)*v;");
10074   verifyFormat("x = (foo *volatile)*v;");
10075   verifyFormat("x = (foo *restrict)*v;");
10076   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10077   verifyFormat("x = (foo *_Nonnull)*v;");
10078   verifyFormat("x = (foo *_Nullable)*v;");
10079   verifyFormat("x = (foo *_Null_unspecified)*v;");
10080   verifyFormat("x = (foo *_Nonnull)*v;");
10081   verifyFormat("x = (foo *[[clang::attr]])*v;");
10082   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10083   verifyFormat("x = (foo *__ptr32)*v;");
10084   verifyFormat("x = (foo *__ptr64)*v;");
10085   verifyFormat("x = (foo *__capability)*v;");
10086 
10087   // Check that we handle multiple trailing qualifiers and skip them all to
10088   // determine that the expression is a cast to a pointer type.
10089   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10090   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10091   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10092   StringRef AllQualifiers =
10093       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10094       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10095   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10096   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10097 
10098   // Also check that address-of is not parsed as a binary bitwise-and:
10099   verifyFormat("x = (foo *const)&v;");
10100   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10101   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10102 
10103   // Check custom qualifiers:
10104   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10105   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10106   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10107   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10108   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10109                CustomQualifier);
10110   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10111                CustomQualifier);
10112 
10113   // Check that unknown identifiers result in binary operator parsing:
10114   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10115   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10116 }
10117 
10118 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10119   verifyFormat("SomeType s [[unused]] (InitValue);");
10120   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10121   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10122   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10123   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10124   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10125                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10126   verifyFormat("[[nodiscard]] bool f() { return false; }");
10127   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10128   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10129   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10130 
10131   // Make sure we do not mistake attributes for array subscripts.
10132   verifyFormat("int a() {}\n"
10133                "[[unused]] int b() {}\n");
10134   verifyFormat("NSArray *arr;\n"
10135                "arr[[Foo() bar]];");
10136 
10137   // On the other hand, we still need to correctly find array subscripts.
10138   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10139 
10140   // Make sure that we do not mistake Objective-C method inside array literals
10141   // as attributes, even if those method names are also keywords.
10142   verifyFormat("@[ [foo bar] ];");
10143   verifyFormat("@[ [NSArray class] ];");
10144   verifyFormat("@[ [foo enum] ];");
10145 
10146   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10147 
10148   // Make sure we do not parse attributes as lambda introducers.
10149   FormatStyle MultiLineFunctions = getLLVMStyle();
10150   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10151   verifyFormat("[[unused]] int b() {\n"
10152                "  return 42;\n"
10153                "}\n",
10154                MultiLineFunctions);
10155 }
10156 
10157 TEST_F(FormatTest, AttributeClass) {
10158   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10159   verifyFormat("class S {\n"
10160                "  S(S&&) = default;\n"
10161                "};",
10162                Style);
10163   verifyFormat("class [[nodiscard]] S {\n"
10164                "  S(S&&) = default;\n"
10165                "};",
10166                Style);
10167   verifyFormat("class __attribute((maybeunused)) S {\n"
10168                "  S(S&&) = default;\n"
10169                "};",
10170                Style);
10171   verifyFormat("struct S {\n"
10172                "  S(S&&) = default;\n"
10173                "};",
10174                Style);
10175   verifyFormat("struct [[nodiscard]] S {\n"
10176                "  S(S&&) = default;\n"
10177                "};",
10178                Style);
10179 }
10180 
10181 TEST_F(FormatTest, AttributesAfterMacro) {
10182   FormatStyle Style = getLLVMStyle();
10183   verifyFormat("MACRO;\n"
10184                "__attribute__((maybe_unused)) int foo() {\n"
10185                "  //...\n"
10186                "}");
10187 
10188   verifyFormat("MACRO;\n"
10189                "[[nodiscard]] int foo() {\n"
10190                "  //...\n"
10191                "}");
10192 
10193   EXPECT_EQ("MACRO\n\n"
10194             "__attribute__((maybe_unused)) int foo() {\n"
10195             "  //...\n"
10196             "}",
10197             format("MACRO\n\n"
10198                    "__attribute__((maybe_unused)) int foo() {\n"
10199                    "  //...\n"
10200                    "}"));
10201 
10202   EXPECT_EQ("MACRO\n\n"
10203             "[[nodiscard]] int foo() {\n"
10204             "  //...\n"
10205             "}",
10206             format("MACRO\n\n"
10207                    "[[nodiscard]] int foo() {\n"
10208                    "  //...\n"
10209                    "}"));
10210 }
10211 
10212 TEST_F(FormatTest, AttributePenaltyBreaking) {
10213   FormatStyle Style = getLLVMStyle();
10214   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10215                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10216                Style);
10217   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10218                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10219                Style);
10220   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10221                "shared_ptr<ALongTypeName> &C d) {\n}",
10222                Style);
10223 }
10224 
10225 TEST_F(FormatTest, UnderstandsEllipsis) {
10226   FormatStyle Style = getLLVMStyle();
10227   verifyFormat("int printf(const char *fmt, ...);");
10228   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10229   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10230 
10231   verifyFormat("template <int *...PP> a;", Style);
10232 
10233   Style.PointerAlignment = FormatStyle::PAS_Left;
10234   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10235 
10236   verifyFormat("template <int*... PP> a;", Style);
10237 
10238   Style.PointerAlignment = FormatStyle::PAS_Middle;
10239   verifyFormat("template <int *... PP> a;", Style);
10240 }
10241 
10242 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10243   EXPECT_EQ("int *a;\n"
10244             "int *a;\n"
10245             "int *a;",
10246             format("int *a;\n"
10247                    "int* a;\n"
10248                    "int *a;",
10249                    getGoogleStyle()));
10250   EXPECT_EQ("int* a;\n"
10251             "int* a;\n"
10252             "int* a;",
10253             format("int* a;\n"
10254                    "int* a;\n"
10255                    "int *a;",
10256                    getGoogleStyle()));
10257   EXPECT_EQ("int *a;\n"
10258             "int *a;\n"
10259             "int *a;",
10260             format("int *a;\n"
10261                    "int * a;\n"
10262                    "int *  a;",
10263                    getGoogleStyle()));
10264   EXPECT_EQ("auto x = [] {\n"
10265             "  int *a;\n"
10266             "  int *a;\n"
10267             "  int *a;\n"
10268             "};",
10269             format("auto x=[]{int *a;\n"
10270                    "int * a;\n"
10271                    "int *  a;};",
10272                    getGoogleStyle()));
10273 }
10274 
10275 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10276   verifyFormat("int f(int &&a) {}");
10277   verifyFormat("int f(int a, char &&b) {}");
10278   verifyFormat("void f() { int &&a = b; }");
10279   verifyGoogleFormat("int f(int a, char&& b) {}");
10280   verifyGoogleFormat("void f() { int&& a = b; }");
10281 
10282   verifyIndependentOfContext("A<int &&> a;");
10283   verifyIndependentOfContext("A<int &&, int &&> a;");
10284   verifyGoogleFormat("A<int&&> a;");
10285   verifyGoogleFormat("A<int&&, int&&> a;");
10286 
10287   // Not rvalue references:
10288   verifyFormat("template <bool B, bool C> class A {\n"
10289                "  static_assert(B && C, \"Something is wrong\");\n"
10290                "};");
10291   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10292   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10293   verifyFormat("#define A(a, b) (a && b)");
10294 }
10295 
10296 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10297   verifyFormat("void f() {\n"
10298                "  x[aaaaaaaaa -\n"
10299                "    b] = 23;\n"
10300                "}",
10301                getLLVMStyleWithColumns(15));
10302 }
10303 
10304 TEST_F(FormatTest, FormatsCasts) {
10305   verifyFormat("Type *A = static_cast<Type *>(P);");
10306   verifyFormat("Type *A = (Type *)P;");
10307   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10308   verifyFormat("int a = (int)(2.0f);");
10309   verifyFormat("int a = (int)2.0f;");
10310   verifyFormat("x[(int32)y];");
10311   verifyFormat("x = (int32)y;");
10312   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10313   verifyFormat("int a = (int)*b;");
10314   verifyFormat("int a = (int)2.0f;");
10315   verifyFormat("int a = (int)~0;");
10316   verifyFormat("int a = (int)++a;");
10317   verifyFormat("int a = (int)sizeof(int);");
10318   verifyFormat("int a = (int)+2;");
10319   verifyFormat("my_int a = (my_int)2.0f;");
10320   verifyFormat("my_int a = (my_int)sizeof(int);");
10321   verifyFormat("return (my_int)aaa;");
10322   verifyFormat("#define x ((int)-1)");
10323   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10324   verifyFormat("#define p(q) ((int *)&q)");
10325   verifyFormat("fn(a)(b) + 1;");
10326 
10327   verifyFormat("void f() { my_int a = (my_int)*b; }");
10328   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10329   verifyFormat("my_int a = (my_int)~0;");
10330   verifyFormat("my_int a = (my_int)++a;");
10331   verifyFormat("my_int a = (my_int)-2;");
10332   verifyFormat("my_int a = (my_int)1;");
10333   verifyFormat("my_int a = (my_int *)1;");
10334   verifyFormat("my_int a = (const my_int)-1;");
10335   verifyFormat("my_int a = (const my_int *)-1;");
10336   verifyFormat("my_int a = (my_int)(my_int)-1;");
10337   verifyFormat("my_int a = (ns::my_int)-2;");
10338   verifyFormat("case (my_int)ONE:");
10339   verifyFormat("auto x = (X)this;");
10340   // Casts in Obj-C style calls used to not be recognized as such.
10341   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10342 
10343   // FIXME: single value wrapped with paren will be treated as cast.
10344   verifyFormat("void f(int i = (kValue)*kMask) {}");
10345 
10346   verifyFormat("{ (void)F; }");
10347 
10348   // Don't break after a cast's
10349   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10350                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10351                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10352 
10353   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10354   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10355   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10356   verifyFormat("bool *y = (bool *)(void *)(x);");
10357   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10358   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10359   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10360   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10361 
10362   // These are not casts.
10363   verifyFormat("void f(int *) {}");
10364   verifyFormat("f(foo)->b;");
10365   verifyFormat("f(foo).b;");
10366   verifyFormat("f(foo)(b);");
10367   verifyFormat("f(foo)[b];");
10368   verifyFormat("[](foo) { return 4; }(bar);");
10369   verifyFormat("(*funptr)(foo)[4];");
10370   verifyFormat("funptrs[4](foo)[4];");
10371   verifyFormat("void f(int *);");
10372   verifyFormat("void f(int *) = 0;");
10373   verifyFormat("void f(SmallVector<int>) {}");
10374   verifyFormat("void f(SmallVector<int>);");
10375   verifyFormat("void f(SmallVector<int>) = 0;");
10376   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10377   verifyFormat("int a = sizeof(int) * b;");
10378   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10379   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10380   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10381   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10382 
10383   // These are not casts, but at some point were confused with casts.
10384   verifyFormat("virtual void foo(int *) override;");
10385   verifyFormat("virtual void foo(char &) const;");
10386   verifyFormat("virtual void foo(int *a, char *) const;");
10387   verifyFormat("int a = sizeof(int *) + b;");
10388   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10389   verifyFormat("bool b = f(g<int>) && c;");
10390   verifyFormat("typedef void (*f)(int i) func;");
10391   verifyFormat("void operator++(int) noexcept;");
10392   verifyFormat("void operator++(int &) noexcept;");
10393   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10394                "&) noexcept;");
10395   verifyFormat(
10396       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10397   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10398   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10399   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10400   verifyFormat("void operator delete(foo &) noexcept;");
10401   verifyFormat("void operator delete(foo) noexcept;");
10402   verifyFormat("void operator delete(int) noexcept;");
10403   verifyFormat("void operator delete(int &) noexcept;");
10404   verifyFormat("void operator delete(int &) volatile noexcept;");
10405   verifyFormat("void operator delete(int &) const");
10406   verifyFormat("void operator delete(int &) = default");
10407   verifyFormat("void operator delete(int &) = delete");
10408   verifyFormat("void operator delete(int &) [[noreturn]]");
10409   verifyFormat("void operator delete(int &) throw();");
10410   verifyFormat("void operator delete(int &) throw(int);");
10411   verifyFormat("auto operator delete(int &) -> int;");
10412   verifyFormat("auto operator delete(int &) override");
10413   verifyFormat("auto operator delete(int &) final");
10414 
10415   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10416                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10417   // FIXME: The indentation here is not ideal.
10418   verifyFormat(
10419       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10420       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10421       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10422 }
10423 
10424 TEST_F(FormatTest, FormatsFunctionTypes) {
10425   verifyFormat("A<bool()> a;");
10426   verifyFormat("A<SomeType()> a;");
10427   verifyFormat("A<void (*)(int, std::string)> a;");
10428   verifyFormat("A<void *(int)>;");
10429   verifyFormat("void *(*a)(int *, SomeType *);");
10430   verifyFormat("int (*func)(void *);");
10431   verifyFormat("void f() { int (*func)(void *); }");
10432   verifyFormat("template <class CallbackClass>\n"
10433                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10434 
10435   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10436   verifyGoogleFormat("void* (*a)(int);");
10437   verifyGoogleFormat(
10438       "template <class CallbackClass>\n"
10439       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10440 
10441   // Other constructs can look somewhat like function types:
10442   verifyFormat("A<sizeof(*x)> a;");
10443   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10444   verifyFormat("some_var = function(*some_pointer_var)[0];");
10445   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10446   verifyFormat("int x = f(&h)();");
10447   verifyFormat("returnsFunction(&param1, &param2)(param);");
10448   verifyFormat("std::function<\n"
10449                "    LooooooooooongTemplatedType<\n"
10450                "        SomeType>*(\n"
10451                "        LooooooooooooooooongType type)>\n"
10452                "    function;",
10453                getGoogleStyleWithColumns(40));
10454 }
10455 
10456 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10457   verifyFormat("A (*foo_)[6];");
10458   verifyFormat("vector<int> (*foo_)[6];");
10459 }
10460 
10461 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10462   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10463                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10464   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10465                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10466   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10467                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10468 
10469   // Different ways of ()-initializiation.
10470   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10471                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10472   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10473                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10474   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10475                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10476   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10477                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10478 
10479   // Lambdas should not confuse the variable declaration heuristic.
10480   verifyFormat("LooooooooooooooooongType\n"
10481                "    variable(nullptr, [](A *a) {});",
10482                getLLVMStyleWithColumns(40));
10483 }
10484 
10485 TEST_F(FormatTest, BreaksLongDeclarations) {
10486   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10487                "    AnotherNameForTheLongType;");
10488   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10489                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10490   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10491                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10492   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10493                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10494   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10495                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10496   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10497                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10498   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10499                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10500   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10501                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10502   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10503                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10504   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10505                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10506   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10507                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10508   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10509                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10510   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10511                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10512   FormatStyle Indented = getLLVMStyle();
10513   Indented.IndentWrappedFunctionNames = true;
10514   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10515                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10516                Indented);
10517   verifyFormat(
10518       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10519       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10520       Indented);
10521   verifyFormat(
10522       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10523       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10524       Indented);
10525   verifyFormat(
10526       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10527       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10528       Indented);
10529 
10530   // FIXME: Without the comment, this breaks after "(".
10531   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10532                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10533                getGoogleStyle());
10534 
10535   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
10536                "                  int LoooooooooooooooooooongParam2) {}");
10537   verifyFormat(
10538       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
10539       "                                   SourceLocation L, IdentifierIn *II,\n"
10540       "                                   Type *T) {}");
10541   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
10542                "ReallyReaaallyLongFunctionName(\n"
10543                "    const std::string &SomeParameter,\n"
10544                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10545                "        &ReallyReallyLongParameterName,\n"
10546                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10547                "        &AnotherLongParameterName) {}");
10548   verifyFormat("template <typename A>\n"
10549                "SomeLoooooooooooooooooooooongType<\n"
10550                "    typename some_namespace::SomeOtherType<A>::Type>\n"
10551                "Function() {}");
10552 
10553   verifyGoogleFormat(
10554       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
10555       "    aaaaaaaaaaaaaaaaaaaaaaa;");
10556   verifyGoogleFormat(
10557       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
10558       "                                   SourceLocation L) {}");
10559   verifyGoogleFormat(
10560       "some_namespace::LongReturnType\n"
10561       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
10562       "    int first_long_parameter, int second_parameter) {}");
10563 
10564   verifyGoogleFormat("template <typename T>\n"
10565                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10566                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
10567   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10568                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
10569 
10570   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
10571                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10572                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10573   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10574                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10575                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
10576   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10577                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
10578                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
10579                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10580 
10581   verifyFormat("template <typename T> // Templates on own line.\n"
10582                "static int            // Some comment.\n"
10583                "MyFunction(int a);",
10584                getLLVMStyle());
10585 }
10586 
10587 TEST_F(FormatTest, FormatsAccessModifiers) {
10588   FormatStyle Style = getLLVMStyle();
10589   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
10590             FormatStyle::ELBAMS_LogicalBlock);
10591   verifyFormat("struct foo {\n"
10592                "private:\n"
10593                "  void f() {}\n"
10594                "\n"
10595                "private:\n"
10596                "  int i;\n"
10597                "\n"
10598                "protected:\n"
10599                "  int j;\n"
10600                "};\n",
10601                Style);
10602   verifyFormat("struct foo {\n"
10603                "private:\n"
10604                "  void f() {}\n"
10605                "\n"
10606                "private:\n"
10607                "  int i;\n"
10608                "\n"
10609                "protected:\n"
10610                "  int j;\n"
10611                "};\n",
10612                "struct foo {\n"
10613                "private:\n"
10614                "  void f() {}\n"
10615                "private:\n"
10616                "  int i;\n"
10617                "protected:\n"
10618                "  int j;\n"
10619                "};\n",
10620                Style);
10621   verifyFormat("struct foo { /* comment */\n"
10622                "private:\n"
10623                "  int i;\n"
10624                "  // comment\n"
10625                "private:\n"
10626                "  int j;\n"
10627                "};\n",
10628                Style);
10629   verifyFormat("struct foo {\n"
10630                "#ifdef FOO\n"
10631                "#endif\n"
10632                "private:\n"
10633                "  int i;\n"
10634                "#ifdef FOO\n"
10635                "private:\n"
10636                "#endif\n"
10637                "  int j;\n"
10638                "};\n",
10639                Style);
10640   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10641   verifyFormat("struct foo {\n"
10642                "private:\n"
10643                "  void f() {}\n"
10644                "private:\n"
10645                "  int i;\n"
10646                "protected:\n"
10647                "  int j;\n"
10648                "};\n",
10649                Style);
10650   verifyFormat("struct foo {\n"
10651                "private:\n"
10652                "  void f() {}\n"
10653                "private:\n"
10654                "  int i;\n"
10655                "protected:\n"
10656                "  int j;\n"
10657                "};\n",
10658                "struct foo {\n"
10659                "\n"
10660                "private:\n"
10661                "  void f() {}\n"
10662                "\n"
10663                "private:\n"
10664                "  int i;\n"
10665                "\n"
10666                "protected:\n"
10667                "  int j;\n"
10668                "};\n",
10669                Style);
10670   verifyFormat("struct foo { /* comment */\n"
10671                "private:\n"
10672                "  int i;\n"
10673                "  // comment\n"
10674                "private:\n"
10675                "  int j;\n"
10676                "};\n",
10677                "struct foo { /* comment */\n"
10678                "\n"
10679                "private:\n"
10680                "  int i;\n"
10681                "  // comment\n"
10682                "\n"
10683                "private:\n"
10684                "  int j;\n"
10685                "};\n",
10686                Style);
10687   verifyFormat("struct foo {\n"
10688                "#ifdef FOO\n"
10689                "#endif\n"
10690                "private:\n"
10691                "  int i;\n"
10692                "#ifdef FOO\n"
10693                "private:\n"
10694                "#endif\n"
10695                "  int j;\n"
10696                "};\n",
10697                "struct foo {\n"
10698                "#ifdef FOO\n"
10699                "#endif\n"
10700                "\n"
10701                "private:\n"
10702                "  int i;\n"
10703                "#ifdef FOO\n"
10704                "\n"
10705                "private:\n"
10706                "#endif\n"
10707                "  int j;\n"
10708                "};\n",
10709                Style);
10710   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10711   verifyFormat("struct foo {\n"
10712                "private:\n"
10713                "  void f() {}\n"
10714                "\n"
10715                "private:\n"
10716                "  int i;\n"
10717                "\n"
10718                "protected:\n"
10719                "  int j;\n"
10720                "};\n",
10721                Style);
10722   verifyFormat("struct foo {\n"
10723                "private:\n"
10724                "  void f() {}\n"
10725                "\n"
10726                "private:\n"
10727                "  int i;\n"
10728                "\n"
10729                "protected:\n"
10730                "  int j;\n"
10731                "};\n",
10732                "struct foo {\n"
10733                "private:\n"
10734                "  void f() {}\n"
10735                "private:\n"
10736                "  int i;\n"
10737                "protected:\n"
10738                "  int j;\n"
10739                "};\n",
10740                Style);
10741   verifyFormat("struct foo { /* comment */\n"
10742                "private:\n"
10743                "  int i;\n"
10744                "  // comment\n"
10745                "\n"
10746                "private:\n"
10747                "  int j;\n"
10748                "};\n",
10749                "struct foo { /* comment */\n"
10750                "private:\n"
10751                "  int i;\n"
10752                "  // comment\n"
10753                "\n"
10754                "private:\n"
10755                "  int j;\n"
10756                "};\n",
10757                Style);
10758   verifyFormat("struct foo {\n"
10759                "#ifdef FOO\n"
10760                "#endif\n"
10761                "\n"
10762                "private:\n"
10763                "  int i;\n"
10764                "#ifdef FOO\n"
10765                "\n"
10766                "private:\n"
10767                "#endif\n"
10768                "  int j;\n"
10769                "};\n",
10770                "struct foo {\n"
10771                "#ifdef FOO\n"
10772                "#endif\n"
10773                "private:\n"
10774                "  int i;\n"
10775                "#ifdef FOO\n"
10776                "private:\n"
10777                "#endif\n"
10778                "  int j;\n"
10779                "};\n",
10780                Style);
10781   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10782   EXPECT_EQ("struct foo {\n"
10783             "\n"
10784             "private:\n"
10785             "  void f() {}\n"
10786             "\n"
10787             "private:\n"
10788             "  int i;\n"
10789             "\n"
10790             "protected:\n"
10791             "  int j;\n"
10792             "};\n",
10793             format("struct foo {\n"
10794                    "\n"
10795                    "private:\n"
10796                    "  void f() {}\n"
10797                    "\n"
10798                    "private:\n"
10799                    "  int i;\n"
10800                    "\n"
10801                    "protected:\n"
10802                    "  int j;\n"
10803                    "};\n",
10804                    Style));
10805   verifyFormat("struct foo {\n"
10806                "private:\n"
10807                "  void f() {}\n"
10808                "private:\n"
10809                "  int i;\n"
10810                "protected:\n"
10811                "  int j;\n"
10812                "};\n",
10813                Style);
10814   EXPECT_EQ("struct foo { /* comment */\n"
10815             "\n"
10816             "private:\n"
10817             "  int i;\n"
10818             "  // comment\n"
10819             "\n"
10820             "private:\n"
10821             "  int j;\n"
10822             "};\n",
10823             format("struct foo { /* comment */\n"
10824                    "\n"
10825                    "private:\n"
10826                    "  int i;\n"
10827                    "  // comment\n"
10828                    "\n"
10829                    "private:\n"
10830                    "  int j;\n"
10831                    "};\n",
10832                    Style));
10833   verifyFormat("struct foo { /* comment */\n"
10834                "private:\n"
10835                "  int i;\n"
10836                "  // comment\n"
10837                "private:\n"
10838                "  int j;\n"
10839                "};\n",
10840                Style);
10841   EXPECT_EQ("struct foo {\n"
10842             "#ifdef FOO\n"
10843             "#endif\n"
10844             "\n"
10845             "private:\n"
10846             "  int i;\n"
10847             "#ifdef FOO\n"
10848             "\n"
10849             "private:\n"
10850             "#endif\n"
10851             "  int j;\n"
10852             "};\n",
10853             format("struct foo {\n"
10854                    "#ifdef FOO\n"
10855                    "#endif\n"
10856                    "\n"
10857                    "private:\n"
10858                    "  int i;\n"
10859                    "#ifdef FOO\n"
10860                    "\n"
10861                    "private:\n"
10862                    "#endif\n"
10863                    "  int j;\n"
10864                    "};\n",
10865                    Style));
10866   verifyFormat("struct foo {\n"
10867                "#ifdef FOO\n"
10868                "#endif\n"
10869                "private:\n"
10870                "  int i;\n"
10871                "#ifdef FOO\n"
10872                "private:\n"
10873                "#endif\n"
10874                "  int j;\n"
10875                "};\n",
10876                Style);
10877 
10878   FormatStyle NoEmptyLines = getLLVMStyle();
10879   NoEmptyLines.MaxEmptyLinesToKeep = 0;
10880   verifyFormat("struct foo {\n"
10881                "private:\n"
10882                "  void f() {}\n"
10883                "\n"
10884                "private:\n"
10885                "  int i;\n"
10886                "\n"
10887                "public:\n"
10888                "protected:\n"
10889                "  int j;\n"
10890                "};\n",
10891                NoEmptyLines);
10892 
10893   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10894   verifyFormat("struct foo {\n"
10895                "private:\n"
10896                "  void f() {}\n"
10897                "private:\n"
10898                "  int i;\n"
10899                "public:\n"
10900                "protected:\n"
10901                "  int j;\n"
10902                "};\n",
10903                NoEmptyLines);
10904 
10905   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10906   verifyFormat("struct foo {\n"
10907                "private:\n"
10908                "  void f() {}\n"
10909                "\n"
10910                "private:\n"
10911                "  int i;\n"
10912                "\n"
10913                "public:\n"
10914                "\n"
10915                "protected:\n"
10916                "  int j;\n"
10917                "};\n",
10918                NoEmptyLines);
10919 }
10920 
10921 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
10922 
10923   FormatStyle Style = getLLVMStyle();
10924   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
10925   verifyFormat("struct foo {\n"
10926                "private:\n"
10927                "  void f() {}\n"
10928                "\n"
10929                "private:\n"
10930                "  int i;\n"
10931                "\n"
10932                "protected:\n"
10933                "  int j;\n"
10934                "};\n",
10935                Style);
10936 
10937   // Check if lines are removed.
10938   verifyFormat("struct foo {\n"
10939                "private:\n"
10940                "  void f() {}\n"
10941                "\n"
10942                "private:\n"
10943                "  int i;\n"
10944                "\n"
10945                "protected:\n"
10946                "  int j;\n"
10947                "};\n",
10948                "struct foo {\n"
10949                "private:\n"
10950                "\n"
10951                "  void f() {}\n"
10952                "\n"
10953                "private:\n"
10954                "\n"
10955                "  int i;\n"
10956                "\n"
10957                "protected:\n"
10958                "\n"
10959                "  int j;\n"
10960                "};\n",
10961                Style);
10962 
10963   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10964   verifyFormat("struct foo {\n"
10965                "private:\n"
10966                "\n"
10967                "  void f() {}\n"
10968                "\n"
10969                "private:\n"
10970                "\n"
10971                "  int i;\n"
10972                "\n"
10973                "protected:\n"
10974                "\n"
10975                "  int j;\n"
10976                "};\n",
10977                Style);
10978 
10979   // Check if lines are added.
10980   verifyFormat("struct foo {\n"
10981                "private:\n"
10982                "\n"
10983                "  void f() {}\n"
10984                "\n"
10985                "private:\n"
10986                "\n"
10987                "  int i;\n"
10988                "\n"
10989                "protected:\n"
10990                "\n"
10991                "  int j;\n"
10992                "};\n",
10993                "struct foo {\n"
10994                "private:\n"
10995                "  void f() {}\n"
10996                "\n"
10997                "private:\n"
10998                "  int i;\n"
10999                "\n"
11000                "protected:\n"
11001                "  int j;\n"
11002                "};\n",
11003                Style);
11004 
11005   // Leave tests rely on the code layout, test::messUp can not be used.
11006   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11007   Style.MaxEmptyLinesToKeep = 0u;
11008   verifyFormat("struct foo {\n"
11009                "private:\n"
11010                "  void f() {}\n"
11011                "\n"
11012                "private:\n"
11013                "  int i;\n"
11014                "\n"
11015                "protected:\n"
11016                "  int j;\n"
11017                "};\n",
11018                Style);
11019 
11020   // Check if MaxEmptyLinesToKeep is respected.
11021   EXPECT_EQ("struct foo {\n"
11022             "private:\n"
11023             "  void f() {}\n"
11024             "\n"
11025             "private:\n"
11026             "  int i;\n"
11027             "\n"
11028             "protected:\n"
11029             "  int j;\n"
11030             "};\n",
11031             format("struct foo {\n"
11032                    "private:\n"
11033                    "\n\n\n"
11034                    "  void f() {}\n"
11035                    "\n"
11036                    "private:\n"
11037                    "\n\n\n"
11038                    "  int i;\n"
11039                    "\n"
11040                    "protected:\n"
11041                    "\n\n\n"
11042                    "  int j;\n"
11043                    "};\n",
11044                    Style));
11045 
11046   Style.MaxEmptyLinesToKeep = 1u;
11047   EXPECT_EQ("struct foo {\n"
11048             "private:\n"
11049             "\n"
11050             "  void f() {}\n"
11051             "\n"
11052             "private:\n"
11053             "\n"
11054             "  int i;\n"
11055             "\n"
11056             "protected:\n"
11057             "\n"
11058             "  int j;\n"
11059             "};\n",
11060             format("struct foo {\n"
11061                    "private:\n"
11062                    "\n"
11063                    "  void f() {}\n"
11064                    "\n"
11065                    "private:\n"
11066                    "\n"
11067                    "  int i;\n"
11068                    "\n"
11069                    "protected:\n"
11070                    "\n"
11071                    "  int j;\n"
11072                    "};\n",
11073                    Style));
11074   // Check if no lines are kept.
11075   EXPECT_EQ("struct foo {\n"
11076             "private:\n"
11077             "  void f() {}\n"
11078             "\n"
11079             "private:\n"
11080             "  int i;\n"
11081             "\n"
11082             "protected:\n"
11083             "  int j;\n"
11084             "};\n",
11085             format("struct foo {\n"
11086                    "private:\n"
11087                    "  void f() {}\n"
11088                    "\n"
11089                    "private:\n"
11090                    "  int i;\n"
11091                    "\n"
11092                    "protected:\n"
11093                    "  int j;\n"
11094                    "};\n",
11095                    Style));
11096   // Check if MaxEmptyLinesToKeep is respected.
11097   EXPECT_EQ("struct foo {\n"
11098             "private:\n"
11099             "\n"
11100             "  void f() {}\n"
11101             "\n"
11102             "private:\n"
11103             "\n"
11104             "  int i;\n"
11105             "\n"
11106             "protected:\n"
11107             "\n"
11108             "  int j;\n"
11109             "};\n",
11110             format("struct foo {\n"
11111                    "private:\n"
11112                    "\n\n\n"
11113                    "  void f() {}\n"
11114                    "\n"
11115                    "private:\n"
11116                    "\n\n\n"
11117                    "  int i;\n"
11118                    "\n"
11119                    "protected:\n"
11120                    "\n\n\n"
11121                    "  int j;\n"
11122                    "};\n",
11123                    Style));
11124 
11125   Style.MaxEmptyLinesToKeep = 10u;
11126   EXPECT_EQ("struct foo {\n"
11127             "private:\n"
11128             "\n\n\n"
11129             "  void f() {}\n"
11130             "\n"
11131             "private:\n"
11132             "\n\n\n"
11133             "  int i;\n"
11134             "\n"
11135             "protected:\n"
11136             "\n\n\n"
11137             "  int j;\n"
11138             "};\n",
11139             format("struct foo {\n"
11140                    "private:\n"
11141                    "\n\n\n"
11142                    "  void f() {}\n"
11143                    "\n"
11144                    "private:\n"
11145                    "\n\n\n"
11146                    "  int i;\n"
11147                    "\n"
11148                    "protected:\n"
11149                    "\n\n\n"
11150                    "  int j;\n"
11151                    "};\n",
11152                    Style));
11153 
11154   // Test with comments.
11155   Style = getLLVMStyle();
11156   verifyFormat("struct foo {\n"
11157                "private:\n"
11158                "  // comment\n"
11159                "  void f() {}\n"
11160                "\n"
11161                "private: /* comment */\n"
11162                "  int i;\n"
11163                "};\n",
11164                Style);
11165   verifyFormat("struct foo {\n"
11166                "private:\n"
11167                "  // comment\n"
11168                "  void f() {}\n"
11169                "\n"
11170                "private: /* comment */\n"
11171                "  int i;\n"
11172                "};\n",
11173                "struct foo {\n"
11174                "private:\n"
11175                "\n"
11176                "  // comment\n"
11177                "  void f() {}\n"
11178                "\n"
11179                "private: /* comment */\n"
11180                "\n"
11181                "  int i;\n"
11182                "};\n",
11183                Style);
11184 
11185   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11186   verifyFormat("struct foo {\n"
11187                "private:\n"
11188                "\n"
11189                "  // comment\n"
11190                "  void f() {}\n"
11191                "\n"
11192                "private: /* comment */\n"
11193                "\n"
11194                "  int i;\n"
11195                "};\n",
11196                "struct foo {\n"
11197                "private:\n"
11198                "  // comment\n"
11199                "  void f() {}\n"
11200                "\n"
11201                "private: /* comment */\n"
11202                "  int i;\n"
11203                "};\n",
11204                Style);
11205   verifyFormat("struct foo {\n"
11206                "private:\n"
11207                "\n"
11208                "  // comment\n"
11209                "  void f() {}\n"
11210                "\n"
11211                "private: /* comment */\n"
11212                "\n"
11213                "  int i;\n"
11214                "};\n",
11215                Style);
11216 
11217   // Test with preprocessor defines.
11218   Style = getLLVMStyle();
11219   verifyFormat("struct foo {\n"
11220                "private:\n"
11221                "#ifdef FOO\n"
11222                "#endif\n"
11223                "  void f() {}\n"
11224                "};\n",
11225                Style);
11226   verifyFormat("struct foo {\n"
11227                "private:\n"
11228                "#ifdef FOO\n"
11229                "#endif\n"
11230                "  void f() {}\n"
11231                "};\n",
11232                "struct foo {\n"
11233                "private:\n"
11234                "\n"
11235                "#ifdef FOO\n"
11236                "#endif\n"
11237                "  void f() {}\n"
11238                "};\n",
11239                Style);
11240 
11241   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11242   verifyFormat("struct foo {\n"
11243                "private:\n"
11244                "\n"
11245                "#ifdef FOO\n"
11246                "#endif\n"
11247                "  void f() {}\n"
11248                "};\n",
11249                "struct foo {\n"
11250                "private:\n"
11251                "#ifdef FOO\n"
11252                "#endif\n"
11253                "  void f() {}\n"
11254                "};\n",
11255                Style);
11256   verifyFormat("struct foo {\n"
11257                "private:\n"
11258                "\n"
11259                "#ifdef FOO\n"
11260                "#endif\n"
11261                "  void f() {}\n"
11262                "};\n",
11263                Style);
11264 }
11265 
11266 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11267   // Combined tests of EmptyLineAfterAccessModifier and
11268   // EmptyLineBeforeAccessModifier.
11269   FormatStyle Style = getLLVMStyle();
11270   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11271   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11272   verifyFormat("struct foo {\n"
11273                "private:\n"
11274                "\n"
11275                "protected:\n"
11276                "};\n",
11277                Style);
11278 
11279   Style.MaxEmptyLinesToKeep = 10u;
11280   // Both remove all new lines.
11281   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11282   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11283   verifyFormat("struct foo {\n"
11284                "private:\n"
11285                "protected:\n"
11286                "};\n",
11287                "struct foo {\n"
11288                "private:\n"
11289                "\n\n\n"
11290                "protected:\n"
11291                "};\n",
11292                Style);
11293 
11294   // Leave tests rely on the code layout, test::messUp can not be used.
11295   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11296   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11297   Style.MaxEmptyLinesToKeep = 10u;
11298   EXPECT_EQ("struct foo {\n"
11299             "private:\n"
11300             "\n\n\n"
11301             "protected:\n"
11302             "};\n",
11303             format("struct foo {\n"
11304                    "private:\n"
11305                    "\n\n\n"
11306                    "protected:\n"
11307                    "};\n",
11308                    Style));
11309   Style.MaxEmptyLinesToKeep = 3u;
11310   EXPECT_EQ("struct foo {\n"
11311             "private:\n"
11312             "\n\n\n"
11313             "protected:\n"
11314             "};\n",
11315             format("struct foo {\n"
11316                    "private:\n"
11317                    "\n\n\n"
11318                    "protected:\n"
11319                    "};\n",
11320                    Style));
11321   Style.MaxEmptyLinesToKeep = 1u;
11322   EXPECT_EQ("struct foo {\n"
11323             "private:\n"
11324             "\n\n\n"
11325             "protected:\n"
11326             "};\n",
11327             format("struct foo {\n"
11328                    "private:\n"
11329                    "\n\n\n"
11330                    "protected:\n"
11331                    "};\n",
11332                    Style)); // Based on new lines in original document and not
11333                             // on the setting.
11334 
11335   Style.MaxEmptyLinesToKeep = 10u;
11336   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11337   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11338   // Newlines are kept if they are greater than zero,
11339   // test::messUp removes all new lines which changes the logic
11340   EXPECT_EQ("struct foo {\n"
11341             "private:\n"
11342             "\n\n\n"
11343             "protected:\n"
11344             "};\n",
11345             format("struct foo {\n"
11346                    "private:\n"
11347                    "\n\n\n"
11348                    "protected:\n"
11349                    "};\n",
11350                    Style));
11351 
11352   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11353   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11354   // test::messUp removes all new lines which changes the logic
11355   EXPECT_EQ("struct foo {\n"
11356             "private:\n"
11357             "\n\n\n"
11358             "protected:\n"
11359             "};\n",
11360             format("struct foo {\n"
11361                    "private:\n"
11362                    "\n\n\n"
11363                    "protected:\n"
11364                    "};\n",
11365                    Style));
11366 
11367   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11368   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11369   EXPECT_EQ("struct foo {\n"
11370             "private:\n"
11371             "\n\n\n"
11372             "protected:\n"
11373             "};\n",
11374             format("struct foo {\n"
11375                    "private:\n"
11376                    "\n\n\n"
11377                    "protected:\n"
11378                    "};\n",
11379                    Style)); // test::messUp removes all new lines which changes
11380                             // the logic.
11381 
11382   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11383   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11384   verifyFormat("struct foo {\n"
11385                "private:\n"
11386                "protected:\n"
11387                "};\n",
11388                "struct foo {\n"
11389                "private:\n"
11390                "\n\n\n"
11391                "protected:\n"
11392                "};\n",
11393                Style);
11394 
11395   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11396   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11397   EXPECT_EQ("struct foo {\n"
11398             "private:\n"
11399             "\n\n\n"
11400             "protected:\n"
11401             "};\n",
11402             format("struct foo {\n"
11403                    "private:\n"
11404                    "\n\n\n"
11405                    "protected:\n"
11406                    "};\n",
11407                    Style)); // test::messUp removes all new lines which changes
11408                             // the logic.
11409 
11410   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11411   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11412   verifyFormat("struct foo {\n"
11413                "private:\n"
11414                "protected:\n"
11415                "};\n",
11416                "struct foo {\n"
11417                "private:\n"
11418                "\n\n\n"
11419                "protected:\n"
11420                "};\n",
11421                Style);
11422 
11423   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11424   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11425   verifyFormat("struct foo {\n"
11426                "private:\n"
11427                "protected:\n"
11428                "};\n",
11429                "struct foo {\n"
11430                "private:\n"
11431                "\n\n\n"
11432                "protected:\n"
11433                "};\n",
11434                Style);
11435 
11436   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11437   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11438   verifyFormat("struct foo {\n"
11439                "private:\n"
11440                "protected:\n"
11441                "};\n",
11442                "struct foo {\n"
11443                "private:\n"
11444                "\n\n\n"
11445                "protected:\n"
11446                "};\n",
11447                Style);
11448 
11449   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11450   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11451   verifyFormat("struct foo {\n"
11452                "private:\n"
11453                "protected:\n"
11454                "};\n",
11455                "struct foo {\n"
11456                "private:\n"
11457                "\n\n\n"
11458                "protected:\n"
11459                "};\n",
11460                Style);
11461 }
11462 
11463 TEST_F(FormatTest, FormatsArrays) {
11464   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11465                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11466   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11467                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11468   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11469                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11470   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11471                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11472   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11473                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11474   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11475                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11476                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11477   verifyFormat(
11478       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11479       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11480       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11481   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11482                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11483 
11484   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11485                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11486   verifyFormat(
11487       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11488       "                                  .aaaaaaa[0]\n"
11489       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11490   verifyFormat("a[::b::c];");
11491 
11492   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11493 
11494   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11495   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11496 }
11497 
11498 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11499   verifyFormat("(a)->b();");
11500   verifyFormat("--a;");
11501 }
11502 
11503 TEST_F(FormatTest, HandlesIncludeDirectives) {
11504   verifyFormat("#include <string>\n"
11505                "#include <a/b/c.h>\n"
11506                "#include \"a/b/string\"\n"
11507                "#include \"string.h\"\n"
11508                "#include \"string.h\"\n"
11509                "#include <a-a>\n"
11510                "#include < path with space >\n"
11511                "#include_next <test.h>"
11512                "#include \"abc.h\" // this is included for ABC\n"
11513                "#include \"some long include\" // with a comment\n"
11514                "#include \"some very long include path\"\n"
11515                "#include <some/very/long/include/path>\n",
11516                getLLVMStyleWithColumns(35));
11517   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11518   EXPECT_EQ("#include <a>", format("#include<a>"));
11519 
11520   verifyFormat("#import <string>");
11521   verifyFormat("#import <a/b/c.h>");
11522   verifyFormat("#import \"a/b/string\"");
11523   verifyFormat("#import \"string.h\"");
11524   verifyFormat("#import \"string.h\"");
11525   verifyFormat("#if __has_include(<strstream>)\n"
11526                "#include <strstream>\n"
11527                "#endif");
11528 
11529   verifyFormat("#define MY_IMPORT <a/b>");
11530 
11531   verifyFormat("#if __has_include(<a/b>)");
11532   verifyFormat("#if __has_include_next(<a/b>)");
11533   verifyFormat("#define F __has_include(<a/b>)");
11534   verifyFormat("#define F __has_include_next(<a/b>)");
11535 
11536   // Protocol buffer definition or missing "#".
11537   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
11538                getLLVMStyleWithColumns(30));
11539 
11540   FormatStyle Style = getLLVMStyle();
11541   Style.AlwaysBreakBeforeMultilineStrings = true;
11542   Style.ColumnLimit = 0;
11543   verifyFormat("#import \"abc.h\"", Style);
11544 
11545   // But 'import' might also be a regular C++ namespace.
11546   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11547                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11548 }
11549 
11550 //===----------------------------------------------------------------------===//
11551 // Error recovery tests.
11552 //===----------------------------------------------------------------------===//
11553 
11554 TEST_F(FormatTest, IncompleteParameterLists) {
11555   FormatStyle NoBinPacking = getLLVMStyle();
11556   NoBinPacking.BinPackParameters = false;
11557   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
11558                "                        double *min_x,\n"
11559                "                        double *max_x,\n"
11560                "                        double *min_y,\n"
11561                "                        double *max_y,\n"
11562                "                        double *min_z,\n"
11563                "                        double *max_z, ) {}",
11564                NoBinPacking);
11565 }
11566 
11567 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
11568   verifyFormat("void f() { return; }\n42");
11569   verifyFormat("void f() {\n"
11570                "  if (0)\n"
11571                "    return;\n"
11572                "}\n"
11573                "42");
11574   verifyFormat("void f() { return }\n42");
11575   verifyFormat("void f() {\n"
11576                "  if (0)\n"
11577                "    return\n"
11578                "}\n"
11579                "42");
11580 }
11581 
11582 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
11583   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
11584   EXPECT_EQ("void f() {\n"
11585             "  if (a)\n"
11586             "    return\n"
11587             "}",
11588             format("void  f  (  )  {  if  ( a )  return  }"));
11589   EXPECT_EQ("namespace N {\n"
11590             "void f()\n"
11591             "}",
11592             format("namespace  N  {  void f()  }"));
11593   EXPECT_EQ("namespace N {\n"
11594             "void f() {}\n"
11595             "void g()\n"
11596             "} // namespace N",
11597             format("namespace N  { void f( ) { } void g( ) }"));
11598 }
11599 
11600 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
11601   verifyFormat("int aaaaaaaa =\n"
11602                "    // Overlylongcomment\n"
11603                "    b;",
11604                getLLVMStyleWithColumns(20));
11605   verifyFormat("function(\n"
11606                "    ShortArgument,\n"
11607                "    LoooooooooooongArgument);\n",
11608                getLLVMStyleWithColumns(20));
11609 }
11610 
11611 TEST_F(FormatTest, IncorrectAccessSpecifier) {
11612   verifyFormat("public:");
11613   verifyFormat("class A {\n"
11614                "public\n"
11615                "  void f() {}\n"
11616                "};");
11617   verifyFormat("public\n"
11618                "int qwerty;");
11619   verifyFormat("public\n"
11620                "B {}");
11621   verifyFormat("public\n"
11622                "{}");
11623   verifyFormat("public\n"
11624                "B { int x; }");
11625 }
11626 
11627 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
11628   verifyFormat("{");
11629   verifyFormat("#})");
11630   verifyNoCrash("(/**/[:!] ?[).");
11631 }
11632 
11633 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
11634   // Found by oss-fuzz:
11635   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
11636   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
11637   Style.ColumnLimit = 60;
11638   verifyNoCrash(
11639       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
11640       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
11641       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
11642       Style);
11643 }
11644 
11645 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
11646   verifyFormat("do {\n}");
11647   verifyFormat("do {\n}\n"
11648                "f();");
11649   verifyFormat("do {\n}\n"
11650                "wheeee(fun);");
11651   verifyFormat("do {\n"
11652                "  f();\n"
11653                "}");
11654 }
11655 
11656 TEST_F(FormatTest, IncorrectCodeMissingParens) {
11657   verifyFormat("if {\n  foo;\n  foo();\n}");
11658   verifyFormat("switch {\n  foo;\n  foo();\n}");
11659   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
11660   verifyFormat("while {\n  foo;\n  foo();\n}");
11661   verifyFormat("do {\n  foo;\n  foo();\n} while;");
11662 }
11663 
11664 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
11665   verifyIncompleteFormat("namespace {\n"
11666                          "class Foo { Foo (\n"
11667                          "};\n"
11668                          "} // namespace");
11669 }
11670 
11671 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
11672   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
11673   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
11674   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
11675   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
11676 
11677   EXPECT_EQ("{\n"
11678             "  {\n"
11679             "    breakme(\n"
11680             "        qwe);\n"
11681             "  }\n",
11682             format("{\n"
11683                    "    {\n"
11684                    " breakme(qwe);\n"
11685                    "}\n",
11686                    getLLVMStyleWithColumns(10)));
11687 }
11688 
11689 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
11690   verifyFormat("int x = {\n"
11691                "    avariable,\n"
11692                "    b(alongervariable)};",
11693                getLLVMStyleWithColumns(25));
11694 }
11695 
11696 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
11697   verifyFormat("return (a)(b){1, 2, 3};");
11698 }
11699 
11700 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
11701   verifyFormat("vector<int> x{1, 2, 3, 4};");
11702   verifyFormat("vector<int> x{\n"
11703                "    1,\n"
11704                "    2,\n"
11705                "    3,\n"
11706                "    4,\n"
11707                "};");
11708   verifyFormat("vector<T> x{{}, {}, {}, {}};");
11709   verifyFormat("f({1, 2});");
11710   verifyFormat("auto v = Foo{-1};");
11711   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
11712   verifyFormat("Class::Class : member{1, 2, 3} {}");
11713   verifyFormat("new vector<int>{1, 2, 3};");
11714   verifyFormat("new int[3]{1, 2, 3};");
11715   verifyFormat("new int{1};");
11716   verifyFormat("return {arg1, arg2};");
11717   verifyFormat("return {arg1, SomeType{parameter}};");
11718   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
11719   verifyFormat("new T{arg1, arg2};");
11720   verifyFormat("f(MyMap[{composite, key}]);");
11721   verifyFormat("class Class {\n"
11722                "  T member = {arg1, arg2};\n"
11723                "};");
11724   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
11725   verifyFormat("const struct A a = {.a = 1, .b = 2};");
11726   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
11727   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
11728   verifyFormat("int a = std::is_integral<int>{} + 0;");
11729 
11730   verifyFormat("int foo(int i) { return fo1{}(i); }");
11731   verifyFormat("int foo(int i) { return fo1{}(i); }");
11732   verifyFormat("auto i = decltype(x){};");
11733   verifyFormat("auto i = typeof(x){};");
11734   verifyFormat("auto i = _Atomic(x){};");
11735   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
11736   verifyFormat("Node n{1, Node{1000}, //\n"
11737                "       2};");
11738   verifyFormat("Aaaa aaaaaaa{\n"
11739                "    {\n"
11740                "        aaaa,\n"
11741                "    },\n"
11742                "};");
11743   verifyFormat("class C : public D {\n"
11744                "  SomeClass SC{2};\n"
11745                "};");
11746   verifyFormat("class C : public A {\n"
11747                "  class D : public B {\n"
11748                "    void f() { int i{2}; }\n"
11749                "  };\n"
11750                "};");
11751   verifyFormat("#define A {a, a},");
11752   // Don't confuse braced list initializers with compound statements.
11753   verifyFormat(
11754       "class A {\n"
11755       "  A() : a{} {}\n"
11756       "  A(int b) : b(b) {}\n"
11757       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
11758       "  int a, b;\n"
11759       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
11760       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
11761       "{}\n"
11762       "};");
11763 
11764   // Avoid breaking between equal sign and opening brace
11765   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
11766   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
11767   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
11768                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
11769                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
11770                "     {\"ccccccccccccccccccccc\", 2}};",
11771                AvoidBreakingFirstArgument);
11772 
11773   // Binpacking only if there is no trailing comma
11774   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
11775                "                      cccccccccc, dddddddddd};",
11776                getLLVMStyleWithColumns(50));
11777   verifyFormat("const Aaaaaa aaaaa = {\n"
11778                "    aaaaaaaaaaa,\n"
11779                "    bbbbbbbbbbb,\n"
11780                "    ccccccccccc,\n"
11781                "    ddddddddddd,\n"
11782                "};",
11783                getLLVMStyleWithColumns(50));
11784 
11785   // Cases where distinguising braced lists and blocks is hard.
11786   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
11787   verifyFormat("void f() {\n"
11788                "  return; // comment\n"
11789                "}\n"
11790                "SomeType t;");
11791   verifyFormat("void f() {\n"
11792                "  if (a) {\n"
11793                "    f();\n"
11794                "  }\n"
11795                "}\n"
11796                "SomeType t;");
11797 
11798   // In combination with BinPackArguments = false.
11799   FormatStyle NoBinPacking = getLLVMStyle();
11800   NoBinPacking.BinPackArguments = false;
11801   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
11802                "                      bbbbb,\n"
11803                "                      ccccc,\n"
11804                "                      ddddd,\n"
11805                "                      eeeee,\n"
11806                "                      ffffff,\n"
11807                "                      ggggg,\n"
11808                "                      hhhhhh,\n"
11809                "                      iiiiii,\n"
11810                "                      jjjjjj,\n"
11811                "                      kkkkkk};",
11812                NoBinPacking);
11813   verifyFormat("const Aaaaaa aaaaa = {\n"
11814                "    aaaaa,\n"
11815                "    bbbbb,\n"
11816                "    ccccc,\n"
11817                "    ddddd,\n"
11818                "    eeeee,\n"
11819                "    ffffff,\n"
11820                "    ggggg,\n"
11821                "    hhhhhh,\n"
11822                "    iiiiii,\n"
11823                "    jjjjjj,\n"
11824                "    kkkkkk,\n"
11825                "};",
11826                NoBinPacking);
11827   verifyFormat(
11828       "const Aaaaaa aaaaa = {\n"
11829       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
11830       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
11831       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
11832       "};",
11833       NoBinPacking);
11834 
11835   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11836   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
11837             "    CDDDP83848_BMCR_REGISTER,\n"
11838             "    CDDDP83848_BMSR_REGISTER,\n"
11839             "    CDDDP83848_RBR_REGISTER};",
11840             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
11841                    "                                CDDDP83848_BMSR_REGISTER,\n"
11842                    "                                CDDDP83848_RBR_REGISTER};",
11843                    NoBinPacking));
11844 
11845   // FIXME: The alignment of these trailing comments might be bad. Then again,
11846   // this might be utterly useless in real code.
11847   verifyFormat("Constructor::Constructor()\n"
11848                "    : some_value{         //\n"
11849                "                 aaaaaaa, //\n"
11850                "                 bbbbbbb} {}");
11851 
11852   // In braced lists, the first comment is always assumed to belong to the
11853   // first element. Thus, it can be moved to the next or previous line as
11854   // appropriate.
11855   EXPECT_EQ("function({// First element:\n"
11856             "          1,\n"
11857             "          // Second element:\n"
11858             "          2});",
11859             format("function({\n"
11860                    "    // First element:\n"
11861                    "    1,\n"
11862                    "    // Second element:\n"
11863                    "    2});"));
11864   EXPECT_EQ("std::vector<int> MyNumbers{\n"
11865             "    // First element:\n"
11866             "    1,\n"
11867             "    // Second element:\n"
11868             "    2};",
11869             format("std::vector<int> MyNumbers{// First element:\n"
11870                    "                           1,\n"
11871                    "                           // Second element:\n"
11872                    "                           2};",
11873                    getLLVMStyleWithColumns(30)));
11874   // A trailing comma should still lead to an enforced line break and no
11875   // binpacking.
11876   EXPECT_EQ("vector<int> SomeVector = {\n"
11877             "    // aaa\n"
11878             "    1,\n"
11879             "    2,\n"
11880             "};",
11881             format("vector<int> SomeVector = { // aaa\n"
11882                    "    1, 2, };"));
11883 
11884   // C++11 brace initializer list l-braces should not be treated any differently
11885   // when breaking before lambda bodies is enabled
11886   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
11887   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
11888   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
11889   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
11890   verifyFormat(
11891       "std::runtime_error{\n"
11892       "    \"Long string which will force a break onto the next line...\"};",
11893       BreakBeforeLambdaBody);
11894 
11895   FormatStyle ExtraSpaces = getLLVMStyle();
11896   ExtraSpaces.Cpp11BracedListStyle = false;
11897   ExtraSpaces.ColumnLimit = 75;
11898   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
11899   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
11900   verifyFormat("f({ 1, 2 });", ExtraSpaces);
11901   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
11902   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
11903   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
11904   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
11905   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
11906   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
11907   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
11908   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
11909   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
11910   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
11911   verifyFormat("class Class {\n"
11912                "  T member = { arg1, arg2 };\n"
11913                "};",
11914                ExtraSpaces);
11915   verifyFormat(
11916       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11917       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
11918       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
11919       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
11920       ExtraSpaces);
11921   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
11922   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
11923                ExtraSpaces);
11924   verifyFormat(
11925       "someFunction(OtherParam,\n"
11926       "             BracedList{ // comment 1 (Forcing interesting break)\n"
11927       "                         param1, param2,\n"
11928       "                         // comment 2\n"
11929       "                         param3, param4 });",
11930       ExtraSpaces);
11931   verifyFormat(
11932       "std::this_thread::sleep_for(\n"
11933       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
11934       ExtraSpaces);
11935   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
11936                "    aaaaaaa,\n"
11937                "    aaaaaaaaaa,\n"
11938                "    aaaaa,\n"
11939                "    aaaaaaaaaaaaaaa,\n"
11940                "    aaa,\n"
11941                "    aaaaaaaaaa,\n"
11942                "    a,\n"
11943                "    aaaaaaaaaaaaaaaaaaaaa,\n"
11944                "    aaaaaaaaaaaa,\n"
11945                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
11946                "    aaaaaaa,\n"
11947                "    a};");
11948   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
11949   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
11950   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
11951 
11952   // Avoid breaking between initializer/equal sign and opening brace
11953   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
11954   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
11955                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11956                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11957                "  { \"ccccccccccccccccccccc\", 2 }\n"
11958                "};",
11959                ExtraSpaces);
11960   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
11961                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11962                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11963                "  { \"ccccccccccccccccccccc\", 2 }\n"
11964                "};",
11965                ExtraSpaces);
11966 
11967   FormatStyle SpaceBeforeBrace = getLLVMStyle();
11968   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
11969   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
11970   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
11971 
11972   FormatStyle SpaceBetweenBraces = getLLVMStyle();
11973   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
11974   SpaceBetweenBraces.SpacesInParentheses = true;
11975   SpaceBetweenBraces.SpacesInSquareBrackets = true;
11976   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
11977   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
11978   verifyFormat("vector< int > x{ // comment 1\n"
11979                "                 1, 2, 3, 4 };",
11980                SpaceBetweenBraces);
11981   SpaceBetweenBraces.ColumnLimit = 20;
11982   EXPECT_EQ("vector< int > x{\n"
11983             "    1, 2, 3, 4 };",
11984             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11985   SpaceBetweenBraces.ColumnLimit = 24;
11986   EXPECT_EQ("vector< int > x{ 1, 2,\n"
11987             "                 3, 4 };",
11988             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11989   EXPECT_EQ("vector< int > x{\n"
11990             "    1,\n"
11991             "    2,\n"
11992             "    3,\n"
11993             "    4,\n"
11994             "};",
11995             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
11996   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
11997   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
11998   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
11999 }
12000 
12001 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12002   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12003                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12004                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12005                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12006                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12007                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12008   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12009                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12010                "                 1, 22, 333, 4444, 55555, //\n"
12011                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12012                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12013   verifyFormat(
12014       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12015       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12016       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12017       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12018       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12019       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12020       "                 7777777};");
12021   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12022                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12023                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12024   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12025                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12026                "    // Separating comment.\n"
12027                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12028   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12029                "    // Leading comment\n"
12030                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12031                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12032   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12033                "                 1, 1, 1, 1};",
12034                getLLVMStyleWithColumns(39));
12035   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12036                "                 1, 1, 1, 1};",
12037                getLLVMStyleWithColumns(38));
12038   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12039                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12040                getLLVMStyleWithColumns(43));
12041   verifyFormat(
12042       "static unsigned SomeValues[10][3] = {\n"
12043       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12044       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12045   verifyFormat("static auto fields = new vector<string>{\n"
12046                "    \"aaaaaaaaaaaaa\",\n"
12047                "    \"aaaaaaaaaaaaa\",\n"
12048                "    \"aaaaaaaaaaaa\",\n"
12049                "    \"aaaaaaaaaaaaaa\",\n"
12050                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12051                "    \"aaaaaaaaaaaa\",\n"
12052                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12053                "};");
12054   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12055   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12056                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12057                "                 3, cccccccccccccccccccccc};",
12058                getLLVMStyleWithColumns(60));
12059 
12060   // Trailing commas.
12061   verifyFormat("vector<int> x = {\n"
12062                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12063                "};",
12064                getLLVMStyleWithColumns(39));
12065   verifyFormat("vector<int> x = {\n"
12066                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12067                "};",
12068                getLLVMStyleWithColumns(39));
12069   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12070                "                 1, 1, 1, 1,\n"
12071                "                 /**/ /**/};",
12072                getLLVMStyleWithColumns(39));
12073 
12074   // Trailing comment in the first line.
12075   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12076                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12077                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12078                "    11111111,   22222222,   333333333,   44444444};");
12079   // Trailing comment in the last line.
12080   verifyFormat("int aaaaa[] = {\n"
12081                "    1, 2, 3, // comment\n"
12082                "    4, 5, 6  // comment\n"
12083                "};");
12084 
12085   // With nested lists, we should either format one item per line or all nested
12086   // lists one on line.
12087   // FIXME: For some nested lists, we can do better.
12088   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12089                "        {aaaaaaaaaaaaaaaaaaa},\n"
12090                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12091                "        {aaaaaaaaaaaaaaaaa}};",
12092                getLLVMStyleWithColumns(60));
12093   verifyFormat(
12094       "SomeStruct my_struct_array = {\n"
12095       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12096       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12097       "    {aaa, aaa},\n"
12098       "    {aaa, aaa},\n"
12099       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12100       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12101       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12102 
12103   // No column layout should be used here.
12104   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12105                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12106 
12107   verifyNoCrash("a<,");
12108 
12109   // No braced initializer here.
12110   verifyFormat("void f() {\n"
12111                "  struct Dummy {};\n"
12112                "  f(v);\n"
12113                "}");
12114 
12115   // Long lists should be formatted in columns even if they are nested.
12116   verifyFormat(
12117       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12118       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12119       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12120       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12121       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12122       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12123 
12124   // Allow "single-column" layout even if that violates the column limit. There
12125   // isn't going to be a better way.
12126   verifyFormat("std::vector<int> a = {\n"
12127                "    aaaaaaaa,\n"
12128                "    aaaaaaaa,\n"
12129                "    aaaaaaaa,\n"
12130                "    aaaaaaaa,\n"
12131                "    aaaaaaaaaa,\n"
12132                "    aaaaaaaa,\n"
12133                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12134                getLLVMStyleWithColumns(30));
12135   verifyFormat("vector<int> aaaa = {\n"
12136                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12137                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12138                "    aaaaaa.aaaaaaa,\n"
12139                "    aaaaaa.aaaaaaa,\n"
12140                "    aaaaaa.aaaaaaa,\n"
12141                "    aaaaaa.aaaaaaa,\n"
12142                "};");
12143 
12144   // Don't create hanging lists.
12145   verifyFormat("someFunction(Param, {List1, List2,\n"
12146                "                     List3});",
12147                getLLVMStyleWithColumns(35));
12148   verifyFormat("someFunction(Param, Param,\n"
12149                "             {List1, List2,\n"
12150                "              List3});",
12151                getLLVMStyleWithColumns(35));
12152   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12153                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12154 }
12155 
12156 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12157   FormatStyle DoNotMerge = getLLVMStyle();
12158   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12159 
12160   verifyFormat("void f() { return 42; }");
12161   verifyFormat("void f() {\n"
12162                "  return 42;\n"
12163                "}",
12164                DoNotMerge);
12165   verifyFormat("void f() {\n"
12166                "  // Comment\n"
12167                "}");
12168   verifyFormat("{\n"
12169                "#error {\n"
12170                "  int a;\n"
12171                "}");
12172   verifyFormat("{\n"
12173                "  int a;\n"
12174                "#error {\n"
12175                "}");
12176   verifyFormat("void f() {} // comment");
12177   verifyFormat("void f() { int a; } // comment");
12178   verifyFormat("void f() {\n"
12179                "} // comment",
12180                DoNotMerge);
12181   verifyFormat("void f() {\n"
12182                "  int a;\n"
12183                "} // comment",
12184                DoNotMerge);
12185   verifyFormat("void f() {\n"
12186                "} // comment",
12187                getLLVMStyleWithColumns(15));
12188 
12189   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12190   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12191 
12192   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12193   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12194   verifyFormat("class C {\n"
12195                "  C()\n"
12196                "      : iiiiiiii(nullptr),\n"
12197                "        kkkkkkk(nullptr),\n"
12198                "        mmmmmmm(nullptr),\n"
12199                "        nnnnnnn(nullptr) {}\n"
12200                "};",
12201                getGoogleStyle());
12202 
12203   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12204   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12205   EXPECT_EQ("class C {\n"
12206             "  A() : b(0) {}\n"
12207             "};",
12208             format("class C{A():b(0){}};", NoColumnLimit));
12209   EXPECT_EQ("A()\n"
12210             "    : b(0) {\n"
12211             "}",
12212             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12213 
12214   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12215   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12216       FormatStyle::SFS_None;
12217   EXPECT_EQ("A()\n"
12218             "    : b(0) {\n"
12219             "}",
12220             format("A():b(0){}", DoNotMergeNoColumnLimit));
12221   EXPECT_EQ("A()\n"
12222             "    : b(0) {\n"
12223             "}",
12224             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12225 
12226   verifyFormat("#define A          \\\n"
12227                "  void f() {       \\\n"
12228                "    int i;         \\\n"
12229                "  }",
12230                getLLVMStyleWithColumns(20));
12231   verifyFormat("#define A           \\\n"
12232                "  void f() { int i; }",
12233                getLLVMStyleWithColumns(21));
12234   verifyFormat("#define A            \\\n"
12235                "  void f() {         \\\n"
12236                "    int i;           \\\n"
12237                "  }                  \\\n"
12238                "  int j;",
12239                getLLVMStyleWithColumns(22));
12240   verifyFormat("#define A             \\\n"
12241                "  void f() { int i; } \\\n"
12242                "  int j;",
12243                getLLVMStyleWithColumns(23));
12244 }
12245 
12246 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12247   FormatStyle MergeEmptyOnly = getLLVMStyle();
12248   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12249   verifyFormat("class C {\n"
12250                "  int f() {}\n"
12251                "};",
12252                MergeEmptyOnly);
12253   verifyFormat("class C {\n"
12254                "  int f() {\n"
12255                "    return 42;\n"
12256                "  }\n"
12257                "};",
12258                MergeEmptyOnly);
12259   verifyFormat("int f() {}", MergeEmptyOnly);
12260   verifyFormat("int f() {\n"
12261                "  return 42;\n"
12262                "}",
12263                MergeEmptyOnly);
12264 
12265   // Also verify behavior when BraceWrapping.AfterFunction = true
12266   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12267   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12268   verifyFormat("int f() {}", MergeEmptyOnly);
12269   verifyFormat("class C {\n"
12270                "  int f() {}\n"
12271                "};",
12272                MergeEmptyOnly);
12273 }
12274 
12275 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12276   FormatStyle MergeInlineOnly = getLLVMStyle();
12277   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12278   verifyFormat("class C {\n"
12279                "  int f() { return 42; }\n"
12280                "};",
12281                MergeInlineOnly);
12282   verifyFormat("int f() {\n"
12283                "  return 42;\n"
12284                "}",
12285                MergeInlineOnly);
12286 
12287   // SFS_Inline implies SFS_Empty
12288   verifyFormat("class C {\n"
12289                "  int f() {}\n"
12290                "};",
12291                MergeInlineOnly);
12292   verifyFormat("int f() {}", MergeInlineOnly);
12293 
12294   // Also verify behavior when BraceWrapping.AfterFunction = true
12295   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12296   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12297   verifyFormat("class C {\n"
12298                "  int f() { return 42; }\n"
12299                "};",
12300                MergeInlineOnly);
12301   verifyFormat("int f()\n"
12302                "{\n"
12303                "  return 42;\n"
12304                "}",
12305                MergeInlineOnly);
12306 
12307   // SFS_Inline implies SFS_Empty
12308   verifyFormat("int f() {}", MergeInlineOnly);
12309   verifyFormat("class C {\n"
12310                "  int f() {}\n"
12311                "};",
12312                MergeInlineOnly);
12313 }
12314 
12315 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12316   FormatStyle MergeInlineOnly = getLLVMStyle();
12317   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12318       FormatStyle::SFS_InlineOnly;
12319   verifyFormat("class C {\n"
12320                "  int f() { return 42; }\n"
12321                "};",
12322                MergeInlineOnly);
12323   verifyFormat("int f() {\n"
12324                "  return 42;\n"
12325                "}",
12326                MergeInlineOnly);
12327 
12328   // SFS_InlineOnly does not imply SFS_Empty
12329   verifyFormat("class C {\n"
12330                "  int f() {}\n"
12331                "};",
12332                MergeInlineOnly);
12333   verifyFormat("int f() {\n"
12334                "}",
12335                MergeInlineOnly);
12336 
12337   // Also verify behavior when BraceWrapping.AfterFunction = true
12338   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12339   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12340   verifyFormat("class C {\n"
12341                "  int f() { return 42; }\n"
12342                "};",
12343                MergeInlineOnly);
12344   verifyFormat("int f()\n"
12345                "{\n"
12346                "  return 42;\n"
12347                "}",
12348                MergeInlineOnly);
12349 
12350   // SFS_InlineOnly does not imply SFS_Empty
12351   verifyFormat("int f()\n"
12352                "{\n"
12353                "}",
12354                MergeInlineOnly);
12355   verifyFormat("class C {\n"
12356                "  int f() {}\n"
12357                "};",
12358                MergeInlineOnly);
12359 }
12360 
12361 TEST_F(FormatTest, SplitEmptyFunction) {
12362   FormatStyle Style = getLLVMStyleWithColumns(40);
12363   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12364   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12365   Style.BraceWrapping.AfterFunction = true;
12366   Style.BraceWrapping.SplitEmptyFunction = false;
12367 
12368   verifyFormat("int f()\n"
12369                "{}",
12370                Style);
12371   verifyFormat("int f()\n"
12372                "{\n"
12373                "  return 42;\n"
12374                "}",
12375                Style);
12376   verifyFormat("int f()\n"
12377                "{\n"
12378                "  // some comment\n"
12379                "}",
12380                Style);
12381 
12382   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12383   verifyFormat("int f() {}", Style);
12384   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12385                "{}",
12386                Style);
12387   verifyFormat("int f()\n"
12388                "{\n"
12389                "  return 0;\n"
12390                "}",
12391                Style);
12392 
12393   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12394   verifyFormat("class Foo {\n"
12395                "  int f() {}\n"
12396                "};\n",
12397                Style);
12398   verifyFormat("class Foo {\n"
12399                "  int f() { return 0; }\n"
12400                "};\n",
12401                Style);
12402   verifyFormat("class Foo {\n"
12403                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12404                "  {}\n"
12405                "};\n",
12406                Style);
12407   verifyFormat("class Foo {\n"
12408                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12409                "  {\n"
12410                "    return 0;\n"
12411                "  }\n"
12412                "};\n",
12413                Style);
12414 
12415   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12416   verifyFormat("int f() {}", Style);
12417   verifyFormat("int f() { return 0; }", Style);
12418   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12419                "{}",
12420                Style);
12421   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12422                "{\n"
12423                "  return 0;\n"
12424                "}",
12425                Style);
12426 }
12427 
12428 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12429   FormatStyle Style = getLLVMStyleWithColumns(40);
12430   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12431   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12432   Style.BraceWrapping.AfterFunction = true;
12433   Style.BraceWrapping.SplitEmptyFunction = true;
12434   Style.BraceWrapping.SplitEmptyRecord = false;
12435 
12436   verifyFormat("class C {};", Style);
12437   verifyFormat("struct C {};", Style);
12438   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12439                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12440                "{\n"
12441                "}",
12442                Style);
12443   verifyFormat("class C {\n"
12444                "  C()\n"
12445                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12446                "        bbbbbbbbbbbbbbbbbbb()\n"
12447                "  {\n"
12448                "  }\n"
12449                "  void\n"
12450                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12451                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12452                "  {\n"
12453                "  }\n"
12454                "};",
12455                Style);
12456 }
12457 
12458 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12459   FormatStyle Style = getLLVMStyle();
12460   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12461   verifyFormat("#ifdef A\n"
12462                "int f() {}\n"
12463                "#else\n"
12464                "int g() {}\n"
12465                "#endif",
12466                Style);
12467 }
12468 
12469 TEST_F(FormatTest, SplitEmptyClass) {
12470   FormatStyle Style = getLLVMStyle();
12471   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12472   Style.BraceWrapping.AfterClass = true;
12473   Style.BraceWrapping.SplitEmptyRecord = false;
12474 
12475   verifyFormat("class Foo\n"
12476                "{};",
12477                Style);
12478   verifyFormat("/* something */ class Foo\n"
12479                "{};",
12480                Style);
12481   verifyFormat("template <typename X> class Foo\n"
12482                "{};",
12483                Style);
12484   verifyFormat("class Foo\n"
12485                "{\n"
12486                "  Foo();\n"
12487                "};",
12488                Style);
12489   verifyFormat("typedef class Foo\n"
12490                "{\n"
12491                "} Foo_t;",
12492                Style);
12493 
12494   Style.BraceWrapping.SplitEmptyRecord = true;
12495   Style.BraceWrapping.AfterStruct = true;
12496   verifyFormat("class rep\n"
12497                "{\n"
12498                "};",
12499                Style);
12500   verifyFormat("struct rep\n"
12501                "{\n"
12502                "};",
12503                Style);
12504   verifyFormat("template <typename T> class rep\n"
12505                "{\n"
12506                "};",
12507                Style);
12508   verifyFormat("template <typename T> struct rep\n"
12509                "{\n"
12510                "};",
12511                Style);
12512   verifyFormat("class rep\n"
12513                "{\n"
12514                "  int x;\n"
12515                "};",
12516                Style);
12517   verifyFormat("struct rep\n"
12518                "{\n"
12519                "  int x;\n"
12520                "};",
12521                Style);
12522   verifyFormat("template <typename T> class rep\n"
12523                "{\n"
12524                "  int x;\n"
12525                "};",
12526                Style);
12527   verifyFormat("template <typename T> struct rep\n"
12528                "{\n"
12529                "  int x;\n"
12530                "};",
12531                Style);
12532   verifyFormat("template <typename T> class rep // Foo\n"
12533                "{\n"
12534                "  int x;\n"
12535                "};",
12536                Style);
12537   verifyFormat("template <typename T> struct rep // Bar\n"
12538                "{\n"
12539                "  int x;\n"
12540                "};",
12541                Style);
12542 
12543   verifyFormat("template <typename T> class rep<T>\n"
12544                "{\n"
12545                "  int x;\n"
12546                "};",
12547                Style);
12548 
12549   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12550                "{\n"
12551                "  int x;\n"
12552                "};",
12553                Style);
12554   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12555                "{\n"
12556                "};",
12557                Style);
12558 
12559   verifyFormat("#include \"stdint.h\"\n"
12560                "namespace rep {}",
12561                Style);
12562   verifyFormat("#include <stdint.h>\n"
12563                "namespace rep {}",
12564                Style);
12565   verifyFormat("#include <stdint.h>\n"
12566                "namespace rep {}",
12567                "#include <stdint.h>\n"
12568                "namespace rep {\n"
12569                "\n"
12570                "\n"
12571                "}",
12572                Style);
12573 }
12574 
12575 TEST_F(FormatTest, SplitEmptyStruct) {
12576   FormatStyle Style = getLLVMStyle();
12577   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12578   Style.BraceWrapping.AfterStruct = true;
12579   Style.BraceWrapping.SplitEmptyRecord = false;
12580 
12581   verifyFormat("struct Foo\n"
12582                "{};",
12583                Style);
12584   verifyFormat("/* something */ struct Foo\n"
12585                "{};",
12586                Style);
12587   verifyFormat("template <typename X> struct Foo\n"
12588                "{};",
12589                Style);
12590   verifyFormat("struct Foo\n"
12591                "{\n"
12592                "  Foo();\n"
12593                "};",
12594                Style);
12595   verifyFormat("typedef struct Foo\n"
12596                "{\n"
12597                "} Foo_t;",
12598                Style);
12599   // typedef struct Bar {} Bar_t;
12600 }
12601 
12602 TEST_F(FormatTest, SplitEmptyUnion) {
12603   FormatStyle Style = getLLVMStyle();
12604   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12605   Style.BraceWrapping.AfterUnion = true;
12606   Style.BraceWrapping.SplitEmptyRecord = false;
12607 
12608   verifyFormat("union Foo\n"
12609                "{};",
12610                Style);
12611   verifyFormat("/* something */ union Foo\n"
12612                "{};",
12613                Style);
12614   verifyFormat("union Foo\n"
12615                "{\n"
12616                "  A,\n"
12617                "};",
12618                Style);
12619   verifyFormat("typedef union Foo\n"
12620                "{\n"
12621                "} Foo_t;",
12622                Style);
12623 }
12624 
12625 TEST_F(FormatTest, SplitEmptyNamespace) {
12626   FormatStyle Style = getLLVMStyle();
12627   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12628   Style.BraceWrapping.AfterNamespace = true;
12629   Style.BraceWrapping.SplitEmptyNamespace = false;
12630 
12631   verifyFormat("namespace Foo\n"
12632                "{};",
12633                Style);
12634   verifyFormat("/* something */ namespace Foo\n"
12635                "{};",
12636                Style);
12637   verifyFormat("inline namespace Foo\n"
12638                "{};",
12639                Style);
12640   verifyFormat("/* something */ inline namespace Foo\n"
12641                "{};",
12642                Style);
12643   verifyFormat("export namespace Foo\n"
12644                "{};",
12645                Style);
12646   verifyFormat("namespace Foo\n"
12647                "{\n"
12648                "void Bar();\n"
12649                "};",
12650                Style);
12651 }
12652 
12653 TEST_F(FormatTest, NeverMergeShortRecords) {
12654   FormatStyle Style = getLLVMStyle();
12655 
12656   verifyFormat("class Foo {\n"
12657                "  Foo();\n"
12658                "};",
12659                Style);
12660   verifyFormat("typedef class Foo {\n"
12661                "  Foo();\n"
12662                "} Foo_t;",
12663                Style);
12664   verifyFormat("struct Foo {\n"
12665                "  Foo();\n"
12666                "};",
12667                Style);
12668   verifyFormat("typedef struct Foo {\n"
12669                "  Foo();\n"
12670                "} Foo_t;",
12671                Style);
12672   verifyFormat("union Foo {\n"
12673                "  A,\n"
12674                "};",
12675                Style);
12676   verifyFormat("typedef union Foo {\n"
12677                "  A,\n"
12678                "} Foo_t;",
12679                Style);
12680   verifyFormat("namespace Foo {\n"
12681                "void Bar();\n"
12682                "};",
12683                Style);
12684 
12685   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12686   Style.BraceWrapping.AfterClass = true;
12687   Style.BraceWrapping.AfterStruct = true;
12688   Style.BraceWrapping.AfterUnion = true;
12689   Style.BraceWrapping.AfterNamespace = true;
12690   verifyFormat("class Foo\n"
12691                "{\n"
12692                "  Foo();\n"
12693                "};",
12694                Style);
12695   verifyFormat("typedef class Foo\n"
12696                "{\n"
12697                "  Foo();\n"
12698                "} Foo_t;",
12699                Style);
12700   verifyFormat("struct Foo\n"
12701                "{\n"
12702                "  Foo();\n"
12703                "};",
12704                Style);
12705   verifyFormat("typedef struct Foo\n"
12706                "{\n"
12707                "  Foo();\n"
12708                "} Foo_t;",
12709                Style);
12710   verifyFormat("union Foo\n"
12711                "{\n"
12712                "  A,\n"
12713                "};",
12714                Style);
12715   verifyFormat("typedef union Foo\n"
12716                "{\n"
12717                "  A,\n"
12718                "} Foo_t;",
12719                Style);
12720   verifyFormat("namespace Foo\n"
12721                "{\n"
12722                "void Bar();\n"
12723                "};",
12724                Style);
12725 }
12726 
12727 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
12728   // Elaborate type variable declarations.
12729   verifyFormat("struct foo a = {bar};\nint n;");
12730   verifyFormat("class foo a = {bar};\nint n;");
12731   verifyFormat("union foo a = {bar};\nint n;");
12732 
12733   // Elaborate types inside function definitions.
12734   verifyFormat("struct foo f() {}\nint n;");
12735   verifyFormat("class foo f() {}\nint n;");
12736   verifyFormat("union foo f() {}\nint n;");
12737 
12738   // Templates.
12739   verifyFormat("template <class X> void f() {}\nint n;");
12740   verifyFormat("template <struct X> void f() {}\nint n;");
12741   verifyFormat("template <union X> void f() {}\nint n;");
12742 
12743   // Actual definitions...
12744   verifyFormat("struct {\n} n;");
12745   verifyFormat(
12746       "template <template <class T, class Y>, class Z> class X {\n} n;");
12747   verifyFormat("union Z {\n  int n;\n} x;");
12748   verifyFormat("class MACRO Z {\n} n;");
12749   verifyFormat("class MACRO(X) Z {\n} n;");
12750   verifyFormat("class __attribute__(X) Z {\n} n;");
12751   verifyFormat("class __declspec(X) Z {\n} n;");
12752   verifyFormat("class A##B##C {\n} n;");
12753   verifyFormat("class alignas(16) Z {\n} n;");
12754   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
12755   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
12756 
12757   // Redefinition from nested context:
12758   verifyFormat("class A::B::C {\n} n;");
12759 
12760   // Template definitions.
12761   verifyFormat(
12762       "template <typename F>\n"
12763       "Matcher(const Matcher<F> &Other,\n"
12764       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
12765       "                             !is_same<F, T>::value>::type * = 0)\n"
12766       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
12767 
12768   // FIXME: This is still incorrectly handled at the formatter side.
12769   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
12770   verifyFormat("int i = SomeFunction(a<b, a> b);");
12771 
12772   // FIXME:
12773   // This now gets parsed incorrectly as class definition.
12774   // verifyFormat("class A<int> f() {\n}\nint n;");
12775 
12776   // Elaborate types where incorrectly parsing the structural element would
12777   // break the indent.
12778   verifyFormat("if (true)\n"
12779                "  class X x;\n"
12780                "else\n"
12781                "  f();\n");
12782 
12783   // This is simply incomplete. Formatting is not important, but must not crash.
12784   verifyFormat("class A:");
12785 }
12786 
12787 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
12788   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
12789             format("#error Leave     all         white!!!!! space* alone!\n"));
12790   EXPECT_EQ(
12791       "#warning Leave     all         white!!!!! space* alone!\n",
12792       format("#warning Leave     all         white!!!!! space* alone!\n"));
12793   EXPECT_EQ("#error 1", format("  #  error   1"));
12794   EXPECT_EQ("#warning 1", format("  #  warning 1"));
12795 }
12796 
12797 TEST_F(FormatTest, FormatHashIfExpressions) {
12798   verifyFormat("#if AAAA && BBBB");
12799   verifyFormat("#if (AAAA && BBBB)");
12800   verifyFormat("#elif (AAAA && BBBB)");
12801   // FIXME: Come up with a better indentation for #elif.
12802   verifyFormat(
12803       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
12804       "    defined(BBBBBBBB)\n"
12805       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
12806       "    defined(BBBBBBBB)\n"
12807       "#endif",
12808       getLLVMStyleWithColumns(65));
12809 }
12810 
12811 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
12812   FormatStyle AllowsMergedIf = getGoogleStyle();
12813   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
12814       FormatStyle::SIS_WithoutElse;
12815   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
12816   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
12817   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
12818   EXPECT_EQ("if (true) return 42;",
12819             format("if (true)\nreturn 42;", AllowsMergedIf));
12820   FormatStyle ShortMergedIf = AllowsMergedIf;
12821   ShortMergedIf.ColumnLimit = 25;
12822   verifyFormat("#define A \\\n"
12823                "  if (true) return 42;",
12824                ShortMergedIf);
12825   verifyFormat("#define A \\\n"
12826                "  f();    \\\n"
12827                "  if (true)\n"
12828                "#define B",
12829                ShortMergedIf);
12830   verifyFormat("#define A \\\n"
12831                "  f();    \\\n"
12832                "  if (true)\n"
12833                "g();",
12834                ShortMergedIf);
12835   verifyFormat("{\n"
12836                "#ifdef A\n"
12837                "  // Comment\n"
12838                "  if (true) continue;\n"
12839                "#endif\n"
12840                "  // Comment\n"
12841                "  if (true) continue;\n"
12842                "}",
12843                ShortMergedIf);
12844   ShortMergedIf.ColumnLimit = 33;
12845   verifyFormat("#define A \\\n"
12846                "  if constexpr (true) return 42;",
12847                ShortMergedIf);
12848   verifyFormat("#define A \\\n"
12849                "  if CONSTEXPR (true) return 42;",
12850                ShortMergedIf);
12851   ShortMergedIf.ColumnLimit = 29;
12852   verifyFormat("#define A                   \\\n"
12853                "  if (aaaaaaaaaa) return 1; \\\n"
12854                "  return 2;",
12855                ShortMergedIf);
12856   ShortMergedIf.ColumnLimit = 28;
12857   verifyFormat("#define A         \\\n"
12858                "  if (aaaaaaaaaa) \\\n"
12859                "    return 1;     \\\n"
12860                "  return 2;",
12861                ShortMergedIf);
12862   verifyFormat("#define A                \\\n"
12863                "  if constexpr (aaaaaaa) \\\n"
12864                "    return 1;            \\\n"
12865                "  return 2;",
12866                ShortMergedIf);
12867   verifyFormat("#define A                \\\n"
12868                "  if CONSTEXPR (aaaaaaa) \\\n"
12869                "    return 1;            \\\n"
12870                "  return 2;",
12871                ShortMergedIf);
12872 }
12873 
12874 TEST_F(FormatTest, FormatStarDependingOnContext) {
12875   verifyFormat("void f(int *a);");
12876   verifyFormat("void f() { f(fint * b); }");
12877   verifyFormat("class A {\n  void f(int *a);\n};");
12878   verifyFormat("class A {\n  int *a;\n};");
12879   verifyFormat("namespace a {\n"
12880                "namespace b {\n"
12881                "class A {\n"
12882                "  void f() {}\n"
12883                "  int *a;\n"
12884                "};\n"
12885                "} // namespace b\n"
12886                "} // namespace a");
12887 }
12888 
12889 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
12890   verifyFormat("while");
12891   verifyFormat("operator");
12892 }
12893 
12894 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
12895   // This code would be painfully slow to format if we didn't skip it.
12896   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
12897                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12898                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12899                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12900                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12901                    "A(1, 1)\n"
12902                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
12903                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12904                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12905                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12906                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12907                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12908                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12909                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12910                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12911                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
12912   // Deeply nested part is untouched, rest is formatted.
12913   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
12914             format(std::string("int    i;\n") + Code + "int    j;\n",
12915                    getLLVMStyle(), SC_ExpectIncomplete));
12916 }
12917 
12918 //===----------------------------------------------------------------------===//
12919 // Objective-C tests.
12920 //===----------------------------------------------------------------------===//
12921 
12922 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
12923   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
12924   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
12925             format("-(NSUInteger)indexOfObject:(id)anObject;"));
12926   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
12927   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
12928   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
12929             format("-(NSInteger)Method3:(id)anObject;"));
12930   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
12931             format("-(NSInteger)Method4:(id)anObject;"));
12932   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
12933             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
12934   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
12935             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
12936   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12937             "forAllCells:(BOOL)flag;",
12938             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12939                    "forAllCells:(BOOL)flag;"));
12940 
12941   // Very long objectiveC method declaration.
12942   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
12943                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
12944   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
12945                "                    inRange:(NSRange)range\n"
12946                "                   outRange:(NSRange)out_range\n"
12947                "                  outRange1:(NSRange)out_range1\n"
12948                "                  outRange2:(NSRange)out_range2\n"
12949                "                  outRange3:(NSRange)out_range3\n"
12950                "                  outRange4:(NSRange)out_range4\n"
12951                "                  outRange5:(NSRange)out_range5\n"
12952                "                  outRange6:(NSRange)out_range6\n"
12953                "                  outRange7:(NSRange)out_range7\n"
12954                "                  outRange8:(NSRange)out_range8\n"
12955                "                  outRange9:(NSRange)out_range9;");
12956 
12957   // When the function name has to be wrapped.
12958   FormatStyle Style = getLLVMStyle();
12959   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
12960   // and always indents instead.
12961   Style.IndentWrappedFunctionNames = false;
12962   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12963                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
12964                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
12965                "}",
12966                Style);
12967   Style.IndentWrappedFunctionNames = true;
12968   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12969                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
12970                "               anotherName:(NSString)dddddddddddddd {\n"
12971                "}",
12972                Style);
12973 
12974   verifyFormat("- (int)sum:(vector<int>)numbers;");
12975   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
12976   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
12977   // protocol lists (but not for template classes):
12978   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
12979 
12980   verifyFormat("- (int (*)())foo:(int (*)())f;");
12981   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
12982 
12983   // If there's no return type (very rare in practice!), LLVM and Google style
12984   // agree.
12985   verifyFormat("- foo;");
12986   verifyFormat("- foo:(int)f;");
12987   verifyGoogleFormat("- foo:(int)foo;");
12988 }
12989 
12990 TEST_F(FormatTest, BreaksStringLiterals) {
12991   EXPECT_EQ("\"some text \"\n"
12992             "\"other\";",
12993             format("\"some text other\";", getLLVMStyleWithColumns(12)));
12994   EXPECT_EQ("\"some text \"\n"
12995             "\"other\";",
12996             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
12997   EXPECT_EQ(
12998       "#define A  \\\n"
12999       "  \"some \"  \\\n"
13000       "  \"text \"  \\\n"
13001       "  \"other\";",
13002       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13003   EXPECT_EQ(
13004       "#define A  \\\n"
13005       "  \"so \"    \\\n"
13006       "  \"text \"  \\\n"
13007       "  \"other\";",
13008       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13009 
13010   EXPECT_EQ("\"some text\"",
13011             format("\"some text\"", getLLVMStyleWithColumns(1)));
13012   EXPECT_EQ("\"some text\"",
13013             format("\"some text\"", getLLVMStyleWithColumns(11)));
13014   EXPECT_EQ("\"some \"\n"
13015             "\"text\"",
13016             format("\"some text\"", getLLVMStyleWithColumns(10)));
13017   EXPECT_EQ("\"some \"\n"
13018             "\"text\"",
13019             format("\"some text\"", getLLVMStyleWithColumns(7)));
13020   EXPECT_EQ("\"some\"\n"
13021             "\" tex\"\n"
13022             "\"t\"",
13023             format("\"some text\"", getLLVMStyleWithColumns(6)));
13024   EXPECT_EQ("\"some\"\n"
13025             "\" tex\"\n"
13026             "\" and\"",
13027             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13028   EXPECT_EQ("\"some\"\n"
13029             "\"/tex\"\n"
13030             "\"/and\"",
13031             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13032 
13033   EXPECT_EQ("variable =\n"
13034             "    \"long string \"\n"
13035             "    \"literal\";",
13036             format("variable = \"long string literal\";",
13037                    getLLVMStyleWithColumns(20)));
13038 
13039   EXPECT_EQ("variable = f(\n"
13040             "    \"long string \"\n"
13041             "    \"literal\",\n"
13042             "    short,\n"
13043             "    loooooooooooooooooooong);",
13044             format("variable = f(\"long string literal\", short, "
13045                    "loooooooooooooooooooong);",
13046                    getLLVMStyleWithColumns(20)));
13047 
13048   EXPECT_EQ(
13049       "f(g(\"long string \"\n"
13050       "    \"literal\"),\n"
13051       "  b);",
13052       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13053   EXPECT_EQ("f(g(\"long string \"\n"
13054             "    \"literal\",\n"
13055             "    a),\n"
13056             "  b);",
13057             format("f(g(\"long string literal\", a), b);",
13058                    getLLVMStyleWithColumns(20)));
13059   EXPECT_EQ(
13060       "f(\"one two\".split(\n"
13061       "    variable));",
13062       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13063   EXPECT_EQ("f(\"one two three four five six \"\n"
13064             "  \"seven\".split(\n"
13065             "      really_looooong_variable));",
13066             format("f(\"one two three four five six seven\"."
13067                    "split(really_looooong_variable));",
13068                    getLLVMStyleWithColumns(33)));
13069 
13070   EXPECT_EQ("f(\"some \"\n"
13071             "  \"text\",\n"
13072             "  other);",
13073             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13074 
13075   // Only break as a last resort.
13076   verifyFormat(
13077       "aaaaaaaaaaaaaaaaaaaa(\n"
13078       "    aaaaaaaaaaaaaaaaaaaa,\n"
13079       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13080 
13081   EXPECT_EQ("\"splitmea\"\n"
13082             "\"trandomp\"\n"
13083             "\"oint\"",
13084             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13085 
13086   EXPECT_EQ("\"split/\"\n"
13087             "\"pathat/\"\n"
13088             "\"slashes\"",
13089             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13090 
13091   EXPECT_EQ("\"split/\"\n"
13092             "\"pathat/\"\n"
13093             "\"slashes\"",
13094             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13095   EXPECT_EQ("\"split at \"\n"
13096             "\"spaces/at/\"\n"
13097             "\"slashes.at.any$\"\n"
13098             "\"non-alphanumeric%\"\n"
13099             "\"1111111111characte\"\n"
13100             "\"rs\"",
13101             format("\"split at "
13102                    "spaces/at/"
13103                    "slashes.at."
13104                    "any$non-"
13105                    "alphanumeric%"
13106                    "1111111111characte"
13107                    "rs\"",
13108                    getLLVMStyleWithColumns(20)));
13109 
13110   // Verify that splitting the strings understands
13111   // Style::AlwaysBreakBeforeMultilineStrings.
13112   EXPECT_EQ("aaaaaaaaaaaa(\n"
13113             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13114             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13115             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13116                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13117                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13118                    getGoogleStyle()));
13119   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13120             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13121             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13122                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13123                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13124                    getGoogleStyle()));
13125   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13126             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13127             format("llvm::outs() << "
13128                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13129                    "aaaaaaaaaaaaaaaaaaa\";"));
13130   EXPECT_EQ("ffff(\n"
13131             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13132             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13133             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13134                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13135                    getGoogleStyle()));
13136 
13137   FormatStyle Style = getLLVMStyleWithColumns(12);
13138   Style.BreakStringLiterals = false;
13139   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13140 
13141   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13142   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13143   EXPECT_EQ("#define A \\\n"
13144             "  \"some \" \\\n"
13145             "  \"text \" \\\n"
13146             "  \"other\";",
13147             format("#define A \"some text other\";", AlignLeft));
13148 }
13149 
13150 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13151   EXPECT_EQ("C a = \"some more \"\n"
13152             "      \"text\";",
13153             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13154 }
13155 
13156 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13157   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13158   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13159   EXPECT_EQ("int i = a(b());",
13160             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13161 }
13162 
13163 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13164   EXPECT_EQ(
13165       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13166       "(\n"
13167       "    \"x\t\");",
13168       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13169              "aaaaaaa("
13170              "\"x\t\");"));
13171 }
13172 
13173 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13174   EXPECT_EQ(
13175       "u8\"utf8 string \"\n"
13176       "u8\"literal\";",
13177       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13178   EXPECT_EQ(
13179       "u\"utf16 string \"\n"
13180       "u\"literal\";",
13181       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13182   EXPECT_EQ(
13183       "U\"utf32 string \"\n"
13184       "U\"literal\";",
13185       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13186   EXPECT_EQ("L\"wide string \"\n"
13187             "L\"literal\";",
13188             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13189   EXPECT_EQ("@\"NSString \"\n"
13190             "@\"literal\";",
13191             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13192   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13193 
13194   // This input makes clang-format try to split the incomplete unicode escape
13195   // sequence, which used to lead to a crasher.
13196   verifyNoCrash(
13197       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13198       getLLVMStyleWithColumns(60));
13199 }
13200 
13201 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13202   FormatStyle Style = getGoogleStyleWithColumns(15);
13203   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13204   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13205   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13206   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13207   EXPECT_EQ("u8R\"x(raw literal)x\";",
13208             format("u8R\"x(raw literal)x\";", Style));
13209 }
13210 
13211 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13212   FormatStyle Style = getLLVMStyleWithColumns(20);
13213   EXPECT_EQ(
13214       "_T(\"aaaaaaaaaaaaaa\")\n"
13215       "_T(\"aaaaaaaaaaaaaa\")\n"
13216       "_T(\"aaaaaaaaaaaa\")",
13217       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13218   EXPECT_EQ("f(x,\n"
13219             "  _T(\"aaaaaaaaaaaa\")\n"
13220             "  _T(\"aaa\"),\n"
13221             "  z);",
13222             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13223 
13224   // FIXME: Handle embedded spaces in one iteration.
13225   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13226   //            "_T(\"aaaaaaaaaaaaa\")\n"
13227   //            "_T(\"aaaaaaaaaaaaa\")\n"
13228   //            "_T(\"a\")",
13229   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13230   //                   getLLVMStyleWithColumns(20)));
13231   EXPECT_EQ(
13232       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13233       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13234   EXPECT_EQ("f(\n"
13235             "#if !TEST\n"
13236             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13237             "#endif\n"
13238             ");",
13239             format("f(\n"
13240                    "#if !TEST\n"
13241                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13242                    "#endif\n"
13243                    ");"));
13244   EXPECT_EQ("f(\n"
13245             "\n"
13246             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13247             format("f(\n"
13248                    "\n"
13249                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13250   // Regression test for accessing tokens past the end of a vector in the
13251   // TokenLexer.
13252   verifyNoCrash(R"(_T(
13253 "
13254 )
13255 )");
13256 }
13257 
13258 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13259   // In a function call with two operands, the second can be broken with no line
13260   // break before it.
13261   EXPECT_EQ(
13262       "func(a, \"long long \"\n"
13263       "        \"long long\");",
13264       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13265   // In a function call with three operands, the second must be broken with a
13266   // line break before it.
13267   EXPECT_EQ("func(a,\n"
13268             "     \"long long long \"\n"
13269             "     \"long\",\n"
13270             "     c);",
13271             format("func(a, \"long long long long\", c);",
13272                    getLLVMStyleWithColumns(24)));
13273   // In a function call with three operands, the third must be broken with a
13274   // line break before it.
13275   EXPECT_EQ("func(a, b,\n"
13276             "     \"long long long \"\n"
13277             "     \"long\");",
13278             format("func(a, b, \"long long long long\");",
13279                    getLLVMStyleWithColumns(24)));
13280   // In a function call with three operands, both the second and the third must
13281   // be broken with a line break before them.
13282   EXPECT_EQ("func(a,\n"
13283             "     \"long long long \"\n"
13284             "     \"long\",\n"
13285             "     \"long long long \"\n"
13286             "     \"long\");",
13287             format("func(a, \"long long long long\", \"long long long long\");",
13288                    getLLVMStyleWithColumns(24)));
13289   // In a chain of << with two operands, the second can be broken with no line
13290   // break before it.
13291   EXPECT_EQ("a << \"line line \"\n"
13292             "     \"line\";",
13293             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13294   // In a chain of << with three operands, the second can be broken with no line
13295   // break before it.
13296   EXPECT_EQ(
13297       "abcde << \"line \"\n"
13298       "         \"line line\"\n"
13299       "      << c;",
13300       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13301   // In a chain of << with three operands, the third must be broken with a line
13302   // break before it.
13303   EXPECT_EQ(
13304       "a << b\n"
13305       "  << \"line line \"\n"
13306       "     \"line\";",
13307       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13308   // In a chain of << with three operands, the second can be broken with no line
13309   // break before it and the third must be broken with a line break before it.
13310   EXPECT_EQ("abcd << \"line line \"\n"
13311             "        \"line\"\n"
13312             "     << \"line line \"\n"
13313             "        \"line\";",
13314             format("abcd << \"line line line\" << \"line line line\";",
13315                    getLLVMStyleWithColumns(20)));
13316   // In a chain of binary operators with two operands, the second can be broken
13317   // with no line break before it.
13318   EXPECT_EQ(
13319       "abcd + \"line line \"\n"
13320       "       \"line line\";",
13321       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13322   // In a chain of binary operators with three operands, the second must be
13323   // broken with a line break before it.
13324   EXPECT_EQ("abcd +\n"
13325             "    \"line line \"\n"
13326             "    \"line line\" +\n"
13327             "    e;",
13328             format("abcd + \"line line line line\" + e;",
13329                    getLLVMStyleWithColumns(20)));
13330   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13331   // the first must be broken with a line break before it.
13332   FormatStyle Style = getLLVMStyleWithColumns(25);
13333   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13334   EXPECT_EQ("someFunction(\n"
13335             "    \"long long long \"\n"
13336             "    \"long\",\n"
13337             "    a);",
13338             format("someFunction(\"long long long long\", a);", Style));
13339 }
13340 
13341 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13342   EXPECT_EQ(
13343       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13344       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13345       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13346       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13347              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13348              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13349 }
13350 
13351 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13352   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13353             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13354   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13355             "multiline raw string literal xxxxxxxxxxxxxx\n"
13356             ")x\",\n"
13357             "              a),\n"
13358             "            b);",
13359             format("fffffffffff(g(R\"x(\n"
13360                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13361                    ")x\", a), b);",
13362                    getGoogleStyleWithColumns(20)));
13363   EXPECT_EQ("fffffffffff(\n"
13364             "    g(R\"x(qqq\n"
13365             "multiline raw string literal xxxxxxxxxxxxxx\n"
13366             ")x\",\n"
13367             "      a),\n"
13368             "    b);",
13369             format("fffffffffff(g(R\"x(qqq\n"
13370                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13371                    ")x\", a), b);",
13372                    getGoogleStyleWithColumns(20)));
13373 
13374   EXPECT_EQ("fffffffffff(R\"x(\n"
13375             "multiline raw string literal xxxxxxxxxxxxxx\n"
13376             ")x\");",
13377             format("fffffffffff(R\"x(\n"
13378                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13379                    ")x\");",
13380                    getGoogleStyleWithColumns(20)));
13381   EXPECT_EQ("fffffffffff(R\"x(\n"
13382             "multiline raw string literal xxxxxxxxxxxxxx\n"
13383             ")x\" + bbbbbb);",
13384             format("fffffffffff(R\"x(\n"
13385                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13386                    ")x\" +   bbbbbb);",
13387                    getGoogleStyleWithColumns(20)));
13388   EXPECT_EQ("fffffffffff(\n"
13389             "    R\"x(\n"
13390             "multiline raw string literal xxxxxxxxxxxxxx\n"
13391             ")x\" +\n"
13392             "    bbbbbb);",
13393             format("fffffffffff(\n"
13394                    " R\"x(\n"
13395                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13396                    ")x\" + bbbbbb);",
13397                    getGoogleStyleWithColumns(20)));
13398   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13399             format("fffffffffff(\n"
13400                    " R\"(single line raw string)\" + bbbbbb);"));
13401 }
13402 
13403 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13404   verifyFormat("string a = \"unterminated;");
13405   EXPECT_EQ("function(\"unterminated,\n"
13406             "         OtherParameter);",
13407             format("function(  \"unterminated,\n"
13408                    "    OtherParameter);"));
13409 }
13410 
13411 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13412   FormatStyle Style = getLLVMStyle();
13413   Style.Standard = FormatStyle::LS_Cpp03;
13414   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13415             format("#define x(_a) printf(\"foo\"_a);", Style));
13416 }
13417 
13418 TEST_F(FormatTest, CppLexVersion) {
13419   FormatStyle Style = getLLVMStyle();
13420   // Formatting of x * y differs if x is a type.
13421   verifyFormat("void foo() { MACRO(a * b); }", Style);
13422   verifyFormat("void foo() { MACRO(int *b); }", Style);
13423 
13424   // LLVM style uses latest lexer.
13425   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13426   Style.Standard = FormatStyle::LS_Cpp17;
13427   // But in c++17, char8_t isn't a keyword.
13428   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13429 }
13430 
13431 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13432 
13433 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13434   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13435             "             \"ddeeefff\");",
13436             format("someFunction(\"aaabbbcccdddeeefff\");",
13437                    getLLVMStyleWithColumns(25)));
13438   EXPECT_EQ("someFunction1234567890(\n"
13439             "    \"aaabbbcccdddeeefff\");",
13440             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13441                    getLLVMStyleWithColumns(26)));
13442   EXPECT_EQ("someFunction1234567890(\n"
13443             "    \"aaabbbcccdddeeeff\"\n"
13444             "    \"f\");",
13445             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13446                    getLLVMStyleWithColumns(25)));
13447   EXPECT_EQ("someFunction1234567890(\n"
13448             "    \"aaabbbcccdddeeeff\"\n"
13449             "    \"f\");",
13450             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13451                    getLLVMStyleWithColumns(24)));
13452   EXPECT_EQ("someFunction(\n"
13453             "    \"aaabbbcc ddde \"\n"
13454             "    \"efff\");",
13455             format("someFunction(\"aaabbbcc ddde efff\");",
13456                    getLLVMStyleWithColumns(25)));
13457   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13458             "             \"ddeeefff\");",
13459             format("someFunction(\"aaabbbccc ddeeefff\");",
13460                    getLLVMStyleWithColumns(25)));
13461   EXPECT_EQ("someFunction1234567890(\n"
13462             "    \"aaabb \"\n"
13463             "    \"cccdddeeefff\");",
13464             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13465                    getLLVMStyleWithColumns(25)));
13466   EXPECT_EQ("#define A          \\\n"
13467             "  string s =       \\\n"
13468             "      \"123456789\"  \\\n"
13469             "      \"0\";         \\\n"
13470             "  int i;",
13471             format("#define A string s = \"1234567890\"; int i;",
13472                    getLLVMStyleWithColumns(20)));
13473   EXPECT_EQ("someFunction(\n"
13474             "    \"aaabbbcc \"\n"
13475             "    \"dddeeefff\");",
13476             format("someFunction(\"aaabbbcc dddeeefff\");",
13477                    getLLVMStyleWithColumns(25)));
13478 }
13479 
13480 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13481   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13482   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13483   EXPECT_EQ("\"test\"\n"
13484             "\"\\n\"",
13485             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
13486   EXPECT_EQ("\"tes\\\\\"\n"
13487             "\"n\"",
13488             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
13489   EXPECT_EQ("\"\\\\\\\\\"\n"
13490             "\"\\n\"",
13491             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
13492   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
13493   EXPECT_EQ("\"\\uff01\"\n"
13494             "\"test\"",
13495             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
13496   EXPECT_EQ("\"\\Uff01ff02\"",
13497             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
13498   EXPECT_EQ("\"\\x000000000001\"\n"
13499             "\"next\"",
13500             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
13501   EXPECT_EQ("\"\\x000000000001next\"",
13502             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
13503   EXPECT_EQ("\"\\x000000000001\"",
13504             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
13505   EXPECT_EQ("\"test\"\n"
13506             "\"\\000000\"\n"
13507             "\"000001\"",
13508             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
13509   EXPECT_EQ("\"test\\000\"\n"
13510             "\"00000000\"\n"
13511             "\"1\"",
13512             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
13513 }
13514 
13515 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
13516   verifyFormat("void f() {\n"
13517                "  return g() {}\n"
13518                "  void h() {}");
13519   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
13520                "g();\n"
13521                "}");
13522 }
13523 
13524 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
13525   verifyFormat(
13526       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
13527 }
13528 
13529 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
13530   verifyFormat("class X {\n"
13531                "  void f() {\n"
13532                "  }\n"
13533                "};",
13534                getLLVMStyleWithColumns(12));
13535 }
13536 
13537 TEST_F(FormatTest, ConfigurableIndentWidth) {
13538   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
13539   EightIndent.IndentWidth = 8;
13540   EightIndent.ContinuationIndentWidth = 8;
13541   verifyFormat("void f() {\n"
13542                "        someFunction();\n"
13543                "        if (true) {\n"
13544                "                f();\n"
13545                "        }\n"
13546                "}",
13547                EightIndent);
13548   verifyFormat("class X {\n"
13549                "        void f() {\n"
13550                "        }\n"
13551                "};",
13552                EightIndent);
13553   verifyFormat("int x[] = {\n"
13554                "        call(),\n"
13555                "        call()};",
13556                EightIndent);
13557 }
13558 
13559 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
13560   verifyFormat("double\n"
13561                "f();",
13562                getLLVMStyleWithColumns(8));
13563 }
13564 
13565 TEST_F(FormatTest, ConfigurableUseOfTab) {
13566   FormatStyle Tab = getLLVMStyleWithColumns(42);
13567   Tab.IndentWidth = 8;
13568   Tab.UseTab = FormatStyle::UT_Always;
13569   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13570 
13571   EXPECT_EQ("if (aaaaaaaa && // q\n"
13572             "    bb)\t\t// w\n"
13573             "\t;",
13574             format("if (aaaaaaaa &&// q\n"
13575                    "bb)// w\n"
13576                    ";",
13577                    Tab));
13578   EXPECT_EQ("if (aaa && bbb) // w\n"
13579             "\t;",
13580             format("if(aaa&&bbb)// w\n"
13581                    ";",
13582                    Tab));
13583 
13584   verifyFormat("class X {\n"
13585                "\tvoid f() {\n"
13586                "\t\tsomeFunction(parameter1,\n"
13587                "\t\t\t     parameter2);\n"
13588                "\t}\n"
13589                "};",
13590                Tab);
13591   verifyFormat("#define A                        \\\n"
13592                "\tvoid f() {               \\\n"
13593                "\t\tsomeFunction(    \\\n"
13594                "\t\t    parameter1,  \\\n"
13595                "\t\t    parameter2); \\\n"
13596                "\t}",
13597                Tab);
13598   verifyFormat("int a;\t      // x\n"
13599                "int bbbbbbbb; // x\n",
13600                Tab);
13601 
13602   Tab.TabWidth = 4;
13603   Tab.IndentWidth = 8;
13604   verifyFormat("class TabWidth4Indent8 {\n"
13605                "\t\tvoid f() {\n"
13606                "\t\t\t\tsomeFunction(parameter1,\n"
13607                "\t\t\t\t\t\t\t parameter2);\n"
13608                "\t\t}\n"
13609                "};",
13610                Tab);
13611 
13612   Tab.TabWidth = 4;
13613   Tab.IndentWidth = 4;
13614   verifyFormat("class TabWidth4Indent4 {\n"
13615                "\tvoid f() {\n"
13616                "\t\tsomeFunction(parameter1,\n"
13617                "\t\t\t\t\t parameter2);\n"
13618                "\t}\n"
13619                "};",
13620                Tab);
13621 
13622   Tab.TabWidth = 8;
13623   Tab.IndentWidth = 4;
13624   verifyFormat("class TabWidth8Indent4 {\n"
13625                "    void f() {\n"
13626                "\tsomeFunction(parameter1,\n"
13627                "\t\t     parameter2);\n"
13628                "    }\n"
13629                "};",
13630                Tab);
13631 
13632   Tab.TabWidth = 8;
13633   Tab.IndentWidth = 8;
13634   EXPECT_EQ("/*\n"
13635             "\t      a\t\tcomment\n"
13636             "\t      in multiple lines\n"
13637             "       */",
13638             format("   /*\t \t \n"
13639                    " \t \t a\t\tcomment\t \t\n"
13640                    " \t \t in multiple lines\t\n"
13641                    " \t  */",
13642                    Tab));
13643 
13644   Tab.UseTab = FormatStyle::UT_ForIndentation;
13645   verifyFormat("{\n"
13646                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13647                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13648                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13649                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13650                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13651                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13652                "};",
13653                Tab);
13654   verifyFormat("enum AA {\n"
13655                "\ta1, // Force multiple lines\n"
13656                "\ta2,\n"
13657                "\ta3\n"
13658                "};",
13659                Tab);
13660   EXPECT_EQ("if (aaaaaaaa && // q\n"
13661             "    bb)         // w\n"
13662             "\t;",
13663             format("if (aaaaaaaa &&// q\n"
13664                    "bb)// w\n"
13665                    ";",
13666                    Tab));
13667   verifyFormat("class X {\n"
13668                "\tvoid f() {\n"
13669                "\t\tsomeFunction(parameter1,\n"
13670                "\t\t             parameter2);\n"
13671                "\t}\n"
13672                "};",
13673                Tab);
13674   verifyFormat("{\n"
13675                "\tQ(\n"
13676                "\t    {\n"
13677                "\t\t    int a;\n"
13678                "\t\t    someFunction(aaaaaaaa,\n"
13679                "\t\t                 bbbbbbb);\n"
13680                "\t    },\n"
13681                "\t    p);\n"
13682                "}",
13683                Tab);
13684   EXPECT_EQ("{\n"
13685             "\t/* aaaa\n"
13686             "\t   bbbb */\n"
13687             "}",
13688             format("{\n"
13689                    "/* aaaa\n"
13690                    "   bbbb */\n"
13691                    "}",
13692                    Tab));
13693   EXPECT_EQ("{\n"
13694             "\t/*\n"
13695             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13696             "\t  bbbbbbbbbbbbb\n"
13697             "\t*/\n"
13698             "}",
13699             format("{\n"
13700                    "/*\n"
13701                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13702                    "*/\n"
13703                    "}",
13704                    Tab));
13705   EXPECT_EQ("{\n"
13706             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13707             "\t// bbbbbbbbbbbbb\n"
13708             "}",
13709             format("{\n"
13710                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13711                    "}",
13712                    Tab));
13713   EXPECT_EQ("{\n"
13714             "\t/*\n"
13715             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13716             "\t  bbbbbbbbbbbbb\n"
13717             "\t*/\n"
13718             "}",
13719             format("{\n"
13720                    "\t/*\n"
13721                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13722                    "\t*/\n"
13723                    "}",
13724                    Tab));
13725   EXPECT_EQ("{\n"
13726             "\t/*\n"
13727             "\n"
13728             "\t*/\n"
13729             "}",
13730             format("{\n"
13731                    "\t/*\n"
13732                    "\n"
13733                    "\t*/\n"
13734                    "}",
13735                    Tab));
13736   EXPECT_EQ("{\n"
13737             "\t/*\n"
13738             " asdf\n"
13739             "\t*/\n"
13740             "}",
13741             format("{\n"
13742                    "\t/*\n"
13743                    " asdf\n"
13744                    "\t*/\n"
13745                    "}",
13746                    Tab));
13747 
13748   verifyFormat("void f() {\n"
13749                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
13750                "\t            : bbbbbbbbbbbbbbbbbb\n"
13751                "}",
13752                Tab);
13753   FormatStyle TabNoBreak = Tab;
13754   TabNoBreak.BreakBeforeTernaryOperators = false;
13755   verifyFormat("void f() {\n"
13756                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
13757                "\t              bbbbbbbbbbbbbbbbbb\n"
13758                "}",
13759                TabNoBreak);
13760   verifyFormat("void f() {\n"
13761                "\treturn true ?\n"
13762                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
13763                "\t           bbbbbbbbbbbbbbbbbbbb\n"
13764                "}",
13765                TabNoBreak);
13766 
13767   Tab.UseTab = FormatStyle::UT_Never;
13768   EXPECT_EQ("/*\n"
13769             "              a\t\tcomment\n"
13770             "              in multiple lines\n"
13771             "       */",
13772             format("   /*\t \t \n"
13773                    " \t \t a\t\tcomment\t \t\n"
13774                    " \t \t in multiple lines\t\n"
13775                    " \t  */",
13776                    Tab));
13777   EXPECT_EQ("/* some\n"
13778             "   comment */",
13779             format(" \t \t /* some\n"
13780                    " \t \t    comment */",
13781                    Tab));
13782   EXPECT_EQ("int a; /* some\n"
13783             "   comment */",
13784             format(" \t \t int a; /* some\n"
13785                    " \t \t    comment */",
13786                    Tab));
13787 
13788   EXPECT_EQ("int a; /* some\n"
13789             "comment */",
13790             format(" \t \t int\ta; /* some\n"
13791                    " \t \t    comment */",
13792                    Tab));
13793   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13794             "    comment */",
13795             format(" \t \t f(\"\t\t\"); /* some\n"
13796                    " \t \t    comment */",
13797                    Tab));
13798   EXPECT_EQ("{\n"
13799             "        /*\n"
13800             "         * Comment\n"
13801             "         */\n"
13802             "        int i;\n"
13803             "}",
13804             format("{\n"
13805                    "\t/*\n"
13806                    "\t * Comment\n"
13807                    "\t */\n"
13808                    "\t int i;\n"
13809                    "}",
13810                    Tab));
13811 
13812   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13813   Tab.TabWidth = 8;
13814   Tab.IndentWidth = 8;
13815   EXPECT_EQ("if (aaaaaaaa && // q\n"
13816             "    bb)         // w\n"
13817             "\t;",
13818             format("if (aaaaaaaa &&// q\n"
13819                    "bb)// w\n"
13820                    ";",
13821                    Tab));
13822   EXPECT_EQ("if (aaa && bbb) // w\n"
13823             "\t;",
13824             format("if(aaa&&bbb)// w\n"
13825                    ";",
13826                    Tab));
13827   verifyFormat("class X {\n"
13828                "\tvoid f() {\n"
13829                "\t\tsomeFunction(parameter1,\n"
13830                "\t\t\t     parameter2);\n"
13831                "\t}\n"
13832                "};",
13833                Tab);
13834   verifyFormat("#define A                        \\\n"
13835                "\tvoid f() {               \\\n"
13836                "\t\tsomeFunction(    \\\n"
13837                "\t\t    parameter1,  \\\n"
13838                "\t\t    parameter2); \\\n"
13839                "\t}",
13840                Tab);
13841   Tab.TabWidth = 4;
13842   Tab.IndentWidth = 8;
13843   verifyFormat("class TabWidth4Indent8 {\n"
13844                "\t\tvoid f() {\n"
13845                "\t\t\t\tsomeFunction(parameter1,\n"
13846                "\t\t\t\t\t\t\t parameter2);\n"
13847                "\t\t}\n"
13848                "};",
13849                Tab);
13850   Tab.TabWidth = 4;
13851   Tab.IndentWidth = 4;
13852   verifyFormat("class TabWidth4Indent4 {\n"
13853                "\tvoid f() {\n"
13854                "\t\tsomeFunction(parameter1,\n"
13855                "\t\t\t\t\t parameter2);\n"
13856                "\t}\n"
13857                "};",
13858                Tab);
13859   Tab.TabWidth = 8;
13860   Tab.IndentWidth = 4;
13861   verifyFormat("class TabWidth8Indent4 {\n"
13862                "    void f() {\n"
13863                "\tsomeFunction(parameter1,\n"
13864                "\t\t     parameter2);\n"
13865                "    }\n"
13866                "};",
13867                Tab);
13868   Tab.TabWidth = 8;
13869   Tab.IndentWidth = 8;
13870   EXPECT_EQ("/*\n"
13871             "\t      a\t\tcomment\n"
13872             "\t      in multiple lines\n"
13873             "       */",
13874             format("   /*\t \t \n"
13875                    " \t \t a\t\tcomment\t \t\n"
13876                    " \t \t in multiple lines\t\n"
13877                    " \t  */",
13878                    Tab));
13879   verifyFormat("{\n"
13880                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13881                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13882                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13883                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13884                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13885                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13886                "};",
13887                Tab);
13888   verifyFormat("enum AA {\n"
13889                "\ta1, // Force multiple lines\n"
13890                "\ta2,\n"
13891                "\ta3\n"
13892                "};",
13893                Tab);
13894   EXPECT_EQ("if (aaaaaaaa && // q\n"
13895             "    bb)         // w\n"
13896             "\t;",
13897             format("if (aaaaaaaa &&// q\n"
13898                    "bb)// w\n"
13899                    ";",
13900                    Tab));
13901   verifyFormat("class X {\n"
13902                "\tvoid f() {\n"
13903                "\t\tsomeFunction(parameter1,\n"
13904                "\t\t\t     parameter2);\n"
13905                "\t}\n"
13906                "};",
13907                Tab);
13908   verifyFormat("{\n"
13909                "\tQ(\n"
13910                "\t    {\n"
13911                "\t\t    int a;\n"
13912                "\t\t    someFunction(aaaaaaaa,\n"
13913                "\t\t\t\t bbbbbbb);\n"
13914                "\t    },\n"
13915                "\t    p);\n"
13916                "}",
13917                Tab);
13918   EXPECT_EQ("{\n"
13919             "\t/* aaaa\n"
13920             "\t   bbbb */\n"
13921             "}",
13922             format("{\n"
13923                    "/* aaaa\n"
13924                    "   bbbb */\n"
13925                    "}",
13926                    Tab));
13927   EXPECT_EQ("{\n"
13928             "\t/*\n"
13929             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13930             "\t  bbbbbbbbbbbbb\n"
13931             "\t*/\n"
13932             "}",
13933             format("{\n"
13934                    "/*\n"
13935                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13936                    "*/\n"
13937                    "}",
13938                    Tab));
13939   EXPECT_EQ("{\n"
13940             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13941             "\t// bbbbbbbbbbbbb\n"
13942             "}",
13943             format("{\n"
13944                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13945                    "}",
13946                    Tab));
13947   EXPECT_EQ("{\n"
13948             "\t/*\n"
13949             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13950             "\t  bbbbbbbbbbbbb\n"
13951             "\t*/\n"
13952             "}",
13953             format("{\n"
13954                    "\t/*\n"
13955                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13956                    "\t*/\n"
13957                    "}",
13958                    Tab));
13959   EXPECT_EQ("{\n"
13960             "\t/*\n"
13961             "\n"
13962             "\t*/\n"
13963             "}",
13964             format("{\n"
13965                    "\t/*\n"
13966                    "\n"
13967                    "\t*/\n"
13968                    "}",
13969                    Tab));
13970   EXPECT_EQ("{\n"
13971             "\t/*\n"
13972             " asdf\n"
13973             "\t*/\n"
13974             "}",
13975             format("{\n"
13976                    "\t/*\n"
13977                    " asdf\n"
13978                    "\t*/\n"
13979                    "}",
13980                    Tab));
13981   EXPECT_EQ("/* some\n"
13982             "   comment */",
13983             format(" \t \t /* some\n"
13984                    " \t \t    comment */",
13985                    Tab));
13986   EXPECT_EQ("int a; /* some\n"
13987             "   comment */",
13988             format(" \t \t int a; /* some\n"
13989                    " \t \t    comment */",
13990                    Tab));
13991   EXPECT_EQ("int a; /* some\n"
13992             "comment */",
13993             format(" \t \t int\ta; /* some\n"
13994                    " \t \t    comment */",
13995                    Tab));
13996   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13997             "    comment */",
13998             format(" \t \t f(\"\t\t\"); /* some\n"
13999                    " \t \t    comment */",
14000                    Tab));
14001   EXPECT_EQ("{\n"
14002             "\t/*\n"
14003             "\t * Comment\n"
14004             "\t */\n"
14005             "\tint i;\n"
14006             "}",
14007             format("{\n"
14008                    "\t/*\n"
14009                    "\t * Comment\n"
14010                    "\t */\n"
14011                    "\t int i;\n"
14012                    "}",
14013                    Tab));
14014   Tab.TabWidth = 2;
14015   Tab.IndentWidth = 2;
14016   EXPECT_EQ("{\n"
14017             "\t/* aaaa\n"
14018             "\t\t bbbb */\n"
14019             "}",
14020             format("{\n"
14021                    "/* aaaa\n"
14022                    "\t bbbb */\n"
14023                    "}",
14024                    Tab));
14025   EXPECT_EQ("{\n"
14026             "\t/*\n"
14027             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14028             "\t\tbbbbbbbbbbbbb\n"
14029             "\t*/\n"
14030             "}",
14031             format("{\n"
14032                    "/*\n"
14033                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14034                    "*/\n"
14035                    "}",
14036                    Tab));
14037   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14038   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14039   Tab.TabWidth = 4;
14040   Tab.IndentWidth = 4;
14041   verifyFormat("class Assign {\n"
14042                "\tvoid f() {\n"
14043                "\t\tint         x      = 123;\n"
14044                "\t\tint         random = 4;\n"
14045                "\t\tstd::string alphabet =\n"
14046                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14047                "\t}\n"
14048                "};",
14049                Tab);
14050 
14051   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14052   Tab.TabWidth = 8;
14053   Tab.IndentWidth = 8;
14054   EXPECT_EQ("if (aaaaaaaa && // q\n"
14055             "    bb)         // w\n"
14056             "\t;",
14057             format("if (aaaaaaaa &&// q\n"
14058                    "bb)// w\n"
14059                    ";",
14060                    Tab));
14061   EXPECT_EQ("if (aaa && bbb) // w\n"
14062             "\t;",
14063             format("if(aaa&&bbb)// w\n"
14064                    ";",
14065                    Tab));
14066   verifyFormat("class X {\n"
14067                "\tvoid f() {\n"
14068                "\t\tsomeFunction(parameter1,\n"
14069                "\t\t             parameter2);\n"
14070                "\t}\n"
14071                "};",
14072                Tab);
14073   verifyFormat("#define A                        \\\n"
14074                "\tvoid f() {               \\\n"
14075                "\t\tsomeFunction(    \\\n"
14076                "\t\t    parameter1,  \\\n"
14077                "\t\t    parameter2); \\\n"
14078                "\t}",
14079                Tab);
14080   Tab.TabWidth = 4;
14081   Tab.IndentWidth = 8;
14082   verifyFormat("class TabWidth4Indent8 {\n"
14083                "\t\tvoid f() {\n"
14084                "\t\t\t\tsomeFunction(parameter1,\n"
14085                "\t\t\t\t             parameter2);\n"
14086                "\t\t}\n"
14087                "};",
14088                Tab);
14089   Tab.TabWidth = 4;
14090   Tab.IndentWidth = 4;
14091   verifyFormat("class TabWidth4Indent4 {\n"
14092                "\tvoid f() {\n"
14093                "\t\tsomeFunction(parameter1,\n"
14094                "\t\t             parameter2);\n"
14095                "\t}\n"
14096                "};",
14097                Tab);
14098   Tab.TabWidth = 8;
14099   Tab.IndentWidth = 4;
14100   verifyFormat("class TabWidth8Indent4 {\n"
14101                "    void f() {\n"
14102                "\tsomeFunction(parameter1,\n"
14103                "\t             parameter2);\n"
14104                "    }\n"
14105                "};",
14106                Tab);
14107   Tab.TabWidth = 8;
14108   Tab.IndentWidth = 8;
14109   EXPECT_EQ("/*\n"
14110             "              a\t\tcomment\n"
14111             "              in multiple lines\n"
14112             "       */",
14113             format("   /*\t \t \n"
14114                    " \t \t a\t\tcomment\t \t\n"
14115                    " \t \t in multiple lines\t\n"
14116                    " \t  */",
14117                    Tab));
14118   verifyFormat("{\n"
14119                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14120                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14121                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14122                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14123                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14124                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14125                "};",
14126                Tab);
14127   verifyFormat("enum AA {\n"
14128                "\ta1, // Force multiple lines\n"
14129                "\ta2,\n"
14130                "\ta3\n"
14131                "};",
14132                Tab);
14133   EXPECT_EQ("if (aaaaaaaa && // q\n"
14134             "    bb)         // w\n"
14135             "\t;",
14136             format("if (aaaaaaaa &&// q\n"
14137                    "bb)// w\n"
14138                    ";",
14139                    Tab));
14140   verifyFormat("class X {\n"
14141                "\tvoid f() {\n"
14142                "\t\tsomeFunction(parameter1,\n"
14143                "\t\t             parameter2);\n"
14144                "\t}\n"
14145                "};",
14146                Tab);
14147   verifyFormat("{\n"
14148                "\tQ(\n"
14149                "\t    {\n"
14150                "\t\t    int a;\n"
14151                "\t\t    someFunction(aaaaaaaa,\n"
14152                "\t\t                 bbbbbbb);\n"
14153                "\t    },\n"
14154                "\t    p);\n"
14155                "}",
14156                Tab);
14157   EXPECT_EQ("{\n"
14158             "\t/* aaaa\n"
14159             "\t   bbbb */\n"
14160             "}",
14161             format("{\n"
14162                    "/* aaaa\n"
14163                    "   bbbb */\n"
14164                    "}",
14165                    Tab));
14166   EXPECT_EQ("{\n"
14167             "\t/*\n"
14168             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14169             "\t  bbbbbbbbbbbbb\n"
14170             "\t*/\n"
14171             "}",
14172             format("{\n"
14173                    "/*\n"
14174                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14175                    "*/\n"
14176                    "}",
14177                    Tab));
14178   EXPECT_EQ("{\n"
14179             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14180             "\t// bbbbbbbbbbbbb\n"
14181             "}",
14182             format("{\n"
14183                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14184                    "}",
14185                    Tab));
14186   EXPECT_EQ("{\n"
14187             "\t/*\n"
14188             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14189             "\t  bbbbbbbbbbbbb\n"
14190             "\t*/\n"
14191             "}",
14192             format("{\n"
14193                    "\t/*\n"
14194                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14195                    "\t*/\n"
14196                    "}",
14197                    Tab));
14198   EXPECT_EQ("{\n"
14199             "\t/*\n"
14200             "\n"
14201             "\t*/\n"
14202             "}",
14203             format("{\n"
14204                    "\t/*\n"
14205                    "\n"
14206                    "\t*/\n"
14207                    "}",
14208                    Tab));
14209   EXPECT_EQ("{\n"
14210             "\t/*\n"
14211             " asdf\n"
14212             "\t*/\n"
14213             "}",
14214             format("{\n"
14215                    "\t/*\n"
14216                    " asdf\n"
14217                    "\t*/\n"
14218                    "}",
14219                    Tab));
14220   EXPECT_EQ("/* some\n"
14221             "   comment */",
14222             format(" \t \t /* some\n"
14223                    " \t \t    comment */",
14224                    Tab));
14225   EXPECT_EQ("int a; /* some\n"
14226             "   comment */",
14227             format(" \t \t int a; /* some\n"
14228                    " \t \t    comment */",
14229                    Tab));
14230   EXPECT_EQ("int a; /* some\n"
14231             "comment */",
14232             format(" \t \t int\ta; /* some\n"
14233                    " \t \t    comment */",
14234                    Tab));
14235   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14236             "    comment */",
14237             format(" \t \t f(\"\t\t\"); /* some\n"
14238                    " \t \t    comment */",
14239                    Tab));
14240   EXPECT_EQ("{\n"
14241             "\t/*\n"
14242             "\t * Comment\n"
14243             "\t */\n"
14244             "\tint i;\n"
14245             "}",
14246             format("{\n"
14247                    "\t/*\n"
14248                    "\t * Comment\n"
14249                    "\t */\n"
14250                    "\t int i;\n"
14251                    "}",
14252                    Tab));
14253   Tab.TabWidth = 2;
14254   Tab.IndentWidth = 2;
14255   EXPECT_EQ("{\n"
14256             "\t/* aaaa\n"
14257             "\t   bbbb */\n"
14258             "}",
14259             format("{\n"
14260                    "/* aaaa\n"
14261                    "   bbbb */\n"
14262                    "}",
14263                    Tab));
14264   EXPECT_EQ("{\n"
14265             "\t/*\n"
14266             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14267             "\t  bbbbbbbbbbbbb\n"
14268             "\t*/\n"
14269             "}",
14270             format("{\n"
14271                    "/*\n"
14272                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14273                    "*/\n"
14274                    "}",
14275                    Tab));
14276   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14277   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14278   Tab.TabWidth = 4;
14279   Tab.IndentWidth = 4;
14280   verifyFormat("class Assign {\n"
14281                "\tvoid f() {\n"
14282                "\t\tint         x      = 123;\n"
14283                "\t\tint         random = 4;\n"
14284                "\t\tstd::string alphabet =\n"
14285                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14286                "\t}\n"
14287                "};",
14288                Tab);
14289   Tab.AlignOperands = FormatStyle::OAS_Align;
14290   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14291                "                 cccccccccccccccccccc;",
14292                Tab);
14293   // no alignment
14294   verifyFormat("int aaaaaaaaaa =\n"
14295                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14296                Tab);
14297   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14298                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14299                "                        : 333333333333333;",
14300                Tab);
14301   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14302   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14303   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14304                "               + cccccccccccccccccccc;",
14305                Tab);
14306 }
14307 
14308 TEST_F(FormatTest, ZeroTabWidth) {
14309   FormatStyle Tab = getLLVMStyleWithColumns(42);
14310   Tab.IndentWidth = 8;
14311   Tab.UseTab = FormatStyle::UT_Never;
14312   Tab.TabWidth = 0;
14313   EXPECT_EQ("void a(){\n"
14314             "    // line starts with '\t'\n"
14315             "};",
14316             format("void a(){\n"
14317                    "\t// line starts with '\t'\n"
14318                    "};",
14319                    Tab));
14320 
14321   EXPECT_EQ("void a(){\n"
14322             "    // line starts with '\t'\n"
14323             "};",
14324             format("void a(){\n"
14325                    "\t\t// line starts with '\t'\n"
14326                    "};",
14327                    Tab));
14328 
14329   Tab.UseTab = FormatStyle::UT_ForIndentation;
14330   EXPECT_EQ("void a(){\n"
14331             "    // line starts with '\t'\n"
14332             "};",
14333             format("void a(){\n"
14334                    "\t// line starts with '\t'\n"
14335                    "};",
14336                    Tab));
14337 
14338   EXPECT_EQ("void a(){\n"
14339             "    // line starts with '\t'\n"
14340             "};",
14341             format("void a(){\n"
14342                    "\t\t// line starts with '\t'\n"
14343                    "};",
14344                    Tab));
14345 
14346   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14347   EXPECT_EQ("void a(){\n"
14348             "    // line starts with '\t'\n"
14349             "};",
14350             format("void a(){\n"
14351                    "\t// line starts with '\t'\n"
14352                    "};",
14353                    Tab));
14354 
14355   EXPECT_EQ("void a(){\n"
14356             "    // line starts with '\t'\n"
14357             "};",
14358             format("void a(){\n"
14359                    "\t\t// line starts with '\t'\n"
14360                    "};",
14361                    Tab));
14362 
14363   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14364   EXPECT_EQ("void a(){\n"
14365             "    // line starts with '\t'\n"
14366             "};",
14367             format("void a(){\n"
14368                    "\t// line starts with '\t'\n"
14369                    "};",
14370                    Tab));
14371 
14372   EXPECT_EQ("void a(){\n"
14373             "    // line starts with '\t'\n"
14374             "};",
14375             format("void a(){\n"
14376                    "\t\t// line starts with '\t'\n"
14377                    "};",
14378                    Tab));
14379 
14380   Tab.UseTab = FormatStyle::UT_Always;
14381   EXPECT_EQ("void a(){\n"
14382             "// line starts with '\t'\n"
14383             "};",
14384             format("void a(){\n"
14385                    "\t// line starts with '\t'\n"
14386                    "};",
14387                    Tab));
14388 
14389   EXPECT_EQ("void a(){\n"
14390             "// line starts with '\t'\n"
14391             "};",
14392             format("void a(){\n"
14393                    "\t\t// line starts with '\t'\n"
14394                    "};",
14395                    Tab));
14396 }
14397 
14398 TEST_F(FormatTest, CalculatesOriginalColumn) {
14399   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14400             "q\"; /* some\n"
14401             "       comment */",
14402             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14403                    "q\"; /* some\n"
14404                    "       comment */",
14405                    getLLVMStyle()));
14406   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14407             "/* some\n"
14408             "   comment */",
14409             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14410                    " /* some\n"
14411                    "    comment */",
14412                    getLLVMStyle()));
14413   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14414             "qqq\n"
14415             "/* some\n"
14416             "   comment */",
14417             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14418                    "qqq\n"
14419                    " /* some\n"
14420                    "    comment */",
14421                    getLLVMStyle()));
14422   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14423             "wwww; /* some\n"
14424             "         comment */",
14425             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14426                    "wwww; /* some\n"
14427                    "         comment */",
14428                    getLLVMStyle()));
14429 }
14430 
14431 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14432   FormatStyle NoSpace = getLLVMStyle();
14433   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14434 
14435   verifyFormat("while(true)\n"
14436                "  continue;",
14437                NoSpace);
14438   verifyFormat("for(;;)\n"
14439                "  continue;",
14440                NoSpace);
14441   verifyFormat("if(true)\n"
14442                "  f();\n"
14443                "else if(true)\n"
14444                "  f();",
14445                NoSpace);
14446   verifyFormat("do {\n"
14447                "  do_something();\n"
14448                "} while(something());",
14449                NoSpace);
14450   verifyFormat("switch(x) {\n"
14451                "default:\n"
14452                "  break;\n"
14453                "}",
14454                NoSpace);
14455   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14456   verifyFormat("size_t x = sizeof(x);", NoSpace);
14457   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14458   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14459   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14460   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14461   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14462   verifyFormat("alignas(128) char a[128];", NoSpace);
14463   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14464   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14465   verifyFormat("int f() throw(Deprecated);", NoSpace);
14466   verifyFormat("typedef void (*cb)(int);", NoSpace);
14467   verifyFormat("T A::operator()();", NoSpace);
14468   verifyFormat("X A::operator++(T);", NoSpace);
14469   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14470 
14471   FormatStyle Space = getLLVMStyle();
14472   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14473 
14474   verifyFormat("int f ();", Space);
14475   verifyFormat("void f (int a, T b) {\n"
14476                "  while (true)\n"
14477                "    continue;\n"
14478                "}",
14479                Space);
14480   verifyFormat("if (true)\n"
14481                "  f ();\n"
14482                "else if (true)\n"
14483                "  f ();",
14484                Space);
14485   verifyFormat("do {\n"
14486                "  do_something ();\n"
14487                "} while (something ());",
14488                Space);
14489   verifyFormat("switch (x) {\n"
14490                "default:\n"
14491                "  break;\n"
14492                "}",
14493                Space);
14494   verifyFormat("A::A () : a (1) {}", Space);
14495   verifyFormat("void f () __attribute__ ((asdf));", Space);
14496   verifyFormat("*(&a + 1);\n"
14497                "&((&a)[1]);\n"
14498                "a[(b + c) * d];\n"
14499                "(((a + 1) * 2) + 3) * 4;",
14500                Space);
14501   verifyFormat("#define A(x) x", Space);
14502   verifyFormat("#define A (x) x", Space);
14503   verifyFormat("#if defined(x)\n"
14504                "#endif",
14505                Space);
14506   verifyFormat("auto i = std::make_unique<int> (5);", Space);
14507   verifyFormat("size_t x = sizeof (x);", Space);
14508   verifyFormat("auto f (int x) -> decltype (x);", Space);
14509   verifyFormat("auto f (int x) -> typeof (x);", Space);
14510   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
14511   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
14512   verifyFormat("int f (T x) noexcept (x.create ());", Space);
14513   verifyFormat("alignas (128) char a[128];", Space);
14514   verifyFormat("size_t x = alignof (MyType);", Space);
14515   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
14516   verifyFormat("int f () throw (Deprecated);", Space);
14517   verifyFormat("typedef void (*cb) (int);", Space);
14518   // FIXME these tests regressed behaviour.
14519   // verifyFormat("T A::operator() ();", Space);
14520   // verifyFormat("X A::operator++ (T);", Space);
14521   verifyFormat("auto lambda = [] () { return 0; };", Space);
14522   verifyFormat("int x = int (y);", Space);
14523 
14524   FormatStyle SomeSpace = getLLVMStyle();
14525   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
14526 
14527   verifyFormat("[]() -> float {}", SomeSpace);
14528   verifyFormat("[] (auto foo) {}", SomeSpace);
14529   verifyFormat("[foo]() -> int {}", SomeSpace);
14530   verifyFormat("int f();", SomeSpace);
14531   verifyFormat("void f (int a, T b) {\n"
14532                "  while (true)\n"
14533                "    continue;\n"
14534                "}",
14535                SomeSpace);
14536   verifyFormat("if (true)\n"
14537                "  f();\n"
14538                "else if (true)\n"
14539                "  f();",
14540                SomeSpace);
14541   verifyFormat("do {\n"
14542                "  do_something();\n"
14543                "} while (something());",
14544                SomeSpace);
14545   verifyFormat("switch (x) {\n"
14546                "default:\n"
14547                "  break;\n"
14548                "}",
14549                SomeSpace);
14550   verifyFormat("A::A() : a (1) {}", SomeSpace);
14551   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
14552   verifyFormat("*(&a + 1);\n"
14553                "&((&a)[1]);\n"
14554                "a[(b + c) * d];\n"
14555                "(((a + 1) * 2) + 3) * 4;",
14556                SomeSpace);
14557   verifyFormat("#define A(x) x", SomeSpace);
14558   verifyFormat("#define A (x) x", SomeSpace);
14559   verifyFormat("#if defined(x)\n"
14560                "#endif",
14561                SomeSpace);
14562   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
14563   verifyFormat("size_t x = sizeof (x);", SomeSpace);
14564   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
14565   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
14566   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
14567   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
14568   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
14569   verifyFormat("alignas (128) char a[128];", SomeSpace);
14570   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
14571   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14572                SomeSpace);
14573   verifyFormat("int f() throw (Deprecated);", SomeSpace);
14574   verifyFormat("typedef void (*cb) (int);", SomeSpace);
14575   verifyFormat("T A::operator()();", SomeSpace);
14576   // FIXME these tests regressed behaviour.
14577   // verifyFormat("X A::operator++ (T);", SomeSpace);
14578   verifyFormat("int x = int (y);", SomeSpace);
14579   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
14580 
14581   FormatStyle SpaceControlStatements = getLLVMStyle();
14582   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14583   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
14584 
14585   verifyFormat("while (true)\n"
14586                "  continue;",
14587                SpaceControlStatements);
14588   verifyFormat("if (true)\n"
14589                "  f();\n"
14590                "else if (true)\n"
14591                "  f();",
14592                SpaceControlStatements);
14593   verifyFormat("for (;;) {\n"
14594                "  do_something();\n"
14595                "}",
14596                SpaceControlStatements);
14597   verifyFormat("do {\n"
14598                "  do_something();\n"
14599                "} while (something());",
14600                SpaceControlStatements);
14601   verifyFormat("switch (x) {\n"
14602                "default:\n"
14603                "  break;\n"
14604                "}",
14605                SpaceControlStatements);
14606 
14607   FormatStyle SpaceFuncDecl = getLLVMStyle();
14608   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14609   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
14610 
14611   verifyFormat("int f ();", SpaceFuncDecl);
14612   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
14613   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
14614   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
14615   verifyFormat("#define A(x) x", SpaceFuncDecl);
14616   verifyFormat("#define A (x) x", SpaceFuncDecl);
14617   verifyFormat("#if defined(x)\n"
14618                "#endif",
14619                SpaceFuncDecl);
14620   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
14621   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
14622   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
14623   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
14624   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
14625   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
14626   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
14627   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
14628   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
14629   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14630                SpaceFuncDecl);
14631   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
14632   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
14633   // FIXME these tests regressed behaviour.
14634   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
14635   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
14636   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
14637   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
14638   verifyFormat("int x = int(y);", SpaceFuncDecl);
14639   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14640                SpaceFuncDecl);
14641 
14642   FormatStyle SpaceFuncDef = getLLVMStyle();
14643   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14644   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
14645 
14646   verifyFormat("int f();", SpaceFuncDef);
14647   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
14648   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
14649   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
14650   verifyFormat("#define A(x) x", SpaceFuncDef);
14651   verifyFormat("#define A (x) x", SpaceFuncDef);
14652   verifyFormat("#if defined(x)\n"
14653                "#endif",
14654                SpaceFuncDef);
14655   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
14656   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
14657   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
14658   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
14659   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
14660   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
14661   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
14662   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
14663   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
14664   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14665                SpaceFuncDef);
14666   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
14667   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
14668   verifyFormat("T A::operator()();", SpaceFuncDef);
14669   verifyFormat("X A::operator++(T);", SpaceFuncDef);
14670   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
14671   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
14672   verifyFormat("int x = int(y);", SpaceFuncDef);
14673   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14674                SpaceFuncDef);
14675 
14676   FormatStyle SpaceIfMacros = getLLVMStyle();
14677   SpaceIfMacros.IfMacros.clear();
14678   SpaceIfMacros.IfMacros.push_back("MYIF");
14679   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14680   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
14681   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
14682   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
14683   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
14684 
14685   FormatStyle SpaceForeachMacros = getLLVMStyle();
14686   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
14687             FormatStyle::SBS_Never);
14688   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
14689   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14690   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
14691   verifyFormat("for (;;) {\n"
14692                "}",
14693                SpaceForeachMacros);
14694   verifyFormat("foreach (Item *item, itemlist) {\n"
14695                "}",
14696                SpaceForeachMacros);
14697   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
14698                "}",
14699                SpaceForeachMacros);
14700   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
14701                "}",
14702                SpaceForeachMacros);
14703   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
14704 
14705   FormatStyle SomeSpace2 = getLLVMStyle();
14706   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14707   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
14708   verifyFormat("[]() -> float {}", SomeSpace2);
14709   verifyFormat("[] (auto foo) {}", SomeSpace2);
14710   verifyFormat("[foo]() -> int {}", SomeSpace2);
14711   verifyFormat("int f();", SomeSpace2);
14712   verifyFormat("void f (int a, T b) {\n"
14713                "  while (true)\n"
14714                "    continue;\n"
14715                "}",
14716                SomeSpace2);
14717   verifyFormat("if (true)\n"
14718                "  f();\n"
14719                "else if (true)\n"
14720                "  f();",
14721                SomeSpace2);
14722   verifyFormat("do {\n"
14723                "  do_something();\n"
14724                "} while (something());",
14725                SomeSpace2);
14726   verifyFormat("switch (x) {\n"
14727                "default:\n"
14728                "  break;\n"
14729                "}",
14730                SomeSpace2);
14731   verifyFormat("A::A() : a (1) {}", SomeSpace2);
14732   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
14733   verifyFormat("*(&a + 1);\n"
14734                "&((&a)[1]);\n"
14735                "a[(b + c) * d];\n"
14736                "(((a + 1) * 2) + 3) * 4;",
14737                SomeSpace2);
14738   verifyFormat("#define A(x) x", SomeSpace2);
14739   verifyFormat("#define A (x) x", SomeSpace2);
14740   verifyFormat("#if defined(x)\n"
14741                "#endif",
14742                SomeSpace2);
14743   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
14744   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
14745   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
14746   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
14747   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
14748   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
14749   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
14750   verifyFormat("alignas (128) char a[128];", SomeSpace2);
14751   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
14752   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14753                SomeSpace2);
14754   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
14755   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
14756   verifyFormat("T A::operator()();", SomeSpace2);
14757   // verifyFormat("X A::operator++ (T);", SomeSpace2);
14758   verifyFormat("int x = int (y);", SomeSpace2);
14759   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
14760 
14761   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
14762   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14763   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
14764       .AfterOverloadedOperator = true;
14765 
14766   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
14767   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
14768   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
14769   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
14770 
14771   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
14772       .AfterOverloadedOperator = false;
14773 
14774   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
14775   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
14776   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
14777   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
14778 }
14779 
14780 TEST_F(FormatTest, SpaceAfterLogicalNot) {
14781   FormatStyle Spaces = getLLVMStyle();
14782   Spaces.SpaceAfterLogicalNot = true;
14783 
14784   verifyFormat("bool x = ! y", Spaces);
14785   verifyFormat("if (! isFailure())", Spaces);
14786   verifyFormat("if (! (a && b))", Spaces);
14787   verifyFormat("\"Error!\"", Spaces);
14788   verifyFormat("! ! x", Spaces);
14789 }
14790 
14791 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
14792   FormatStyle Spaces = getLLVMStyle();
14793 
14794   Spaces.SpacesInParentheses = true;
14795   verifyFormat("do_something( ::globalVar );", Spaces);
14796   verifyFormat("call( x, y, z );", Spaces);
14797   verifyFormat("call();", Spaces);
14798   verifyFormat("std::function<void( int, int )> callback;", Spaces);
14799   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
14800                Spaces);
14801   verifyFormat("while ( (bool)1 )\n"
14802                "  continue;",
14803                Spaces);
14804   verifyFormat("for ( ;; )\n"
14805                "  continue;",
14806                Spaces);
14807   verifyFormat("if ( true )\n"
14808                "  f();\n"
14809                "else if ( true )\n"
14810                "  f();",
14811                Spaces);
14812   verifyFormat("do {\n"
14813                "  do_something( (int)i );\n"
14814                "} while ( something() );",
14815                Spaces);
14816   verifyFormat("switch ( x ) {\n"
14817                "default:\n"
14818                "  break;\n"
14819                "}",
14820                Spaces);
14821 
14822   Spaces.SpacesInParentheses = false;
14823   Spaces.SpacesInCStyleCastParentheses = true;
14824   verifyFormat("Type *A = ( Type * )P;", Spaces);
14825   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
14826   verifyFormat("x = ( int32 )y;", Spaces);
14827   verifyFormat("int a = ( int )(2.0f);", Spaces);
14828   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
14829   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
14830   verifyFormat("#define x (( int )-1)", Spaces);
14831 
14832   // Run the first set of tests again with:
14833   Spaces.SpacesInParentheses = false;
14834   Spaces.SpaceInEmptyParentheses = true;
14835   Spaces.SpacesInCStyleCastParentheses = true;
14836   verifyFormat("call(x, y, z);", Spaces);
14837   verifyFormat("call( );", Spaces);
14838   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14839   verifyFormat("while (( bool )1)\n"
14840                "  continue;",
14841                Spaces);
14842   verifyFormat("for (;;)\n"
14843                "  continue;",
14844                Spaces);
14845   verifyFormat("if (true)\n"
14846                "  f( );\n"
14847                "else if (true)\n"
14848                "  f( );",
14849                Spaces);
14850   verifyFormat("do {\n"
14851                "  do_something(( int )i);\n"
14852                "} while (something( ));",
14853                Spaces);
14854   verifyFormat("switch (x) {\n"
14855                "default:\n"
14856                "  break;\n"
14857                "}",
14858                Spaces);
14859 
14860   // Run the first set of tests again with:
14861   Spaces.SpaceAfterCStyleCast = true;
14862   verifyFormat("call(x, y, z);", Spaces);
14863   verifyFormat("call( );", Spaces);
14864   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14865   verifyFormat("while (( bool ) 1)\n"
14866                "  continue;",
14867                Spaces);
14868   verifyFormat("for (;;)\n"
14869                "  continue;",
14870                Spaces);
14871   verifyFormat("if (true)\n"
14872                "  f( );\n"
14873                "else if (true)\n"
14874                "  f( );",
14875                Spaces);
14876   verifyFormat("do {\n"
14877                "  do_something(( int ) i);\n"
14878                "} while (something( ));",
14879                Spaces);
14880   verifyFormat("switch (x) {\n"
14881                "default:\n"
14882                "  break;\n"
14883                "}",
14884                Spaces);
14885   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
14886   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
14887   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
14888   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
14889   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
14890 
14891   // Run subset of tests again with:
14892   Spaces.SpacesInCStyleCastParentheses = false;
14893   Spaces.SpaceAfterCStyleCast = true;
14894   verifyFormat("while ((bool) 1)\n"
14895                "  continue;",
14896                Spaces);
14897   verifyFormat("do {\n"
14898                "  do_something((int) i);\n"
14899                "} while (something( ));",
14900                Spaces);
14901 
14902   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
14903   verifyFormat("size_t idx = (size_t) a;", Spaces);
14904   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
14905   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14906   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14907   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14908   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14909   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
14910   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
14911   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
14912   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
14913   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
14914   Spaces.ColumnLimit = 80;
14915   Spaces.IndentWidth = 4;
14916   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14917   verifyFormat("void foo( ) {\n"
14918                "    size_t foo = (*(function))(\n"
14919                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14920                "BarrrrrrrrrrrrLong,\n"
14921                "        FoooooooooLooooong);\n"
14922                "}",
14923                Spaces);
14924   Spaces.SpaceAfterCStyleCast = false;
14925   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
14926   verifyFormat("size_t idx = (size_t)a;", Spaces);
14927   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
14928   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14929   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14930   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14931   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14932 
14933   verifyFormat("void foo( ) {\n"
14934                "    size_t foo = (*(function))(\n"
14935                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14936                "BarrrrrrrrrrrrLong,\n"
14937                "        FoooooooooLooooong);\n"
14938                "}",
14939                Spaces);
14940 }
14941 
14942 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
14943   verifyFormat("int a[5];");
14944   verifyFormat("a[3] += 42;");
14945 
14946   FormatStyle Spaces = getLLVMStyle();
14947   Spaces.SpacesInSquareBrackets = true;
14948   // Not lambdas.
14949   verifyFormat("int a[ 5 ];", Spaces);
14950   verifyFormat("a[ 3 ] += 42;", Spaces);
14951   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
14952   verifyFormat("double &operator[](int i) { return 0; }\n"
14953                "int i;",
14954                Spaces);
14955   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
14956   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
14957   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
14958   // Lambdas.
14959   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
14960   verifyFormat("return [ i, args... ] {};", Spaces);
14961   verifyFormat("int foo = [ &bar ]() {};", Spaces);
14962   verifyFormat("int foo = [ = ]() {};", Spaces);
14963   verifyFormat("int foo = [ & ]() {};", Spaces);
14964   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
14965   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
14966 }
14967 
14968 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
14969   FormatStyle NoSpaceStyle = getLLVMStyle();
14970   verifyFormat("int a[5];", NoSpaceStyle);
14971   verifyFormat("a[3] += 42;", NoSpaceStyle);
14972 
14973   verifyFormat("int a[1];", NoSpaceStyle);
14974   verifyFormat("int 1 [a];", NoSpaceStyle);
14975   verifyFormat("int a[1][2];", NoSpaceStyle);
14976   verifyFormat("a[7] = 5;", NoSpaceStyle);
14977   verifyFormat("int a = (f())[23];", NoSpaceStyle);
14978   verifyFormat("f([] {})", NoSpaceStyle);
14979 
14980   FormatStyle Space = getLLVMStyle();
14981   Space.SpaceBeforeSquareBrackets = true;
14982   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
14983   verifyFormat("return [i, args...] {};", Space);
14984 
14985   verifyFormat("int a [5];", Space);
14986   verifyFormat("a [3] += 42;", Space);
14987   verifyFormat("constexpr char hello []{\"hello\"};", Space);
14988   verifyFormat("double &operator[](int i) { return 0; }\n"
14989                "int i;",
14990                Space);
14991   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
14992   verifyFormat("int i = a [a][a]->f();", Space);
14993   verifyFormat("int i = (*b) [a]->f();", Space);
14994 
14995   verifyFormat("int a [1];", Space);
14996   verifyFormat("int 1 [a];", Space);
14997   verifyFormat("int a [1][2];", Space);
14998   verifyFormat("a [7] = 5;", Space);
14999   verifyFormat("int a = (f()) [23];", Space);
15000   verifyFormat("f([] {})", Space);
15001 }
15002 
15003 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15004   verifyFormat("int a = 5;");
15005   verifyFormat("a += 42;");
15006   verifyFormat("a or_eq 8;");
15007 
15008   FormatStyle Spaces = getLLVMStyle();
15009   Spaces.SpaceBeforeAssignmentOperators = false;
15010   verifyFormat("int a= 5;", Spaces);
15011   verifyFormat("a+= 42;", Spaces);
15012   verifyFormat("a or_eq 8;", Spaces);
15013 }
15014 
15015 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15016   verifyFormat("class Foo : public Bar {};");
15017   verifyFormat("Foo::Foo() : foo(1) {}");
15018   verifyFormat("for (auto a : b) {\n}");
15019   verifyFormat("int x = a ? b : c;");
15020   verifyFormat("{\n"
15021                "label0:\n"
15022                "  int x = 0;\n"
15023                "}");
15024   verifyFormat("switch (x) {\n"
15025                "case 1:\n"
15026                "default:\n"
15027                "}");
15028   verifyFormat("switch (allBraces) {\n"
15029                "case 1: {\n"
15030                "  break;\n"
15031                "}\n"
15032                "case 2: {\n"
15033                "  [[fallthrough]];\n"
15034                "}\n"
15035                "default: {\n"
15036                "  break;\n"
15037                "}\n"
15038                "}");
15039 
15040   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15041   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15042   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15043   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15044   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15045   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15046   verifyFormat("{\n"
15047                "label1:\n"
15048                "  int x = 0;\n"
15049                "}",
15050                CtorInitializerStyle);
15051   verifyFormat("switch (x) {\n"
15052                "case 1:\n"
15053                "default:\n"
15054                "}",
15055                CtorInitializerStyle);
15056   verifyFormat("switch (allBraces) {\n"
15057                "case 1: {\n"
15058                "  break;\n"
15059                "}\n"
15060                "case 2: {\n"
15061                "  [[fallthrough]];\n"
15062                "}\n"
15063                "default: {\n"
15064                "  break;\n"
15065                "}\n"
15066                "}",
15067                CtorInitializerStyle);
15068   CtorInitializerStyle.BreakConstructorInitializers =
15069       FormatStyle::BCIS_AfterColon;
15070   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15071                "    aaaaaaaaaaaaaaaa(1),\n"
15072                "    bbbbbbbbbbbbbbbb(2) {}",
15073                CtorInitializerStyle);
15074   CtorInitializerStyle.BreakConstructorInitializers =
15075       FormatStyle::BCIS_BeforeComma;
15076   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15077                "    : aaaaaaaaaaaaaaaa(1)\n"
15078                "    , bbbbbbbbbbbbbbbb(2) {}",
15079                CtorInitializerStyle);
15080   CtorInitializerStyle.BreakConstructorInitializers =
15081       FormatStyle::BCIS_BeforeColon;
15082   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15083                "    : aaaaaaaaaaaaaaaa(1),\n"
15084                "      bbbbbbbbbbbbbbbb(2) {}",
15085                CtorInitializerStyle);
15086   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15087   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15088                ": aaaaaaaaaaaaaaaa(1),\n"
15089                "  bbbbbbbbbbbbbbbb(2) {}",
15090                CtorInitializerStyle);
15091 
15092   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15093   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15094   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15095   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15096   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15097   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15098   verifyFormat("{\n"
15099                "label2:\n"
15100                "  int x = 0;\n"
15101                "}",
15102                InheritanceStyle);
15103   verifyFormat("switch (x) {\n"
15104                "case 1:\n"
15105                "default:\n"
15106                "}",
15107                InheritanceStyle);
15108   verifyFormat("switch (allBraces) {\n"
15109                "case 1: {\n"
15110                "  break;\n"
15111                "}\n"
15112                "case 2: {\n"
15113                "  [[fallthrough]];\n"
15114                "}\n"
15115                "default: {\n"
15116                "  break;\n"
15117                "}\n"
15118                "}",
15119                InheritanceStyle);
15120   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15121   verifyFormat("class Foooooooooooooooooooooo\n"
15122                "    : public aaaaaaaaaaaaaaaaaa,\n"
15123                "      public bbbbbbbbbbbbbbbbbb {\n"
15124                "}",
15125                InheritanceStyle);
15126   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15127   verifyFormat("class Foooooooooooooooooooooo:\n"
15128                "    public aaaaaaaaaaaaaaaaaa,\n"
15129                "    public bbbbbbbbbbbbbbbbbb {\n"
15130                "}",
15131                InheritanceStyle);
15132   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15133   verifyFormat("class Foooooooooooooooooooooo\n"
15134                "    : public aaaaaaaaaaaaaaaaaa\n"
15135                "    , public bbbbbbbbbbbbbbbbbb {\n"
15136                "}",
15137                InheritanceStyle);
15138   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15139   verifyFormat("class Foooooooooooooooooooooo\n"
15140                "    : public aaaaaaaaaaaaaaaaaa,\n"
15141                "      public bbbbbbbbbbbbbbbbbb {\n"
15142                "}",
15143                InheritanceStyle);
15144   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15145   verifyFormat("class Foooooooooooooooooooooo\n"
15146                ": public aaaaaaaaaaaaaaaaaa,\n"
15147                "  public bbbbbbbbbbbbbbbbbb {}",
15148                InheritanceStyle);
15149 
15150   FormatStyle ForLoopStyle = getLLVMStyle();
15151   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15152   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15153   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15154   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15155   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15156   verifyFormat("{\n"
15157                "label2:\n"
15158                "  int x = 0;\n"
15159                "}",
15160                ForLoopStyle);
15161   verifyFormat("switch (x) {\n"
15162                "case 1:\n"
15163                "default:\n"
15164                "}",
15165                ForLoopStyle);
15166   verifyFormat("switch (allBraces) {\n"
15167                "case 1: {\n"
15168                "  break;\n"
15169                "}\n"
15170                "case 2: {\n"
15171                "  [[fallthrough]];\n"
15172                "}\n"
15173                "default: {\n"
15174                "  break;\n"
15175                "}\n"
15176                "}",
15177                ForLoopStyle);
15178 
15179   FormatStyle CaseStyle = getLLVMStyle();
15180   CaseStyle.SpaceBeforeCaseColon = true;
15181   verifyFormat("class Foo : public Bar {};", CaseStyle);
15182   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15183   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15184   verifyFormat("int x = a ? b : c;", CaseStyle);
15185   verifyFormat("switch (x) {\n"
15186                "case 1 :\n"
15187                "default :\n"
15188                "}",
15189                CaseStyle);
15190   verifyFormat("switch (allBraces) {\n"
15191                "case 1 : {\n"
15192                "  break;\n"
15193                "}\n"
15194                "case 2 : {\n"
15195                "  [[fallthrough]];\n"
15196                "}\n"
15197                "default : {\n"
15198                "  break;\n"
15199                "}\n"
15200                "}",
15201                CaseStyle);
15202 
15203   FormatStyle NoSpaceStyle = getLLVMStyle();
15204   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15205   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15206   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15207   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15208   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15209   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15210   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15211   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15212   verifyFormat("{\n"
15213                "label3:\n"
15214                "  int x = 0;\n"
15215                "}",
15216                NoSpaceStyle);
15217   verifyFormat("switch (x) {\n"
15218                "case 1:\n"
15219                "default:\n"
15220                "}",
15221                NoSpaceStyle);
15222   verifyFormat("switch (allBraces) {\n"
15223                "case 1: {\n"
15224                "  break;\n"
15225                "}\n"
15226                "case 2: {\n"
15227                "  [[fallthrough]];\n"
15228                "}\n"
15229                "default: {\n"
15230                "  break;\n"
15231                "}\n"
15232                "}",
15233                NoSpaceStyle);
15234 
15235   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15236   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15237   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15238   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15239   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15240   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15241   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15242   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15243   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15244   verifyFormat("{\n"
15245                "label3:\n"
15246                "  int x = 0;\n"
15247                "}",
15248                InvertedSpaceStyle);
15249   verifyFormat("switch (x) {\n"
15250                "case 1 :\n"
15251                "case 2 : {\n"
15252                "  break;\n"
15253                "}\n"
15254                "default :\n"
15255                "  break;\n"
15256                "}",
15257                InvertedSpaceStyle);
15258   verifyFormat("switch (allBraces) {\n"
15259                "case 1 : {\n"
15260                "  break;\n"
15261                "}\n"
15262                "case 2 : {\n"
15263                "  [[fallthrough]];\n"
15264                "}\n"
15265                "default : {\n"
15266                "  break;\n"
15267                "}\n"
15268                "}",
15269                InvertedSpaceStyle);
15270 }
15271 
15272 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15273   FormatStyle Style = getLLVMStyle();
15274 
15275   Style.PointerAlignment = FormatStyle::PAS_Left;
15276   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15277   verifyFormat("void* const* x = NULL;", Style);
15278 
15279 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15280   do {                                                                         \
15281     Style.PointerAlignment = FormatStyle::Pointers;                            \
15282     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15283     verifyFormat(Code, Style);                                                 \
15284   } while (false)
15285 
15286   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15287   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15288   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15289 
15290   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15291   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15292   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15293 
15294   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15295   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15296   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15297 
15298   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15299   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15300   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15301 
15302   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15303   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15304                         SAPQ_Default);
15305   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15306                         SAPQ_Default);
15307 
15308   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15309   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15310                         SAPQ_Before);
15311   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15312                         SAPQ_Before);
15313 
15314   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15315   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15316   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15317                         SAPQ_After);
15318 
15319   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15320   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15321   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15322 
15323 #undef verifyQualifierSpaces
15324 
15325   FormatStyle Spaces = getLLVMStyle();
15326   Spaces.AttributeMacros.push_back("qualified");
15327   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15328   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15329   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15330   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15331   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15332   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15333   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15334   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15335   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15336   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15337   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15338   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15339   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15340 
15341   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15342   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15343   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15344   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15345   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15346   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15347   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15348   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15349   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15350   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15351   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15352   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15353   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15354   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15355   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15356 
15357   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15358   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15359   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15360   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15361   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15362   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15363   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15364   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15365 }
15366 
15367 TEST_F(FormatTest, AlignConsecutiveMacros) {
15368   FormatStyle Style = getLLVMStyle();
15369   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15370   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15371   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15372 
15373   verifyFormat("#define a 3\n"
15374                "#define bbbb 4\n"
15375                "#define ccc (5)",
15376                Style);
15377 
15378   verifyFormat("#define f(x) (x * x)\n"
15379                "#define fff(x, y, z) (x * y + z)\n"
15380                "#define ffff(x, y) (x - y)",
15381                Style);
15382 
15383   verifyFormat("#define foo(x, y) (x + y)\n"
15384                "#define bar (5, 6)(2 + 2)",
15385                Style);
15386 
15387   verifyFormat("#define a 3\n"
15388                "#define bbbb 4\n"
15389                "#define ccc (5)\n"
15390                "#define f(x) (x * x)\n"
15391                "#define fff(x, y, z) (x * y + z)\n"
15392                "#define ffff(x, y) (x - y)",
15393                Style);
15394 
15395   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15396   verifyFormat("#define a    3\n"
15397                "#define bbbb 4\n"
15398                "#define ccc  (5)",
15399                Style);
15400 
15401   verifyFormat("#define f(x)         (x * x)\n"
15402                "#define fff(x, y, z) (x * y + z)\n"
15403                "#define ffff(x, y)   (x - y)",
15404                Style);
15405 
15406   verifyFormat("#define foo(x, y) (x + y)\n"
15407                "#define bar       (5, 6)(2 + 2)",
15408                Style);
15409 
15410   verifyFormat("#define a            3\n"
15411                "#define bbbb         4\n"
15412                "#define ccc          (5)\n"
15413                "#define f(x)         (x * x)\n"
15414                "#define fff(x, y, z) (x * y + z)\n"
15415                "#define ffff(x, y)   (x - y)",
15416                Style);
15417 
15418   verifyFormat("#define a         5\n"
15419                "#define foo(x, y) (x + y)\n"
15420                "#define CCC       (6)\n"
15421                "auto lambda = []() {\n"
15422                "  auto  ii = 0;\n"
15423                "  float j  = 0;\n"
15424                "  return 0;\n"
15425                "};\n"
15426                "int   i  = 0;\n"
15427                "float i2 = 0;\n"
15428                "auto  v  = type{\n"
15429                "    i = 1,   //\n"
15430                "    (i = 2), //\n"
15431                "    i = 3    //\n"
15432                "};",
15433                Style);
15434 
15435   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15436   Style.ColumnLimit = 20;
15437 
15438   verifyFormat("#define a          \\\n"
15439                "  \"aabbbbbbbbbbbb\"\n"
15440                "#define D          \\\n"
15441                "  \"aabbbbbbbbbbbb\" \\\n"
15442                "  \"ccddeeeeeeeee\"\n"
15443                "#define B          \\\n"
15444                "  \"QQQQQQQQQQQQQ\"  \\\n"
15445                "  \"FFFFFFFFFFFFF\"  \\\n"
15446                "  \"LLLLLLLL\"\n",
15447                Style);
15448 
15449   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15450   verifyFormat("#define a          \\\n"
15451                "  \"aabbbbbbbbbbbb\"\n"
15452                "#define D          \\\n"
15453                "  \"aabbbbbbbbbbbb\" \\\n"
15454                "  \"ccddeeeeeeeee\"\n"
15455                "#define B          \\\n"
15456                "  \"QQQQQQQQQQQQQ\"  \\\n"
15457                "  \"FFFFFFFFFFFFF\"  \\\n"
15458                "  \"LLLLLLLL\"\n",
15459                Style);
15460 
15461   // Test across comments
15462   Style.MaxEmptyLinesToKeep = 10;
15463   Style.ReflowComments = false;
15464   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
15465   EXPECT_EQ("#define a    3\n"
15466             "// line comment\n"
15467             "#define bbbb 4\n"
15468             "#define ccc  (5)",
15469             format("#define a 3\n"
15470                    "// line comment\n"
15471                    "#define bbbb 4\n"
15472                    "#define ccc (5)",
15473                    Style));
15474 
15475   EXPECT_EQ("#define a    3\n"
15476             "/* block comment */\n"
15477             "#define bbbb 4\n"
15478             "#define ccc  (5)",
15479             format("#define a  3\n"
15480                    "/* block comment */\n"
15481                    "#define bbbb 4\n"
15482                    "#define ccc (5)",
15483                    Style));
15484 
15485   EXPECT_EQ("#define a    3\n"
15486             "/* multi-line *\n"
15487             " * block comment */\n"
15488             "#define bbbb 4\n"
15489             "#define ccc  (5)",
15490             format("#define a 3\n"
15491                    "/* multi-line *\n"
15492                    " * block comment */\n"
15493                    "#define bbbb 4\n"
15494                    "#define ccc (5)",
15495                    Style));
15496 
15497   EXPECT_EQ("#define a    3\n"
15498             "// multi-line line comment\n"
15499             "//\n"
15500             "#define bbbb 4\n"
15501             "#define ccc  (5)",
15502             format("#define a  3\n"
15503                    "// multi-line line comment\n"
15504                    "//\n"
15505                    "#define bbbb 4\n"
15506                    "#define ccc (5)",
15507                    Style));
15508 
15509   EXPECT_EQ("#define a 3\n"
15510             "// empty lines still break.\n"
15511             "\n"
15512             "#define bbbb 4\n"
15513             "#define ccc  (5)",
15514             format("#define a     3\n"
15515                    "// empty lines still break.\n"
15516                    "\n"
15517                    "#define bbbb     4\n"
15518                    "#define ccc  (5)",
15519                    Style));
15520 
15521   // Test across empty lines
15522   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
15523   EXPECT_EQ("#define a    3\n"
15524             "\n"
15525             "#define bbbb 4\n"
15526             "#define ccc  (5)",
15527             format("#define a 3\n"
15528                    "\n"
15529                    "#define bbbb 4\n"
15530                    "#define ccc (5)",
15531                    Style));
15532 
15533   EXPECT_EQ("#define a    3\n"
15534             "\n"
15535             "\n"
15536             "\n"
15537             "#define bbbb 4\n"
15538             "#define ccc  (5)",
15539             format("#define a        3\n"
15540                    "\n"
15541                    "\n"
15542                    "\n"
15543                    "#define bbbb 4\n"
15544                    "#define ccc (5)",
15545                    Style));
15546 
15547   EXPECT_EQ("#define a 3\n"
15548             "// comments should break alignment\n"
15549             "//\n"
15550             "#define bbbb 4\n"
15551             "#define ccc  (5)",
15552             format("#define a        3\n"
15553                    "// comments should break alignment\n"
15554                    "//\n"
15555                    "#define bbbb 4\n"
15556                    "#define ccc (5)",
15557                    Style));
15558 
15559   // Test across empty lines and comments
15560   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
15561   verifyFormat("#define a    3\n"
15562                "\n"
15563                "// line comment\n"
15564                "#define bbbb 4\n"
15565                "#define ccc  (5)",
15566                Style);
15567 
15568   EXPECT_EQ("#define a    3\n"
15569             "\n"
15570             "\n"
15571             "/* multi-line *\n"
15572             " * block comment */\n"
15573             "\n"
15574             "\n"
15575             "#define bbbb 4\n"
15576             "#define ccc  (5)",
15577             format("#define a 3\n"
15578                    "\n"
15579                    "\n"
15580                    "/* multi-line *\n"
15581                    " * block comment */\n"
15582                    "\n"
15583                    "\n"
15584                    "#define bbbb 4\n"
15585                    "#define ccc (5)",
15586                    Style));
15587 
15588   EXPECT_EQ("#define a    3\n"
15589             "\n"
15590             "\n"
15591             "/* multi-line *\n"
15592             " * block comment */\n"
15593             "\n"
15594             "\n"
15595             "#define bbbb 4\n"
15596             "#define ccc  (5)",
15597             format("#define a 3\n"
15598                    "\n"
15599                    "\n"
15600                    "/* multi-line *\n"
15601                    " * block comment */\n"
15602                    "\n"
15603                    "\n"
15604                    "#define bbbb 4\n"
15605                    "#define ccc       (5)",
15606                    Style));
15607 }
15608 
15609 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
15610   FormatStyle Alignment = getLLVMStyle();
15611   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15612   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
15613 
15614   Alignment.MaxEmptyLinesToKeep = 10;
15615   /* Test alignment across empty lines */
15616   EXPECT_EQ("int a           = 5;\n"
15617             "\n"
15618             "int oneTwoThree = 123;",
15619             format("int a       = 5;\n"
15620                    "\n"
15621                    "int oneTwoThree= 123;",
15622                    Alignment));
15623   EXPECT_EQ("int a           = 5;\n"
15624             "int one         = 1;\n"
15625             "\n"
15626             "int oneTwoThree = 123;",
15627             format("int a = 5;\n"
15628                    "int one = 1;\n"
15629                    "\n"
15630                    "int oneTwoThree = 123;",
15631                    Alignment));
15632   EXPECT_EQ("int a           = 5;\n"
15633             "int one         = 1;\n"
15634             "\n"
15635             "int oneTwoThree = 123;\n"
15636             "int oneTwo      = 12;",
15637             format("int a = 5;\n"
15638                    "int one = 1;\n"
15639                    "\n"
15640                    "int oneTwoThree = 123;\n"
15641                    "int oneTwo = 12;",
15642                    Alignment));
15643 
15644   /* Test across comments */
15645   EXPECT_EQ("int a = 5;\n"
15646             "/* block comment */\n"
15647             "int oneTwoThree = 123;",
15648             format("int a = 5;\n"
15649                    "/* block comment */\n"
15650                    "int oneTwoThree=123;",
15651                    Alignment));
15652 
15653   EXPECT_EQ("int a = 5;\n"
15654             "// line comment\n"
15655             "int oneTwoThree = 123;",
15656             format("int a = 5;\n"
15657                    "// line comment\n"
15658                    "int oneTwoThree=123;",
15659                    Alignment));
15660 
15661   /* Test across comments and newlines */
15662   EXPECT_EQ("int a = 5;\n"
15663             "\n"
15664             "/* block comment */\n"
15665             "int oneTwoThree = 123;",
15666             format("int a = 5;\n"
15667                    "\n"
15668                    "/* block comment */\n"
15669                    "int oneTwoThree=123;",
15670                    Alignment));
15671 
15672   EXPECT_EQ("int a = 5;\n"
15673             "\n"
15674             "// line comment\n"
15675             "int oneTwoThree = 123;",
15676             format("int a = 5;\n"
15677                    "\n"
15678                    "// line comment\n"
15679                    "int oneTwoThree=123;",
15680                    Alignment));
15681 }
15682 
15683 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
15684   FormatStyle Alignment = getLLVMStyle();
15685   Alignment.AlignConsecutiveDeclarations =
15686       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15687   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15688 
15689   Alignment.MaxEmptyLinesToKeep = 10;
15690   /* Test alignment across empty lines */
15691   EXPECT_EQ("int         a = 5;\n"
15692             "\n"
15693             "float const oneTwoThree = 123;",
15694             format("int a = 5;\n"
15695                    "\n"
15696                    "float const oneTwoThree = 123;",
15697                    Alignment));
15698   EXPECT_EQ("int         a = 5;\n"
15699             "float const one = 1;\n"
15700             "\n"
15701             "int         oneTwoThree = 123;",
15702             format("int a = 5;\n"
15703                    "float const one = 1;\n"
15704                    "\n"
15705                    "int oneTwoThree = 123;",
15706                    Alignment));
15707 
15708   /* Test across comments */
15709   EXPECT_EQ("float const a = 5;\n"
15710             "/* block comment */\n"
15711             "int         oneTwoThree = 123;",
15712             format("float const a = 5;\n"
15713                    "/* block comment */\n"
15714                    "int oneTwoThree=123;",
15715                    Alignment));
15716 
15717   EXPECT_EQ("float const a = 5;\n"
15718             "// line comment\n"
15719             "int         oneTwoThree = 123;",
15720             format("float const a = 5;\n"
15721                    "// line comment\n"
15722                    "int oneTwoThree=123;",
15723                    Alignment));
15724 
15725   /* Test across comments and newlines */
15726   EXPECT_EQ("float const a = 5;\n"
15727             "\n"
15728             "/* block comment */\n"
15729             "int         oneTwoThree = 123;",
15730             format("float const a = 5;\n"
15731                    "\n"
15732                    "/* block comment */\n"
15733                    "int         oneTwoThree=123;",
15734                    Alignment));
15735 
15736   EXPECT_EQ("float const a = 5;\n"
15737             "\n"
15738             "// line comment\n"
15739             "int         oneTwoThree = 123;",
15740             format("float const a = 5;\n"
15741                    "\n"
15742                    "// line comment\n"
15743                    "int oneTwoThree=123;",
15744                    Alignment));
15745 }
15746 
15747 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
15748   FormatStyle Alignment = getLLVMStyle();
15749   Alignment.AlignConsecutiveBitFields =
15750       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15751 
15752   Alignment.MaxEmptyLinesToKeep = 10;
15753   /* Test alignment across empty lines */
15754   EXPECT_EQ("int a            : 5;\n"
15755             "\n"
15756             "int longbitfield : 6;",
15757             format("int a : 5;\n"
15758                    "\n"
15759                    "int longbitfield : 6;",
15760                    Alignment));
15761   EXPECT_EQ("int a            : 5;\n"
15762             "int one          : 1;\n"
15763             "\n"
15764             "int longbitfield : 6;",
15765             format("int a : 5;\n"
15766                    "int one : 1;\n"
15767                    "\n"
15768                    "int longbitfield : 6;",
15769                    Alignment));
15770 
15771   /* Test across comments */
15772   EXPECT_EQ("int a            : 5;\n"
15773             "/* block comment */\n"
15774             "int longbitfield : 6;",
15775             format("int a : 5;\n"
15776                    "/* block comment */\n"
15777                    "int longbitfield : 6;",
15778                    Alignment));
15779   EXPECT_EQ("int a            : 5;\n"
15780             "int one          : 1;\n"
15781             "// line comment\n"
15782             "int longbitfield : 6;",
15783             format("int a : 5;\n"
15784                    "int one : 1;\n"
15785                    "// line comment\n"
15786                    "int longbitfield : 6;",
15787                    Alignment));
15788 
15789   /* Test across comments and newlines */
15790   EXPECT_EQ("int a            : 5;\n"
15791             "/* block comment */\n"
15792             "\n"
15793             "int longbitfield : 6;",
15794             format("int a : 5;\n"
15795                    "/* block comment */\n"
15796                    "\n"
15797                    "int longbitfield : 6;",
15798                    Alignment));
15799   EXPECT_EQ("int a            : 5;\n"
15800             "int one          : 1;\n"
15801             "\n"
15802             "// line comment\n"
15803             "\n"
15804             "int longbitfield : 6;",
15805             format("int a : 5;\n"
15806                    "int one : 1;\n"
15807                    "\n"
15808                    "// line comment \n"
15809                    "\n"
15810                    "int longbitfield : 6;",
15811                    Alignment));
15812 }
15813 
15814 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
15815   FormatStyle Alignment = getLLVMStyle();
15816   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15817   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
15818 
15819   Alignment.MaxEmptyLinesToKeep = 10;
15820   /* Test alignment across empty lines */
15821   EXPECT_EQ("int a = 5;\n"
15822             "\n"
15823             "int oneTwoThree = 123;",
15824             format("int a       = 5;\n"
15825                    "\n"
15826                    "int oneTwoThree= 123;",
15827                    Alignment));
15828   EXPECT_EQ("int a   = 5;\n"
15829             "int one = 1;\n"
15830             "\n"
15831             "int oneTwoThree = 123;",
15832             format("int a = 5;\n"
15833                    "int one = 1;\n"
15834                    "\n"
15835                    "int oneTwoThree = 123;",
15836                    Alignment));
15837 
15838   /* Test across comments */
15839   EXPECT_EQ("int a           = 5;\n"
15840             "/* block comment */\n"
15841             "int oneTwoThree = 123;",
15842             format("int a = 5;\n"
15843                    "/* block comment */\n"
15844                    "int oneTwoThree=123;",
15845                    Alignment));
15846 
15847   EXPECT_EQ("int a           = 5;\n"
15848             "// line comment\n"
15849             "int oneTwoThree = 123;",
15850             format("int a = 5;\n"
15851                    "// line comment\n"
15852                    "int oneTwoThree=123;",
15853                    Alignment));
15854 
15855   EXPECT_EQ("int a           = 5;\n"
15856             "/*\n"
15857             " * multi-line block comment\n"
15858             " */\n"
15859             "int oneTwoThree = 123;",
15860             format("int a = 5;\n"
15861                    "/*\n"
15862                    " * multi-line block comment\n"
15863                    " */\n"
15864                    "int oneTwoThree=123;",
15865                    Alignment));
15866 
15867   EXPECT_EQ("int a           = 5;\n"
15868             "//\n"
15869             "// multi-line line comment\n"
15870             "//\n"
15871             "int oneTwoThree = 123;",
15872             format("int a = 5;\n"
15873                    "//\n"
15874                    "// multi-line line comment\n"
15875                    "//\n"
15876                    "int oneTwoThree=123;",
15877                    Alignment));
15878 
15879   /* Test across comments and newlines */
15880   EXPECT_EQ("int a = 5;\n"
15881             "\n"
15882             "/* block comment */\n"
15883             "int oneTwoThree = 123;",
15884             format("int a = 5;\n"
15885                    "\n"
15886                    "/* block comment */\n"
15887                    "int oneTwoThree=123;",
15888                    Alignment));
15889 
15890   EXPECT_EQ("int a = 5;\n"
15891             "\n"
15892             "// line comment\n"
15893             "int oneTwoThree = 123;",
15894             format("int a = 5;\n"
15895                    "\n"
15896                    "// line comment\n"
15897                    "int oneTwoThree=123;",
15898                    Alignment));
15899 }
15900 
15901 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
15902   FormatStyle Alignment = getLLVMStyle();
15903   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15904   Alignment.AlignConsecutiveAssignments =
15905       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15906   verifyFormat("int a           = 5;\n"
15907                "int oneTwoThree = 123;",
15908                Alignment);
15909   verifyFormat("int a           = method();\n"
15910                "int oneTwoThree = 133;",
15911                Alignment);
15912   verifyFormat("a &= 5;\n"
15913                "bcd *= 5;\n"
15914                "ghtyf += 5;\n"
15915                "dvfvdb -= 5;\n"
15916                "a /= 5;\n"
15917                "vdsvsv %= 5;\n"
15918                "sfdbddfbdfbb ^= 5;\n"
15919                "dvsdsv |= 5;\n"
15920                "int dsvvdvsdvvv = 123;",
15921                Alignment);
15922   verifyFormat("int i = 1, j = 10;\n"
15923                "something = 2000;",
15924                Alignment);
15925   verifyFormat("something = 2000;\n"
15926                "int i = 1, j = 10;\n",
15927                Alignment);
15928   verifyFormat("something = 2000;\n"
15929                "another   = 911;\n"
15930                "int i = 1, j = 10;\n"
15931                "oneMore = 1;\n"
15932                "i       = 2;",
15933                Alignment);
15934   verifyFormat("int a   = 5;\n"
15935                "int one = 1;\n"
15936                "method();\n"
15937                "int oneTwoThree = 123;\n"
15938                "int oneTwo      = 12;",
15939                Alignment);
15940   verifyFormat("int oneTwoThree = 123;\n"
15941                "int oneTwo      = 12;\n"
15942                "method();\n",
15943                Alignment);
15944   verifyFormat("int oneTwoThree = 123; // comment\n"
15945                "int oneTwo      = 12;  // comment",
15946                Alignment);
15947 
15948   // Bug 25167
15949   /* Uncomment when fixed
15950     verifyFormat("#if A\n"
15951                  "#else\n"
15952                  "int aaaaaaaa = 12;\n"
15953                  "#endif\n"
15954                  "#if B\n"
15955                  "#else\n"
15956                  "int a = 12;\n"
15957                  "#endif\n",
15958                  Alignment);
15959     verifyFormat("enum foo {\n"
15960                  "#if A\n"
15961                  "#else\n"
15962                  "  aaaaaaaa = 12;\n"
15963                  "#endif\n"
15964                  "#if B\n"
15965                  "#else\n"
15966                  "  a = 12;\n"
15967                  "#endif\n"
15968                  "};\n",
15969                  Alignment);
15970   */
15971 
15972   Alignment.MaxEmptyLinesToKeep = 10;
15973   /* Test alignment across empty lines */
15974   EXPECT_EQ("int a           = 5;\n"
15975             "\n"
15976             "int oneTwoThree = 123;",
15977             format("int a       = 5;\n"
15978                    "\n"
15979                    "int oneTwoThree= 123;",
15980                    Alignment));
15981   EXPECT_EQ("int a           = 5;\n"
15982             "int one         = 1;\n"
15983             "\n"
15984             "int oneTwoThree = 123;",
15985             format("int a = 5;\n"
15986                    "int one = 1;\n"
15987                    "\n"
15988                    "int oneTwoThree = 123;",
15989                    Alignment));
15990   EXPECT_EQ("int a           = 5;\n"
15991             "int one         = 1;\n"
15992             "\n"
15993             "int oneTwoThree = 123;\n"
15994             "int oneTwo      = 12;",
15995             format("int a = 5;\n"
15996                    "int one = 1;\n"
15997                    "\n"
15998                    "int oneTwoThree = 123;\n"
15999                    "int oneTwo = 12;",
16000                    Alignment));
16001 
16002   /* Test across comments */
16003   EXPECT_EQ("int a           = 5;\n"
16004             "/* block comment */\n"
16005             "int oneTwoThree = 123;",
16006             format("int a = 5;\n"
16007                    "/* block comment */\n"
16008                    "int oneTwoThree=123;",
16009                    Alignment));
16010 
16011   EXPECT_EQ("int a           = 5;\n"
16012             "// line comment\n"
16013             "int oneTwoThree = 123;",
16014             format("int a = 5;\n"
16015                    "// line comment\n"
16016                    "int oneTwoThree=123;",
16017                    Alignment));
16018 
16019   /* Test across comments and newlines */
16020   EXPECT_EQ("int a           = 5;\n"
16021             "\n"
16022             "/* block comment */\n"
16023             "int oneTwoThree = 123;",
16024             format("int a = 5;\n"
16025                    "\n"
16026                    "/* block comment */\n"
16027                    "int oneTwoThree=123;",
16028                    Alignment));
16029 
16030   EXPECT_EQ("int a           = 5;\n"
16031             "\n"
16032             "// line comment\n"
16033             "int oneTwoThree = 123;",
16034             format("int a = 5;\n"
16035                    "\n"
16036                    "// line comment\n"
16037                    "int oneTwoThree=123;",
16038                    Alignment));
16039 
16040   EXPECT_EQ("int a           = 5;\n"
16041             "//\n"
16042             "// multi-line line comment\n"
16043             "//\n"
16044             "int oneTwoThree = 123;",
16045             format("int a = 5;\n"
16046                    "//\n"
16047                    "// multi-line line comment\n"
16048                    "//\n"
16049                    "int oneTwoThree=123;",
16050                    Alignment));
16051 
16052   EXPECT_EQ("int a           = 5;\n"
16053             "/*\n"
16054             " *  multi-line block comment\n"
16055             " */\n"
16056             "int oneTwoThree = 123;",
16057             format("int a = 5;\n"
16058                    "/*\n"
16059                    " *  multi-line block comment\n"
16060                    " */\n"
16061                    "int oneTwoThree=123;",
16062                    Alignment));
16063 
16064   EXPECT_EQ("int a           = 5;\n"
16065             "\n"
16066             "/* block comment */\n"
16067             "\n"
16068             "\n"
16069             "\n"
16070             "int oneTwoThree = 123;",
16071             format("int a = 5;\n"
16072                    "\n"
16073                    "/* block comment */\n"
16074                    "\n"
16075                    "\n"
16076                    "\n"
16077                    "int oneTwoThree=123;",
16078                    Alignment));
16079 
16080   EXPECT_EQ("int a           = 5;\n"
16081             "\n"
16082             "// line comment\n"
16083             "\n"
16084             "\n"
16085             "\n"
16086             "int oneTwoThree = 123;",
16087             format("int a = 5;\n"
16088                    "\n"
16089                    "// line comment\n"
16090                    "\n"
16091                    "\n"
16092                    "\n"
16093                    "int oneTwoThree=123;",
16094                    Alignment));
16095 
16096   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16097   verifyFormat("#define A \\\n"
16098                "  int aaaa       = 12; \\\n"
16099                "  int b          = 23; \\\n"
16100                "  int ccc        = 234; \\\n"
16101                "  int dddddddddd = 2345;",
16102                Alignment);
16103   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16104   verifyFormat("#define A               \\\n"
16105                "  int aaaa       = 12;  \\\n"
16106                "  int b          = 23;  \\\n"
16107                "  int ccc        = 234; \\\n"
16108                "  int dddddddddd = 2345;",
16109                Alignment);
16110   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16111   verifyFormat("#define A                                                      "
16112                "                \\\n"
16113                "  int aaaa       = 12;                                         "
16114                "                \\\n"
16115                "  int b          = 23;                                         "
16116                "                \\\n"
16117                "  int ccc        = 234;                                        "
16118                "                \\\n"
16119                "  int dddddddddd = 2345;",
16120                Alignment);
16121   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16122                "k = 4, int l = 5,\n"
16123                "                  int m = 6) {\n"
16124                "  int j      = 10;\n"
16125                "  otherThing = 1;\n"
16126                "}",
16127                Alignment);
16128   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16129                "  int i   = 1;\n"
16130                "  int j   = 2;\n"
16131                "  int big = 10000;\n"
16132                "}",
16133                Alignment);
16134   verifyFormat("class C {\n"
16135                "public:\n"
16136                "  int i            = 1;\n"
16137                "  virtual void f() = 0;\n"
16138                "};",
16139                Alignment);
16140   verifyFormat("int i = 1;\n"
16141                "if (SomeType t = getSomething()) {\n"
16142                "}\n"
16143                "int j   = 2;\n"
16144                "int big = 10000;",
16145                Alignment);
16146   verifyFormat("int j = 7;\n"
16147                "for (int k = 0; k < N; ++k) {\n"
16148                "}\n"
16149                "int j   = 2;\n"
16150                "int big = 10000;\n"
16151                "}",
16152                Alignment);
16153   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16154   verifyFormat("int i = 1;\n"
16155                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16156                "    = someLooooooooooooooooongFunction();\n"
16157                "int j = 2;",
16158                Alignment);
16159   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16160   verifyFormat("int i = 1;\n"
16161                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16162                "    someLooooooooooooooooongFunction();\n"
16163                "int j = 2;",
16164                Alignment);
16165 
16166   verifyFormat("auto lambda = []() {\n"
16167                "  auto i = 0;\n"
16168                "  return 0;\n"
16169                "};\n"
16170                "int i  = 0;\n"
16171                "auto v = type{\n"
16172                "    i = 1,   //\n"
16173                "    (i = 2), //\n"
16174                "    i = 3    //\n"
16175                "};",
16176                Alignment);
16177 
16178   verifyFormat(
16179       "int i      = 1;\n"
16180       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16181       "                          loooooooooooooooooooooongParameterB);\n"
16182       "int j      = 2;",
16183       Alignment);
16184 
16185   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16186                "          typename B   = very_long_type_name_1,\n"
16187                "          typename T_2 = very_long_type_name_2>\n"
16188                "auto foo() {}\n",
16189                Alignment);
16190   verifyFormat("int a, b = 1;\n"
16191                "int c  = 2;\n"
16192                "int dd = 3;\n",
16193                Alignment);
16194   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16195                "float b[1][] = {{3.f}};\n",
16196                Alignment);
16197   verifyFormat("for (int i = 0; i < 1; i++)\n"
16198                "  int x = 1;\n",
16199                Alignment);
16200   verifyFormat("for (i = 0; i < 1; i++)\n"
16201                "  x = 1;\n"
16202                "y = 1;\n",
16203                Alignment);
16204 
16205   Alignment.ReflowComments = true;
16206   Alignment.ColumnLimit = 50;
16207   EXPECT_EQ("int x   = 0;\n"
16208             "int yy  = 1; /// specificlennospace\n"
16209             "int zzz = 2;\n",
16210             format("int x   = 0;\n"
16211                    "int yy  = 1; ///specificlennospace\n"
16212                    "int zzz = 2;\n",
16213                    Alignment));
16214 }
16215 
16216 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16217   FormatStyle Alignment = getLLVMStyle();
16218   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16219   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16220   verifyFormat("int a = 5;\n"
16221                "int oneTwoThree = 123;",
16222                Alignment);
16223   verifyFormat("int a = 5;\n"
16224                "int oneTwoThree = 123;",
16225                Alignment);
16226 
16227   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16228   verifyFormat("int a           = 5;\n"
16229                "int oneTwoThree = 123;",
16230                Alignment);
16231   verifyFormat("int a           = method();\n"
16232                "int oneTwoThree = 133;",
16233                Alignment);
16234   verifyFormat("a &= 5;\n"
16235                "bcd *= 5;\n"
16236                "ghtyf += 5;\n"
16237                "dvfvdb -= 5;\n"
16238                "a /= 5;\n"
16239                "vdsvsv %= 5;\n"
16240                "sfdbddfbdfbb ^= 5;\n"
16241                "dvsdsv |= 5;\n"
16242                "int dsvvdvsdvvv = 123;",
16243                Alignment);
16244   verifyFormat("int i = 1, j = 10;\n"
16245                "something = 2000;",
16246                Alignment);
16247   verifyFormat("something = 2000;\n"
16248                "int i = 1, j = 10;\n",
16249                Alignment);
16250   verifyFormat("something = 2000;\n"
16251                "another   = 911;\n"
16252                "int i = 1, j = 10;\n"
16253                "oneMore = 1;\n"
16254                "i       = 2;",
16255                Alignment);
16256   verifyFormat("int a   = 5;\n"
16257                "int one = 1;\n"
16258                "method();\n"
16259                "int oneTwoThree = 123;\n"
16260                "int oneTwo      = 12;",
16261                Alignment);
16262   verifyFormat("int oneTwoThree = 123;\n"
16263                "int oneTwo      = 12;\n"
16264                "method();\n",
16265                Alignment);
16266   verifyFormat("int oneTwoThree = 123; // comment\n"
16267                "int oneTwo      = 12;  // comment",
16268                Alignment);
16269 
16270   // Bug 25167
16271   /* Uncomment when fixed
16272     verifyFormat("#if A\n"
16273                  "#else\n"
16274                  "int aaaaaaaa = 12;\n"
16275                  "#endif\n"
16276                  "#if B\n"
16277                  "#else\n"
16278                  "int a = 12;\n"
16279                  "#endif\n",
16280                  Alignment);
16281     verifyFormat("enum foo {\n"
16282                  "#if A\n"
16283                  "#else\n"
16284                  "  aaaaaaaa = 12;\n"
16285                  "#endif\n"
16286                  "#if B\n"
16287                  "#else\n"
16288                  "  a = 12;\n"
16289                  "#endif\n"
16290                  "};\n",
16291                  Alignment);
16292   */
16293 
16294   EXPECT_EQ("int a = 5;\n"
16295             "\n"
16296             "int oneTwoThree = 123;",
16297             format("int a       = 5;\n"
16298                    "\n"
16299                    "int oneTwoThree= 123;",
16300                    Alignment));
16301   EXPECT_EQ("int a   = 5;\n"
16302             "int one = 1;\n"
16303             "\n"
16304             "int oneTwoThree = 123;",
16305             format("int a = 5;\n"
16306                    "int one = 1;\n"
16307                    "\n"
16308                    "int oneTwoThree = 123;",
16309                    Alignment));
16310   EXPECT_EQ("int a   = 5;\n"
16311             "int one = 1;\n"
16312             "\n"
16313             "int oneTwoThree = 123;\n"
16314             "int oneTwo      = 12;",
16315             format("int a = 5;\n"
16316                    "int one = 1;\n"
16317                    "\n"
16318                    "int oneTwoThree = 123;\n"
16319                    "int oneTwo = 12;",
16320                    Alignment));
16321   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16322   verifyFormat("#define A \\\n"
16323                "  int aaaa       = 12; \\\n"
16324                "  int b          = 23; \\\n"
16325                "  int ccc        = 234; \\\n"
16326                "  int dddddddddd = 2345;",
16327                Alignment);
16328   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16329   verifyFormat("#define A               \\\n"
16330                "  int aaaa       = 12;  \\\n"
16331                "  int b          = 23;  \\\n"
16332                "  int ccc        = 234; \\\n"
16333                "  int dddddddddd = 2345;",
16334                Alignment);
16335   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16336   verifyFormat("#define A                                                      "
16337                "                \\\n"
16338                "  int aaaa       = 12;                                         "
16339                "                \\\n"
16340                "  int b          = 23;                                         "
16341                "                \\\n"
16342                "  int ccc        = 234;                                        "
16343                "                \\\n"
16344                "  int dddddddddd = 2345;",
16345                Alignment);
16346   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16347                "k = 4, int l = 5,\n"
16348                "                  int m = 6) {\n"
16349                "  int j      = 10;\n"
16350                "  otherThing = 1;\n"
16351                "}",
16352                Alignment);
16353   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16354                "  int i   = 1;\n"
16355                "  int j   = 2;\n"
16356                "  int big = 10000;\n"
16357                "}",
16358                Alignment);
16359   verifyFormat("class C {\n"
16360                "public:\n"
16361                "  int i            = 1;\n"
16362                "  virtual void f() = 0;\n"
16363                "};",
16364                Alignment);
16365   verifyFormat("int i = 1;\n"
16366                "if (SomeType t = getSomething()) {\n"
16367                "}\n"
16368                "int j   = 2;\n"
16369                "int big = 10000;",
16370                Alignment);
16371   verifyFormat("int j = 7;\n"
16372                "for (int k = 0; k < N; ++k) {\n"
16373                "}\n"
16374                "int j   = 2;\n"
16375                "int big = 10000;\n"
16376                "}",
16377                Alignment);
16378   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16379   verifyFormat("int i = 1;\n"
16380                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16381                "    = someLooooooooooooooooongFunction();\n"
16382                "int j = 2;",
16383                Alignment);
16384   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16385   verifyFormat("int i = 1;\n"
16386                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16387                "    someLooooooooooooooooongFunction();\n"
16388                "int j = 2;",
16389                Alignment);
16390 
16391   verifyFormat("auto lambda = []() {\n"
16392                "  auto i = 0;\n"
16393                "  return 0;\n"
16394                "};\n"
16395                "int i  = 0;\n"
16396                "auto v = type{\n"
16397                "    i = 1,   //\n"
16398                "    (i = 2), //\n"
16399                "    i = 3    //\n"
16400                "};",
16401                Alignment);
16402 
16403   verifyFormat(
16404       "int i      = 1;\n"
16405       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16406       "                          loooooooooooooooooooooongParameterB);\n"
16407       "int j      = 2;",
16408       Alignment);
16409 
16410   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16411                "          typename B   = very_long_type_name_1,\n"
16412                "          typename T_2 = very_long_type_name_2>\n"
16413                "auto foo() {}\n",
16414                Alignment);
16415   verifyFormat("int a, b = 1;\n"
16416                "int c  = 2;\n"
16417                "int dd = 3;\n",
16418                Alignment);
16419   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16420                "float b[1][] = {{3.f}};\n",
16421                Alignment);
16422   verifyFormat("for (int i = 0; i < 1; i++)\n"
16423                "  int x = 1;\n",
16424                Alignment);
16425   verifyFormat("for (i = 0; i < 1; i++)\n"
16426                "  x = 1;\n"
16427                "y = 1;\n",
16428                Alignment);
16429 
16430   Alignment.ReflowComments = true;
16431   Alignment.ColumnLimit = 50;
16432   EXPECT_EQ("int x   = 0;\n"
16433             "int yy  = 1; /// specificlennospace\n"
16434             "int zzz = 2;\n",
16435             format("int x   = 0;\n"
16436                    "int yy  = 1; ///specificlennospace\n"
16437                    "int zzz = 2;\n",
16438                    Alignment));
16439 }
16440 
16441 TEST_F(FormatTest, AlignConsecutiveBitFields) {
16442   FormatStyle Alignment = getLLVMStyle();
16443   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
16444   verifyFormat("int const a     : 5;\n"
16445                "int oneTwoThree : 23;",
16446                Alignment);
16447 
16448   // Initializers are allowed starting with c++2a
16449   verifyFormat("int const a     : 5 = 1;\n"
16450                "int oneTwoThree : 23 = 0;",
16451                Alignment);
16452 
16453   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16454   verifyFormat("int const a           : 5;\n"
16455                "int       oneTwoThree : 23;",
16456                Alignment);
16457 
16458   verifyFormat("int const a           : 5;  // comment\n"
16459                "int       oneTwoThree : 23; // comment",
16460                Alignment);
16461 
16462   verifyFormat("int const a           : 5 = 1;\n"
16463                "int       oneTwoThree : 23 = 0;",
16464                Alignment);
16465 
16466   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16467   verifyFormat("int const a           : 5  = 1;\n"
16468                "int       oneTwoThree : 23 = 0;",
16469                Alignment);
16470   verifyFormat("int const a           : 5  = {1};\n"
16471                "int       oneTwoThree : 23 = 0;",
16472                Alignment);
16473 
16474   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
16475   verifyFormat("int const a          :5;\n"
16476                "int       oneTwoThree:23;",
16477                Alignment);
16478 
16479   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
16480   verifyFormat("int const a           :5;\n"
16481                "int       oneTwoThree :23;",
16482                Alignment);
16483 
16484   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
16485   verifyFormat("int const a          : 5;\n"
16486                "int       oneTwoThree: 23;",
16487                Alignment);
16488 
16489   // Known limitations: ':' is only recognized as a bitfield colon when
16490   // followed by a number.
16491   /*
16492   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
16493                "int a           : 5;",
16494                Alignment);
16495   */
16496 }
16497 
16498 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
16499   FormatStyle Alignment = getLLVMStyle();
16500   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16501   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16502   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16503   verifyFormat("float const a = 5;\n"
16504                "int oneTwoThree = 123;",
16505                Alignment);
16506   verifyFormat("int a = 5;\n"
16507                "float const oneTwoThree = 123;",
16508                Alignment);
16509 
16510   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16511   verifyFormat("float const a = 5;\n"
16512                "int         oneTwoThree = 123;",
16513                Alignment);
16514   verifyFormat("int         a = method();\n"
16515                "float const oneTwoThree = 133;",
16516                Alignment);
16517   verifyFormat("int i = 1, j = 10;\n"
16518                "something = 2000;",
16519                Alignment);
16520   verifyFormat("something = 2000;\n"
16521                "int i = 1, j = 10;\n",
16522                Alignment);
16523   verifyFormat("float      something = 2000;\n"
16524                "double     another = 911;\n"
16525                "int        i = 1, j = 10;\n"
16526                "const int *oneMore = 1;\n"
16527                "unsigned   i = 2;",
16528                Alignment);
16529   verifyFormat("float a = 5;\n"
16530                "int   one = 1;\n"
16531                "method();\n"
16532                "const double       oneTwoThree = 123;\n"
16533                "const unsigned int oneTwo = 12;",
16534                Alignment);
16535   verifyFormat("int      oneTwoThree{0}; // comment\n"
16536                "unsigned oneTwo;         // comment",
16537                Alignment);
16538   verifyFormat("unsigned int       *a;\n"
16539                "int                *b;\n"
16540                "unsigned int Const *c;\n"
16541                "unsigned int const *d;\n"
16542                "unsigned int Const &e;\n"
16543                "unsigned int const &f;",
16544                Alignment);
16545   verifyFormat("Const unsigned int *c;\n"
16546                "const unsigned int *d;\n"
16547                "Const unsigned int &e;\n"
16548                "const unsigned int &f;\n"
16549                "const unsigned      g;\n"
16550                "Const unsigned      h;",
16551                Alignment);
16552   EXPECT_EQ("float const a = 5;\n"
16553             "\n"
16554             "int oneTwoThree = 123;",
16555             format("float const   a = 5;\n"
16556                    "\n"
16557                    "int           oneTwoThree= 123;",
16558                    Alignment));
16559   EXPECT_EQ("float a = 5;\n"
16560             "int   one = 1;\n"
16561             "\n"
16562             "unsigned oneTwoThree = 123;",
16563             format("float    a = 5;\n"
16564                    "int      one = 1;\n"
16565                    "\n"
16566                    "unsigned oneTwoThree = 123;",
16567                    Alignment));
16568   EXPECT_EQ("float a = 5;\n"
16569             "int   one = 1;\n"
16570             "\n"
16571             "unsigned oneTwoThree = 123;\n"
16572             "int      oneTwo = 12;",
16573             format("float    a = 5;\n"
16574                    "int one = 1;\n"
16575                    "\n"
16576                    "unsigned oneTwoThree = 123;\n"
16577                    "int oneTwo = 12;",
16578                    Alignment));
16579   // Function prototype alignment
16580   verifyFormat("int    a();\n"
16581                "double b();",
16582                Alignment);
16583   verifyFormat("int    a(int x);\n"
16584                "double b();",
16585                Alignment);
16586   unsigned OldColumnLimit = Alignment.ColumnLimit;
16587   // We need to set ColumnLimit to zero, in order to stress nested alignments,
16588   // otherwise the function parameters will be re-flowed onto a single line.
16589   Alignment.ColumnLimit = 0;
16590   EXPECT_EQ("int    a(int   x,\n"
16591             "         float y);\n"
16592             "double b(int    x,\n"
16593             "         double y);",
16594             format("int a(int x,\n"
16595                    " float y);\n"
16596                    "double b(int x,\n"
16597                    " double y);",
16598                    Alignment));
16599   // This ensures that function parameters of function declarations are
16600   // correctly indented when their owning functions are indented.
16601   // The failure case here is for 'double y' to not be indented enough.
16602   EXPECT_EQ("double a(int x);\n"
16603             "int    b(int    y,\n"
16604             "         double z);",
16605             format("double a(int x);\n"
16606                    "int b(int y,\n"
16607                    " double z);",
16608                    Alignment));
16609   // Set ColumnLimit low so that we induce wrapping immediately after
16610   // the function name and opening paren.
16611   Alignment.ColumnLimit = 13;
16612   verifyFormat("int function(\n"
16613                "    int  x,\n"
16614                "    bool y);",
16615                Alignment);
16616   Alignment.ColumnLimit = OldColumnLimit;
16617   // Ensure function pointers don't screw up recursive alignment
16618   verifyFormat("int    a(int x, void (*fp)(int y));\n"
16619                "double b();",
16620                Alignment);
16621   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16622   // Ensure recursive alignment is broken by function braces, so that the
16623   // "a = 1" does not align with subsequent assignments inside the function
16624   // body.
16625   verifyFormat("int func(int a = 1) {\n"
16626                "  int b  = 2;\n"
16627                "  int cc = 3;\n"
16628                "}",
16629                Alignment);
16630   verifyFormat("float      something = 2000;\n"
16631                "double     another   = 911;\n"
16632                "int        i = 1, j = 10;\n"
16633                "const int *oneMore = 1;\n"
16634                "unsigned   i       = 2;",
16635                Alignment);
16636   verifyFormat("int      oneTwoThree = {0}; // comment\n"
16637                "unsigned oneTwo      = 0;   // comment",
16638                Alignment);
16639   // Make sure that scope is correctly tracked, in the absence of braces
16640   verifyFormat("for (int i = 0; i < n; i++)\n"
16641                "  j = i;\n"
16642                "double x = 1;\n",
16643                Alignment);
16644   verifyFormat("if (int i = 0)\n"
16645                "  j = i;\n"
16646                "double x = 1;\n",
16647                Alignment);
16648   // Ensure operator[] and operator() are comprehended
16649   verifyFormat("struct test {\n"
16650                "  long long int foo();\n"
16651                "  int           operator[](int a);\n"
16652                "  double        bar();\n"
16653                "};\n",
16654                Alignment);
16655   verifyFormat("struct test {\n"
16656                "  long long int foo();\n"
16657                "  int           operator()(int a);\n"
16658                "  double        bar();\n"
16659                "};\n",
16660                Alignment);
16661   // http://llvm.org/PR52914
16662   verifyFormat("char *a[]     = {\"a\", // comment\n"
16663                "                 \"bb\"};\n"
16664                "int   bbbbbbb = 0;",
16665                Alignment);
16666 
16667   // PAS_Right
16668   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16669             "  int const i   = 1;\n"
16670             "  int      *j   = 2;\n"
16671             "  int       big = 10000;\n"
16672             "\n"
16673             "  unsigned oneTwoThree = 123;\n"
16674             "  int      oneTwo      = 12;\n"
16675             "  method();\n"
16676             "  float k  = 2;\n"
16677             "  int   ll = 10000;\n"
16678             "}",
16679             format("void SomeFunction(int parameter= 0) {\n"
16680                    " int const  i= 1;\n"
16681                    "  int *j=2;\n"
16682                    " int big  =  10000;\n"
16683                    "\n"
16684                    "unsigned oneTwoThree  =123;\n"
16685                    "int oneTwo = 12;\n"
16686                    "  method();\n"
16687                    "float k= 2;\n"
16688                    "int ll=10000;\n"
16689                    "}",
16690                    Alignment));
16691   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16692             "  int const i   = 1;\n"
16693             "  int     **j   = 2, ***k;\n"
16694             "  int      &k   = i;\n"
16695             "  int     &&l   = i + j;\n"
16696             "  int       big = 10000;\n"
16697             "\n"
16698             "  unsigned oneTwoThree = 123;\n"
16699             "  int      oneTwo      = 12;\n"
16700             "  method();\n"
16701             "  float k  = 2;\n"
16702             "  int   ll = 10000;\n"
16703             "}",
16704             format("void SomeFunction(int parameter= 0) {\n"
16705                    " int const  i= 1;\n"
16706                    "  int **j=2,***k;\n"
16707                    "int &k=i;\n"
16708                    "int &&l=i+j;\n"
16709                    " int big  =  10000;\n"
16710                    "\n"
16711                    "unsigned oneTwoThree  =123;\n"
16712                    "int oneTwo = 12;\n"
16713                    "  method();\n"
16714                    "float k= 2;\n"
16715                    "int ll=10000;\n"
16716                    "}",
16717                    Alignment));
16718   // variables are aligned at their name, pointers are at the right most
16719   // position
16720   verifyFormat("int   *a;\n"
16721                "int  **b;\n"
16722                "int ***c;\n"
16723                "int    foobar;\n",
16724                Alignment);
16725 
16726   // PAS_Left
16727   FormatStyle AlignmentLeft = Alignment;
16728   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
16729   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16730             "  int const i   = 1;\n"
16731             "  int*      j   = 2;\n"
16732             "  int       big = 10000;\n"
16733             "\n"
16734             "  unsigned oneTwoThree = 123;\n"
16735             "  int      oneTwo      = 12;\n"
16736             "  method();\n"
16737             "  float k  = 2;\n"
16738             "  int   ll = 10000;\n"
16739             "}",
16740             format("void SomeFunction(int parameter= 0) {\n"
16741                    " int const  i= 1;\n"
16742                    "  int *j=2;\n"
16743                    " int big  =  10000;\n"
16744                    "\n"
16745                    "unsigned oneTwoThree  =123;\n"
16746                    "int oneTwo = 12;\n"
16747                    "  method();\n"
16748                    "float k= 2;\n"
16749                    "int ll=10000;\n"
16750                    "}",
16751                    AlignmentLeft));
16752   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16753             "  int const i   = 1;\n"
16754             "  int**     j   = 2;\n"
16755             "  int&      k   = i;\n"
16756             "  int&&     l   = i + j;\n"
16757             "  int       big = 10000;\n"
16758             "\n"
16759             "  unsigned oneTwoThree = 123;\n"
16760             "  int      oneTwo      = 12;\n"
16761             "  method();\n"
16762             "  float k  = 2;\n"
16763             "  int   ll = 10000;\n"
16764             "}",
16765             format("void SomeFunction(int parameter= 0) {\n"
16766                    " int const  i= 1;\n"
16767                    "  int **j=2;\n"
16768                    "int &k=i;\n"
16769                    "int &&l=i+j;\n"
16770                    " int big  =  10000;\n"
16771                    "\n"
16772                    "unsigned oneTwoThree  =123;\n"
16773                    "int oneTwo = 12;\n"
16774                    "  method();\n"
16775                    "float k= 2;\n"
16776                    "int ll=10000;\n"
16777                    "}",
16778                    AlignmentLeft));
16779   // variables are aligned at their name, pointers are at the left most position
16780   verifyFormat("int*   a;\n"
16781                "int**  b;\n"
16782                "int*** c;\n"
16783                "int    foobar;\n",
16784                AlignmentLeft);
16785 
16786   // PAS_Middle
16787   FormatStyle AlignmentMiddle = Alignment;
16788   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
16789   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16790             "  int const i   = 1;\n"
16791             "  int *     j   = 2;\n"
16792             "  int       big = 10000;\n"
16793             "\n"
16794             "  unsigned oneTwoThree = 123;\n"
16795             "  int      oneTwo      = 12;\n"
16796             "  method();\n"
16797             "  float k  = 2;\n"
16798             "  int   ll = 10000;\n"
16799             "}",
16800             format("void SomeFunction(int parameter= 0) {\n"
16801                    " int const  i= 1;\n"
16802                    "  int *j=2;\n"
16803                    " int big  =  10000;\n"
16804                    "\n"
16805                    "unsigned oneTwoThree  =123;\n"
16806                    "int oneTwo = 12;\n"
16807                    "  method();\n"
16808                    "float k= 2;\n"
16809                    "int ll=10000;\n"
16810                    "}",
16811                    AlignmentMiddle));
16812   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16813             "  int const i   = 1;\n"
16814             "  int **    j   = 2, ***k;\n"
16815             "  int &     k   = i;\n"
16816             "  int &&    l   = i + j;\n"
16817             "  int       big = 10000;\n"
16818             "\n"
16819             "  unsigned oneTwoThree = 123;\n"
16820             "  int      oneTwo      = 12;\n"
16821             "  method();\n"
16822             "  float k  = 2;\n"
16823             "  int   ll = 10000;\n"
16824             "}",
16825             format("void SomeFunction(int parameter= 0) {\n"
16826                    " int const  i= 1;\n"
16827                    "  int **j=2,***k;\n"
16828                    "int &k=i;\n"
16829                    "int &&l=i+j;\n"
16830                    " int big  =  10000;\n"
16831                    "\n"
16832                    "unsigned oneTwoThree  =123;\n"
16833                    "int oneTwo = 12;\n"
16834                    "  method();\n"
16835                    "float k= 2;\n"
16836                    "int ll=10000;\n"
16837                    "}",
16838                    AlignmentMiddle));
16839   // variables are aligned at their name, pointers are in the middle
16840   verifyFormat("int *   a;\n"
16841                "int *   b;\n"
16842                "int *** c;\n"
16843                "int     foobar;\n",
16844                AlignmentMiddle);
16845 
16846   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16847   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16848   verifyFormat("#define A \\\n"
16849                "  int       aaaa = 12; \\\n"
16850                "  float     b = 23; \\\n"
16851                "  const int ccc = 234; \\\n"
16852                "  unsigned  dddddddddd = 2345;",
16853                Alignment);
16854   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16855   verifyFormat("#define A              \\\n"
16856                "  int       aaaa = 12; \\\n"
16857                "  float     b = 23;    \\\n"
16858                "  const int ccc = 234; \\\n"
16859                "  unsigned  dddddddddd = 2345;",
16860                Alignment);
16861   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16862   Alignment.ColumnLimit = 30;
16863   verifyFormat("#define A                    \\\n"
16864                "  int       aaaa = 12;       \\\n"
16865                "  float     b = 23;          \\\n"
16866                "  const int ccc = 234;       \\\n"
16867                "  int       dddddddddd = 2345;",
16868                Alignment);
16869   Alignment.ColumnLimit = 80;
16870   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16871                "k = 4, int l = 5,\n"
16872                "                  int m = 6) {\n"
16873                "  const int j = 10;\n"
16874                "  otherThing = 1;\n"
16875                "}",
16876                Alignment);
16877   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16878                "  int const i = 1;\n"
16879                "  int      *j = 2;\n"
16880                "  int       big = 10000;\n"
16881                "}",
16882                Alignment);
16883   verifyFormat("class C {\n"
16884                "public:\n"
16885                "  int          i = 1;\n"
16886                "  virtual void f() = 0;\n"
16887                "};",
16888                Alignment);
16889   verifyFormat("float i = 1;\n"
16890                "if (SomeType t = getSomething()) {\n"
16891                "}\n"
16892                "const unsigned j = 2;\n"
16893                "int            big = 10000;",
16894                Alignment);
16895   verifyFormat("float j = 7;\n"
16896                "for (int k = 0; k < N; ++k) {\n"
16897                "}\n"
16898                "unsigned j = 2;\n"
16899                "int      big = 10000;\n"
16900                "}",
16901                Alignment);
16902   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16903   verifyFormat("float              i = 1;\n"
16904                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16905                "    = someLooooooooooooooooongFunction();\n"
16906                "int j = 2;",
16907                Alignment);
16908   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16909   verifyFormat("int                i = 1;\n"
16910                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16911                "    someLooooooooooooooooongFunction();\n"
16912                "int j = 2;",
16913                Alignment);
16914 
16915   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16916   verifyFormat("auto lambda = []() {\n"
16917                "  auto  ii = 0;\n"
16918                "  float j  = 0;\n"
16919                "  return 0;\n"
16920                "};\n"
16921                "int   i  = 0;\n"
16922                "float i2 = 0;\n"
16923                "auto  v  = type{\n"
16924                "    i = 1,   //\n"
16925                "    (i = 2), //\n"
16926                "    i = 3    //\n"
16927                "};",
16928                Alignment);
16929   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16930 
16931   verifyFormat(
16932       "int      i = 1;\n"
16933       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16934       "                          loooooooooooooooooooooongParameterB);\n"
16935       "int      j = 2;",
16936       Alignment);
16937 
16938   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
16939   // We expect declarations and assignments to align, as long as it doesn't
16940   // exceed the column limit, starting a new alignment sequence whenever it
16941   // happens.
16942   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16943   Alignment.ColumnLimit = 30;
16944   verifyFormat("float    ii              = 1;\n"
16945                "unsigned j               = 2;\n"
16946                "int someVerylongVariable = 1;\n"
16947                "AnotherLongType  ll = 123456;\n"
16948                "VeryVeryLongType k  = 2;\n"
16949                "int              myvar = 1;",
16950                Alignment);
16951   Alignment.ColumnLimit = 80;
16952   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16953 
16954   verifyFormat(
16955       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
16956       "          typename LongType, typename B>\n"
16957       "auto foo() {}\n",
16958       Alignment);
16959   verifyFormat("float a, b = 1;\n"
16960                "int   c = 2;\n"
16961                "int   dd = 3;\n",
16962                Alignment);
16963   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
16964                "float b[1][] = {{3.f}};\n",
16965                Alignment);
16966   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16967   verifyFormat("float a, b = 1;\n"
16968                "int   c  = 2;\n"
16969                "int   dd = 3;\n",
16970                Alignment);
16971   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
16972                "float b[1][] = {{3.f}};\n",
16973                Alignment);
16974   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16975 
16976   Alignment.ColumnLimit = 30;
16977   Alignment.BinPackParameters = false;
16978   verifyFormat("void foo(float     a,\n"
16979                "         float     b,\n"
16980                "         int       c,\n"
16981                "         uint32_t *d) {\n"
16982                "  int   *e = 0;\n"
16983                "  float  f = 0;\n"
16984                "  double g = 0;\n"
16985                "}\n"
16986                "void bar(ino_t     a,\n"
16987                "         int       b,\n"
16988                "         uint32_t *c,\n"
16989                "         bool      d) {}\n",
16990                Alignment);
16991   Alignment.BinPackParameters = true;
16992   Alignment.ColumnLimit = 80;
16993 
16994   // Bug 33507
16995   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16996   verifyFormat(
16997       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
16998       "  static const Version verVs2017;\n"
16999       "  return true;\n"
17000       "});\n",
17001       Alignment);
17002   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17003 
17004   // See llvm.org/PR35641
17005   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17006   verifyFormat("int func() { //\n"
17007                "  int      b;\n"
17008                "  unsigned c;\n"
17009                "}",
17010                Alignment);
17011 
17012   // See PR37175
17013   FormatStyle Style = getMozillaStyle();
17014   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17015   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
17016             "foo(int a);",
17017             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
17018 
17019   Alignment.PointerAlignment = FormatStyle::PAS_Left;
17020   verifyFormat("unsigned int*       a;\n"
17021                "int*                b;\n"
17022                "unsigned int Const* c;\n"
17023                "unsigned int const* d;\n"
17024                "unsigned int Const& e;\n"
17025                "unsigned int const& f;",
17026                Alignment);
17027   verifyFormat("Const unsigned int* c;\n"
17028                "const unsigned int* d;\n"
17029                "Const unsigned int& e;\n"
17030                "const unsigned int& f;\n"
17031                "const unsigned      g;\n"
17032                "Const unsigned      h;",
17033                Alignment);
17034 
17035   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17036   verifyFormat("unsigned int *       a;\n"
17037                "int *                b;\n"
17038                "unsigned int Const * c;\n"
17039                "unsigned int const * d;\n"
17040                "unsigned int Const & e;\n"
17041                "unsigned int const & f;",
17042                Alignment);
17043   verifyFormat("Const unsigned int * c;\n"
17044                "const unsigned int * d;\n"
17045                "Const unsigned int & e;\n"
17046                "const unsigned int & f;\n"
17047                "const unsigned       g;\n"
17048                "Const unsigned       h;",
17049                Alignment);
17050 }
17051 
17052 TEST_F(FormatTest, AlignWithLineBreaks) {
17053   auto Style = getLLVMStyleWithColumns(120);
17054 
17055   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
17056   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
17057   verifyFormat("void foo() {\n"
17058                "  int myVar = 5;\n"
17059                "  double x = 3.14;\n"
17060                "  auto str = \"Hello \"\n"
17061                "             \"World\";\n"
17062                "  auto s = \"Hello \"\n"
17063                "           \"Again\";\n"
17064                "}",
17065                Style);
17066 
17067   // clang-format off
17068   verifyFormat("void foo() {\n"
17069                "  const int capacityBefore = Entries.capacity();\n"
17070                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17071                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17072                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17073                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17074                "}",
17075                Style);
17076   // clang-format on
17077 
17078   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17079   verifyFormat("void foo() {\n"
17080                "  int myVar = 5;\n"
17081                "  double x  = 3.14;\n"
17082                "  auto str  = \"Hello \"\n"
17083                "              \"World\";\n"
17084                "  auto s    = \"Hello \"\n"
17085                "              \"Again\";\n"
17086                "}",
17087                Style);
17088 
17089   // clang-format off
17090   verifyFormat("void foo() {\n"
17091                "  const int capacityBefore = Entries.capacity();\n"
17092                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17093                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17094                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17095                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17096                "}",
17097                Style);
17098   // clang-format on
17099 
17100   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17101   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17102   verifyFormat("void foo() {\n"
17103                "  int    myVar = 5;\n"
17104                "  double x = 3.14;\n"
17105                "  auto   str = \"Hello \"\n"
17106                "               \"World\";\n"
17107                "  auto   s = \"Hello \"\n"
17108                "             \"Again\";\n"
17109                "}",
17110                Style);
17111 
17112   // clang-format off
17113   verifyFormat("void foo() {\n"
17114                "  const int  capacityBefore = Entries.capacity();\n"
17115                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17116                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17117                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17118                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17119                "}",
17120                Style);
17121   // clang-format on
17122 
17123   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17124   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17125 
17126   verifyFormat("void foo() {\n"
17127                "  int    myVar = 5;\n"
17128                "  double x     = 3.14;\n"
17129                "  auto   str   = \"Hello \"\n"
17130                "                 \"World\";\n"
17131                "  auto   s     = \"Hello \"\n"
17132                "                 \"Again\";\n"
17133                "}",
17134                Style);
17135 
17136   // clang-format off
17137   verifyFormat("void foo() {\n"
17138                "  const int  capacityBefore = Entries.capacity();\n"
17139                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17140                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17141                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17142                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17143                "}",
17144                Style);
17145   // clang-format on
17146 
17147   Style = getLLVMStyleWithColumns(120);
17148   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17149   Style.ContinuationIndentWidth = 4;
17150   Style.IndentWidth = 4;
17151 
17152   // clang-format off
17153   verifyFormat("void SomeFunc() {\n"
17154                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17155                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17156                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17157                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17158                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17159                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17160                "}",
17161                Style);
17162   // clang-format on
17163 
17164   Style.BinPackArguments = false;
17165 
17166   // clang-format off
17167   verifyFormat("void SomeFunc() {\n"
17168                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
17169                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17170                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
17171                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17172                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
17173                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17174                "}",
17175                Style);
17176   // clang-format on
17177 }
17178 
17179 TEST_F(FormatTest, AlignWithInitializerPeriods) {
17180   auto Style = getLLVMStyleWithColumns(60);
17181 
17182   verifyFormat("void foo1(void) {\n"
17183                "  BYTE p[1] = 1;\n"
17184                "  A B = {.one_foooooooooooooooo = 2,\n"
17185                "         .two_fooooooooooooo = 3,\n"
17186                "         .three_fooooooooooooo = 4};\n"
17187                "  BYTE payload = 2;\n"
17188                "}",
17189                Style);
17190 
17191   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17192   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
17193   verifyFormat("void foo2(void) {\n"
17194                "  BYTE p[1]    = 1;\n"
17195                "  A B          = {.one_foooooooooooooooo = 2,\n"
17196                "                  .two_fooooooooooooo    = 3,\n"
17197                "                  .three_fooooooooooooo  = 4};\n"
17198                "  BYTE payload = 2;\n"
17199                "}",
17200                Style);
17201 
17202   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17203   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17204   verifyFormat("void foo3(void) {\n"
17205                "  BYTE p[1] = 1;\n"
17206                "  A    B = {.one_foooooooooooooooo = 2,\n"
17207                "            .two_fooooooooooooo = 3,\n"
17208                "            .three_fooooooooooooo = 4};\n"
17209                "  BYTE payload = 2;\n"
17210                "}",
17211                Style);
17212 
17213   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17214   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17215   verifyFormat("void foo4(void) {\n"
17216                "  BYTE p[1]    = 1;\n"
17217                "  A    B       = {.one_foooooooooooooooo = 2,\n"
17218                "                  .two_fooooooooooooo    = 3,\n"
17219                "                  .three_fooooooooooooo  = 4};\n"
17220                "  BYTE payload = 2;\n"
17221                "}",
17222                Style);
17223 }
17224 
17225 TEST_F(FormatTest, LinuxBraceBreaking) {
17226   FormatStyle LinuxBraceStyle = getLLVMStyle();
17227   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
17228   verifyFormat("namespace a\n"
17229                "{\n"
17230                "class A\n"
17231                "{\n"
17232                "  void f()\n"
17233                "  {\n"
17234                "    if (true) {\n"
17235                "      a();\n"
17236                "      b();\n"
17237                "    } else {\n"
17238                "      a();\n"
17239                "    }\n"
17240                "  }\n"
17241                "  void g() { return; }\n"
17242                "};\n"
17243                "struct B {\n"
17244                "  int x;\n"
17245                "};\n"
17246                "} // namespace a\n",
17247                LinuxBraceStyle);
17248   verifyFormat("enum X {\n"
17249                "  Y = 0,\n"
17250                "}\n",
17251                LinuxBraceStyle);
17252   verifyFormat("struct S {\n"
17253                "  int Type;\n"
17254                "  union {\n"
17255                "    int x;\n"
17256                "    double y;\n"
17257                "  } Value;\n"
17258                "  class C\n"
17259                "  {\n"
17260                "    MyFavoriteType Value;\n"
17261                "  } Class;\n"
17262                "}\n",
17263                LinuxBraceStyle);
17264 }
17265 
17266 TEST_F(FormatTest, MozillaBraceBreaking) {
17267   FormatStyle MozillaBraceStyle = getLLVMStyle();
17268   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
17269   MozillaBraceStyle.FixNamespaceComments = false;
17270   verifyFormat("namespace a {\n"
17271                "class A\n"
17272                "{\n"
17273                "  void f()\n"
17274                "  {\n"
17275                "    if (true) {\n"
17276                "      a();\n"
17277                "      b();\n"
17278                "    }\n"
17279                "  }\n"
17280                "  void g() { return; }\n"
17281                "};\n"
17282                "enum E\n"
17283                "{\n"
17284                "  A,\n"
17285                "  // foo\n"
17286                "  B,\n"
17287                "  C\n"
17288                "};\n"
17289                "struct B\n"
17290                "{\n"
17291                "  int x;\n"
17292                "};\n"
17293                "}\n",
17294                MozillaBraceStyle);
17295   verifyFormat("struct S\n"
17296                "{\n"
17297                "  int Type;\n"
17298                "  union\n"
17299                "  {\n"
17300                "    int x;\n"
17301                "    double y;\n"
17302                "  } Value;\n"
17303                "  class C\n"
17304                "  {\n"
17305                "    MyFavoriteType Value;\n"
17306                "  } Class;\n"
17307                "}\n",
17308                MozillaBraceStyle);
17309 }
17310 
17311 TEST_F(FormatTest, StroustrupBraceBreaking) {
17312   FormatStyle StroustrupBraceStyle = getLLVMStyle();
17313   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
17314   verifyFormat("namespace a {\n"
17315                "class A {\n"
17316                "  void f()\n"
17317                "  {\n"
17318                "    if (true) {\n"
17319                "      a();\n"
17320                "      b();\n"
17321                "    }\n"
17322                "  }\n"
17323                "  void g() { return; }\n"
17324                "};\n"
17325                "struct B {\n"
17326                "  int x;\n"
17327                "};\n"
17328                "} // namespace a\n",
17329                StroustrupBraceStyle);
17330 
17331   verifyFormat("void foo()\n"
17332                "{\n"
17333                "  if (a) {\n"
17334                "    a();\n"
17335                "  }\n"
17336                "  else {\n"
17337                "    b();\n"
17338                "  }\n"
17339                "}\n",
17340                StroustrupBraceStyle);
17341 
17342   verifyFormat("#ifdef _DEBUG\n"
17343                "int foo(int i = 0)\n"
17344                "#else\n"
17345                "int foo(int i = 5)\n"
17346                "#endif\n"
17347                "{\n"
17348                "  return i;\n"
17349                "}",
17350                StroustrupBraceStyle);
17351 
17352   verifyFormat("void foo() {}\n"
17353                "void bar()\n"
17354                "#ifdef _DEBUG\n"
17355                "{\n"
17356                "  foo();\n"
17357                "}\n"
17358                "#else\n"
17359                "{\n"
17360                "}\n"
17361                "#endif",
17362                StroustrupBraceStyle);
17363 
17364   verifyFormat("void foobar() { int i = 5; }\n"
17365                "#ifdef _DEBUG\n"
17366                "void bar() {}\n"
17367                "#else\n"
17368                "void bar() { foobar(); }\n"
17369                "#endif",
17370                StroustrupBraceStyle);
17371 }
17372 
17373 TEST_F(FormatTest, AllmanBraceBreaking) {
17374   FormatStyle AllmanBraceStyle = getLLVMStyle();
17375   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
17376 
17377   EXPECT_EQ("namespace a\n"
17378             "{\n"
17379             "void f();\n"
17380             "void g();\n"
17381             "} // namespace a\n",
17382             format("namespace a\n"
17383                    "{\n"
17384                    "void f();\n"
17385                    "void g();\n"
17386                    "}\n",
17387                    AllmanBraceStyle));
17388 
17389   verifyFormat("namespace a\n"
17390                "{\n"
17391                "class A\n"
17392                "{\n"
17393                "  void f()\n"
17394                "  {\n"
17395                "    if (true)\n"
17396                "    {\n"
17397                "      a();\n"
17398                "      b();\n"
17399                "    }\n"
17400                "  }\n"
17401                "  void g() { return; }\n"
17402                "};\n"
17403                "struct B\n"
17404                "{\n"
17405                "  int x;\n"
17406                "};\n"
17407                "union C\n"
17408                "{\n"
17409                "};\n"
17410                "} // namespace a",
17411                AllmanBraceStyle);
17412 
17413   verifyFormat("void f()\n"
17414                "{\n"
17415                "  if (true)\n"
17416                "  {\n"
17417                "    a();\n"
17418                "  }\n"
17419                "  else if (false)\n"
17420                "  {\n"
17421                "    b();\n"
17422                "  }\n"
17423                "  else\n"
17424                "  {\n"
17425                "    c();\n"
17426                "  }\n"
17427                "}\n",
17428                AllmanBraceStyle);
17429 
17430   verifyFormat("void f()\n"
17431                "{\n"
17432                "  for (int i = 0; i < 10; ++i)\n"
17433                "  {\n"
17434                "    a();\n"
17435                "  }\n"
17436                "  while (false)\n"
17437                "  {\n"
17438                "    b();\n"
17439                "  }\n"
17440                "  do\n"
17441                "  {\n"
17442                "    c();\n"
17443                "  } while (false)\n"
17444                "}\n",
17445                AllmanBraceStyle);
17446 
17447   verifyFormat("void f(int a)\n"
17448                "{\n"
17449                "  switch (a)\n"
17450                "  {\n"
17451                "  case 0:\n"
17452                "    break;\n"
17453                "  case 1:\n"
17454                "  {\n"
17455                "    break;\n"
17456                "  }\n"
17457                "  case 2:\n"
17458                "  {\n"
17459                "  }\n"
17460                "  break;\n"
17461                "  default:\n"
17462                "    break;\n"
17463                "  }\n"
17464                "}\n",
17465                AllmanBraceStyle);
17466 
17467   verifyFormat("enum X\n"
17468                "{\n"
17469                "  Y = 0,\n"
17470                "}\n",
17471                AllmanBraceStyle);
17472   verifyFormat("enum X\n"
17473                "{\n"
17474                "  Y = 0\n"
17475                "}\n",
17476                AllmanBraceStyle);
17477 
17478   verifyFormat("@interface BSApplicationController ()\n"
17479                "{\n"
17480                "@private\n"
17481                "  id _extraIvar;\n"
17482                "}\n"
17483                "@end\n",
17484                AllmanBraceStyle);
17485 
17486   verifyFormat("#ifdef _DEBUG\n"
17487                "int foo(int i = 0)\n"
17488                "#else\n"
17489                "int foo(int i = 5)\n"
17490                "#endif\n"
17491                "{\n"
17492                "  return i;\n"
17493                "}",
17494                AllmanBraceStyle);
17495 
17496   verifyFormat("void foo() {}\n"
17497                "void bar()\n"
17498                "#ifdef _DEBUG\n"
17499                "{\n"
17500                "  foo();\n"
17501                "}\n"
17502                "#else\n"
17503                "{\n"
17504                "}\n"
17505                "#endif",
17506                AllmanBraceStyle);
17507 
17508   verifyFormat("void foobar() { int i = 5; }\n"
17509                "#ifdef _DEBUG\n"
17510                "void bar() {}\n"
17511                "#else\n"
17512                "void bar() { foobar(); }\n"
17513                "#endif",
17514                AllmanBraceStyle);
17515 
17516   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
17517             FormatStyle::SLS_All);
17518 
17519   verifyFormat("[](int i) { return i + 2; };\n"
17520                "[](int i, int j)\n"
17521                "{\n"
17522                "  auto x = i + j;\n"
17523                "  auto y = i * j;\n"
17524                "  return x ^ y;\n"
17525                "};\n"
17526                "void foo()\n"
17527                "{\n"
17528                "  auto shortLambda = [](int i) { return i + 2; };\n"
17529                "  auto longLambda = [](int i, int j)\n"
17530                "  {\n"
17531                "    auto x = i + j;\n"
17532                "    auto y = i * j;\n"
17533                "    return x ^ y;\n"
17534                "  };\n"
17535                "}",
17536                AllmanBraceStyle);
17537 
17538   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17539 
17540   verifyFormat("[](int i)\n"
17541                "{\n"
17542                "  return i + 2;\n"
17543                "};\n"
17544                "[](int i, int j)\n"
17545                "{\n"
17546                "  auto x = i + j;\n"
17547                "  auto y = i * j;\n"
17548                "  return x ^ y;\n"
17549                "};\n"
17550                "void foo()\n"
17551                "{\n"
17552                "  auto shortLambda = [](int i)\n"
17553                "  {\n"
17554                "    return i + 2;\n"
17555                "  };\n"
17556                "  auto longLambda = [](int i, int j)\n"
17557                "  {\n"
17558                "    auto x = i + j;\n"
17559                "    auto y = i * j;\n"
17560                "    return x ^ y;\n"
17561                "  };\n"
17562                "}",
17563                AllmanBraceStyle);
17564 
17565   // Reset
17566   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
17567 
17568   // This shouldn't affect ObjC blocks..
17569   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
17570                "  // ...\n"
17571                "  int i;\n"
17572                "}];",
17573                AllmanBraceStyle);
17574   verifyFormat("void (^block)(void) = ^{\n"
17575                "  // ...\n"
17576                "  int i;\n"
17577                "};",
17578                AllmanBraceStyle);
17579   // .. or dict literals.
17580   verifyFormat("void f()\n"
17581                "{\n"
17582                "  // ...\n"
17583                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
17584                "}",
17585                AllmanBraceStyle);
17586   verifyFormat("void f()\n"
17587                "{\n"
17588                "  // ...\n"
17589                "  [object someMethod:@{a : @\"b\"}];\n"
17590                "}",
17591                AllmanBraceStyle);
17592   verifyFormat("int f()\n"
17593                "{ // comment\n"
17594                "  return 42;\n"
17595                "}",
17596                AllmanBraceStyle);
17597 
17598   AllmanBraceStyle.ColumnLimit = 19;
17599   verifyFormat("void f() { int i; }", AllmanBraceStyle);
17600   AllmanBraceStyle.ColumnLimit = 18;
17601   verifyFormat("void f()\n"
17602                "{\n"
17603                "  int i;\n"
17604                "}",
17605                AllmanBraceStyle);
17606   AllmanBraceStyle.ColumnLimit = 80;
17607 
17608   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
17609   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
17610       FormatStyle::SIS_WithoutElse;
17611   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
17612   verifyFormat("void f(bool b)\n"
17613                "{\n"
17614                "  if (b)\n"
17615                "  {\n"
17616                "    return;\n"
17617                "  }\n"
17618                "}\n",
17619                BreakBeforeBraceShortIfs);
17620   verifyFormat("void f(bool b)\n"
17621                "{\n"
17622                "  if constexpr (b)\n"
17623                "  {\n"
17624                "    return;\n"
17625                "  }\n"
17626                "}\n",
17627                BreakBeforeBraceShortIfs);
17628   verifyFormat("void f(bool b)\n"
17629                "{\n"
17630                "  if CONSTEXPR (b)\n"
17631                "  {\n"
17632                "    return;\n"
17633                "  }\n"
17634                "}\n",
17635                BreakBeforeBraceShortIfs);
17636   verifyFormat("void f(bool b)\n"
17637                "{\n"
17638                "  if (b) return;\n"
17639                "}\n",
17640                BreakBeforeBraceShortIfs);
17641   verifyFormat("void f(bool b)\n"
17642                "{\n"
17643                "  if constexpr (b) return;\n"
17644                "}\n",
17645                BreakBeforeBraceShortIfs);
17646   verifyFormat("void f(bool b)\n"
17647                "{\n"
17648                "  if CONSTEXPR (b) return;\n"
17649                "}\n",
17650                BreakBeforeBraceShortIfs);
17651   verifyFormat("void f(bool b)\n"
17652                "{\n"
17653                "  while (b)\n"
17654                "  {\n"
17655                "    return;\n"
17656                "  }\n"
17657                "}\n",
17658                BreakBeforeBraceShortIfs);
17659 }
17660 
17661 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
17662   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
17663   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
17664 
17665   // Make a few changes to the style for testing purposes
17666   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
17667       FormatStyle::SFS_Empty;
17668   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17669 
17670   // FIXME: this test case can't decide whether there should be a blank line
17671   // after the ~D() line or not. It adds one if one doesn't exist in the test
17672   // and it removes the line if one exists.
17673   /*
17674   verifyFormat("class A;\n"
17675                "namespace B\n"
17676                "  {\n"
17677                "class C;\n"
17678                "// Comment\n"
17679                "class D\n"
17680                "  {\n"
17681                "public:\n"
17682                "  D();\n"
17683                "  ~D() {}\n"
17684                "private:\n"
17685                "  enum E\n"
17686                "    {\n"
17687                "    F\n"
17688                "    }\n"
17689                "  };\n"
17690                "  } // namespace B\n",
17691                WhitesmithsBraceStyle);
17692   */
17693 
17694   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
17695   verifyFormat("namespace a\n"
17696                "  {\n"
17697                "class A\n"
17698                "  {\n"
17699                "  void f()\n"
17700                "    {\n"
17701                "    if (true)\n"
17702                "      {\n"
17703                "      a();\n"
17704                "      b();\n"
17705                "      }\n"
17706                "    }\n"
17707                "  void g()\n"
17708                "    {\n"
17709                "    return;\n"
17710                "    }\n"
17711                "  };\n"
17712                "struct B\n"
17713                "  {\n"
17714                "  int x;\n"
17715                "  };\n"
17716                "  } // namespace a",
17717                WhitesmithsBraceStyle);
17718 
17719   verifyFormat("namespace a\n"
17720                "  {\n"
17721                "namespace b\n"
17722                "  {\n"
17723                "class A\n"
17724                "  {\n"
17725                "  void f()\n"
17726                "    {\n"
17727                "    if (true)\n"
17728                "      {\n"
17729                "      a();\n"
17730                "      b();\n"
17731                "      }\n"
17732                "    }\n"
17733                "  void g()\n"
17734                "    {\n"
17735                "    return;\n"
17736                "    }\n"
17737                "  };\n"
17738                "struct B\n"
17739                "  {\n"
17740                "  int x;\n"
17741                "  };\n"
17742                "  } // namespace b\n"
17743                "  } // namespace a",
17744                WhitesmithsBraceStyle);
17745 
17746   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
17747   verifyFormat("namespace a\n"
17748                "  {\n"
17749                "namespace b\n"
17750                "  {\n"
17751                "  class A\n"
17752                "    {\n"
17753                "    void f()\n"
17754                "      {\n"
17755                "      if (true)\n"
17756                "        {\n"
17757                "        a();\n"
17758                "        b();\n"
17759                "        }\n"
17760                "      }\n"
17761                "    void g()\n"
17762                "      {\n"
17763                "      return;\n"
17764                "      }\n"
17765                "    };\n"
17766                "  struct B\n"
17767                "    {\n"
17768                "    int x;\n"
17769                "    };\n"
17770                "  } // namespace b\n"
17771                "  } // namespace a",
17772                WhitesmithsBraceStyle);
17773 
17774   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
17775   verifyFormat("namespace a\n"
17776                "  {\n"
17777                "  namespace b\n"
17778                "    {\n"
17779                "    class A\n"
17780                "      {\n"
17781                "      void f()\n"
17782                "        {\n"
17783                "        if (true)\n"
17784                "          {\n"
17785                "          a();\n"
17786                "          b();\n"
17787                "          }\n"
17788                "        }\n"
17789                "      void g()\n"
17790                "        {\n"
17791                "        return;\n"
17792                "        }\n"
17793                "      };\n"
17794                "    struct B\n"
17795                "      {\n"
17796                "      int x;\n"
17797                "      };\n"
17798                "    } // namespace b\n"
17799                "  }   // namespace a",
17800                WhitesmithsBraceStyle);
17801 
17802   verifyFormat("void f()\n"
17803                "  {\n"
17804                "  if (true)\n"
17805                "    {\n"
17806                "    a();\n"
17807                "    }\n"
17808                "  else if (false)\n"
17809                "    {\n"
17810                "    b();\n"
17811                "    }\n"
17812                "  else\n"
17813                "    {\n"
17814                "    c();\n"
17815                "    }\n"
17816                "  }\n",
17817                WhitesmithsBraceStyle);
17818 
17819   verifyFormat("void f()\n"
17820                "  {\n"
17821                "  for (int i = 0; i < 10; ++i)\n"
17822                "    {\n"
17823                "    a();\n"
17824                "    }\n"
17825                "  while (false)\n"
17826                "    {\n"
17827                "    b();\n"
17828                "    }\n"
17829                "  do\n"
17830                "    {\n"
17831                "    c();\n"
17832                "    } while (false)\n"
17833                "  }\n",
17834                WhitesmithsBraceStyle);
17835 
17836   WhitesmithsBraceStyle.IndentCaseLabels = true;
17837   verifyFormat("void switchTest1(int a)\n"
17838                "  {\n"
17839                "  switch (a)\n"
17840                "    {\n"
17841                "    case 2:\n"
17842                "      {\n"
17843                "      }\n"
17844                "      break;\n"
17845                "    }\n"
17846                "  }\n",
17847                WhitesmithsBraceStyle);
17848 
17849   verifyFormat("void switchTest2(int a)\n"
17850                "  {\n"
17851                "  switch (a)\n"
17852                "    {\n"
17853                "    case 0:\n"
17854                "      break;\n"
17855                "    case 1:\n"
17856                "      {\n"
17857                "      break;\n"
17858                "      }\n"
17859                "    case 2:\n"
17860                "      {\n"
17861                "      }\n"
17862                "      break;\n"
17863                "    default:\n"
17864                "      break;\n"
17865                "    }\n"
17866                "  }\n",
17867                WhitesmithsBraceStyle);
17868 
17869   verifyFormat("void switchTest3(int a)\n"
17870                "  {\n"
17871                "  switch (a)\n"
17872                "    {\n"
17873                "    case 0:\n"
17874                "      {\n"
17875                "      foo(x);\n"
17876                "      }\n"
17877                "      break;\n"
17878                "    default:\n"
17879                "      {\n"
17880                "      foo(1);\n"
17881                "      }\n"
17882                "      break;\n"
17883                "    }\n"
17884                "  }\n",
17885                WhitesmithsBraceStyle);
17886 
17887   WhitesmithsBraceStyle.IndentCaseLabels = false;
17888 
17889   verifyFormat("void switchTest4(int a)\n"
17890                "  {\n"
17891                "  switch (a)\n"
17892                "    {\n"
17893                "  case 2:\n"
17894                "    {\n"
17895                "    }\n"
17896                "    break;\n"
17897                "    }\n"
17898                "  }\n",
17899                WhitesmithsBraceStyle);
17900 
17901   verifyFormat("void switchTest5(int a)\n"
17902                "  {\n"
17903                "  switch (a)\n"
17904                "    {\n"
17905                "  case 0:\n"
17906                "    break;\n"
17907                "  case 1:\n"
17908                "    {\n"
17909                "    foo();\n"
17910                "    break;\n"
17911                "    }\n"
17912                "  case 2:\n"
17913                "    {\n"
17914                "    }\n"
17915                "    break;\n"
17916                "  default:\n"
17917                "    break;\n"
17918                "    }\n"
17919                "  }\n",
17920                WhitesmithsBraceStyle);
17921 
17922   verifyFormat("void switchTest6(int a)\n"
17923                "  {\n"
17924                "  switch (a)\n"
17925                "    {\n"
17926                "  case 0:\n"
17927                "    {\n"
17928                "    foo(x);\n"
17929                "    }\n"
17930                "    break;\n"
17931                "  default:\n"
17932                "    {\n"
17933                "    foo(1);\n"
17934                "    }\n"
17935                "    break;\n"
17936                "    }\n"
17937                "  }\n",
17938                WhitesmithsBraceStyle);
17939 
17940   verifyFormat("enum X\n"
17941                "  {\n"
17942                "  Y = 0, // testing\n"
17943                "  }\n",
17944                WhitesmithsBraceStyle);
17945 
17946   verifyFormat("enum X\n"
17947                "  {\n"
17948                "  Y = 0\n"
17949                "  }\n",
17950                WhitesmithsBraceStyle);
17951   verifyFormat("enum X\n"
17952                "  {\n"
17953                "  Y = 0,\n"
17954                "  Z = 1\n"
17955                "  };\n",
17956                WhitesmithsBraceStyle);
17957 
17958   verifyFormat("@interface BSApplicationController ()\n"
17959                "  {\n"
17960                "@private\n"
17961                "  id _extraIvar;\n"
17962                "  }\n"
17963                "@end\n",
17964                WhitesmithsBraceStyle);
17965 
17966   verifyFormat("#ifdef _DEBUG\n"
17967                "int foo(int i = 0)\n"
17968                "#else\n"
17969                "int foo(int i = 5)\n"
17970                "#endif\n"
17971                "  {\n"
17972                "  return i;\n"
17973                "  }",
17974                WhitesmithsBraceStyle);
17975 
17976   verifyFormat("void foo() {}\n"
17977                "void bar()\n"
17978                "#ifdef _DEBUG\n"
17979                "  {\n"
17980                "  foo();\n"
17981                "  }\n"
17982                "#else\n"
17983                "  {\n"
17984                "  }\n"
17985                "#endif",
17986                WhitesmithsBraceStyle);
17987 
17988   verifyFormat("void foobar()\n"
17989                "  {\n"
17990                "  int i = 5;\n"
17991                "  }\n"
17992                "#ifdef _DEBUG\n"
17993                "void bar()\n"
17994                "  {\n"
17995                "  }\n"
17996                "#else\n"
17997                "void bar()\n"
17998                "  {\n"
17999                "  foobar();\n"
18000                "  }\n"
18001                "#endif",
18002                WhitesmithsBraceStyle);
18003 
18004   // This shouldn't affect ObjC blocks..
18005   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18006                "  // ...\n"
18007                "  int i;\n"
18008                "}];",
18009                WhitesmithsBraceStyle);
18010   verifyFormat("void (^block)(void) = ^{\n"
18011                "  // ...\n"
18012                "  int i;\n"
18013                "};",
18014                WhitesmithsBraceStyle);
18015   // .. or dict literals.
18016   verifyFormat("void f()\n"
18017                "  {\n"
18018                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18019                "  }",
18020                WhitesmithsBraceStyle);
18021 
18022   verifyFormat("int f()\n"
18023                "  { // comment\n"
18024                "  return 42;\n"
18025                "  }",
18026                WhitesmithsBraceStyle);
18027 
18028   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
18029   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18030       FormatStyle::SIS_OnlyFirstIf;
18031   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18032   verifyFormat("void f(bool b)\n"
18033                "  {\n"
18034                "  if (b)\n"
18035                "    {\n"
18036                "    return;\n"
18037                "    }\n"
18038                "  }\n",
18039                BreakBeforeBraceShortIfs);
18040   verifyFormat("void f(bool b)\n"
18041                "  {\n"
18042                "  if (b) return;\n"
18043                "  }\n",
18044                BreakBeforeBraceShortIfs);
18045   verifyFormat("void f(bool b)\n"
18046                "  {\n"
18047                "  while (b)\n"
18048                "    {\n"
18049                "    return;\n"
18050                "    }\n"
18051                "  }\n",
18052                BreakBeforeBraceShortIfs);
18053 }
18054 
18055 TEST_F(FormatTest, GNUBraceBreaking) {
18056   FormatStyle GNUBraceStyle = getLLVMStyle();
18057   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
18058   verifyFormat("namespace a\n"
18059                "{\n"
18060                "class A\n"
18061                "{\n"
18062                "  void f()\n"
18063                "  {\n"
18064                "    int a;\n"
18065                "    {\n"
18066                "      int b;\n"
18067                "    }\n"
18068                "    if (true)\n"
18069                "      {\n"
18070                "        a();\n"
18071                "        b();\n"
18072                "      }\n"
18073                "  }\n"
18074                "  void g() { return; }\n"
18075                "}\n"
18076                "} // namespace a",
18077                GNUBraceStyle);
18078 
18079   verifyFormat("void f()\n"
18080                "{\n"
18081                "  if (true)\n"
18082                "    {\n"
18083                "      a();\n"
18084                "    }\n"
18085                "  else if (false)\n"
18086                "    {\n"
18087                "      b();\n"
18088                "    }\n"
18089                "  else\n"
18090                "    {\n"
18091                "      c();\n"
18092                "    }\n"
18093                "}\n",
18094                GNUBraceStyle);
18095 
18096   verifyFormat("void f()\n"
18097                "{\n"
18098                "  for (int i = 0; i < 10; ++i)\n"
18099                "    {\n"
18100                "      a();\n"
18101                "    }\n"
18102                "  while (false)\n"
18103                "    {\n"
18104                "      b();\n"
18105                "    }\n"
18106                "  do\n"
18107                "    {\n"
18108                "      c();\n"
18109                "    }\n"
18110                "  while (false);\n"
18111                "}\n",
18112                GNUBraceStyle);
18113 
18114   verifyFormat("void f(int a)\n"
18115                "{\n"
18116                "  switch (a)\n"
18117                "    {\n"
18118                "    case 0:\n"
18119                "      break;\n"
18120                "    case 1:\n"
18121                "      {\n"
18122                "        break;\n"
18123                "      }\n"
18124                "    case 2:\n"
18125                "      {\n"
18126                "      }\n"
18127                "      break;\n"
18128                "    default:\n"
18129                "      break;\n"
18130                "    }\n"
18131                "}\n",
18132                GNUBraceStyle);
18133 
18134   verifyFormat("enum X\n"
18135                "{\n"
18136                "  Y = 0,\n"
18137                "}\n",
18138                GNUBraceStyle);
18139 
18140   verifyFormat("@interface BSApplicationController ()\n"
18141                "{\n"
18142                "@private\n"
18143                "  id _extraIvar;\n"
18144                "}\n"
18145                "@end\n",
18146                GNUBraceStyle);
18147 
18148   verifyFormat("#ifdef _DEBUG\n"
18149                "int foo(int i = 0)\n"
18150                "#else\n"
18151                "int foo(int i = 5)\n"
18152                "#endif\n"
18153                "{\n"
18154                "  return i;\n"
18155                "}",
18156                GNUBraceStyle);
18157 
18158   verifyFormat("void foo() {}\n"
18159                "void bar()\n"
18160                "#ifdef _DEBUG\n"
18161                "{\n"
18162                "  foo();\n"
18163                "}\n"
18164                "#else\n"
18165                "{\n"
18166                "}\n"
18167                "#endif",
18168                GNUBraceStyle);
18169 
18170   verifyFormat("void foobar() { int i = 5; }\n"
18171                "#ifdef _DEBUG\n"
18172                "void bar() {}\n"
18173                "#else\n"
18174                "void bar() { foobar(); }\n"
18175                "#endif",
18176                GNUBraceStyle);
18177 }
18178 
18179 TEST_F(FormatTest, WebKitBraceBreaking) {
18180   FormatStyle WebKitBraceStyle = getLLVMStyle();
18181   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
18182   WebKitBraceStyle.FixNamespaceComments = false;
18183   verifyFormat("namespace a {\n"
18184                "class A {\n"
18185                "  void f()\n"
18186                "  {\n"
18187                "    if (true) {\n"
18188                "      a();\n"
18189                "      b();\n"
18190                "    }\n"
18191                "  }\n"
18192                "  void g() { return; }\n"
18193                "};\n"
18194                "enum E {\n"
18195                "  A,\n"
18196                "  // foo\n"
18197                "  B,\n"
18198                "  C\n"
18199                "};\n"
18200                "struct B {\n"
18201                "  int x;\n"
18202                "};\n"
18203                "}\n",
18204                WebKitBraceStyle);
18205   verifyFormat("struct S {\n"
18206                "  int Type;\n"
18207                "  union {\n"
18208                "    int x;\n"
18209                "    double y;\n"
18210                "  } Value;\n"
18211                "  class C {\n"
18212                "    MyFavoriteType Value;\n"
18213                "  } Class;\n"
18214                "};\n",
18215                WebKitBraceStyle);
18216 }
18217 
18218 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
18219   verifyFormat("void f() {\n"
18220                "  try {\n"
18221                "  } catch (const Exception &e) {\n"
18222                "  }\n"
18223                "}\n",
18224                getLLVMStyle());
18225 }
18226 
18227 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
18228   auto Style = getLLVMStyle();
18229   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18230   Style.AlignConsecutiveAssignments =
18231       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18232   Style.AlignConsecutiveDeclarations =
18233       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18234   verifyFormat("struct test demo[] = {\n"
18235                "    {56,    23, \"hello\"},\n"
18236                "    {-1, 93463, \"world\"},\n"
18237                "    { 7,     5,    \"!!\"}\n"
18238                "};\n",
18239                Style);
18240 
18241   verifyFormat("struct test demo[] = {\n"
18242                "    {56,    23, \"hello\"}, // first line\n"
18243                "    {-1, 93463, \"world\"}, // second line\n"
18244                "    { 7,     5,    \"!!\"}  // third line\n"
18245                "};\n",
18246                Style);
18247 
18248   verifyFormat("struct test demo[4] = {\n"
18249                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18250                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18251                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18252                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18253                "};\n",
18254                Style);
18255 
18256   verifyFormat("struct test demo[3] = {\n"
18257                "    {56,    23, \"hello\"},\n"
18258                "    {-1, 93463, \"world\"},\n"
18259                "    { 7,     5,    \"!!\"}\n"
18260                "};\n",
18261                Style);
18262 
18263   verifyFormat("struct test demo[3] = {\n"
18264                "    {int{56},    23, \"hello\"},\n"
18265                "    {int{-1}, 93463, \"world\"},\n"
18266                "    { int{7},     5,    \"!!\"}\n"
18267                "};\n",
18268                Style);
18269 
18270   verifyFormat("struct test demo[] = {\n"
18271                "    {56,    23, \"hello\"},\n"
18272                "    {-1, 93463, \"world\"},\n"
18273                "    { 7,     5,    \"!!\"},\n"
18274                "};\n",
18275                Style);
18276 
18277   verifyFormat("test demo[] = {\n"
18278                "    {56,    23, \"hello\"},\n"
18279                "    {-1, 93463, \"world\"},\n"
18280                "    { 7,     5,    \"!!\"},\n"
18281                "};\n",
18282                Style);
18283 
18284   verifyFormat("demo = std::array<struct test, 3>{\n"
18285                "    test{56,    23, \"hello\"},\n"
18286                "    test{-1, 93463, \"world\"},\n"
18287                "    test{ 7,     5,    \"!!\"},\n"
18288                "};\n",
18289                Style);
18290 
18291   verifyFormat("test demo[] = {\n"
18292                "    {56,    23, \"hello\"},\n"
18293                "#if X\n"
18294                "    {-1, 93463, \"world\"},\n"
18295                "#endif\n"
18296                "    { 7,     5,    \"!!\"}\n"
18297                "};\n",
18298                Style);
18299 
18300   verifyFormat(
18301       "test demo[] = {\n"
18302       "    { 7,    23,\n"
18303       "     \"hello world i am a very long line that really, in any\"\n"
18304       "     \"just world, ought to be split over multiple lines\"},\n"
18305       "    {-1, 93463,                                  \"world\"},\n"
18306       "    {56,     5,                                     \"!!\"}\n"
18307       "};\n",
18308       Style);
18309 
18310   verifyFormat("return GradForUnaryCwise(g, {\n"
18311                "                                {{\"sign\"}, \"Sign\",  "
18312                "  {\"x\", \"dy\"}},\n"
18313                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
18314                ", \"sign\"}},\n"
18315                "});\n",
18316                Style);
18317 
18318   Style.ColumnLimit = 0;
18319   EXPECT_EQ(
18320       "test demo[] = {\n"
18321       "    {56,    23, \"hello world i am a very long line that really, "
18322       "in any just world, ought to be split over multiple lines\"},\n"
18323       "    {-1, 93463,                                                  "
18324       "                                                 \"world\"},\n"
18325       "    { 7,     5,                                                  "
18326       "                                                    \"!!\"},\n"
18327       "};",
18328       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18329              "that really, in any just world, ought to be split over multiple "
18330              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18331              Style));
18332 
18333   Style.ColumnLimit = 80;
18334   verifyFormat("test demo[] = {\n"
18335                "    {56,    23, /* a comment */ \"hello\"},\n"
18336                "    {-1, 93463,                 \"world\"},\n"
18337                "    { 7,     5,                    \"!!\"}\n"
18338                "};\n",
18339                Style);
18340 
18341   verifyFormat("test demo[] = {\n"
18342                "    {56,    23,                    \"hello\"},\n"
18343                "    {-1, 93463, \"world\" /* comment here */},\n"
18344                "    { 7,     5,                       \"!!\"}\n"
18345                "};\n",
18346                Style);
18347 
18348   verifyFormat("test demo[] = {\n"
18349                "    {56, /* a comment */ 23, \"hello\"},\n"
18350                "    {-1,              93463, \"world\"},\n"
18351                "    { 7,                  5,    \"!!\"}\n"
18352                "};\n",
18353                Style);
18354 
18355   Style.ColumnLimit = 20;
18356   EXPECT_EQ(
18357       "demo = std::array<\n"
18358       "    struct test, 3>{\n"
18359       "    test{\n"
18360       "         56,    23,\n"
18361       "         \"hello \"\n"
18362       "         \"world i \"\n"
18363       "         \"am a very \"\n"
18364       "         \"long line \"\n"
18365       "         \"that \"\n"
18366       "         \"really, \"\n"
18367       "         \"in any \"\n"
18368       "         \"just \"\n"
18369       "         \"world, \"\n"
18370       "         \"ought to \"\n"
18371       "         \"be split \"\n"
18372       "         \"over \"\n"
18373       "         \"multiple \"\n"
18374       "         \"lines\"},\n"
18375       "    test{-1, 93463,\n"
18376       "         \"world\"},\n"
18377       "    test{ 7,     5,\n"
18378       "         \"!!\"   },\n"
18379       "};",
18380       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18381              "i am a very long line that really, in any just world, ought "
18382              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18383              "test{7, 5, \"!!\"},};",
18384              Style));
18385   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18386   Style = getLLVMStyleWithColumns(50);
18387   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18388   verifyFormat("static A x = {\n"
18389                "    {{init1, init2, init3, init4},\n"
18390                "     {init1, init2, init3, init4}}\n"
18391                "};",
18392                Style);
18393   Style.ColumnLimit = 100;
18394   EXPECT_EQ(
18395       "test demo[] = {\n"
18396       "    {56,    23,\n"
18397       "     \"hello world i am a very long line that really, in any just world"
18398       ", ought to be split over \"\n"
18399       "     \"multiple lines\"  },\n"
18400       "    {-1, 93463, \"world\"},\n"
18401       "    { 7,     5,    \"!!\"},\n"
18402       "};",
18403       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18404              "that really, in any just world, ought to be split over multiple "
18405              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18406              Style));
18407 
18408   Style = getLLVMStyleWithColumns(50);
18409   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18410   Style.AlignConsecutiveAssignments =
18411       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18412   Style.AlignConsecutiveDeclarations =
18413       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18414   verifyFormat("struct test demo[] = {\n"
18415                "    {56,    23, \"hello\"},\n"
18416                "    {-1, 93463, \"world\"},\n"
18417                "    { 7,     5,    \"!!\"}\n"
18418                "};\n"
18419                "static A x = {\n"
18420                "    {{init1, init2, init3, init4},\n"
18421                "     {init1, init2, init3, init4}}\n"
18422                "};",
18423                Style);
18424   Style.ColumnLimit = 100;
18425   Style.AlignConsecutiveAssignments =
18426       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18427   Style.AlignConsecutiveDeclarations =
18428       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18429   verifyFormat("struct test demo[] = {\n"
18430                "    {56,    23, \"hello\"},\n"
18431                "    {-1, 93463, \"world\"},\n"
18432                "    { 7,     5,    \"!!\"}\n"
18433                "};\n"
18434                "struct test demo[4] = {\n"
18435                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18436                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18437                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18438                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18439                "};\n",
18440                Style);
18441   EXPECT_EQ(
18442       "test demo[] = {\n"
18443       "    {56,\n"
18444       "     \"hello world i am a very long line that really, in any just world"
18445       ", ought to be split over \"\n"
18446       "     \"multiple lines\",    23},\n"
18447       "    {-1,      \"world\", 93463},\n"
18448       "    { 7,         \"!!\",     5},\n"
18449       "};",
18450       format("test demo[] = {{56, \"hello world i am a very long line "
18451              "that really, in any just world, ought to be split over multiple "
18452              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
18453              Style));
18454 }
18455 
18456 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
18457   auto Style = getLLVMStyle();
18458   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18459   /* FIXME: This case gets misformatted.
18460   verifyFormat("auto foo = Items{\n"
18461                "    Section{0, bar(), },\n"
18462                "    Section{1, boo()  }\n"
18463                "};\n",
18464                Style);
18465   */
18466   verifyFormat("auto foo = Items{\n"
18467                "    Section{\n"
18468                "            0, bar(),\n"
18469                "            }\n"
18470                "};\n",
18471                Style);
18472   verifyFormat("struct test demo[] = {\n"
18473                "    {56, 23,    \"hello\"},\n"
18474                "    {-1, 93463, \"world\"},\n"
18475                "    {7,  5,     \"!!\"   }\n"
18476                "};\n",
18477                Style);
18478   verifyFormat("struct test demo[] = {\n"
18479                "    {56, 23,    \"hello\"}, // first line\n"
18480                "    {-1, 93463, \"world\"}, // second line\n"
18481                "    {7,  5,     \"!!\"   }  // third line\n"
18482                "};\n",
18483                Style);
18484   verifyFormat("struct test demo[4] = {\n"
18485                "    {56,  23,    21, \"oh\"      }, // first line\n"
18486                "    {-1,  93463, 22, \"my\"      }, // second line\n"
18487                "    {7,   5,     1,  \"goodness\"}  // third line\n"
18488                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
18489                "};\n",
18490                Style);
18491   verifyFormat("struct test demo[3] = {\n"
18492                "    {56, 23,    \"hello\"},\n"
18493                "    {-1, 93463, \"world\"},\n"
18494                "    {7,  5,     \"!!\"   }\n"
18495                "};\n",
18496                Style);
18497 
18498   verifyFormat("struct test demo[3] = {\n"
18499                "    {int{56}, 23,    \"hello\"},\n"
18500                "    {int{-1}, 93463, \"world\"},\n"
18501                "    {int{7},  5,     \"!!\"   }\n"
18502                "};\n",
18503                Style);
18504   verifyFormat("struct test demo[] = {\n"
18505                "    {56, 23,    \"hello\"},\n"
18506                "    {-1, 93463, \"world\"},\n"
18507                "    {7,  5,     \"!!\"   },\n"
18508                "};\n",
18509                Style);
18510   verifyFormat("test demo[] = {\n"
18511                "    {56, 23,    \"hello\"},\n"
18512                "    {-1, 93463, \"world\"},\n"
18513                "    {7,  5,     \"!!\"   },\n"
18514                "};\n",
18515                Style);
18516   verifyFormat("demo = std::array<struct test, 3>{\n"
18517                "    test{56, 23,    \"hello\"},\n"
18518                "    test{-1, 93463, \"world\"},\n"
18519                "    test{7,  5,     \"!!\"   },\n"
18520                "};\n",
18521                Style);
18522   verifyFormat("test demo[] = {\n"
18523                "    {56, 23,    \"hello\"},\n"
18524                "#if X\n"
18525                "    {-1, 93463, \"world\"},\n"
18526                "#endif\n"
18527                "    {7,  5,     \"!!\"   }\n"
18528                "};\n",
18529                Style);
18530   verifyFormat(
18531       "test demo[] = {\n"
18532       "    {7,  23,\n"
18533       "     \"hello world i am a very long line that really, in any\"\n"
18534       "     \"just world, ought to be split over multiple lines\"},\n"
18535       "    {-1, 93463, \"world\"                                 },\n"
18536       "    {56, 5,     \"!!\"                                    }\n"
18537       "};\n",
18538       Style);
18539 
18540   verifyFormat("return GradForUnaryCwise(g, {\n"
18541                "                                {{\"sign\"}, \"Sign\", {\"x\", "
18542                "\"dy\"}   },\n"
18543                "                                {{\"dx\"},   \"Mul\",  "
18544                "{\"dy\", \"sign\"}},\n"
18545                "});\n",
18546                Style);
18547 
18548   Style.ColumnLimit = 0;
18549   EXPECT_EQ(
18550       "test demo[] = {\n"
18551       "    {56, 23,    \"hello world i am a very long line that really, in any "
18552       "just world, ought to be split over multiple lines\"},\n"
18553       "    {-1, 93463, \"world\"                                               "
18554       "                                                   },\n"
18555       "    {7,  5,     \"!!\"                                                  "
18556       "                                                   },\n"
18557       "};",
18558       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18559              "that really, in any just world, ought to be split over multiple "
18560              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18561              Style));
18562 
18563   Style.ColumnLimit = 80;
18564   verifyFormat("test demo[] = {\n"
18565                "    {56, 23,    /* a comment */ \"hello\"},\n"
18566                "    {-1, 93463, \"world\"                },\n"
18567                "    {7,  5,     \"!!\"                   }\n"
18568                "};\n",
18569                Style);
18570 
18571   verifyFormat("test demo[] = {\n"
18572                "    {56, 23,    \"hello\"                   },\n"
18573                "    {-1, 93463, \"world\" /* comment here */},\n"
18574                "    {7,  5,     \"!!\"                      }\n"
18575                "};\n",
18576                Style);
18577 
18578   verifyFormat("test demo[] = {\n"
18579                "    {56, /* a comment */ 23, \"hello\"},\n"
18580                "    {-1, 93463,              \"world\"},\n"
18581                "    {7,  5,                  \"!!\"   }\n"
18582                "};\n",
18583                Style);
18584 
18585   Style.ColumnLimit = 20;
18586   EXPECT_EQ(
18587       "demo = std::array<\n"
18588       "    struct test, 3>{\n"
18589       "    test{\n"
18590       "         56, 23,\n"
18591       "         \"hello \"\n"
18592       "         \"world i \"\n"
18593       "         \"am a very \"\n"
18594       "         \"long line \"\n"
18595       "         \"that \"\n"
18596       "         \"really, \"\n"
18597       "         \"in any \"\n"
18598       "         \"just \"\n"
18599       "         \"world, \"\n"
18600       "         \"ought to \"\n"
18601       "         \"be split \"\n"
18602       "         \"over \"\n"
18603       "         \"multiple \"\n"
18604       "         \"lines\"},\n"
18605       "    test{-1, 93463,\n"
18606       "         \"world\"},\n"
18607       "    test{7,  5,\n"
18608       "         \"!!\"   },\n"
18609       "};",
18610       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18611              "i am a very long line that really, in any just world, ought "
18612              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18613              "test{7, 5, \"!!\"},};",
18614              Style));
18615 
18616   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18617   Style = getLLVMStyleWithColumns(50);
18618   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18619   verifyFormat("static A x = {\n"
18620                "    {{init1, init2, init3, init4},\n"
18621                "     {init1, init2, init3, init4}}\n"
18622                "};",
18623                Style);
18624   Style.ColumnLimit = 100;
18625   EXPECT_EQ(
18626       "test demo[] = {\n"
18627       "    {56, 23,\n"
18628       "     \"hello world i am a very long line that really, in any just world"
18629       ", ought to be split over \"\n"
18630       "     \"multiple lines\"  },\n"
18631       "    {-1, 93463, \"world\"},\n"
18632       "    {7,  5,     \"!!\"   },\n"
18633       "};",
18634       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18635              "that really, in any just world, ought to be split over multiple "
18636              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18637              Style));
18638 }
18639 
18640 TEST_F(FormatTest, UnderstandsPragmas) {
18641   verifyFormat("#pragma omp reduction(| : var)");
18642   verifyFormat("#pragma omp reduction(+ : var)");
18643 
18644   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
18645             "(including parentheses).",
18646             format("#pragma    mark   Any non-hyphenated or hyphenated string "
18647                    "(including parentheses)."));
18648 }
18649 
18650 TEST_F(FormatTest, UnderstandPragmaOption) {
18651   verifyFormat("#pragma option -C -A");
18652 
18653   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
18654 }
18655 
18656 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
18657   FormatStyle Style = getLLVMStyleWithColumns(20);
18658 
18659   // See PR41213
18660   EXPECT_EQ("/*\n"
18661             " *\t9012345\n"
18662             " * /8901\n"
18663             " */",
18664             format("/*\n"
18665                    " *\t9012345 /8901\n"
18666                    " */",
18667                    Style));
18668   EXPECT_EQ("/*\n"
18669             " *345678\n"
18670             " *\t/8901\n"
18671             " */",
18672             format("/*\n"
18673                    " *345678\t/8901\n"
18674                    " */",
18675                    Style));
18676 
18677   verifyFormat("int a; // the\n"
18678                "       // comment",
18679                Style);
18680   EXPECT_EQ("int a; /* first line\n"
18681             "        * second\n"
18682             "        * line third\n"
18683             "        * line\n"
18684             "        */",
18685             format("int a; /* first line\n"
18686                    "        * second\n"
18687                    "        * line third\n"
18688                    "        * line\n"
18689                    "        */",
18690                    Style));
18691   EXPECT_EQ("int a; // first line\n"
18692             "       // second\n"
18693             "       // line third\n"
18694             "       // line",
18695             format("int a; // first line\n"
18696                    "       // second line\n"
18697                    "       // third line",
18698                    Style));
18699 
18700   Style.PenaltyExcessCharacter = 90;
18701   verifyFormat("int a; // the comment", Style);
18702   EXPECT_EQ("int a; // the comment\n"
18703             "       // aaa",
18704             format("int a; // the comment aaa", Style));
18705   EXPECT_EQ("int a; /* first line\n"
18706             "        * second line\n"
18707             "        * third line\n"
18708             "        */",
18709             format("int a; /* first line\n"
18710                    "        * second line\n"
18711                    "        * third line\n"
18712                    "        */",
18713                    Style));
18714   EXPECT_EQ("int a; // first line\n"
18715             "       // second line\n"
18716             "       // third line",
18717             format("int a; // first line\n"
18718                    "       // second line\n"
18719                    "       // third line",
18720                    Style));
18721   // FIXME: Investigate why this is not getting the same layout as the test
18722   // above.
18723   EXPECT_EQ("int a; /* first line\n"
18724             "        * second line\n"
18725             "        * third line\n"
18726             "        */",
18727             format("int a; /* first line second line third line"
18728                    "\n*/",
18729                    Style));
18730 
18731   EXPECT_EQ("// foo bar baz bazfoo\n"
18732             "// foo bar foo bar\n",
18733             format("// foo bar baz bazfoo\n"
18734                    "// foo bar foo           bar\n",
18735                    Style));
18736   EXPECT_EQ("// foo bar baz bazfoo\n"
18737             "// foo bar foo bar\n",
18738             format("// foo bar baz      bazfoo\n"
18739                    "// foo            bar foo bar\n",
18740                    Style));
18741 
18742   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
18743   // next one.
18744   EXPECT_EQ("// foo bar baz bazfoo\n"
18745             "// bar foo bar\n",
18746             format("// foo bar baz      bazfoo bar\n"
18747                    "// foo            bar\n",
18748                    Style));
18749 
18750   EXPECT_EQ("// foo bar baz bazfoo\n"
18751             "// foo bar baz bazfoo\n"
18752             "// bar foo bar\n",
18753             format("// foo bar baz      bazfoo\n"
18754                    "// foo bar baz      bazfoo bar\n"
18755                    "// foo bar\n",
18756                    Style));
18757 
18758   EXPECT_EQ("// foo bar baz bazfoo\n"
18759             "// foo bar baz bazfoo\n"
18760             "// bar foo bar\n",
18761             format("// foo bar baz      bazfoo\n"
18762                    "// foo bar baz      bazfoo bar\n"
18763                    "// foo           bar\n",
18764                    Style));
18765 
18766   // Make sure we do not keep protruding characters if strict mode reflow is
18767   // cheaper than keeping protruding characters.
18768   Style.ColumnLimit = 21;
18769   EXPECT_EQ(
18770       "// foo foo foo foo\n"
18771       "// foo foo foo foo\n"
18772       "// foo foo foo foo\n",
18773       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
18774 
18775   EXPECT_EQ("int a = /* long block\n"
18776             "           comment */\n"
18777             "    42;",
18778             format("int a = /* long block comment */ 42;", Style));
18779 }
18780 
18781 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
18782   FormatStyle Style = getLLVMStyle();
18783   Style.ColumnLimit = 8;
18784   Style.PenaltyExcessCharacter = 15;
18785   verifyFormat("int foo(\n"
18786                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
18787                Style);
18788   Style.PenaltyBreakOpenParenthesis = 200;
18789   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
18790             format("int foo(\n"
18791                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
18792                    Style));
18793 }
18794 
18795 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
18796   FormatStyle Style = getLLVMStyle();
18797   Style.ColumnLimit = 5;
18798   Style.PenaltyExcessCharacter = 150;
18799   verifyFormat("foo((\n"
18800                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
18801 
18802                Style);
18803   Style.PenaltyBreakOpenParenthesis = 100000;
18804   EXPECT_EQ("foo((int)\n"
18805             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
18806             format("foo((\n"
18807                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
18808                    Style));
18809 }
18810 
18811 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
18812   FormatStyle Style = getLLVMStyle();
18813   Style.ColumnLimit = 4;
18814   Style.PenaltyExcessCharacter = 100;
18815   verifyFormat("for (\n"
18816                "    int iiiiiiiiiiiiiiiii =\n"
18817                "        0;\n"
18818                "    iiiiiiiiiiiiiiiii <\n"
18819                "    2;\n"
18820                "    iiiiiiiiiiiiiiiii++) {\n"
18821                "}",
18822 
18823                Style);
18824   Style.PenaltyBreakOpenParenthesis = 1250;
18825   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
18826             "         0;\n"
18827             "     iiiiiiiiiiiiiiiii <\n"
18828             "     2;\n"
18829             "     iiiiiiiiiiiiiiiii++) {\n"
18830             "}",
18831             format("for (\n"
18832                    "    int iiiiiiiiiiiiiiiii =\n"
18833                    "        0;\n"
18834                    "    iiiiiiiiiiiiiiiii <\n"
18835                    "    2;\n"
18836                    "    iiiiiiiiiiiiiiiii++) {\n"
18837                    "}",
18838                    Style));
18839 }
18840 
18841 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
18842   for (size_t i = 1; i < Styles.size(); ++i)                                   \
18843   EXPECT_EQ(Styles[0], Styles[i])                                              \
18844       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
18845 
18846 TEST_F(FormatTest, GetsPredefinedStyleByName) {
18847   SmallVector<FormatStyle, 3> Styles;
18848   Styles.resize(3);
18849 
18850   Styles[0] = getLLVMStyle();
18851   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
18852   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
18853   EXPECT_ALL_STYLES_EQUAL(Styles);
18854 
18855   Styles[0] = getGoogleStyle();
18856   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
18857   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
18858   EXPECT_ALL_STYLES_EQUAL(Styles);
18859 
18860   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18861   EXPECT_TRUE(
18862       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
18863   EXPECT_TRUE(
18864       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
18865   EXPECT_ALL_STYLES_EQUAL(Styles);
18866 
18867   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
18868   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
18869   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
18870   EXPECT_ALL_STYLES_EQUAL(Styles);
18871 
18872   Styles[0] = getMozillaStyle();
18873   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
18874   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
18875   EXPECT_ALL_STYLES_EQUAL(Styles);
18876 
18877   Styles[0] = getWebKitStyle();
18878   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
18879   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
18880   EXPECT_ALL_STYLES_EQUAL(Styles);
18881 
18882   Styles[0] = getGNUStyle();
18883   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
18884   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
18885   EXPECT_ALL_STYLES_EQUAL(Styles);
18886 
18887   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
18888 }
18889 
18890 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
18891   SmallVector<FormatStyle, 8> Styles;
18892   Styles.resize(2);
18893 
18894   Styles[0] = getGoogleStyle();
18895   Styles[1] = getLLVMStyle();
18896   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18897   EXPECT_ALL_STYLES_EQUAL(Styles);
18898 
18899   Styles.resize(5);
18900   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18901   Styles[1] = getLLVMStyle();
18902   Styles[1].Language = FormatStyle::LK_JavaScript;
18903   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18904 
18905   Styles[2] = getLLVMStyle();
18906   Styles[2].Language = FormatStyle::LK_JavaScript;
18907   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
18908                                   "BasedOnStyle: Google",
18909                                   &Styles[2])
18910                    .value());
18911 
18912   Styles[3] = getLLVMStyle();
18913   Styles[3].Language = FormatStyle::LK_JavaScript;
18914   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
18915                                   "Language: JavaScript",
18916                                   &Styles[3])
18917                    .value());
18918 
18919   Styles[4] = getLLVMStyle();
18920   Styles[4].Language = FormatStyle::LK_JavaScript;
18921   EXPECT_EQ(0, parseConfiguration("---\n"
18922                                   "BasedOnStyle: LLVM\n"
18923                                   "IndentWidth: 123\n"
18924                                   "---\n"
18925                                   "BasedOnStyle: Google\n"
18926                                   "Language: JavaScript",
18927                                   &Styles[4])
18928                    .value());
18929   EXPECT_ALL_STYLES_EQUAL(Styles);
18930 }
18931 
18932 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
18933   Style.FIELD = false;                                                         \
18934   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
18935   EXPECT_TRUE(Style.FIELD);                                                    \
18936   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
18937   EXPECT_FALSE(Style.FIELD);
18938 
18939 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
18940 
18941 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
18942   Style.STRUCT.FIELD = false;                                                  \
18943   EXPECT_EQ(0,                                                                 \
18944             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
18945                 .value());                                                     \
18946   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
18947   EXPECT_EQ(0,                                                                 \
18948             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
18949                 .value());                                                     \
18950   EXPECT_FALSE(Style.STRUCT.FIELD);
18951 
18952 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
18953   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
18954 
18955 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
18956   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
18957   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
18958   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
18959 
18960 TEST_F(FormatTest, ParsesConfigurationBools) {
18961   FormatStyle Style = {};
18962   Style.Language = FormatStyle::LK_Cpp;
18963   CHECK_PARSE_BOOL(AlignTrailingComments);
18964   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
18965   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
18966   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
18967   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
18968   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
18969   CHECK_PARSE_BOOL(BinPackArguments);
18970   CHECK_PARSE_BOOL(BinPackParameters);
18971   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
18972   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
18973   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
18974   CHECK_PARSE_BOOL(BreakStringLiterals);
18975   CHECK_PARSE_BOOL(CompactNamespaces);
18976   CHECK_PARSE_BOOL(DeriveLineEnding);
18977   CHECK_PARSE_BOOL(DerivePointerAlignment);
18978   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
18979   CHECK_PARSE_BOOL(DisableFormat);
18980   CHECK_PARSE_BOOL(IndentAccessModifiers);
18981   CHECK_PARSE_BOOL(IndentCaseLabels);
18982   CHECK_PARSE_BOOL(IndentCaseBlocks);
18983   CHECK_PARSE_BOOL(IndentGotoLabels);
18984   CHECK_PARSE_BOOL(IndentRequires);
18985   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
18986   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
18987   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
18988   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
18989   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
18990   CHECK_PARSE_BOOL(ReflowComments);
18991   CHECK_PARSE_BOOL(RemoveBracesLLVM);
18992   CHECK_PARSE_BOOL(SortUsingDeclarations);
18993   CHECK_PARSE_BOOL(SpacesInParentheses);
18994   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
18995   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
18996   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
18997   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
18998   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
18999   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
19000   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
19001   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
19002   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
19003   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
19004   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
19005   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
19006   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
19007   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
19008   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
19009   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
19010   CHECK_PARSE_BOOL(UseCRLF);
19011 
19012   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
19013   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
19014   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
19015   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
19016   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
19017   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
19018   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
19019   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
19020   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
19021   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
19022   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
19023   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
19024   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
19025   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
19026   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
19027   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
19028   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
19029   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
19030   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
19031   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19032                           AfterFunctionDeclarationName);
19033   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19034                           AfterFunctionDefinitionName);
19035   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
19036   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
19037   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
19038 }
19039 
19040 #undef CHECK_PARSE_BOOL
19041 
19042 TEST_F(FormatTest, ParsesConfiguration) {
19043   FormatStyle Style = {};
19044   Style.Language = FormatStyle::LK_Cpp;
19045   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
19046   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
19047               ConstructorInitializerIndentWidth, 1234u);
19048   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
19049   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
19050   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
19051   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
19052   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
19053               PenaltyBreakBeforeFirstCallParameter, 1234u);
19054   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
19055               PenaltyBreakTemplateDeclaration, 1234u);
19056   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
19057               1234u);
19058   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
19059   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
19060               PenaltyReturnTypeOnItsOwnLine, 1234u);
19061   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
19062               SpacesBeforeTrailingComments, 1234u);
19063   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
19064   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
19065   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
19066 
19067   Style.QualifierAlignment = FormatStyle::QAS_Right;
19068   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
19069               FormatStyle::QAS_Leave);
19070   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
19071               FormatStyle::QAS_Right);
19072   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
19073               FormatStyle::QAS_Left);
19074   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
19075               FormatStyle::QAS_Custom);
19076 
19077   Style.QualifierOrder.clear();
19078   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
19079               std::vector<std::string>({"const", "volatile", "type"}));
19080   Style.QualifierOrder.clear();
19081   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
19082               std::vector<std::string>({"const", "type"}));
19083   Style.QualifierOrder.clear();
19084   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
19085               std::vector<std::string>({"volatile", "type"}));
19086 
19087   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
19088   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
19089               FormatStyle::ACS_None);
19090   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
19091               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
19092   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
19093               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
19094   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
19095               AlignConsecutiveAssignments,
19096               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19097   // For backwards compability, false / true should still parse
19098   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
19099               FormatStyle::ACS_None);
19100   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
19101               FormatStyle::ACS_Consecutive);
19102 
19103   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
19104   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
19105               FormatStyle::ACS_None);
19106   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
19107               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
19108   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
19109               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
19110   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
19111               AlignConsecutiveBitFields,
19112               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19113   // For backwards compability, false / true should still parse
19114   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
19115               FormatStyle::ACS_None);
19116   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
19117               FormatStyle::ACS_Consecutive);
19118 
19119   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
19120   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
19121               FormatStyle::ACS_None);
19122   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
19123               FormatStyle::ACS_Consecutive);
19124   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
19125               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
19126   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
19127               AlignConsecutiveMacros,
19128               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19129   // For backwards compability, false / true should still parse
19130   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
19131               FormatStyle::ACS_None);
19132   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
19133               FormatStyle::ACS_Consecutive);
19134 
19135   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
19136   CHECK_PARSE("AlignConsecutiveDeclarations: None",
19137               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
19138   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
19139               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
19140   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
19141               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
19142   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
19143               AlignConsecutiveDeclarations,
19144               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19145   // For backwards compability, false / true should still parse
19146   CHECK_PARSE("AlignConsecutiveDeclarations: false",
19147               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
19148   CHECK_PARSE("AlignConsecutiveDeclarations: true",
19149               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
19150 
19151   Style.PointerAlignment = FormatStyle::PAS_Middle;
19152   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
19153               FormatStyle::PAS_Left);
19154   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
19155               FormatStyle::PAS_Right);
19156   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
19157               FormatStyle::PAS_Middle);
19158   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
19159   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
19160               FormatStyle::RAS_Pointer);
19161   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
19162               FormatStyle::RAS_Left);
19163   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
19164               FormatStyle::RAS_Right);
19165   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
19166               FormatStyle::RAS_Middle);
19167   // For backward compatibility:
19168   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
19169               FormatStyle::PAS_Left);
19170   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
19171               FormatStyle::PAS_Right);
19172   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
19173               FormatStyle::PAS_Middle);
19174 
19175   Style.Standard = FormatStyle::LS_Auto;
19176   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
19177   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
19178   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
19179   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
19180   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
19181   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
19182   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
19183   // Legacy aliases:
19184   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
19185   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
19186   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
19187   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
19188 
19189   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
19190   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
19191               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
19192   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
19193               FormatStyle::BOS_None);
19194   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
19195               FormatStyle::BOS_All);
19196   // For backward compatibility:
19197   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
19198               FormatStyle::BOS_None);
19199   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
19200               FormatStyle::BOS_All);
19201 
19202   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
19203   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
19204               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
19205   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
19206               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
19207   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
19208               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
19209   // For backward compatibility:
19210   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
19211               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
19212 
19213   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
19214   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
19215               FormatStyle::BILS_AfterComma);
19216   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
19217               FormatStyle::BILS_BeforeComma);
19218   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
19219               FormatStyle::BILS_AfterColon);
19220   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
19221               FormatStyle::BILS_BeforeColon);
19222   // For backward compatibility:
19223   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
19224               FormatStyle::BILS_BeforeComma);
19225 
19226   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19227   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
19228               FormatStyle::PCIS_Never);
19229   CHECK_PARSE("PackConstructorInitializers: BinPack",
19230               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19231   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
19232               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19233   CHECK_PARSE("PackConstructorInitializers: NextLine",
19234               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19235   // For backward compatibility:
19236   CHECK_PARSE("BasedOnStyle: Google\n"
19237               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19238               "AllowAllConstructorInitializersOnNextLine: false",
19239               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19240   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
19241   CHECK_PARSE("BasedOnStyle: Google\n"
19242               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
19243               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19244   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19245               "AllowAllConstructorInitializersOnNextLine: true",
19246               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19247   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19248   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19249               "AllowAllConstructorInitializersOnNextLine: false",
19250               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19251 
19252   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
19253   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
19254               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
19255   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
19256               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
19257   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
19258               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
19259   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
19260               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
19261 
19262   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19263   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
19264               FormatStyle::BAS_Align);
19265   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
19266               FormatStyle::BAS_DontAlign);
19267   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
19268               FormatStyle::BAS_AlwaysBreak);
19269   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
19270               FormatStyle::BAS_BlockIndent);
19271   // For backward compatibility:
19272   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
19273               FormatStyle::BAS_DontAlign);
19274   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
19275               FormatStyle::BAS_Align);
19276 
19277   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
19278   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
19279               FormatStyle::ENAS_DontAlign);
19280   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
19281               FormatStyle::ENAS_Left);
19282   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
19283               FormatStyle::ENAS_Right);
19284   // For backward compatibility:
19285   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
19286               FormatStyle::ENAS_Left);
19287   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
19288               FormatStyle::ENAS_Right);
19289 
19290   Style.AlignOperands = FormatStyle::OAS_Align;
19291   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
19292               FormatStyle::OAS_DontAlign);
19293   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
19294   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
19295               FormatStyle::OAS_AlignAfterOperator);
19296   // For backward compatibility:
19297   CHECK_PARSE("AlignOperands: false", AlignOperands,
19298               FormatStyle::OAS_DontAlign);
19299   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
19300 
19301   Style.UseTab = FormatStyle::UT_ForIndentation;
19302   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
19303   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
19304   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
19305   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
19306               FormatStyle::UT_ForContinuationAndIndentation);
19307   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
19308               FormatStyle::UT_AlignWithSpaces);
19309   // For backward compatibility:
19310   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
19311   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
19312 
19313   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
19314   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
19315               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19316   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
19317               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
19318   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
19319               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19320   // For backward compatibility:
19321   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
19322               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19323   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
19324               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19325 
19326   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
19327   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
19328               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19329   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
19330               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
19331   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
19332               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
19333   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
19334               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19335   // For backward compatibility:
19336   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
19337               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19338   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
19339               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19340 
19341   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
19342   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
19343               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
19344   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
19345               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
19346   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
19347               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
19348   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
19349               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
19350 
19351   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
19352   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
19353               FormatStyle::SBPO_Never);
19354   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
19355               FormatStyle::SBPO_Always);
19356   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
19357               FormatStyle::SBPO_ControlStatements);
19358   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
19359               SpaceBeforeParens,
19360               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19361   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
19362               FormatStyle::SBPO_NonEmptyParentheses);
19363   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
19364               FormatStyle::SBPO_Custom);
19365   // For backward compatibility:
19366   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
19367               FormatStyle::SBPO_Never);
19368   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
19369               FormatStyle::SBPO_ControlStatements);
19370   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
19371               SpaceBeforeParens,
19372               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19373 
19374   Style.ColumnLimit = 123;
19375   FormatStyle BaseStyle = getLLVMStyle();
19376   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
19377   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
19378 
19379   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
19380   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
19381               FormatStyle::BS_Attach);
19382   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
19383               FormatStyle::BS_Linux);
19384   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
19385               FormatStyle::BS_Mozilla);
19386   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
19387               FormatStyle::BS_Stroustrup);
19388   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
19389               FormatStyle::BS_Allman);
19390   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
19391               FormatStyle::BS_Whitesmiths);
19392   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
19393   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
19394               FormatStyle::BS_WebKit);
19395   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
19396               FormatStyle::BS_Custom);
19397 
19398   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
19399   CHECK_PARSE("BraceWrapping:\n"
19400               "  AfterControlStatement: MultiLine",
19401               BraceWrapping.AfterControlStatement,
19402               FormatStyle::BWACS_MultiLine);
19403   CHECK_PARSE("BraceWrapping:\n"
19404               "  AfterControlStatement: Always",
19405               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19406   CHECK_PARSE("BraceWrapping:\n"
19407               "  AfterControlStatement: Never",
19408               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19409   // For backward compatibility:
19410   CHECK_PARSE("BraceWrapping:\n"
19411               "  AfterControlStatement: true",
19412               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19413   CHECK_PARSE("BraceWrapping:\n"
19414               "  AfterControlStatement: false",
19415               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19416 
19417   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
19418   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
19419               FormatStyle::RTBS_None);
19420   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
19421               FormatStyle::RTBS_All);
19422   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
19423               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
19424   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
19425               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
19426   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
19427               AlwaysBreakAfterReturnType,
19428               FormatStyle::RTBS_TopLevelDefinitions);
19429 
19430   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
19431   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
19432               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
19433   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
19434               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19435   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
19436               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19437   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
19438               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19439   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
19440               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19441 
19442   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
19443   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
19444               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
19445   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
19446               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
19447   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
19448               AlwaysBreakAfterDefinitionReturnType,
19449               FormatStyle::DRTBS_TopLevel);
19450 
19451   Style.NamespaceIndentation = FormatStyle::NI_All;
19452   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
19453               FormatStyle::NI_None);
19454   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
19455               FormatStyle::NI_Inner);
19456   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
19457               FormatStyle::NI_All);
19458 
19459   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
19460   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
19461               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19462   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
19463               AllowShortIfStatementsOnASingleLine,
19464               FormatStyle::SIS_WithoutElse);
19465   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
19466               AllowShortIfStatementsOnASingleLine,
19467               FormatStyle::SIS_OnlyFirstIf);
19468   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
19469               AllowShortIfStatementsOnASingleLine,
19470               FormatStyle::SIS_AllIfsAndElse);
19471   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
19472               AllowShortIfStatementsOnASingleLine,
19473               FormatStyle::SIS_OnlyFirstIf);
19474   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
19475               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19476   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
19477               AllowShortIfStatementsOnASingleLine,
19478               FormatStyle::SIS_WithoutElse);
19479 
19480   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
19481   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
19482               FormatStyle::IEBS_AfterExternBlock);
19483   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
19484               FormatStyle::IEBS_Indent);
19485   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
19486               FormatStyle::IEBS_NoIndent);
19487   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
19488               FormatStyle::IEBS_Indent);
19489   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
19490               FormatStyle::IEBS_NoIndent);
19491 
19492   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
19493   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
19494               FormatStyle::BFCS_Both);
19495   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
19496               FormatStyle::BFCS_None);
19497   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
19498               FormatStyle::BFCS_Before);
19499   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
19500               FormatStyle::BFCS_After);
19501 
19502   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
19503   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
19504               FormatStyle::SJSIO_After);
19505   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
19506               FormatStyle::SJSIO_Before);
19507 
19508   // FIXME: This is required because parsing a configuration simply overwrites
19509   // the first N elements of the list instead of resetting it.
19510   Style.ForEachMacros.clear();
19511   std::vector<std::string> BoostForeach;
19512   BoostForeach.push_back("BOOST_FOREACH");
19513   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
19514   std::vector<std::string> BoostAndQForeach;
19515   BoostAndQForeach.push_back("BOOST_FOREACH");
19516   BoostAndQForeach.push_back("Q_FOREACH");
19517   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
19518               BoostAndQForeach);
19519 
19520   Style.IfMacros.clear();
19521   std::vector<std::string> CustomIfs;
19522   CustomIfs.push_back("MYIF");
19523   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
19524 
19525   Style.AttributeMacros.clear();
19526   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
19527               std::vector<std::string>{"__capability"});
19528   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
19529               std::vector<std::string>({"attr1", "attr2"}));
19530 
19531   Style.StatementAttributeLikeMacros.clear();
19532   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
19533               StatementAttributeLikeMacros,
19534               std::vector<std::string>({"emit", "Q_EMIT"}));
19535 
19536   Style.StatementMacros.clear();
19537   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
19538               std::vector<std::string>{"QUNUSED"});
19539   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
19540               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
19541 
19542   Style.NamespaceMacros.clear();
19543   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
19544               std::vector<std::string>{"TESTSUITE"});
19545   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
19546               std::vector<std::string>({"TESTSUITE", "SUITE"}));
19547 
19548   Style.WhitespaceSensitiveMacros.clear();
19549   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
19550               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
19551   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
19552               WhitespaceSensitiveMacros,
19553               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
19554   Style.WhitespaceSensitiveMacros.clear();
19555   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
19556               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
19557   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
19558               WhitespaceSensitiveMacros,
19559               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
19560 
19561   Style.IncludeStyle.IncludeCategories.clear();
19562   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
19563       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
19564   CHECK_PARSE("IncludeCategories:\n"
19565               "  - Regex: abc/.*\n"
19566               "    Priority: 2\n"
19567               "  - Regex: .*\n"
19568               "    Priority: 1\n"
19569               "    CaseSensitive: true\n",
19570               IncludeStyle.IncludeCategories, ExpectedCategories);
19571   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
19572               "abc$");
19573   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
19574               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
19575 
19576   Style.SortIncludes = FormatStyle::SI_Never;
19577   CHECK_PARSE("SortIncludes: true", SortIncludes,
19578               FormatStyle::SI_CaseSensitive);
19579   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
19580   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
19581               FormatStyle::SI_CaseInsensitive);
19582   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
19583               FormatStyle::SI_CaseSensitive);
19584   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
19585 
19586   Style.RawStringFormats.clear();
19587   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
19588       {
19589           FormatStyle::LK_TextProto,
19590           {"pb", "proto"},
19591           {"PARSE_TEXT_PROTO"},
19592           /*CanonicalDelimiter=*/"",
19593           "llvm",
19594       },
19595       {
19596           FormatStyle::LK_Cpp,
19597           {"cc", "cpp"},
19598           {"C_CODEBLOCK", "CPPEVAL"},
19599           /*CanonicalDelimiter=*/"cc",
19600           /*BasedOnStyle=*/"",
19601       },
19602   };
19603 
19604   CHECK_PARSE("RawStringFormats:\n"
19605               "  - Language: TextProto\n"
19606               "    Delimiters:\n"
19607               "      - 'pb'\n"
19608               "      - 'proto'\n"
19609               "    EnclosingFunctions:\n"
19610               "      - 'PARSE_TEXT_PROTO'\n"
19611               "    BasedOnStyle: llvm\n"
19612               "  - Language: Cpp\n"
19613               "    Delimiters:\n"
19614               "      - 'cc'\n"
19615               "      - 'cpp'\n"
19616               "    EnclosingFunctions:\n"
19617               "      - 'C_CODEBLOCK'\n"
19618               "      - 'CPPEVAL'\n"
19619               "    CanonicalDelimiter: 'cc'",
19620               RawStringFormats, ExpectedRawStringFormats);
19621 
19622   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19623               "  Minimum: 0\n"
19624               "  Maximum: 0",
19625               SpacesInLineCommentPrefix.Minimum, 0u);
19626   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
19627   Style.SpacesInLineCommentPrefix.Minimum = 1;
19628   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19629               "  Minimum: 2",
19630               SpacesInLineCommentPrefix.Minimum, 0u);
19631   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19632               "  Maximum: -1",
19633               SpacesInLineCommentPrefix.Maximum, -1u);
19634   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19635               "  Minimum: 2",
19636               SpacesInLineCommentPrefix.Minimum, 2u);
19637   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19638               "  Maximum: 1",
19639               SpacesInLineCommentPrefix.Maximum, 1u);
19640   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
19641 
19642   Style.SpacesInAngles = FormatStyle::SIAS_Always;
19643   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
19644   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
19645               FormatStyle::SIAS_Always);
19646   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
19647   // For backward compatibility:
19648   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
19649   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
19650 }
19651 
19652 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
19653   FormatStyle Style = {};
19654   Style.Language = FormatStyle::LK_Cpp;
19655   CHECK_PARSE("Language: Cpp\n"
19656               "IndentWidth: 12",
19657               IndentWidth, 12u);
19658   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
19659                                "IndentWidth: 34",
19660                                &Style),
19661             ParseError::Unsuitable);
19662   FormatStyle BinPackedTCS = {};
19663   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
19664   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
19665                                "InsertTrailingCommas: Wrapped",
19666                                &BinPackedTCS),
19667             ParseError::BinPackTrailingCommaConflict);
19668   EXPECT_EQ(12u, Style.IndentWidth);
19669   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
19670   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19671 
19672   Style.Language = FormatStyle::LK_JavaScript;
19673   CHECK_PARSE("Language: JavaScript\n"
19674               "IndentWidth: 12",
19675               IndentWidth, 12u);
19676   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
19677   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
19678                                "IndentWidth: 34",
19679                                &Style),
19680             ParseError::Unsuitable);
19681   EXPECT_EQ(23u, Style.IndentWidth);
19682   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
19683   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19684 
19685   CHECK_PARSE("BasedOnStyle: LLVM\n"
19686               "IndentWidth: 67",
19687               IndentWidth, 67u);
19688 
19689   CHECK_PARSE("---\n"
19690               "Language: JavaScript\n"
19691               "IndentWidth: 12\n"
19692               "---\n"
19693               "Language: Cpp\n"
19694               "IndentWidth: 34\n"
19695               "...\n",
19696               IndentWidth, 12u);
19697 
19698   Style.Language = FormatStyle::LK_Cpp;
19699   CHECK_PARSE("---\n"
19700               "Language: JavaScript\n"
19701               "IndentWidth: 12\n"
19702               "---\n"
19703               "Language: Cpp\n"
19704               "IndentWidth: 34\n"
19705               "...\n",
19706               IndentWidth, 34u);
19707   CHECK_PARSE("---\n"
19708               "IndentWidth: 78\n"
19709               "---\n"
19710               "Language: JavaScript\n"
19711               "IndentWidth: 56\n"
19712               "...\n",
19713               IndentWidth, 78u);
19714 
19715   Style.ColumnLimit = 123;
19716   Style.IndentWidth = 234;
19717   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
19718   Style.TabWidth = 345;
19719   EXPECT_FALSE(parseConfiguration("---\n"
19720                                   "IndentWidth: 456\n"
19721                                   "BreakBeforeBraces: Allman\n"
19722                                   "---\n"
19723                                   "Language: JavaScript\n"
19724                                   "IndentWidth: 111\n"
19725                                   "TabWidth: 111\n"
19726                                   "---\n"
19727                                   "Language: Cpp\n"
19728                                   "BreakBeforeBraces: Stroustrup\n"
19729                                   "TabWidth: 789\n"
19730                                   "...\n",
19731                                   &Style));
19732   EXPECT_EQ(123u, Style.ColumnLimit);
19733   EXPECT_EQ(456u, Style.IndentWidth);
19734   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
19735   EXPECT_EQ(789u, Style.TabWidth);
19736 
19737   EXPECT_EQ(parseConfiguration("---\n"
19738                                "Language: JavaScript\n"
19739                                "IndentWidth: 56\n"
19740                                "---\n"
19741                                "IndentWidth: 78\n"
19742                                "...\n",
19743                                &Style),
19744             ParseError::Error);
19745   EXPECT_EQ(parseConfiguration("---\n"
19746                                "Language: JavaScript\n"
19747                                "IndentWidth: 56\n"
19748                                "---\n"
19749                                "Language: JavaScript\n"
19750                                "IndentWidth: 78\n"
19751                                "...\n",
19752                                &Style),
19753             ParseError::Error);
19754 
19755   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19756 }
19757 
19758 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
19759   FormatStyle Style = {};
19760   Style.Language = FormatStyle::LK_JavaScript;
19761   Style.BreakBeforeTernaryOperators = true;
19762   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
19763   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19764 
19765   Style.BreakBeforeTernaryOperators = true;
19766   EXPECT_EQ(0, parseConfiguration("---\n"
19767                                   "BasedOnStyle: Google\n"
19768                                   "---\n"
19769                                   "Language: JavaScript\n"
19770                                   "IndentWidth: 76\n"
19771                                   "...\n",
19772                                   &Style)
19773                    .value());
19774   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19775   EXPECT_EQ(76u, Style.IndentWidth);
19776   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19777 }
19778 
19779 TEST_F(FormatTest, ConfigurationRoundTripTest) {
19780   FormatStyle Style = getLLVMStyle();
19781   std::string YAML = configurationAsText(Style);
19782   FormatStyle ParsedStyle = {};
19783   ParsedStyle.Language = FormatStyle::LK_Cpp;
19784   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
19785   EXPECT_EQ(Style, ParsedStyle);
19786 }
19787 
19788 TEST_F(FormatTest, WorksFor8bitEncodings) {
19789   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
19790             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
19791             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
19792             "\"\xef\xee\xf0\xf3...\"",
19793             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
19794                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
19795                    "\xef\xee\xf0\xf3...\"",
19796                    getLLVMStyleWithColumns(12)));
19797 }
19798 
19799 TEST_F(FormatTest, HandlesUTF8BOM) {
19800   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
19801   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
19802             format("\xef\xbb\xbf#include <iostream>"));
19803   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
19804             format("\xef\xbb\xbf\n#include <iostream>"));
19805 }
19806 
19807 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
19808 #if !defined(_MSC_VER)
19809 
19810 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
19811   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
19812                getLLVMStyleWithColumns(35));
19813   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
19814                getLLVMStyleWithColumns(31));
19815   verifyFormat("// Однажды в студёную зимнюю пору...",
19816                getLLVMStyleWithColumns(36));
19817   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
19818   verifyFormat("/* Однажды в студёную зимнюю пору... */",
19819                getLLVMStyleWithColumns(39));
19820   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
19821                getLLVMStyleWithColumns(35));
19822 }
19823 
19824 TEST_F(FormatTest, SplitsUTF8Strings) {
19825   // Non-printable characters' width is currently considered to be the length in
19826   // bytes in UTF8. The characters can be displayed in very different manner
19827   // (zero-width, single width with a substitution glyph, expanded to their code
19828   // (e.g. "<8d>"), so there's no single correct way to handle them.
19829   EXPECT_EQ("\"aaaaÄ\"\n"
19830             "\"\xc2\x8d\";",
19831             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19832   EXPECT_EQ("\"aaaaaaaÄ\"\n"
19833             "\"\xc2\x8d\";",
19834             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19835   EXPECT_EQ("\"Однажды, в \"\n"
19836             "\"студёную \"\n"
19837             "\"зимнюю \"\n"
19838             "\"пору,\"",
19839             format("\"Однажды, в студёную зимнюю пору,\"",
19840                    getLLVMStyleWithColumns(13)));
19841   EXPECT_EQ(
19842       "\"一 二 三 \"\n"
19843       "\"四 五六 \"\n"
19844       "\"七 八 九 \"\n"
19845       "\"十\"",
19846       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
19847   EXPECT_EQ("\"一\t\"\n"
19848             "\"二 \t\"\n"
19849             "\"三 四 \"\n"
19850             "\"五\t\"\n"
19851             "\"六 \t\"\n"
19852             "\"七 \"\n"
19853             "\"八九十\tqq\"",
19854             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
19855                    getLLVMStyleWithColumns(11)));
19856 
19857   // UTF8 character in an escape sequence.
19858   EXPECT_EQ("\"aaaaaa\"\n"
19859             "\"\\\xC2\x8D\"",
19860             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
19861 }
19862 
19863 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
19864   EXPECT_EQ("const char *sssss =\n"
19865             "    \"一二三四五六七八\\\n"
19866             " 九 十\";",
19867             format("const char *sssss = \"一二三四五六七八\\\n"
19868                    " 九 十\";",
19869                    getLLVMStyleWithColumns(30)));
19870 }
19871 
19872 TEST_F(FormatTest, SplitsUTF8LineComments) {
19873   EXPECT_EQ("// aaaaÄ\xc2\x8d",
19874             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
19875   EXPECT_EQ("// Я из лесу\n"
19876             "// вышел; был\n"
19877             "// сильный\n"
19878             "// мороз.",
19879             format("// Я из лесу вышел; был сильный мороз.",
19880                    getLLVMStyleWithColumns(13)));
19881   EXPECT_EQ("// 一二三\n"
19882             "// 四五六七\n"
19883             "// 八  九\n"
19884             "// 十",
19885             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
19886 }
19887 
19888 TEST_F(FormatTest, SplitsUTF8BlockComments) {
19889   EXPECT_EQ("/* Гляжу,\n"
19890             " * поднимается\n"
19891             " * медленно в\n"
19892             " * гору\n"
19893             " * Лошадка,\n"
19894             " * везущая\n"
19895             " * хворосту\n"
19896             " * воз. */",
19897             format("/* Гляжу, поднимается медленно в гору\n"
19898                    " * Лошадка, везущая хворосту воз. */",
19899                    getLLVMStyleWithColumns(13)));
19900   EXPECT_EQ(
19901       "/* 一二三\n"
19902       " * 四五六七\n"
19903       " * 八  九\n"
19904       " * 十  */",
19905       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
19906   EXPECT_EQ("/* �������� ��������\n"
19907             " * ��������\n"
19908             " * ������-�� */",
19909             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
19910 }
19911 
19912 #endif // _MSC_VER
19913 
19914 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
19915   FormatStyle Style = getLLVMStyle();
19916 
19917   Style.ConstructorInitializerIndentWidth = 4;
19918   verifyFormat(
19919       "SomeClass::Constructor()\n"
19920       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19921       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19922       Style);
19923 
19924   Style.ConstructorInitializerIndentWidth = 2;
19925   verifyFormat(
19926       "SomeClass::Constructor()\n"
19927       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19928       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19929       Style);
19930 
19931   Style.ConstructorInitializerIndentWidth = 0;
19932   verifyFormat(
19933       "SomeClass::Constructor()\n"
19934       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19935       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19936       Style);
19937   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19938   verifyFormat(
19939       "SomeLongTemplateVariableName<\n"
19940       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
19941       Style);
19942   verifyFormat("bool smaller = 1 < "
19943                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
19944                "                       "
19945                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
19946                Style);
19947 
19948   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
19949   verifyFormat("SomeClass::Constructor() :\n"
19950                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
19951                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
19952                Style);
19953 }
19954 
19955 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
19956   FormatStyle Style = getLLVMStyle();
19957   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
19958   Style.ConstructorInitializerIndentWidth = 4;
19959   verifyFormat("SomeClass::Constructor()\n"
19960                "    : a(a)\n"
19961                "    , b(b)\n"
19962                "    , c(c) {}",
19963                Style);
19964   verifyFormat("SomeClass::Constructor()\n"
19965                "    : a(a) {}",
19966                Style);
19967 
19968   Style.ColumnLimit = 0;
19969   verifyFormat("SomeClass::Constructor()\n"
19970                "    : a(a) {}",
19971                Style);
19972   verifyFormat("SomeClass::Constructor() noexcept\n"
19973                "    : a(a) {}",
19974                Style);
19975   verifyFormat("SomeClass::Constructor()\n"
19976                "    : a(a)\n"
19977                "    , b(b)\n"
19978                "    , c(c) {}",
19979                Style);
19980   verifyFormat("SomeClass::Constructor()\n"
19981                "    : a(a) {\n"
19982                "  foo();\n"
19983                "  bar();\n"
19984                "}",
19985                Style);
19986 
19987   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
19988   verifyFormat("SomeClass::Constructor()\n"
19989                "    : a(a)\n"
19990                "    , b(b)\n"
19991                "    , c(c) {\n}",
19992                Style);
19993   verifyFormat("SomeClass::Constructor()\n"
19994                "    : a(a) {\n}",
19995                Style);
19996 
19997   Style.ColumnLimit = 80;
19998   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
19999   Style.ConstructorInitializerIndentWidth = 2;
20000   verifyFormat("SomeClass::Constructor()\n"
20001                "  : a(a)\n"
20002                "  , b(b)\n"
20003                "  , c(c) {}",
20004                Style);
20005 
20006   Style.ConstructorInitializerIndentWidth = 0;
20007   verifyFormat("SomeClass::Constructor()\n"
20008                ": a(a)\n"
20009                ", b(b)\n"
20010                ", c(c) {}",
20011                Style);
20012 
20013   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20014   Style.ConstructorInitializerIndentWidth = 4;
20015   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
20016   verifyFormat(
20017       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
20018       Style);
20019   verifyFormat(
20020       "SomeClass::Constructor()\n"
20021       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
20022       Style);
20023   Style.ConstructorInitializerIndentWidth = 4;
20024   Style.ColumnLimit = 60;
20025   verifyFormat("SomeClass::Constructor()\n"
20026                "    : aaaaaaaa(aaaaaaaa)\n"
20027                "    , aaaaaaaa(aaaaaaaa)\n"
20028                "    , aaaaaaaa(aaaaaaaa) {}",
20029                Style);
20030 }
20031 
20032 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
20033   FormatStyle Style = getLLVMStyle();
20034   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20035   Style.ConstructorInitializerIndentWidth = 4;
20036   verifyFormat("SomeClass::Constructor()\n"
20037                "    : a{a}\n"
20038                "    , b{b} {}",
20039                Style);
20040   verifyFormat("SomeClass::Constructor()\n"
20041                "    : a{a}\n"
20042                "#if CONDITION\n"
20043                "    , b{b}\n"
20044                "#endif\n"
20045                "{\n}",
20046                Style);
20047   Style.ConstructorInitializerIndentWidth = 2;
20048   verifyFormat("SomeClass::Constructor()\n"
20049                "#if CONDITION\n"
20050                "  : a{a}\n"
20051                "#endif\n"
20052                "  , b{b}\n"
20053                "  , c{c} {\n}",
20054                Style);
20055   Style.ConstructorInitializerIndentWidth = 0;
20056   verifyFormat("SomeClass::Constructor()\n"
20057                ": a{a}\n"
20058                "#ifdef CONDITION\n"
20059                ", b{b}\n"
20060                "#else\n"
20061                ", c{c}\n"
20062                "#endif\n"
20063                ", d{d} {\n}",
20064                Style);
20065   Style.ConstructorInitializerIndentWidth = 4;
20066   verifyFormat("SomeClass::Constructor()\n"
20067                "    : a{a}\n"
20068                "#if WINDOWS\n"
20069                "#if DEBUG\n"
20070                "    , b{0}\n"
20071                "#else\n"
20072                "    , b{1}\n"
20073                "#endif\n"
20074                "#else\n"
20075                "#if DEBUG\n"
20076                "    , b{2}\n"
20077                "#else\n"
20078                "    , b{3}\n"
20079                "#endif\n"
20080                "#endif\n"
20081                "{\n}",
20082                Style);
20083   verifyFormat("SomeClass::Constructor()\n"
20084                "    : a{a}\n"
20085                "#if WINDOWS\n"
20086                "    , b{0}\n"
20087                "#if DEBUG\n"
20088                "    , c{0}\n"
20089                "#else\n"
20090                "    , c{1}\n"
20091                "#endif\n"
20092                "#else\n"
20093                "#if DEBUG\n"
20094                "    , c{2}\n"
20095                "#else\n"
20096                "    , c{3}\n"
20097                "#endif\n"
20098                "    , b{1}\n"
20099                "#endif\n"
20100                "{\n}",
20101                Style);
20102 }
20103 
20104 TEST_F(FormatTest, Destructors) {
20105   verifyFormat("void F(int &i) { i.~int(); }");
20106   verifyFormat("void F(int &i) { i->~int(); }");
20107 }
20108 
20109 TEST_F(FormatTest, FormatsWithWebKitStyle) {
20110   FormatStyle Style = getWebKitStyle();
20111 
20112   // Don't indent in outer namespaces.
20113   verifyFormat("namespace outer {\n"
20114                "int i;\n"
20115                "namespace inner {\n"
20116                "    int i;\n"
20117                "} // namespace inner\n"
20118                "} // namespace outer\n"
20119                "namespace other_outer {\n"
20120                "int i;\n"
20121                "}",
20122                Style);
20123 
20124   // Don't indent case labels.
20125   verifyFormat("switch (variable) {\n"
20126                "case 1:\n"
20127                "case 2:\n"
20128                "    doSomething();\n"
20129                "    break;\n"
20130                "default:\n"
20131                "    ++variable;\n"
20132                "}",
20133                Style);
20134 
20135   // Wrap before binary operators.
20136   EXPECT_EQ("void f()\n"
20137             "{\n"
20138             "    if (aaaaaaaaaaaaaaaa\n"
20139             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
20140             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20141             "        return;\n"
20142             "}",
20143             format("void f() {\n"
20144                    "if (aaaaaaaaaaaaaaaa\n"
20145                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
20146                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20147                    "return;\n"
20148                    "}",
20149                    Style));
20150 
20151   // Allow functions on a single line.
20152   verifyFormat("void f() { return; }", Style);
20153 
20154   // Allow empty blocks on a single line and insert a space in empty blocks.
20155   EXPECT_EQ("void f() { }", format("void f() {}", Style));
20156   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
20157   // However, don't merge non-empty short loops.
20158   EXPECT_EQ("while (true) {\n"
20159             "    continue;\n"
20160             "}",
20161             format("while (true) { continue; }", Style));
20162 
20163   // Constructor initializers are formatted one per line with the "," on the
20164   // new line.
20165   verifyFormat("Constructor()\n"
20166                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
20167                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
20168                "          aaaaaaaaaaaaaa)\n"
20169                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
20170                "{\n"
20171                "}",
20172                Style);
20173   verifyFormat("SomeClass::Constructor()\n"
20174                "    : a(a)\n"
20175                "{\n"
20176                "}",
20177                Style);
20178   EXPECT_EQ("SomeClass::Constructor()\n"
20179             "    : a(a)\n"
20180             "{\n"
20181             "}",
20182             format("SomeClass::Constructor():a(a){}", Style));
20183   verifyFormat("SomeClass::Constructor()\n"
20184                "    : a(a)\n"
20185                "    , b(b)\n"
20186                "    , c(c)\n"
20187                "{\n"
20188                "}",
20189                Style);
20190   verifyFormat("SomeClass::Constructor()\n"
20191                "    : a(a)\n"
20192                "{\n"
20193                "    foo();\n"
20194                "    bar();\n"
20195                "}",
20196                Style);
20197 
20198   // Access specifiers should be aligned left.
20199   verifyFormat("class C {\n"
20200                "public:\n"
20201                "    int i;\n"
20202                "};",
20203                Style);
20204 
20205   // Do not align comments.
20206   verifyFormat("int a; // Do not\n"
20207                "double b; // align comments.",
20208                Style);
20209 
20210   // Do not align operands.
20211   EXPECT_EQ("ASSERT(aaaa\n"
20212             "    || bbbb);",
20213             format("ASSERT ( aaaa\n||bbbb);", Style));
20214 
20215   // Accept input's line breaks.
20216   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
20217             "    || bbbbbbbbbbbbbbb) {\n"
20218             "    i++;\n"
20219             "}",
20220             format("if (aaaaaaaaaaaaaaa\n"
20221                    "|| bbbbbbbbbbbbbbb) { i++; }",
20222                    Style));
20223   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
20224             "    i++;\n"
20225             "}",
20226             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
20227 
20228   // Don't automatically break all macro definitions (llvm.org/PR17842).
20229   verifyFormat("#define aNumber 10", Style);
20230   // However, generally keep the line breaks that the user authored.
20231   EXPECT_EQ("#define aNumber \\\n"
20232             "    10",
20233             format("#define aNumber \\\n"
20234                    " 10",
20235                    Style));
20236 
20237   // Keep empty and one-element array literals on a single line.
20238   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
20239             "                                  copyItems:YES];",
20240             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
20241                    "copyItems:YES];",
20242                    Style));
20243   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
20244             "                                  copyItems:YES];",
20245             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
20246                    "             copyItems:YES];",
20247                    Style));
20248   // FIXME: This does not seem right, there should be more indentation before
20249   // the array literal's entries. Nested blocks have the same problem.
20250   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20251             "    @\"a\",\n"
20252             "    @\"a\"\n"
20253             "]\n"
20254             "                                  copyItems:YES];",
20255             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20256                    "     @\"a\",\n"
20257                    "     @\"a\"\n"
20258                    "     ]\n"
20259                    "       copyItems:YES];",
20260                    Style));
20261   EXPECT_EQ(
20262       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20263       "                                  copyItems:YES];",
20264       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20265              "   copyItems:YES];",
20266              Style));
20267 
20268   verifyFormat("[self.a b:c c:d];", Style);
20269   EXPECT_EQ("[self.a b:c\n"
20270             "        c:d];",
20271             format("[self.a b:c\n"
20272                    "c:d];",
20273                    Style));
20274 }
20275 
20276 TEST_F(FormatTest, FormatsLambdas) {
20277   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
20278   verifyFormat(
20279       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
20280   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
20281   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
20282   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
20283   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
20284   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
20285   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
20286   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
20287   verifyFormat("int x = f(*+[] {});");
20288   verifyFormat("void f() {\n"
20289                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
20290                "}\n");
20291   verifyFormat("void f() {\n"
20292                "  other(x.begin(), //\n"
20293                "        x.end(),   //\n"
20294                "        [&](int, int) { return 1; });\n"
20295                "}\n");
20296   verifyFormat("void f() {\n"
20297                "  other.other.other.other.other(\n"
20298                "      x.begin(), x.end(),\n"
20299                "      [something, rather](int, int, int, int, int, int, int) { "
20300                "return 1; });\n"
20301                "}\n");
20302   verifyFormat(
20303       "void f() {\n"
20304       "  other.other.other.other.other(\n"
20305       "      x.begin(), x.end(),\n"
20306       "      [something, rather](int, int, int, int, int, int, int) {\n"
20307       "        //\n"
20308       "      });\n"
20309       "}\n");
20310   verifyFormat("SomeFunction([]() { // A cool function...\n"
20311                "  return 43;\n"
20312                "});");
20313   EXPECT_EQ("SomeFunction([]() {\n"
20314             "#define A a\n"
20315             "  return 43;\n"
20316             "});",
20317             format("SomeFunction([](){\n"
20318                    "#define A a\n"
20319                    "return 43;\n"
20320                    "});"));
20321   verifyFormat("void f() {\n"
20322                "  SomeFunction([](decltype(x), A *a) {});\n"
20323                "  SomeFunction([](typeof(x), A *a) {});\n"
20324                "  SomeFunction([](_Atomic(x), A *a) {});\n"
20325                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
20326                "}");
20327   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20328                "    [](const aaaaaaaaaa &a) { return a; });");
20329   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
20330                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
20331                "});");
20332   verifyFormat("Constructor()\n"
20333                "    : Field([] { // comment\n"
20334                "        int i;\n"
20335                "      }) {}");
20336   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
20337                "  return some_parameter.size();\n"
20338                "};");
20339   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
20340                "    [](const string &s) { return s; };");
20341   verifyFormat("int i = aaaaaa ? 1 //\n"
20342                "               : [] {\n"
20343                "                   return 2; //\n"
20344                "                 }();");
20345   verifyFormat("llvm::errs() << \"number of twos is \"\n"
20346                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
20347                "                  return x == 2; // force break\n"
20348                "                });");
20349   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20350                "    [=](int iiiiiiiiiiii) {\n"
20351                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
20352                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
20353                "    });",
20354                getLLVMStyleWithColumns(60));
20355 
20356   verifyFormat("SomeFunction({[&] {\n"
20357                "                // comment\n"
20358                "              },\n"
20359                "              [&] {\n"
20360                "                // comment\n"
20361                "              }});");
20362   verifyFormat("SomeFunction({[&] {\n"
20363                "  // comment\n"
20364                "}});");
20365   verifyFormat(
20366       "virtual aaaaaaaaaaaaaaaa(\n"
20367       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
20368       "    aaaaa aaaaaaaaa);");
20369 
20370   // Lambdas with return types.
20371   verifyFormat("int c = []() -> int { return 2; }();\n");
20372   verifyFormat("int c = []() -> int * { return 2; }();\n");
20373   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
20374   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
20375   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
20376   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
20377   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
20378   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
20379   verifyFormat("[a, a]() -> a<1> {};");
20380   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
20381   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
20382   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
20383   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
20384   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
20385   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
20386   verifyFormat("[]() -> foo<!5> { return {}; };");
20387   verifyFormat("[]() -> foo<~5> { return {}; };");
20388   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
20389   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
20390   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
20391   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
20392   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
20393   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
20394   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
20395   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
20396   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
20397   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
20398   verifyFormat("namespace bar {\n"
20399                "// broken:\n"
20400                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
20401                "} // namespace bar");
20402   verifyFormat("namespace bar {\n"
20403                "// broken:\n"
20404                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
20405                "} // namespace bar");
20406   verifyFormat("namespace bar {\n"
20407                "// broken:\n"
20408                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
20409                "} // namespace bar");
20410   verifyFormat("namespace bar {\n"
20411                "// broken:\n"
20412                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
20413                "} // namespace bar");
20414   verifyFormat("namespace bar {\n"
20415                "// broken:\n"
20416                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
20417                "} // namespace bar");
20418   verifyFormat("namespace bar {\n"
20419                "// broken:\n"
20420                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
20421                "} // namespace bar");
20422   verifyFormat("namespace bar {\n"
20423                "// broken:\n"
20424                "auto foo{[]() -> foo<!5> { return {}; }};\n"
20425                "} // namespace bar");
20426   verifyFormat("namespace bar {\n"
20427                "// broken:\n"
20428                "auto foo{[]() -> foo<~5> { return {}; }};\n"
20429                "} // namespace bar");
20430   verifyFormat("namespace bar {\n"
20431                "// broken:\n"
20432                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
20433                "} // namespace bar");
20434   verifyFormat("namespace bar {\n"
20435                "// broken:\n"
20436                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
20437                "} // namespace bar");
20438   verifyFormat("namespace bar {\n"
20439                "// broken:\n"
20440                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
20441                "} // namespace bar");
20442   verifyFormat("namespace bar {\n"
20443                "// broken:\n"
20444                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
20445                "} // namespace bar");
20446   verifyFormat("namespace bar {\n"
20447                "// broken:\n"
20448                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
20449                "} // namespace bar");
20450   verifyFormat("namespace bar {\n"
20451                "// broken:\n"
20452                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
20453                "} // namespace bar");
20454   verifyFormat("namespace bar {\n"
20455                "// broken:\n"
20456                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
20457                "} // namespace bar");
20458   verifyFormat("namespace bar {\n"
20459                "// broken:\n"
20460                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
20461                "} // namespace bar");
20462   verifyFormat("namespace bar {\n"
20463                "// broken:\n"
20464                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
20465                "} // namespace bar");
20466   verifyFormat("namespace bar {\n"
20467                "// broken:\n"
20468                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
20469                "} // namespace bar");
20470   verifyFormat("[]() -> a<1> {};");
20471   verifyFormat("[]() -> a<1> { ; };");
20472   verifyFormat("[]() -> a<1> { ; }();");
20473   verifyFormat("[a, a]() -> a<true> {};");
20474   verifyFormat("[]() -> a<true> {};");
20475   verifyFormat("[]() -> a<true> { ; };");
20476   verifyFormat("[]() -> a<true> { ; }();");
20477   verifyFormat("[a, a]() -> a<false> {};");
20478   verifyFormat("[]() -> a<false> {};");
20479   verifyFormat("[]() -> a<false> { ; };");
20480   verifyFormat("[]() -> a<false> { ; }();");
20481   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
20482   verifyFormat("namespace bar {\n"
20483                "auto foo{[]() -> foo<false> { ; }};\n"
20484                "} // namespace bar");
20485   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
20486                "                   int j) -> int {\n"
20487                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
20488                "};");
20489   verifyFormat(
20490       "aaaaaaaaaaaaaaaaaaaaaa(\n"
20491       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
20492       "      return aaaaaaaaaaaaaaaaa;\n"
20493       "    });",
20494       getLLVMStyleWithColumns(70));
20495   verifyFormat("[]() //\n"
20496                "    -> int {\n"
20497                "  return 1; //\n"
20498                "};");
20499   verifyFormat("[]() -> Void<T...> {};");
20500   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
20501   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
20502   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
20503   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
20504   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
20505   verifyFormat("return int{[x = x]() { return x; }()};");
20506 
20507   // Lambdas with explicit template argument lists.
20508   verifyFormat(
20509       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
20510 
20511   // Multiple lambdas in the same parentheses change indentation rules. These
20512   // lambdas are forced to start on new lines.
20513   verifyFormat("SomeFunction(\n"
20514                "    []() {\n"
20515                "      //\n"
20516                "    },\n"
20517                "    []() {\n"
20518                "      //\n"
20519                "    });");
20520 
20521   // A lambda passed as arg0 is always pushed to the next line.
20522   verifyFormat("SomeFunction(\n"
20523                "    [this] {\n"
20524                "      //\n"
20525                "    },\n"
20526                "    1);\n");
20527 
20528   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
20529   // the arg0 case above.
20530   auto Style = getGoogleStyle();
20531   Style.BinPackArguments = false;
20532   verifyFormat("SomeFunction(\n"
20533                "    a,\n"
20534                "    [this] {\n"
20535                "      //\n"
20536                "    },\n"
20537                "    b);\n",
20538                Style);
20539   verifyFormat("SomeFunction(\n"
20540                "    a,\n"
20541                "    [this] {\n"
20542                "      //\n"
20543                "    },\n"
20544                "    b);\n");
20545 
20546   // A lambda with a very long line forces arg0 to be pushed out irrespective of
20547   // the BinPackArguments value (as long as the code is wide enough).
20548   verifyFormat(
20549       "something->SomeFunction(\n"
20550       "    a,\n"
20551       "    [this] {\n"
20552       "      "
20553       "D0000000000000000000000000000000000000000000000000000000000001();\n"
20554       "    },\n"
20555       "    b);\n");
20556 
20557   // A multi-line lambda is pulled up as long as the introducer fits on the
20558   // previous line and there are no further args.
20559   verifyFormat("function(1, [this, that] {\n"
20560                "  //\n"
20561                "});\n");
20562   verifyFormat("function([this, that] {\n"
20563                "  //\n"
20564                "});\n");
20565   // FIXME: this format is not ideal and we should consider forcing the first
20566   // arg onto its own line.
20567   verifyFormat("function(a, b, c, //\n"
20568                "         d, [this, that] {\n"
20569                "           //\n"
20570                "         });\n");
20571 
20572   // Multiple lambdas are treated correctly even when there is a short arg0.
20573   verifyFormat("SomeFunction(\n"
20574                "    1,\n"
20575                "    [this] {\n"
20576                "      //\n"
20577                "    },\n"
20578                "    [this] {\n"
20579                "      //\n"
20580                "    },\n"
20581                "    1);\n");
20582 
20583   // More complex introducers.
20584   verifyFormat("return [i, args...] {};");
20585 
20586   // Not lambdas.
20587   verifyFormat("constexpr char hello[]{\"hello\"};");
20588   verifyFormat("double &operator[](int i) { return 0; }\n"
20589                "int i;");
20590   verifyFormat("std::unique_ptr<int[]> foo() {}");
20591   verifyFormat("int i = a[a][a]->f();");
20592   verifyFormat("int i = (*b)[a]->f();");
20593 
20594   // Other corner cases.
20595   verifyFormat("void f() {\n"
20596                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
20597                "  );\n"
20598                "}");
20599 
20600   // Lambdas created through weird macros.
20601   verifyFormat("void f() {\n"
20602                "  MACRO((const AA &a) { return 1; });\n"
20603                "  MACRO((AA &a) { return 1; });\n"
20604                "}");
20605 
20606   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
20607                "      doo_dah();\n"
20608                "      doo_dah();\n"
20609                "    })) {\n"
20610                "}");
20611   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
20612                "                doo_dah();\n"
20613                "                doo_dah();\n"
20614                "              })) {\n"
20615                "}");
20616   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
20617                "                doo_dah();\n"
20618                "                doo_dah();\n"
20619                "              })) {\n"
20620                "}");
20621   verifyFormat("auto lambda = []() {\n"
20622                "  int a = 2\n"
20623                "#if A\n"
20624                "          + 2\n"
20625                "#endif\n"
20626                "      ;\n"
20627                "};");
20628 
20629   // Lambdas with complex multiline introducers.
20630   verifyFormat(
20631       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20632       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
20633       "        -> ::std::unordered_set<\n"
20634       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
20635       "      //\n"
20636       "    });");
20637 
20638   FormatStyle DoNotMerge = getLLVMStyle();
20639   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
20640   verifyFormat("auto c = []() {\n"
20641                "  return b;\n"
20642                "};",
20643                "auto c = []() { return b; };", DoNotMerge);
20644   verifyFormat("auto c = []() {\n"
20645                "};",
20646                " auto c = []() {};", DoNotMerge);
20647 
20648   FormatStyle MergeEmptyOnly = getLLVMStyle();
20649   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
20650   verifyFormat("auto c = []() {\n"
20651                "  return b;\n"
20652                "};",
20653                "auto c = []() {\n"
20654                "  return b;\n"
20655                " };",
20656                MergeEmptyOnly);
20657   verifyFormat("auto c = []() {};",
20658                "auto c = []() {\n"
20659                "};",
20660                MergeEmptyOnly);
20661 
20662   FormatStyle MergeInline = getLLVMStyle();
20663   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
20664   verifyFormat("auto c = []() {\n"
20665                "  return b;\n"
20666                "};",
20667                "auto c = []() { return b; };", MergeInline);
20668   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
20669                MergeInline);
20670   verifyFormat("function([]() { return b; }, a)",
20671                "function([]() { return b; }, a)", MergeInline);
20672   verifyFormat("function(a, []() { return b; })",
20673                "function(a, []() { return b; })", MergeInline);
20674 
20675   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
20676   // AllowShortLambdasOnASingleLine
20677   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
20678   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
20679   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
20680   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20681       FormatStyle::ShortLambdaStyle::SLS_None;
20682   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
20683                "    []()\n"
20684                "    {\n"
20685                "      return 17;\n"
20686                "    });",
20687                LLVMWithBeforeLambdaBody);
20688   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
20689                "    []()\n"
20690                "    {\n"
20691                "    });",
20692                LLVMWithBeforeLambdaBody);
20693   verifyFormat("auto fct_SLS_None = []()\n"
20694                "{\n"
20695                "  return 17;\n"
20696                "};",
20697                LLVMWithBeforeLambdaBody);
20698   verifyFormat("TwoNestedLambdas_SLS_None(\n"
20699                "    []()\n"
20700                "    {\n"
20701                "      return Call(\n"
20702                "          []()\n"
20703                "          {\n"
20704                "            return 17;\n"
20705                "          });\n"
20706                "    });",
20707                LLVMWithBeforeLambdaBody);
20708   verifyFormat("void Fct() {\n"
20709                "  return {[]()\n"
20710                "          {\n"
20711                "            return 17;\n"
20712                "          }};\n"
20713                "}",
20714                LLVMWithBeforeLambdaBody);
20715 
20716   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20717       FormatStyle::ShortLambdaStyle::SLS_Empty;
20718   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
20719                "    []()\n"
20720                "    {\n"
20721                "      return 17;\n"
20722                "    });",
20723                LLVMWithBeforeLambdaBody);
20724   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
20725                LLVMWithBeforeLambdaBody);
20726   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
20727                "ongFunctionName_SLS_Empty(\n"
20728                "    []() {});",
20729                LLVMWithBeforeLambdaBody);
20730   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
20731                "                                []()\n"
20732                "                                {\n"
20733                "                                  return 17;\n"
20734                "                                });",
20735                LLVMWithBeforeLambdaBody);
20736   verifyFormat("auto fct_SLS_Empty = []()\n"
20737                "{\n"
20738                "  return 17;\n"
20739                "};",
20740                LLVMWithBeforeLambdaBody);
20741   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
20742                "    []()\n"
20743                "    {\n"
20744                "      return Call([]() {});\n"
20745                "    });",
20746                LLVMWithBeforeLambdaBody);
20747   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
20748                "                           []()\n"
20749                "                           {\n"
20750                "                             return Call([]() {});\n"
20751                "                           });",
20752                LLVMWithBeforeLambdaBody);
20753   verifyFormat(
20754       "FctWithLongLineInLambda_SLS_Empty(\n"
20755       "    []()\n"
20756       "    {\n"
20757       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20758       "                               AndShouldNotBeConsiderAsInline,\n"
20759       "                               LambdaBodyMustBeBreak);\n"
20760       "    });",
20761       LLVMWithBeforeLambdaBody);
20762 
20763   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20764       FormatStyle::ShortLambdaStyle::SLS_Inline;
20765   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
20766                LLVMWithBeforeLambdaBody);
20767   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
20768                LLVMWithBeforeLambdaBody);
20769   verifyFormat("auto fct_SLS_Inline = []()\n"
20770                "{\n"
20771                "  return 17;\n"
20772                "};",
20773                LLVMWithBeforeLambdaBody);
20774   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
20775                "17; }); });",
20776                LLVMWithBeforeLambdaBody);
20777   verifyFormat(
20778       "FctWithLongLineInLambda_SLS_Inline(\n"
20779       "    []()\n"
20780       "    {\n"
20781       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20782       "                               AndShouldNotBeConsiderAsInline,\n"
20783       "                               LambdaBodyMustBeBreak);\n"
20784       "    });",
20785       LLVMWithBeforeLambdaBody);
20786   verifyFormat("FctWithMultipleParams_SLS_Inline("
20787                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20788                "                                 []() { return 17; });",
20789                LLVMWithBeforeLambdaBody);
20790   verifyFormat(
20791       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
20792       LLVMWithBeforeLambdaBody);
20793 
20794   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20795       FormatStyle::ShortLambdaStyle::SLS_All;
20796   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
20797                LLVMWithBeforeLambdaBody);
20798   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
20799                LLVMWithBeforeLambdaBody);
20800   verifyFormat("auto fct_SLS_All = []() { return 17; };",
20801                LLVMWithBeforeLambdaBody);
20802   verifyFormat("FctWithOneParam_SLS_All(\n"
20803                "    []()\n"
20804                "    {\n"
20805                "      // A cool function...\n"
20806                "      return 43;\n"
20807                "    });",
20808                LLVMWithBeforeLambdaBody);
20809   verifyFormat("FctWithMultipleParams_SLS_All("
20810                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20811                "                              []() { return 17; });",
20812                LLVMWithBeforeLambdaBody);
20813   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
20814                LLVMWithBeforeLambdaBody);
20815   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
20816                LLVMWithBeforeLambdaBody);
20817   verifyFormat(
20818       "FctWithLongLineInLambda_SLS_All(\n"
20819       "    []()\n"
20820       "    {\n"
20821       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20822       "                               AndShouldNotBeConsiderAsInline,\n"
20823       "                               LambdaBodyMustBeBreak);\n"
20824       "    });",
20825       LLVMWithBeforeLambdaBody);
20826   verifyFormat(
20827       "auto fct_SLS_All = []()\n"
20828       "{\n"
20829       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20830       "                           AndShouldNotBeConsiderAsInline,\n"
20831       "                           LambdaBodyMustBeBreak);\n"
20832       "};",
20833       LLVMWithBeforeLambdaBody);
20834   LLVMWithBeforeLambdaBody.BinPackParameters = false;
20835   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
20836                LLVMWithBeforeLambdaBody);
20837   verifyFormat(
20838       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
20839       "                                FirstParam,\n"
20840       "                                SecondParam,\n"
20841       "                                ThirdParam,\n"
20842       "                                FourthParam);",
20843       LLVMWithBeforeLambdaBody);
20844   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20845                "    []() { return "
20846                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
20847                "    FirstParam,\n"
20848                "    SecondParam,\n"
20849                "    ThirdParam,\n"
20850                "    FourthParam);",
20851                LLVMWithBeforeLambdaBody);
20852   verifyFormat(
20853       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
20854       "                                SecondParam,\n"
20855       "                                ThirdParam,\n"
20856       "                                FourthParam,\n"
20857       "                                []() { return SomeValueNotSoLong; });",
20858       LLVMWithBeforeLambdaBody);
20859   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20860                "    []()\n"
20861                "    {\n"
20862                "      return "
20863                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
20864                "eConsiderAsInline;\n"
20865                "    });",
20866                LLVMWithBeforeLambdaBody);
20867   verifyFormat(
20868       "FctWithLongLineInLambda_SLS_All(\n"
20869       "    []()\n"
20870       "    {\n"
20871       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20872       "                               AndShouldNotBeConsiderAsInline,\n"
20873       "                               LambdaBodyMustBeBreak);\n"
20874       "    });",
20875       LLVMWithBeforeLambdaBody);
20876   verifyFormat("FctWithTwoParams_SLS_All(\n"
20877                "    []()\n"
20878                "    {\n"
20879                "      // A cool function...\n"
20880                "      return 43;\n"
20881                "    },\n"
20882                "    87);",
20883                LLVMWithBeforeLambdaBody);
20884   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
20885                LLVMWithBeforeLambdaBody);
20886   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
20887                LLVMWithBeforeLambdaBody);
20888   verifyFormat(
20889       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
20890       LLVMWithBeforeLambdaBody);
20891   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
20892                "}); }, x);",
20893                LLVMWithBeforeLambdaBody);
20894   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20895                "    []()\n"
20896                "    {\n"
20897                "      // A cool function...\n"
20898                "      return Call([]() { return 17; });\n"
20899                "    });",
20900                LLVMWithBeforeLambdaBody);
20901   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20902                "    []()\n"
20903                "    {\n"
20904                "      return Call(\n"
20905                "          []()\n"
20906                "          {\n"
20907                "            // A cool function...\n"
20908                "            return 17;\n"
20909                "          });\n"
20910                "    });",
20911                LLVMWithBeforeLambdaBody);
20912 
20913   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20914       FormatStyle::ShortLambdaStyle::SLS_None;
20915 
20916   verifyFormat("auto select = [this]() -> const Library::Object *\n"
20917                "{\n"
20918                "  return MyAssignment::SelectFromList(this);\n"
20919                "};\n",
20920                LLVMWithBeforeLambdaBody);
20921 
20922   verifyFormat("auto select = [this]() -> const Library::Object &\n"
20923                "{\n"
20924                "  return MyAssignment::SelectFromList(this);\n"
20925                "};\n",
20926                LLVMWithBeforeLambdaBody);
20927 
20928   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
20929                "{\n"
20930                "  return MyAssignment::SelectFromList(this);\n"
20931                "};\n",
20932                LLVMWithBeforeLambdaBody);
20933 
20934   verifyFormat("namespace test {\n"
20935                "class Test {\n"
20936                "public:\n"
20937                "  Test() = default;\n"
20938                "};\n"
20939                "} // namespace test",
20940                LLVMWithBeforeLambdaBody);
20941 
20942   // Lambdas with different indentation styles.
20943   Style = getLLVMStyleWithColumns(100);
20944   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20945             "  return promise.then(\n"
20946             "      [this, &someVariable, someObject = "
20947             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20948             "        return someObject.startAsyncAction().then(\n"
20949             "            [this, &someVariable](AsyncActionResult result) "
20950             "mutable { result.processMore(); });\n"
20951             "      });\n"
20952             "}\n",
20953             format("SomeResult doSomething(SomeObject promise) {\n"
20954                    "  return promise.then([this, &someVariable, someObject = "
20955                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20956                    "    return someObject.startAsyncAction().then([this, "
20957                    "&someVariable](AsyncActionResult result) mutable {\n"
20958                    "      result.processMore();\n"
20959                    "    });\n"
20960                    "  });\n"
20961                    "}\n",
20962                    Style));
20963   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20964   verifyFormat("test() {\n"
20965                "  ([]() -> {\n"
20966                "    int b = 32;\n"
20967                "    return 3;\n"
20968                "  }).foo();\n"
20969                "}",
20970                Style);
20971   verifyFormat("test() {\n"
20972                "  []() -> {\n"
20973                "    int b = 32;\n"
20974                "    return 3;\n"
20975                "  }\n"
20976                "}",
20977                Style);
20978   verifyFormat("std::sort(v.begin(), v.end(),\n"
20979                "          [](const auto &someLongArgumentName, const auto "
20980                "&someOtherLongArgumentName) {\n"
20981                "  return someLongArgumentName.someMemberVariable < "
20982                "someOtherLongArgumentName.someMemberVariable;\n"
20983                "});",
20984                Style);
20985   verifyFormat("test() {\n"
20986                "  (\n"
20987                "      []() -> {\n"
20988                "        int b = 32;\n"
20989                "        return 3;\n"
20990                "      },\n"
20991                "      foo, bar)\n"
20992                "      .foo();\n"
20993                "}",
20994                Style);
20995   verifyFormat("test() {\n"
20996                "  ([]() -> {\n"
20997                "    int b = 32;\n"
20998                "    return 3;\n"
20999                "  })\n"
21000                "      .foo()\n"
21001                "      .bar();\n"
21002                "}",
21003                Style);
21004   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21005             "  return promise.then(\n"
21006             "      [this, &someVariable, someObject = "
21007             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21008             "    return someObject.startAsyncAction().then(\n"
21009             "        [this, &someVariable](AsyncActionResult result) mutable { "
21010             "result.processMore(); });\n"
21011             "  });\n"
21012             "}\n",
21013             format("SomeResult doSomething(SomeObject promise) {\n"
21014                    "  return promise.then([this, &someVariable, someObject = "
21015                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21016                    "    return someObject.startAsyncAction().then([this, "
21017                    "&someVariable](AsyncActionResult result) mutable {\n"
21018                    "      result.processMore();\n"
21019                    "    });\n"
21020                    "  });\n"
21021                    "}\n",
21022                    Style));
21023   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21024             "  return promise.then([this, &someVariable] {\n"
21025             "    return someObject.startAsyncAction().then(\n"
21026             "        [this, &someVariable](AsyncActionResult result) mutable { "
21027             "result.processMore(); });\n"
21028             "  });\n"
21029             "}\n",
21030             format("SomeResult doSomething(SomeObject promise) {\n"
21031                    "  return promise.then([this, &someVariable] {\n"
21032                    "    return someObject.startAsyncAction().then([this, "
21033                    "&someVariable](AsyncActionResult result) mutable {\n"
21034                    "      result.processMore();\n"
21035                    "    });\n"
21036                    "  });\n"
21037                    "}\n",
21038                    Style));
21039   Style = getGoogleStyle();
21040   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21041   EXPECT_EQ("#define A                                       \\\n"
21042             "  [] {                                          \\\n"
21043             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
21044             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
21045             "      }",
21046             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
21047                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
21048                    Style));
21049   // TODO: The current formatting has a minor issue that's not worth fixing
21050   // right now whereby the closing brace is indented relative to the signature
21051   // instead of being aligned. This only happens with macros.
21052 }
21053 
21054 TEST_F(FormatTest, LambdaWithLineComments) {
21055   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21056   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21057   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21058   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21059       FormatStyle::ShortLambdaStyle::SLS_All;
21060 
21061   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
21062   verifyFormat("auto k = []() // comment\n"
21063                "{ return; }",
21064                LLVMWithBeforeLambdaBody);
21065   verifyFormat("auto k = []() /* comment */ { return; }",
21066                LLVMWithBeforeLambdaBody);
21067   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
21068                LLVMWithBeforeLambdaBody);
21069   verifyFormat("auto k = []() // X\n"
21070                "{ return; }",
21071                LLVMWithBeforeLambdaBody);
21072   verifyFormat(
21073       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
21074       "{ return; }",
21075       LLVMWithBeforeLambdaBody);
21076 }
21077 
21078 TEST_F(FormatTest, EmptyLinesInLambdas) {
21079   verifyFormat("auto lambda = []() {\n"
21080                "  x(); //\n"
21081                "};",
21082                "auto lambda = []() {\n"
21083                "\n"
21084                "  x(); //\n"
21085                "\n"
21086                "};");
21087 }
21088 
21089 TEST_F(FormatTest, FormatsBlocks) {
21090   FormatStyle ShortBlocks = getLLVMStyle();
21091   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21092   verifyFormat("int (^Block)(int, int);", ShortBlocks);
21093   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
21094   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
21095   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
21096   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
21097   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
21098 
21099   verifyFormat("foo(^{ bar(); });", ShortBlocks);
21100   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
21101   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
21102 
21103   verifyFormat("[operation setCompletionBlock:^{\n"
21104                "  [self onOperationDone];\n"
21105                "}];");
21106   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
21107                "  [self onOperationDone];\n"
21108                "}]};");
21109   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
21110                "  f();\n"
21111                "}];");
21112   verifyFormat("int a = [operation block:^int(int *i) {\n"
21113                "  return 1;\n"
21114                "}];");
21115   verifyFormat("[myObject doSomethingWith:arg1\n"
21116                "                      aaa:^int(int *a) {\n"
21117                "                        return 1;\n"
21118                "                      }\n"
21119                "                      bbb:f(a * bbbbbbbb)];");
21120 
21121   verifyFormat("[operation setCompletionBlock:^{\n"
21122                "  [self.delegate newDataAvailable];\n"
21123                "}];",
21124                getLLVMStyleWithColumns(60));
21125   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
21126                "  NSString *path = [self sessionFilePath];\n"
21127                "  if (path) {\n"
21128                "    // ...\n"
21129                "  }\n"
21130                "});");
21131   verifyFormat("[[SessionService sharedService]\n"
21132                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21133                "      if (window) {\n"
21134                "        [self windowDidLoad:window];\n"
21135                "      } else {\n"
21136                "        [self errorLoadingWindow];\n"
21137                "      }\n"
21138                "    }];");
21139   verifyFormat("void (^largeBlock)(void) = ^{\n"
21140                "  // ...\n"
21141                "};\n",
21142                getLLVMStyleWithColumns(40));
21143   verifyFormat("[[SessionService sharedService]\n"
21144                "    loadWindowWithCompletionBlock: //\n"
21145                "        ^(SessionWindow *window) {\n"
21146                "          if (window) {\n"
21147                "            [self windowDidLoad:window];\n"
21148                "          } else {\n"
21149                "            [self errorLoadingWindow];\n"
21150                "          }\n"
21151                "        }];",
21152                getLLVMStyleWithColumns(60));
21153   verifyFormat("[myObject doSomethingWith:arg1\n"
21154                "    firstBlock:^(Foo *a) {\n"
21155                "      // ...\n"
21156                "      int i;\n"
21157                "    }\n"
21158                "    secondBlock:^(Bar *b) {\n"
21159                "      // ...\n"
21160                "      int i;\n"
21161                "    }\n"
21162                "    thirdBlock:^Foo(Bar *b) {\n"
21163                "      // ...\n"
21164                "      int i;\n"
21165                "    }];");
21166   verifyFormat("[myObject doSomethingWith:arg1\n"
21167                "               firstBlock:-1\n"
21168                "              secondBlock:^(Bar *b) {\n"
21169                "                // ...\n"
21170                "                int i;\n"
21171                "              }];");
21172 
21173   verifyFormat("f(^{\n"
21174                "  @autoreleasepool {\n"
21175                "    if (a) {\n"
21176                "      g();\n"
21177                "    }\n"
21178                "  }\n"
21179                "});");
21180   verifyFormat("Block b = ^int *(A *a, B *b) {}");
21181   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
21182                "};");
21183 
21184   FormatStyle FourIndent = getLLVMStyle();
21185   FourIndent.ObjCBlockIndentWidth = 4;
21186   verifyFormat("[operation setCompletionBlock:^{\n"
21187                "    [self onOperationDone];\n"
21188                "}];",
21189                FourIndent);
21190 }
21191 
21192 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
21193   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
21194 
21195   verifyFormat("[[SessionService sharedService] "
21196                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21197                "  if (window) {\n"
21198                "    [self windowDidLoad:window];\n"
21199                "  } else {\n"
21200                "    [self errorLoadingWindow];\n"
21201                "  }\n"
21202                "}];",
21203                ZeroColumn);
21204   EXPECT_EQ("[[SessionService sharedService]\n"
21205             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21206             "      if (window) {\n"
21207             "        [self windowDidLoad:window];\n"
21208             "      } else {\n"
21209             "        [self errorLoadingWindow];\n"
21210             "      }\n"
21211             "    }];",
21212             format("[[SessionService sharedService]\n"
21213                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21214                    "                if (window) {\n"
21215                    "    [self windowDidLoad:window];\n"
21216                    "  } else {\n"
21217                    "    [self errorLoadingWindow];\n"
21218                    "  }\n"
21219                    "}];",
21220                    ZeroColumn));
21221   verifyFormat("[myObject doSomethingWith:arg1\n"
21222                "    firstBlock:^(Foo *a) {\n"
21223                "      // ...\n"
21224                "      int i;\n"
21225                "    }\n"
21226                "    secondBlock:^(Bar *b) {\n"
21227                "      // ...\n"
21228                "      int i;\n"
21229                "    }\n"
21230                "    thirdBlock:^Foo(Bar *b) {\n"
21231                "      // ...\n"
21232                "      int i;\n"
21233                "    }];",
21234                ZeroColumn);
21235   verifyFormat("f(^{\n"
21236                "  @autoreleasepool {\n"
21237                "    if (a) {\n"
21238                "      g();\n"
21239                "    }\n"
21240                "  }\n"
21241                "});",
21242                ZeroColumn);
21243   verifyFormat("void (^largeBlock)(void) = ^{\n"
21244                "  // ...\n"
21245                "};",
21246                ZeroColumn);
21247 
21248   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21249   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
21250             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21251   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
21252   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
21253             "  int i;\n"
21254             "};",
21255             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21256 }
21257 
21258 TEST_F(FormatTest, SupportsCRLF) {
21259   EXPECT_EQ("int a;\r\n"
21260             "int b;\r\n"
21261             "int c;\r\n",
21262             format("int a;\r\n"
21263                    "  int b;\r\n"
21264                    "    int c;\r\n",
21265                    getLLVMStyle()));
21266   EXPECT_EQ("int a;\r\n"
21267             "int b;\r\n"
21268             "int c;\r\n",
21269             format("int a;\r\n"
21270                    "  int b;\n"
21271                    "    int c;\r\n",
21272                    getLLVMStyle()));
21273   EXPECT_EQ("int a;\n"
21274             "int b;\n"
21275             "int c;\n",
21276             format("int a;\r\n"
21277                    "  int b;\n"
21278                    "    int c;\n",
21279                    getLLVMStyle()));
21280   EXPECT_EQ("\"aaaaaaa \"\r\n"
21281             "\"bbbbbbb\";\r\n",
21282             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
21283   EXPECT_EQ("#define A \\\r\n"
21284             "  b;      \\\r\n"
21285             "  c;      \\\r\n"
21286             "  d;\r\n",
21287             format("#define A \\\r\n"
21288                    "  b; \\\r\n"
21289                    "  c; d; \r\n",
21290                    getGoogleStyle()));
21291 
21292   EXPECT_EQ("/*\r\n"
21293             "multi line block comments\r\n"
21294             "should not introduce\r\n"
21295             "an extra carriage return\r\n"
21296             "*/\r\n",
21297             format("/*\r\n"
21298                    "multi line block comments\r\n"
21299                    "should not introduce\r\n"
21300                    "an extra carriage return\r\n"
21301                    "*/\r\n"));
21302   EXPECT_EQ("/*\r\n"
21303             "\r\n"
21304             "*/",
21305             format("/*\r\n"
21306                    "    \r\r\r\n"
21307                    "*/"));
21308 
21309   FormatStyle style = getLLVMStyle();
21310 
21311   style.DeriveLineEnding = true;
21312   style.UseCRLF = false;
21313   EXPECT_EQ("union FooBarBazQux {\n"
21314             "  int foo;\n"
21315             "  int bar;\n"
21316             "  int baz;\n"
21317             "};",
21318             format("union FooBarBazQux {\r\n"
21319                    "  int foo;\n"
21320                    "  int bar;\r\n"
21321                    "  int baz;\n"
21322                    "};",
21323                    style));
21324   style.UseCRLF = true;
21325   EXPECT_EQ("union FooBarBazQux {\r\n"
21326             "  int foo;\r\n"
21327             "  int bar;\r\n"
21328             "  int baz;\r\n"
21329             "};",
21330             format("union FooBarBazQux {\r\n"
21331                    "  int foo;\n"
21332                    "  int bar;\r\n"
21333                    "  int baz;\n"
21334                    "};",
21335                    style));
21336 
21337   style.DeriveLineEnding = false;
21338   style.UseCRLF = false;
21339   EXPECT_EQ("union FooBarBazQux {\n"
21340             "  int foo;\n"
21341             "  int bar;\n"
21342             "  int baz;\n"
21343             "  int qux;\n"
21344             "};",
21345             format("union FooBarBazQux {\r\n"
21346                    "  int foo;\n"
21347                    "  int bar;\r\n"
21348                    "  int baz;\n"
21349                    "  int qux;\r\n"
21350                    "};",
21351                    style));
21352   style.UseCRLF = true;
21353   EXPECT_EQ("union FooBarBazQux {\r\n"
21354             "  int foo;\r\n"
21355             "  int bar;\r\n"
21356             "  int baz;\r\n"
21357             "  int qux;\r\n"
21358             "};",
21359             format("union FooBarBazQux {\r\n"
21360                    "  int foo;\n"
21361                    "  int bar;\r\n"
21362                    "  int baz;\n"
21363                    "  int qux;\n"
21364                    "};",
21365                    style));
21366 
21367   style.DeriveLineEnding = true;
21368   style.UseCRLF = false;
21369   EXPECT_EQ("union FooBarBazQux {\r\n"
21370             "  int foo;\r\n"
21371             "  int bar;\r\n"
21372             "  int baz;\r\n"
21373             "  int qux;\r\n"
21374             "};",
21375             format("union FooBarBazQux {\r\n"
21376                    "  int foo;\n"
21377                    "  int bar;\r\n"
21378                    "  int baz;\n"
21379                    "  int qux;\r\n"
21380                    "};",
21381                    style));
21382   style.UseCRLF = true;
21383   EXPECT_EQ("union FooBarBazQux {\n"
21384             "  int foo;\n"
21385             "  int bar;\n"
21386             "  int baz;\n"
21387             "  int qux;\n"
21388             "};",
21389             format("union FooBarBazQux {\r\n"
21390                    "  int foo;\n"
21391                    "  int bar;\r\n"
21392                    "  int baz;\n"
21393                    "  int qux;\n"
21394                    "};",
21395                    style));
21396 }
21397 
21398 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
21399   verifyFormat("MY_CLASS(C) {\n"
21400                "  int i;\n"
21401                "  int j;\n"
21402                "};");
21403 }
21404 
21405 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
21406   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
21407   TwoIndent.ContinuationIndentWidth = 2;
21408 
21409   EXPECT_EQ("int i =\n"
21410             "  longFunction(\n"
21411             "    arg);",
21412             format("int i = longFunction(arg);", TwoIndent));
21413 
21414   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
21415   SixIndent.ContinuationIndentWidth = 6;
21416 
21417   EXPECT_EQ("int i =\n"
21418             "      longFunction(\n"
21419             "            arg);",
21420             format("int i = longFunction(arg);", SixIndent));
21421 }
21422 
21423 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
21424   FormatStyle Style = getLLVMStyle();
21425   verifyFormat("int Foo::getter(\n"
21426                "    //\n"
21427                ") const {\n"
21428                "  return foo;\n"
21429                "}",
21430                Style);
21431   verifyFormat("void Foo::setter(\n"
21432                "    //\n"
21433                ") {\n"
21434                "  foo = 1;\n"
21435                "}",
21436                Style);
21437 }
21438 
21439 TEST_F(FormatTest, SpacesInAngles) {
21440   FormatStyle Spaces = getLLVMStyle();
21441   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21442 
21443   verifyFormat("vector< ::std::string > x1;", Spaces);
21444   verifyFormat("Foo< int, Bar > x2;", Spaces);
21445   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
21446 
21447   verifyFormat("static_cast< int >(arg);", Spaces);
21448   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
21449   verifyFormat("f< int, float >();", Spaces);
21450   verifyFormat("template <> g() {}", Spaces);
21451   verifyFormat("template < std::vector< int > > f() {}", Spaces);
21452   verifyFormat("std::function< void(int, int) > fct;", Spaces);
21453   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
21454                Spaces);
21455 
21456   Spaces.Standard = FormatStyle::LS_Cpp03;
21457   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21458   verifyFormat("A< A< int > >();", Spaces);
21459 
21460   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
21461   verifyFormat("A<A<int> >();", Spaces);
21462 
21463   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
21464   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
21465                Spaces);
21466   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
21467                Spaces);
21468 
21469   verifyFormat("A<A<int> >();", Spaces);
21470   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
21471   verifyFormat("A< A< int > >();", Spaces);
21472 
21473   Spaces.Standard = FormatStyle::LS_Cpp11;
21474   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21475   verifyFormat("A< A< int > >();", Spaces);
21476 
21477   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
21478   verifyFormat("vector<::std::string> x4;", Spaces);
21479   verifyFormat("vector<int> x5;", Spaces);
21480   verifyFormat("Foo<int, Bar> x6;", Spaces);
21481   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
21482 
21483   verifyFormat("A<A<int>>();", Spaces);
21484 
21485   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
21486   verifyFormat("vector<::std::string> x4;", Spaces);
21487   verifyFormat("vector< ::std::string > x4;", Spaces);
21488   verifyFormat("vector<int> x5;", Spaces);
21489   verifyFormat("vector< int > x5;", Spaces);
21490   verifyFormat("Foo<int, Bar> x6;", Spaces);
21491   verifyFormat("Foo< int, Bar > x6;", Spaces);
21492   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
21493   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
21494 
21495   verifyFormat("A<A<int>>();", Spaces);
21496   verifyFormat("A< A< int > >();", Spaces);
21497   verifyFormat("A<A<int > >();", Spaces);
21498   verifyFormat("A< A< int>>();", Spaces);
21499 
21500   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21501   verifyFormat("// clang-format off\n"
21502                "foo<<<1, 1>>>();\n"
21503                "// clang-format on\n",
21504                Spaces);
21505   verifyFormat("// clang-format off\n"
21506                "foo< < <1, 1> > >();\n"
21507                "// clang-format on\n",
21508                Spaces);
21509 }
21510 
21511 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
21512   FormatStyle Style = getLLVMStyle();
21513   Style.SpaceAfterTemplateKeyword = false;
21514   verifyFormat("template<int> void foo();", Style);
21515 }
21516 
21517 TEST_F(FormatTest, TripleAngleBrackets) {
21518   verifyFormat("f<<<1, 1>>>();");
21519   verifyFormat("f<<<1, 1, 1, s>>>();");
21520   verifyFormat("f<<<a, b, c, d>>>();");
21521   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
21522   verifyFormat("f<param><<<1, 1>>>();");
21523   verifyFormat("f<1><<<1, 1>>>();");
21524   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
21525   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21526                "aaaaaaaaaaa<<<\n    1, 1>>>();");
21527   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
21528                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
21529 }
21530 
21531 TEST_F(FormatTest, MergeLessLessAtEnd) {
21532   verifyFormat("<<");
21533   EXPECT_EQ("< < <", format("\\\n<<<"));
21534   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21535                "aaallvm::outs() <<");
21536   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21537                "aaaallvm::outs()\n    <<");
21538 }
21539 
21540 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
21541   std::string code = "#if A\n"
21542                      "#if B\n"
21543                      "a.\n"
21544                      "#endif\n"
21545                      "    a = 1;\n"
21546                      "#else\n"
21547                      "#endif\n"
21548                      "#if C\n"
21549                      "#else\n"
21550                      "#endif\n";
21551   EXPECT_EQ(code, format(code));
21552 }
21553 
21554 TEST_F(FormatTest, HandleConflictMarkers) {
21555   // Git/SVN conflict markers.
21556   EXPECT_EQ("int a;\n"
21557             "void f() {\n"
21558             "  callme(some(parameter1,\n"
21559             "<<<<<<< text by the vcs\n"
21560             "              parameter2),\n"
21561             "||||||| text by the vcs\n"
21562             "              parameter2),\n"
21563             "         parameter3,\n"
21564             "======= text by the vcs\n"
21565             "              parameter2, parameter3),\n"
21566             ">>>>>>> text by the vcs\n"
21567             "         otherparameter);\n",
21568             format("int a;\n"
21569                    "void f() {\n"
21570                    "  callme(some(parameter1,\n"
21571                    "<<<<<<< text by the vcs\n"
21572                    "  parameter2),\n"
21573                    "||||||| text by the vcs\n"
21574                    "  parameter2),\n"
21575                    "  parameter3,\n"
21576                    "======= text by the vcs\n"
21577                    "  parameter2,\n"
21578                    "  parameter3),\n"
21579                    ">>>>>>> text by the vcs\n"
21580                    "  otherparameter);\n"));
21581 
21582   // Perforce markers.
21583   EXPECT_EQ("void f() {\n"
21584             "  function(\n"
21585             ">>>> text by the vcs\n"
21586             "      parameter,\n"
21587             "==== text by the vcs\n"
21588             "      parameter,\n"
21589             "==== text by the vcs\n"
21590             "      parameter,\n"
21591             "<<<< text by the vcs\n"
21592             "      parameter);\n",
21593             format("void f() {\n"
21594                    "  function(\n"
21595                    ">>>> text by the vcs\n"
21596                    "  parameter,\n"
21597                    "==== text by the vcs\n"
21598                    "  parameter,\n"
21599                    "==== text by the vcs\n"
21600                    "  parameter,\n"
21601                    "<<<< text by the vcs\n"
21602                    "  parameter);\n"));
21603 
21604   EXPECT_EQ("<<<<<<<\n"
21605             "|||||||\n"
21606             "=======\n"
21607             ">>>>>>>",
21608             format("<<<<<<<\n"
21609                    "|||||||\n"
21610                    "=======\n"
21611                    ">>>>>>>"));
21612 
21613   EXPECT_EQ("<<<<<<<\n"
21614             "|||||||\n"
21615             "int i;\n"
21616             "=======\n"
21617             ">>>>>>>",
21618             format("<<<<<<<\n"
21619                    "|||||||\n"
21620                    "int i;\n"
21621                    "=======\n"
21622                    ">>>>>>>"));
21623 
21624   // FIXME: Handle parsing of macros around conflict markers correctly:
21625   EXPECT_EQ("#define Macro \\\n"
21626             "<<<<<<<\n"
21627             "Something \\\n"
21628             "|||||||\n"
21629             "Else \\\n"
21630             "=======\n"
21631             "Other \\\n"
21632             ">>>>>>>\n"
21633             "    End int i;\n",
21634             format("#define Macro \\\n"
21635                    "<<<<<<<\n"
21636                    "  Something \\\n"
21637                    "|||||||\n"
21638                    "  Else \\\n"
21639                    "=======\n"
21640                    "  Other \\\n"
21641                    ">>>>>>>\n"
21642                    "  End\n"
21643                    "int i;\n"));
21644 
21645   verifyFormat(R"(====
21646 #ifdef A
21647 a
21648 #else
21649 b
21650 #endif
21651 )");
21652 }
21653 
21654 TEST_F(FormatTest, DisableRegions) {
21655   EXPECT_EQ("int i;\n"
21656             "// clang-format off\n"
21657             "  int j;\n"
21658             "// clang-format on\n"
21659             "int k;",
21660             format(" int  i;\n"
21661                    "   // clang-format off\n"
21662                    "  int j;\n"
21663                    " // clang-format on\n"
21664                    "   int   k;"));
21665   EXPECT_EQ("int i;\n"
21666             "/* clang-format off */\n"
21667             "  int j;\n"
21668             "/* clang-format on */\n"
21669             "int k;",
21670             format(" int  i;\n"
21671                    "   /* clang-format off */\n"
21672                    "  int j;\n"
21673                    " /* clang-format on */\n"
21674                    "   int   k;"));
21675 
21676   // Don't reflow comments within disabled regions.
21677   EXPECT_EQ("// clang-format off\n"
21678             "// long long long long long long line\n"
21679             "/* clang-format on */\n"
21680             "/* long long long\n"
21681             " * long long long\n"
21682             " * line */\n"
21683             "int i;\n"
21684             "/* clang-format off */\n"
21685             "/* long long long long long long line */\n",
21686             format("// clang-format off\n"
21687                    "// long long long long long long line\n"
21688                    "/* clang-format on */\n"
21689                    "/* long long long long long long line */\n"
21690                    "int i;\n"
21691                    "/* clang-format off */\n"
21692                    "/* long long long long long long line */\n",
21693                    getLLVMStyleWithColumns(20)));
21694 }
21695 
21696 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
21697   format("? ) =");
21698   verifyNoCrash("#define a\\\n /**/}");
21699 }
21700 
21701 TEST_F(FormatTest, FormatsTableGenCode) {
21702   FormatStyle Style = getLLVMStyle();
21703   Style.Language = FormatStyle::LK_TableGen;
21704   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
21705 }
21706 
21707 TEST_F(FormatTest, ArrayOfTemplates) {
21708   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
21709             format("auto a = new unique_ptr<int > [ 10];"));
21710 
21711   FormatStyle Spaces = getLLVMStyle();
21712   Spaces.SpacesInSquareBrackets = true;
21713   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
21714             format("auto a = new unique_ptr<int > [10];", Spaces));
21715 }
21716 
21717 TEST_F(FormatTest, ArrayAsTemplateType) {
21718   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
21719             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
21720 
21721   FormatStyle Spaces = getLLVMStyle();
21722   Spaces.SpacesInSquareBrackets = true;
21723   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
21724             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
21725 }
21726 
21727 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
21728 
21729 TEST(FormatStyle, GetStyleWithEmptyFileName) {
21730   llvm::vfs::InMemoryFileSystem FS;
21731   auto Style1 = getStyle("file", "", "Google", "", &FS);
21732   ASSERT_TRUE((bool)Style1);
21733   ASSERT_EQ(*Style1, getGoogleStyle());
21734 }
21735 
21736 TEST(FormatStyle, GetStyleOfFile) {
21737   llvm::vfs::InMemoryFileSystem FS;
21738   // Test 1: format file in the same directory.
21739   ASSERT_TRUE(
21740       FS.addFile("/a/.clang-format", 0,
21741                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
21742   ASSERT_TRUE(
21743       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21744   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
21745   ASSERT_TRUE((bool)Style1);
21746   ASSERT_EQ(*Style1, getLLVMStyle());
21747 
21748   // Test 2.1: fallback to default.
21749   ASSERT_TRUE(
21750       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21751   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
21752   ASSERT_TRUE((bool)Style2);
21753   ASSERT_EQ(*Style2, getMozillaStyle());
21754 
21755   // Test 2.2: no format on 'none' fallback style.
21756   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21757   ASSERT_TRUE((bool)Style2);
21758   ASSERT_EQ(*Style2, getNoStyle());
21759 
21760   // Test 2.3: format if config is found with no based style while fallback is
21761   // 'none'.
21762   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
21763                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
21764   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21765   ASSERT_TRUE((bool)Style2);
21766   ASSERT_EQ(*Style2, getLLVMStyle());
21767 
21768   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
21769   Style2 = getStyle("{}", "a.h", "none", "", &FS);
21770   ASSERT_TRUE((bool)Style2);
21771   ASSERT_EQ(*Style2, getLLVMStyle());
21772 
21773   // Test 3: format file in parent directory.
21774   ASSERT_TRUE(
21775       FS.addFile("/c/.clang-format", 0,
21776                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21777   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
21778                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21779   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21780   ASSERT_TRUE((bool)Style3);
21781   ASSERT_EQ(*Style3, getGoogleStyle());
21782 
21783   // Test 4: error on invalid fallback style
21784   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
21785   ASSERT_FALSE((bool)Style4);
21786   llvm::consumeError(Style4.takeError());
21787 
21788   // Test 5: error on invalid yaml on command line
21789   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
21790   ASSERT_FALSE((bool)Style5);
21791   llvm::consumeError(Style5.takeError());
21792 
21793   // Test 6: error on invalid style
21794   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
21795   ASSERT_FALSE((bool)Style6);
21796   llvm::consumeError(Style6.takeError());
21797 
21798   // Test 7: found config file, error on parsing it
21799   ASSERT_TRUE(
21800       FS.addFile("/d/.clang-format", 0,
21801                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
21802                                                   "InvalidKey: InvalidValue")));
21803   ASSERT_TRUE(
21804       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21805   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
21806   ASSERT_FALSE((bool)Style7a);
21807   llvm::consumeError(Style7a.takeError());
21808 
21809   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
21810   ASSERT_TRUE((bool)Style7b);
21811 
21812   // Test 8: inferred per-language defaults apply.
21813   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
21814   ASSERT_TRUE((bool)StyleTd);
21815   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
21816 
21817   // Test 9.1.1: overwriting a file style, when no parent file exists with no
21818   // fallback style.
21819   ASSERT_TRUE(FS.addFile(
21820       "/e/sub/.clang-format", 0,
21821       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
21822                                        "ColumnLimit: 20")));
21823   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
21824                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21825   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21826   ASSERT_TRUE(static_cast<bool>(Style9));
21827   ASSERT_EQ(*Style9, [] {
21828     auto Style = getNoStyle();
21829     Style.ColumnLimit = 20;
21830     return Style;
21831   }());
21832 
21833   // Test 9.1.2: propagate more than one level with no parent file.
21834   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
21835                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21836   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
21837                          llvm::MemoryBuffer::getMemBuffer(
21838                              "BasedOnStyle: InheritParentConfig\n"
21839                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
21840   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
21841 
21842   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
21843   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
21844   ASSERT_TRUE(static_cast<bool>(Style9));
21845   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
21846     auto Style = getNoStyle();
21847     Style.ColumnLimit = 20;
21848     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
21849     return Style;
21850   }());
21851 
21852   // Test 9.2: with LLVM fallback style
21853   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
21854   ASSERT_TRUE(static_cast<bool>(Style9));
21855   ASSERT_EQ(*Style9, [] {
21856     auto Style = getLLVMStyle();
21857     Style.ColumnLimit = 20;
21858     return Style;
21859   }());
21860 
21861   // Test 9.3: with a parent file
21862   ASSERT_TRUE(
21863       FS.addFile("/e/.clang-format", 0,
21864                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
21865                                                   "UseTab: Always")));
21866   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21867   ASSERT_TRUE(static_cast<bool>(Style9));
21868   ASSERT_EQ(*Style9, [] {
21869     auto Style = getGoogleStyle();
21870     Style.ColumnLimit = 20;
21871     Style.UseTab = FormatStyle::UT_Always;
21872     return Style;
21873   }());
21874 
21875   // Test 9.4: propagate more than one level with a parent file.
21876   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
21877     auto Style = getGoogleStyle();
21878     Style.ColumnLimit = 20;
21879     Style.UseTab = FormatStyle::UT_Always;
21880     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
21881     return Style;
21882   }();
21883 
21884   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
21885   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
21886   ASSERT_TRUE(static_cast<bool>(Style9));
21887   ASSERT_EQ(*Style9, SubSubStyle);
21888 
21889   // Test 9.5: use InheritParentConfig as style name
21890   Style9 =
21891       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
21892   ASSERT_TRUE(static_cast<bool>(Style9));
21893   ASSERT_EQ(*Style9, SubSubStyle);
21894 
21895   // Test 9.6: use command line style with inheritance
21896   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
21897                     "none", "", &FS);
21898   ASSERT_TRUE(static_cast<bool>(Style9));
21899   ASSERT_EQ(*Style9, SubSubStyle);
21900 
21901   // Test 9.7: use command line style with inheritance and own config
21902   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
21903                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
21904                     "/e/sub/code.cpp", "none", "", &FS);
21905   ASSERT_TRUE(static_cast<bool>(Style9));
21906   ASSERT_EQ(*Style9, SubSubStyle);
21907 
21908   // Test 9.8: use inheritance from a file without BasedOnStyle
21909   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
21910                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
21911   ASSERT_TRUE(
21912       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
21913                  llvm::MemoryBuffer::getMemBuffer(
21914                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
21915   // Make sure we do not use the fallback style
21916   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
21917   ASSERT_TRUE(static_cast<bool>(Style9));
21918   ASSERT_EQ(*Style9, [] {
21919     auto Style = getLLVMStyle();
21920     Style.ColumnLimit = 123;
21921     return Style;
21922   }());
21923 
21924   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
21925   ASSERT_TRUE(static_cast<bool>(Style9));
21926   ASSERT_EQ(*Style9, [] {
21927     auto Style = getLLVMStyle();
21928     Style.ColumnLimit = 123;
21929     Style.IndentWidth = 7;
21930     return Style;
21931   }());
21932 
21933   // Test 9.9: use inheritance from a specific config file.
21934   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
21935                     "none", "", &FS);
21936   ASSERT_TRUE(static_cast<bool>(Style9));
21937   ASSERT_EQ(*Style9, SubSubStyle);
21938 }
21939 
21940 TEST(FormatStyle, GetStyleOfSpecificFile) {
21941   llvm::vfs::InMemoryFileSystem FS;
21942   // Specify absolute path to a format file in a parent directory.
21943   ASSERT_TRUE(
21944       FS.addFile("/e/.clang-format", 0,
21945                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
21946   ASSERT_TRUE(
21947       FS.addFile("/e/explicit.clang-format", 0,
21948                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21949   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
21950                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21951   auto Style = getStyle("file:/e/explicit.clang-format",
21952                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21953   ASSERT_TRUE(static_cast<bool>(Style));
21954   ASSERT_EQ(*Style, getGoogleStyle());
21955 
21956   // Specify relative path to a format file.
21957   ASSERT_TRUE(
21958       FS.addFile("../../e/explicit.clang-format", 0,
21959                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21960   Style = getStyle("file:../../e/explicit.clang-format",
21961                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21962   ASSERT_TRUE(static_cast<bool>(Style));
21963   ASSERT_EQ(*Style, getGoogleStyle());
21964 
21965   // Specify path to a format file that does not exist.
21966   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
21967                    "LLVM", "", &FS);
21968   ASSERT_FALSE(static_cast<bool>(Style));
21969   llvm::consumeError(Style.takeError());
21970 
21971   // Specify path to a file on the filesystem.
21972   SmallString<128> FormatFilePath;
21973   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
21974       "FormatFileTest", "tpl", FormatFilePath);
21975   EXPECT_FALSE((bool)ECF);
21976   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
21977   EXPECT_FALSE((bool)ECF);
21978   FormatFileTest << "BasedOnStyle: Google\n";
21979   FormatFileTest.close();
21980 
21981   SmallString<128> TestFilePath;
21982   std::error_code ECT =
21983       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
21984   EXPECT_FALSE((bool)ECT);
21985   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
21986   CodeFileTest << "int i;\n";
21987   CodeFileTest.close();
21988 
21989   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
21990   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
21991 
21992   llvm::sys::fs::remove(FormatFilePath.c_str());
21993   llvm::sys::fs::remove(TestFilePath.c_str());
21994   ASSERT_TRUE(static_cast<bool>(Style));
21995   ASSERT_EQ(*Style, getGoogleStyle());
21996 }
21997 
21998 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
21999   // Column limit is 20.
22000   std::string Code = "Type *a =\n"
22001                      "    new Type();\n"
22002                      "g(iiiii, 0, jjjjj,\n"
22003                      "  0, kkkkk, 0, mm);\n"
22004                      "int  bad     = format   ;";
22005   std::string Expected = "auto a = new Type();\n"
22006                          "g(iiiii, nullptr,\n"
22007                          "  jjjjj, nullptr,\n"
22008                          "  kkkkk, nullptr,\n"
22009                          "  mm);\n"
22010                          "int  bad     = format   ;";
22011   FileID ID = Context.createInMemoryFile("format.cpp", Code);
22012   tooling::Replacements Replaces = toReplacements(
22013       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
22014                             "auto "),
22015        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
22016                             "nullptr"),
22017        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
22018                             "nullptr"),
22019        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
22020                             "nullptr")});
22021 
22022   FormatStyle Style = getLLVMStyle();
22023   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
22024   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22025   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22026       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22027   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22028   EXPECT_TRUE(static_cast<bool>(Result));
22029   EXPECT_EQ(Expected, *Result);
22030 }
22031 
22032 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
22033   std::string Code = "#include \"a.h\"\n"
22034                      "#include \"c.h\"\n"
22035                      "\n"
22036                      "int main() {\n"
22037                      "  return 0;\n"
22038                      "}";
22039   std::string Expected = "#include \"a.h\"\n"
22040                          "#include \"b.h\"\n"
22041                          "#include \"c.h\"\n"
22042                          "\n"
22043                          "int main() {\n"
22044                          "  return 0;\n"
22045                          "}";
22046   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
22047   tooling::Replacements Replaces = toReplacements(
22048       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
22049                             "#include \"b.h\"\n")});
22050 
22051   FormatStyle Style = getLLVMStyle();
22052   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
22053   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22054   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22055       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22056   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22057   EXPECT_TRUE(static_cast<bool>(Result));
22058   EXPECT_EQ(Expected, *Result);
22059 }
22060 
22061 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
22062   EXPECT_EQ("using std::cin;\n"
22063             "using std::cout;",
22064             format("using std::cout;\n"
22065                    "using std::cin;",
22066                    getGoogleStyle()));
22067 }
22068 
22069 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
22070   FormatStyle Style = getLLVMStyle();
22071   Style.Standard = FormatStyle::LS_Cpp03;
22072   // cpp03 recognize this string as identifier u8 and literal character 'a'
22073   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
22074 }
22075 
22076 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
22077   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
22078   // all modes, including C++11, C++14 and C++17
22079   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
22080 }
22081 
22082 TEST_F(FormatTest, DoNotFormatLikelyXml) {
22083   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
22084   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
22085 }
22086 
22087 TEST_F(FormatTest, StructuredBindings) {
22088   // Structured bindings is a C++17 feature.
22089   // all modes, including C++11, C++14 and C++17
22090   verifyFormat("auto [a, b] = f();");
22091   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
22092   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
22093   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
22094   EXPECT_EQ("auto const volatile [a, b] = f();",
22095             format("auto  const   volatile[a, b] = f();"));
22096   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
22097   EXPECT_EQ("auto &[a, b, c] = f();",
22098             format("auto   &[  a  ,  b,c   ] = f();"));
22099   EXPECT_EQ("auto &&[a, b, c] = f();",
22100             format("auto   &&[  a  ,  b,c   ] = f();"));
22101   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
22102   EXPECT_EQ("auto const volatile &&[a, b] = f();",
22103             format("auto  const  volatile  &&[a, b] = f();"));
22104   EXPECT_EQ("auto const &&[a, b] = f();",
22105             format("auto  const   &&  [a, b] = f();"));
22106   EXPECT_EQ("const auto &[a, b] = f();",
22107             format("const  auto  &  [a, b] = f();"));
22108   EXPECT_EQ("const auto volatile &&[a, b] = f();",
22109             format("const  auto   volatile  &&[a, b] = f();"));
22110   EXPECT_EQ("volatile const auto &&[a, b] = f();",
22111             format("volatile  const  auto   &&[a, b] = f();"));
22112   EXPECT_EQ("const auto &&[a, b] = f();",
22113             format("const  auto  &&  [a, b] = f();"));
22114 
22115   // Make sure we don't mistake structured bindings for lambdas.
22116   FormatStyle PointerMiddle = getLLVMStyle();
22117   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
22118   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
22119   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
22120   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
22121   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
22122   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
22123   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
22124   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
22125   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
22126   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
22127   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
22128   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
22129   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
22130 
22131   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
22132             format("for (const auto   &&   [a, b] : some_range) {\n}"));
22133   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
22134             format("for (const auto   &   [a, b] : some_range) {\n}"));
22135   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
22136             format("for (const auto[a, b] : some_range) {\n}"));
22137   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
22138   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
22139   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
22140   EXPECT_EQ("auto const &[x, y](expr);",
22141             format("auto  const  &  [x,y]  (expr);"));
22142   EXPECT_EQ("auto const &&[x, y](expr);",
22143             format("auto  const  &&  [x,y]  (expr);"));
22144   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
22145   EXPECT_EQ("auto const &[x, y]{expr};",
22146             format("auto  const  &  [x,y]  {expr};"));
22147   EXPECT_EQ("auto const &&[x, y]{expr};",
22148             format("auto  const  &&  [x,y]  {expr};"));
22149 
22150   FormatStyle Spaces = getLLVMStyle();
22151   Spaces.SpacesInSquareBrackets = true;
22152   verifyFormat("auto [ a, b ] = f();", Spaces);
22153   verifyFormat("auto &&[ a, b ] = f();", Spaces);
22154   verifyFormat("auto &[ a, b ] = f();", Spaces);
22155   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
22156   verifyFormat("auto const &[ a, b ] = f();", Spaces);
22157 }
22158 
22159 TEST_F(FormatTest, FileAndCode) {
22160   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
22161   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
22162   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
22163   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
22164   EXPECT_EQ(FormatStyle::LK_ObjC,
22165             guessLanguage("foo.h", "@interface Foo\n@end\n"));
22166   EXPECT_EQ(
22167       FormatStyle::LK_ObjC,
22168       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
22169   EXPECT_EQ(FormatStyle::LK_ObjC,
22170             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
22171   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
22172   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
22173   EXPECT_EQ(FormatStyle::LK_ObjC,
22174             guessLanguage("foo", "@interface Foo\n@end\n"));
22175   EXPECT_EQ(FormatStyle::LK_ObjC,
22176             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
22177   EXPECT_EQ(
22178       FormatStyle::LK_ObjC,
22179       guessLanguage("foo.h",
22180                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
22181   EXPECT_EQ(
22182       FormatStyle::LK_Cpp,
22183       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
22184 }
22185 
22186 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
22187   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
22188   EXPECT_EQ(FormatStyle::LK_ObjC,
22189             guessLanguage("foo.h", "array[[calculator getIndex]];"));
22190   EXPECT_EQ(FormatStyle::LK_Cpp,
22191             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
22192   EXPECT_EQ(
22193       FormatStyle::LK_Cpp,
22194       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
22195   EXPECT_EQ(FormatStyle::LK_ObjC,
22196             guessLanguage("foo.h", "[[noreturn foo] bar];"));
22197   EXPECT_EQ(FormatStyle::LK_Cpp,
22198             guessLanguage("foo.h", "[[clang::fallthrough]];"));
22199   EXPECT_EQ(FormatStyle::LK_ObjC,
22200             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
22201   EXPECT_EQ(FormatStyle::LK_Cpp,
22202             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
22203   EXPECT_EQ(FormatStyle::LK_Cpp,
22204             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
22205   EXPECT_EQ(FormatStyle::LK_ObjC,
22206             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
22207   EXPECT_EQ(FormatStyle::LK_Cpp,
22208             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
22209   EXPECT_EQ(
22210       FormatStyle::LK_Cpp,
22211       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
22212   EXPECT_EQ(
22213       FormatStyle::LK_Cpp,
22214       guessLanguage("foo.h",
22215                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
22216   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
22217 }
22218 
22219 TEST_F(FormatTest, GuessLanguageWithCaret) {
22220   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
22221   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
22222   EXPECT_EQ(FormatStyle::LK_ObjC,
22223             guessLanguage("foo.h", "int(^)(char, float);"));
22224   EXPECT_EQ(FormatStyle::LK_ObjC,
22225             guessLanguage("foo.h", "int(^foo)(char, float);"));
22226   EXPECT_EQ(FormatStyle::LK_ObjC,
22227             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
22228   EXPECT_EQ(FormatStyle::LK_ObjC,
22229             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
22230   EXPECT_EQ(
22231       FormatStyle::LK_ObjC,
22232       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
22233 }
22234 
22235 TEST_F(FormatTest, GuessLanguageWithPragmas) {
22236   EXPECT_EQ(FormatStyle::LK_Cpp,
22237             guessLanguage("foo.h", "__pragma(warning(disable:))"));
22238   EXPECT_EQ(FormatStyle::LK_Cpp,
22239             guessLanguage("foo.h", "#pragma(warning(disable:))"));
22240   EXPECT_EQ(FormatStyle::LK_Cpp,
22241             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
22242 }
22243 
22244 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
22245   // ASM symbolic names are identifiers that must be surrounded by [] without
22246   // space in between:
22247   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
22248 
22249   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
22250   verifyFormat(R"(//
22251 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
22252 )");
22253 
22254   // A list of several ASM symbolic names.
22255   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
22256 
22257   // ASM symbolic names in inline ASM with inputs and outputs.
22258   verifyFormat(R"(//
22259 asm("cmoveq %1, %2, %[result]"
22260     : [result] "=r"(result)
22261     : "r"(test), "r"(new), "[result]"(old));
22262 )");
22263 
22264   // ASM symbolic names in inline ASM with no outputs.
22265   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
22266 }
22267 
22268 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
22269   EXPECT_EQ(FormatStyle::LK_Cpp,
22270             guessLanguage("foo.h", "void f() {\n"
22271                                    "  asm (\"mov %[e], %[d]\"\n"
22272                                    "     : [d] \"=rm\" (d)\n"
22273                                    "       [e] \"rm\" (*e));\n"
22274                                    "}"));
22275   EXPECT_EQ(FormatStyle::LK_Cpp,
22276             guessLanguage("foo.h", "void f() {\n"
22277                                    "  _asm (\"mov %[e], %[d]\"\n"
22278                                    "     : [d] \"=rm\" (d)\n"
22279                                    "       [e] \"rm\" (*e));\n"
22280                                    "}"));
22281   EXPECT_EQ(FormatStyle::LK_Cpp,
22282             guessLanguage("foo.h", "void f() {\n"
22283                                    "  __asm (\"mov %[e], %[d]\"\n"
22284                                    "     : [d] \"=rm\" (d)\n"
22285                                    "       [e] \"rm\" (*e));\n"
22286                                    "}"));
22287   EXPECT_EQ(FormatStyle::LK_Cpp,
22288             guessLanguage("foo.h", "void f() {\n"
22289                                    "  __asm__ (\"mov %[e], %[d]\"\n"
22290                                    "     : [d] \"=rm\" (d)\n"
22291                                    "       [e] \"rm\" (*e));\n"
22292                                    "}"));
22293   EXPECT_EQ(FormatStyle::LK_Cpp,
22294             guessLanguage("foo.h", "void f() {\n"
22295                                    "  asm (\"mov %[e], %[d]\"\n"
22296                                    "     : [d] \"=rm\" (d),\n"
22297                                    "       [e] \"rm\" (*e));\n"
22298                                    "}"));
22299   EXPECT_EQ(FormatStyle::LK_Cpp,
22300             guessLanguage("foo.h", "void f() {\n"
22301                                    "  asm volatile (\"mov %[e], %[d]\"\n"
22302                                    "     : [d] \"=rm\" (d)\n"
22303                                    "       [e] \"rm\" (*e));\n"
22304                                    "}"));
22305 }
22306 
22307 TEST_F(FormatTest, GuessLanguageWithChildLines) {
22308   EXPECT_EQ(FormatStyle::LK_Cpp,
22309             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
22310   EXPECT_EQ(FormatStyle::LK_ObjC,
22311             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
22312   EXPECT_EQ(
22313       FormatStyle::LK_Cpp,
22314       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
22315   EXPECT_EQ(
22316       FormatStyle::LK_ObjC,
22317       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
22318 }
22319 
22320 TEST_F(FormatTest, TypenameMacros) {
22321   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
22322 
22323   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
22324   FormatStyle Google = getGoogleStyleWithColumns(0);
22325   Google.TypenameMacros = TypenameMacros;
22326   verifyFormat("struct foo {\n"
22327                "  int bar;\n"
22328                "  TAILQ_ENTRY(a) bleh;\n"
22329                "};",
22330                Google);
22331 
22332   FormatStyle Macros = getLLVMStyle();
22333   Macros.TypenameMacros = TypenameMacros;
22334 
22335   verifyFormat("STACK_OF(int) a;", Macros);
22336   verifyFormat("STACK_OF(int) *a;", Macros);
22337   verifyFormat("STACK_OF(int const *) *a;", Macros);
22338   verifyFormat("STACK_OF(int *const) *a;", Macros);
22339   verifyFormat("STACK_OF(int, string) a;", Macros);
22340   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
22341   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
22342   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
22343   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
22344   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
22345   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
22346 
22347   Macros.PointerAlignment = FormatStyle::PAS_Left;
22348   verifyFormat("STACK_OF(int)* a;", Macros);
22349   verifyFormat("STACK_OF(int*)* a;", Macros);
22350   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
22351   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
22352   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
22353 }
22354 
22355 TEST_F(FormatTest, AtomicQualifier) {
22356   // Check that we treate _Atomic as a type and not a function call
22357   FormatStyle Google = getGoogleStyleWithColumns(0);
22358   verifyFormat("struct foo {\n"
22359                "  int a1;\n"
22360                "  _Atomic(a) a2;\n"
22361                "  _Atomic(_Atomic(int) *const) a3;\n"
22362                "};",
22363                Google);
22364   verifyFormat("_Atomic(uint64_t) a;");
22365   verifyFormat("_Atomic(uint64_t) *a;");
22366   verifyFormat("_Atomic(uint64_t const *) *a;");
22367   verifyFormat("_Atomic(uint64_t *const) *a;");
22368   verifyFormat("_Atomic(const uint64_t *) *a;");
22369   verifyFormat("_Atomic(uint64_t) a;");
22370   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
22371   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
22372   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
22373   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
22374 
22375   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
22376   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
22377   FormatStyle Style = getLLVMStyle();
22378   Style.PointerAlignment = FormatStyle::PAS_Left;
22379   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
22380   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
22381   verifyFormat("_Atomic(int)* a;", Style);
22382   verifyFormat("_Atomic(int*)* a;", Style);
22383   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
22384 
22385   Style.SpacesInCStyleCastParentheses = true;
22386   Style.SpacesInParentheses = false;
22387   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
22388   Style.SpacesInCStyleCastParentheses = false;
22389   Style.SpacesInParentheses = true;
22390   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
22391   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
22392 }
22393 
22394 TEST_F(FormatTest, AmbersandInLamda) {
22395   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
22396   FormatStyle AlignStyle = getLLVMStyle();
22397   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
22398   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22399   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
22400   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22401 }
22402 
22403 TEST_F(FormatTest, SpacesInConditionalStatement) {
22404   FormatStyle Spaces = getLLVMStyle();
22405   Spaces.IfMacros.clear();
22406   Spaces.IfMacros.push_back("MYIF");
22407   Spaces.SpacesInConditionalStatement = true;
22408   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
22409   verifyFormat("if ( !a )\n  return;", Spaces);
22410   verifyFormat("if ( a )\n  return;", Spaces);
22411   verifyFormat("if constexpr ( a )\n  return;", Spaces);
22412   verifyFormat("MYIF ( a )\n  return;", Spaces);
22413   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
22414   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
22415   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
22416   verifyFormat("while ( a )\n  return;", Spaces);
22417   verifyFormat("while ( (a && b) )\n  return;", Spaces);
22418   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
22419   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
22420   // Check that space on the left of "::" is inserted as expected at beginning
22421   // of condition.
22422   verifyFormat("while ( ::func() )\n  return;", Spaces);
22423 
22424   // Check impact of ControlStatementsExceptControlMacros is honored.
22425   Spaces.SpaceBeforeParens =
22426       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
22427   verifyFormat("MYIF( a )\n  return;", Spaces);
22428   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
22429   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
22430 }
22431 
22432 TEST_F(FormatTest, AlternativeOperators) {
22433   // Test case for ensuring alternate operators are not
22434   // combined with their right most neighbour.
22435   verifyFormat("int a and b;");
22436   verifyFormat("int a and_eq b;");
22437   verifyFormat("int a bitand b;");
22438   verifyFormat("int a bitor b;");
22439   verifyFormat("int a compl b;");
22440   verifyFormat("int a not b;");
22441   verifyFormat("int a not_eq b;");
22442   verifyFormat("int a or b;");
22443   verifyFormat("int a xor b;");
22444   verifyFormat("int a xor_eq b;");
22445   verifyFormat("return this not_eq bitand other;");
22446   verifyFormat("bool operator not_eq(const X bitand other)");
22447 
22448   verifyFormat("int a and 5;");
22449   verifyFormat("int a and_eq 5;");
22450   verifyFormat("int a bitand 5;");
22451   verifyFormat("int a bitor 5;");
22452   verifyFormat("int a compl 5;");
22453   verifyFormat("int a not 5;");
22454   verifyFormat("int a not_eq 5;");
22455   verifyFormat("int a or 5;");
22456   verifyFormat("int a xor 5;");
22457   verifyFormat("int a xor_eq 5;");
22458 
22459   verifyFormat("int a compl(5);");
22460   verifyFormat("int a not(5);");
22461 
22462   /* FIXME handle alternate tokens
22463    * https://en.cppreference.com/w/cpp/language/operator_alternative
22464   // alternative tokens
22465   verifyFormat("compl foo();");     //  ~foo();
22466   verifyFormat("foo() <%%>;");      // foo();
22467   verifyFormat("void foo() <%%>;"); // void foo(){}
22468   verifyFormat("int a <:1:>;");     // int a[1];[
22469   verifyFormat("%:define ABC abc"); // #define ABC abc
22470   verifyFormat("%:%:");             // ##
22471   */
22472 }
22473 
22474 TEST_F(FormatTest, STLWhileNotDefineChed) {
22475   verifyFormat("#if defined(while)\n"
22476                "#define while EMIT WARNING C4005\n"
22477                "#endif // while");
22478 }
22479 
22480 TEST_F(FormatTest, OperatorSpacing) {
22481   FormatStyle Style = getLLVMStyle();
22482   Style.PointerAlignment = FormatStyle::PAS_Right;
22483   verifyFormat("Foo::operator*();", Style);
22484   verifyFormat("Foo::operator void *();", Style);
22485   verifyFormat("Foo::operator void **();", Style);
22486   verifyFormat("Foo::operator void *&();", Style);
22487   verifyFormat("Foo::operator void *&&();", Style);
22488   verifyFormat("Foo::operator void const *();", Style);
22489   verifyFormat("Foo::operator void const **();", Style);
22490   verifyFormat("Foo::operator void const *&();", Style);
22491   verifyFormat("Foo::operator void const *&&();", Style);
22492   verifyFormat("Foo::operator()(void *);", Style);
22493   verifyFormat("Foo::operator*(void *);", Style);
22494   verifyFormat("Foo::operator*();", Style);
22495   verifyFormat("Foo::operator**();", Style);
22496   verifyFormat("Foo::operator&();", Style);
22497   verifyFormat("Foo::operator<int> *();", Style);
22498   verifyFormat("Foo::operator<Foo> *();", Style);
22499   verifyFormat("Foo::operator<int> **();", Style);
22500   verifyFormat("Foo::operator<Foo> **();", Style);
22501   verifyFormat("Foo::operator<int> &();", Style);
22502   verifyFormat("Foo::operator<Foo> &();", Style);
22503   verifyFormat("Foo::operator<int> &&();", Style);
22504   verifyFormat("Foo::operator<Foo> &&();", Style);
22505   verifyFormat("Foo::operator<int> *&();", Style);
22506   verifyFormat("Foo::operator<Foo> *&();", Style);
22507   verifyFormat("Foo::operator<int> *&&();", Style);
22508   verifyFormat("Foo::operator<Foo> *&&();", Style);
22509   verifyFormat("operator*(int (*)(), class Foo);", Style);
22510 
22511   verifyFormat("Foo::operator&();", Style);
22512   verifyFormat("Foo::operator void &();", Style);
22513   verifyFormat("Foo::operator void const &();", Style);
22514   verifyFormat("Foo::operator()(void &);", Style);
22515   verifyFormat("Foo::operator&(void &);", Style);
22516   verifyFormat("Foo::operator&();", Style);
22517   verifyFormat("operator&(int (&)(), class Foo);", Style);
22518   verifyFormat("operator&&(int (&)(), class Foo);", Style);
22519 
22520   verifyFormat("Foo::operator&&();", Style);
22521   verifyFormat("Foo::operator**();", Style);
22522   verifyFormat("Foo::operator void &&();", Style);
22523   verifyFormat("Foo::operator void const &&();", Style);
22524   verifyFormat("Foo::operator()(void &&);", Style);
22525   verifyFormat("Foo::operator&&(void &&);", Style);
22526   verifyFormat("Foo::operator&&();", Style);
22527   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22528   verifyFormat("operator const nsTArrayRight<E> &()", Style);
22529   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
22530                Style);
22531   verifyFormat("operator void **()", Style);
22532   verifyFormat("operator const FooRight<Object> &()", Style);
22533   verifyFormat("operator const FooRight<Object> *()", Style);
22534   verifyFormat("operator const FooRight<Object> **()", Style);
22535   verifyFormat("operator const FooRight<Object> *&()", Style);
22536   verifyFormat("operator const FooRight<Object> *&&()", Style);
22537 
22538   Style.PointerAlignment = FormatStyle::PAS_Left;
22539   verifyFormat("Foo::operator*();", Style);
22540   verifyFormat("Foo::operator**();", Style);
22541   verifyFormat("Foo::operator void*();", Style);
22542   verifyFormat("Foo::operator void**();", Style);
22543   verifyFormat("Foo::operator void*&();", Style);
22544   verifyFormat("Foo::operator void*&&();", Style);
22545   verifyFormat("Foo::operator void const*();", Style);
22546   verifyFormat("Foo::operator void const**();", Style);
22547   verifyFormat("Foo::operator void const*&();", Style);
22548   verifyFormat("Foo::operator void const*&&();", Style);
22549   verifyFormat("Foo::operator/*comment*/ void*();", Style);
22550   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
22551   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
22552   verifyFormat("Foo::operator()(void*);", Style);
22553   verifyFormat("Foo::operator*(void*);", Style);
22554   verifyFormat("Foo::operator*();", Style);
22555   verifyFormat("Foo::operator<int>*();", Style);
22556   verifyFormat("Foo::operator<Foo>*();", Style);
22557   verifyFormat("Foo::operator<int>**();", Style);
22558   verifyFormat("Foo::operator<Foo>**();", Style);
22559   verifyFormat("Foo::operator<Foo>*&();", Style);
22560   verifyFormat("Foo::operator<int>&();", Style);
22561   verifyFormat("Foo::operator<Foo>&();", Style);
22562   verifyFormat("Foo::operator<int>&&();", Style);
22563   verifyFormat("Foo::operator<Foo>&&();", Style);
22564   verifyFormat("Foo::operator<int>*&();", Style);
22565   verifyFormat("Foo::operator<Foo>*&();", Style);
22566   verifyFormat("operator*(int (*)(), class Foo);", Style);
22567 
22568   verifyFormat("Foo::operator&();", Style);
22569   verifyFormat("Foo::operator void&();", Style);
22570   verifyFormat("Foo::operator void const&();", Style);
22571   verifyFormat("Foo::operator/*comment*/ void&();", Style);
22572   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
22573   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
22574   verifyFormat("Foo::operator()(void&);", Style);
22575   verifyFormat("Foo::operator&(void&);", Style);
22576   verifyFormat("Foo::operator&();", Style);
22577   verifyFormat("operator&(int (&)(), class Foo);", Style);
22578   verifyFormat("operator&(int (&&)(), class Foo);", Style);
22579   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22580 
22581   verifyFormat("Foo::operator&&();", Style);
22582   verifyFormat("Foo::operator void&&();", Style);
22583   verifyFormat("Foo::operator void const&&();", Style);
22584   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
22585   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
22586   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
22587   verifyFormat("Foo::operator()(void&&);", Style);
22588   verifyFormat("Foo::operator&&(void&&);", Style);
22589   verifyFormat("Foo::operator&&();", Style);
22590   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22591   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
22592   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
22593                Style);
22594   verifyFormat("operator void**()", Style);
22595   verifyFormat("operator const FooLeft<Object>&()", Style);
22596   verifyFormat("operator const FooLeft<Object>*()", Style);
22597   verifyFormat("operator const FooLeft<Object>**()", Style);
22598   verifyFormat("operator const FooLeft<Object>*&()", Style);
22599   verifyFormat("operator const FooLeft<Object>*&&()", Style);
22600 
22601   // PR45107
22602   verifyFormat("operator Vector<String>&();", Style);
22603   verifyFormat("operator const Vector<String>&();", Style);
22604   verifyFormat("operator foo::Bar*();", Style);
22605   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
22606   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
22607                Style);
22608 
22609   Style.PointerAlignment = FormatStyle::PAS_Middle;
22610   verifyFormat("Foo::operator*();", Style);
22611   verifyFormat("Foo::operator void *();", Style);
22612   verifyFormat("Foo::operator()(void *);", Style);
22613   verifyFormat("Foo::operator*(void *);", Style);
22614   verifyFormat("Foo::operator*();", Style);
22615   verifyFormat("operator*(int (*)(), class Foo);", Style);
22616 
22617   verifyFormat("Foo::operator&();", Style);
22618   verifyFormat("Foo::operator void &();", Style);
22619   verifyFormat("Foo::operator void const &();", Style);
22620   verifyFormat("Foo::operator()(void &);", Style);
22621   verifyFormat("Foo::operator&(void &);", Style);
22622   verifyFormat("Foo::operator&();", Style);
22623   verifyFormat("operator&(int (&)(), class Foo);", Style);
22624 
22625   verifyFormat("Foo::operator&&();", Style);
22626   verifyFormat("Foo::operator void &&();", Style);
22627   verifyFormat("Foo::operator void const &&();", Style);
22628   verifyFormat("Foo::operator()(void &&);", Style);
22629   verifyFormat("Foo::operator&&(void &&);", Style);
22630   verifyFormat("Foo::operator&&();", Style);
22631   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22632 }
22633 
22634 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
22635   FormatStyle Style = getLLVMStyle();
22636   // PR46157
22637   verifyFormat("foo(operator+, -42);", Style);
22638   verifyFormat("foo(operator++, -42);", Style);
22639   verifyFormat("foo(operator--, -42);", Style);
22640   verifyFormat("foo(-42, operator--);", Style);
22641   verifyFormat("foo(-42, operator, );", Style);
22642   verifyFormat("foo(operator, , -42);", Style);
22643 }
22644 
22645 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
22646   FormatStyle Style = getLLVMStyle();
22647   Style.WhitespaceSensitiveMacros.push_back("FOO");
22648 
22649   // Don't use the helpers here, since 'mess up' will change the whitespace
22650   // and these are all whitespace sensitive by definition
22651   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
22652             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
22653   EXPECT_EQ(
22654       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
22655       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
22656   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
22657             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
22658   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
22659             "       Still=Intentional);",
22660             format("FOO(String-ized&Messy+But,: :\n"
22661                    "       Still=Intentional);",
22662                    Style));
22663   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
22664   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
22665             "       Still=Intentional);",
22666             format("FOO(String-ized=&Messy+But,: :\n"
22667                    "       Still=Intentional);",
22668                    Style));
22669 
22670   Style.ColumnLimit = 21;
22671   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
22672             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
22673 }
22674 
22675 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
22676   // These tests are not in NamespaceFixer because that doesn't
22677   // test its interaction with line wrapping
22678   FormatStyle Style = getLLVMStyleWithColumns(80);
22679   verifyFormat("namespace {\n"
22680                "int i;\n"
22681                "int j;\n"
22682                "} // namespace",
22683                Style);
22684 
22685   verifyFormat("namespace AAA {\n"
22686                "int i;\n"
22687                "int j;\n"
22688                "} // namespace AAA",
22689                Style);
22690 
22691   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
22692             "int i;\n"
22693             "int j;\n"
22694             "} // namespace Averyveryveryverylongnamespace",
22695             format("namespace Averyveryveryverylongnamespace {\n"
22696                    "int i;\n"
22697                    "int j;\n"
22698                    "}",
22699                    Style));
22700 
22701   EXPECT_EQ(
22702       "namespace "
22703       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
22704       "    went::mad::now {\n"
22705       "int i;\n"
22706       "int j;\n"
22707       "} // namespace\n"
22708       "  // "
22709       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
22710       "went::mad::now",
22711       format("namespace "
22712              "would::it::save::you::a::lot::of::time::if_::i::"
22713              "just::gave::up::and_::went::mad::now {\n"
22714              "int i;\n"
22715              "int j;\n"
22716              "}",
22717              Style));
22718 
22719   // This used to duplicate the comment again and again on subsequent runs
22720   EXPECT_EQ(
22721       "namespace "
22722       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
22723       "    went::mad::now {\n"
22724       "int i;\n"
22725       "int j;\n"
22726       "} // namespace\n"
22727       "  // "
22728       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
22729       "went::mad::now",
22730       format("namespace "
22731              "would::it::save::you::a::lot::of::time::if_::i::"
22732              "just::gave::up::and_::went::mad::now {\n"
22733              "int i;\n"
22734              "int j;\n"
22735              "} // namespace\n"
22736              "  // "
22737              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
22738              "and_::went::mad::now",
22739              Style));
22740 }
22741 
22742 TEST_F(FormatTest, LikelyUnlikely) {
22743   FormatStyle Style = getLLVMStyle();
22744 
22745   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22746                "  return 29;\n"
22747                "}",
22748                Style);
22749 
22750   verifyFormat("if (argc > 5) [[likely]] {\n"
22751                "  return 29;\n"
22752                "}",
22753                Style);
22754 
22755   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22756                "  return 29;\n"
22757                "} else [[likely]] {\n"
22758                "  return 42;\n"
22759                "}\n",
22760                Style);
22761 
22762   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22763                "  return 29;\n"
22764                "} else if (argc > 10) [[likely]] {\n"
22765                "  return 99;\n"
22766                "} else {\n"
22767                "  return 42;\n"
22768                "}\n",
22769                Style);
22770 
22771   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
22772                "  return 29;\n"
22773                "}",
22774                Style);
22775 
22776   verifyFormat("if (argc > 5) [[unlikely]]\n"
22777                "  return 29;\n",
22778                Style);
22779   verifyFormat("if (argc > 5) [[likely]]\n"
22780                "  return 29;\n",
22781                Style);
22782 
22783   Style.AttributeMacros.push_back("UNLIKELY");
22784   Style.AttributeMacros.push_back("LIKELY");
22785   verifyFormat("if (argc > 5) UNLIKELY\n"
22786                "  return 29;\n",
22787                Style);
22788 
22789   verifyFormat("if (argc > 5) UNLIKELY {\n"
22790                "  return 29;\n"
22791                "}",
22792                Style);
22793   verifyFormat("if (argc > 5) UNLIKELY {\n"
22794                "  return 29;\n"
22795                "} else [[likely]] {\n"
22796                "  return 42;\n"
22797                "}\n",
22798                Style);
22799   verifyFormat("if (argc > 5) UNLIKELY {\n"
22800                "  return 29;\n"
22801                "} else LIKELY {\n"
22802                "  return 42;\n"
22803                "}\n",
22804                Style);
22805   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22806                "  return 29;\n"
22807                "} else LIKELY {\n"
22808                "  return 42;\n"
22809                "}\n",
22810                Style);
22811 }
22812 
22813 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
22814   verifyFormat("Constructor()\n"
22815                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
22816                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
22817                "aaaaaaaaaaaaaaaaaat))");
22818   verifyFormat("Constructor()\n"
22819                "    : aaaaaaaaaaaaa(aaaaaa), "
22820                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
22821 
22822   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
22823   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
22824   verifyFormat("Constructor()\n"
22825                "    : aaaaaa(aaaaaa),\n"
22826                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
22827                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
22828                StyleWithWhitespacePenalty);
22829   verifyFormat("Constructor()\n"
22830                "    : aaaaaaaaaaaaa(aaaaaa), "
22831                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
22832                StyleWithWhitespacePenalty);
22833 }
22834 
22835 TEST_F(FormatTest, LLVMDefaultStyle) {
22836   FormatStyle Style = getLLVMStyle();
22837   verifyFormat("extern \"C\" {\n"
22838                "int foo();\n"
22839                "}",
22840                Style);
22841 }
22842 TEST_F(FormatTest, GNUDefaultStyle) {
22843   FormatStyle Style = getGNUStyle();
22844   verifyFormat("extern \"C\"\n"
22845                "{\n"
22846                "  int foo ();\n"
22847                "}",
22848                Style);
22849 }
22850 TEST_F(FormatTest, MozillaDefaultStyle) {
22851   FormatStyle Style = getMozillaStyle();
22852   verifyFormat("extern \"C\"\n"
22853                "{\n"
22854                "  int foo();\n"
22855                "}",
22856                Style);
22857 }
22858 TEST_F(FormatTest, GoogleDefaultStyle) {
22859   FormatStyle Style = getGoogleStyle();
22860   verifyFormat("extern \"C\" {\n"
22861                "int foo();\n"
22862                "}",
22863                Style);
22864 }
22865 TEST_F(FormatTest, ChromiumDefaultStyle) {
22866   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
22867   verifyFormat("extern \"C\" {\n"
22868                "int foo();\n"
22869                "}",
22870                Style);
22871 }
22872 TEST_F(FormatTest, MicrosoftDefaultStyle) {
22873   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
22874   verifyFormat("extern \"C\"\n"
22875                "{\n"
22876                "    int foo();\n"
22877                "}",
22878                Style);
22879 }
22880 TEST_F(FormatTest, WebKitDefaultStyle) {
22881   FormatStyle Style = getWebKitStyle();
22882   verifyFormat("extern \"C\" {\n"
22883                "int foo();\n"
22884                "}",
22885                Style);
22886 }
22887 
22888 TEST_F(FormatTest, ConceptsAndRequires) {
22889   FormatStyle Style = getLLVMStyle();
22890   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
22891 
22892   verifyFormat("template <typename T>\n"
22893                "concept Hashable = requires(T a) {\n"
22894                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22895                "};",
22896                Style);
22897   verifyFormat("template <typename T>\n"
22898                "concept EqualityComparable = requires(T a, T b) {\n"
22899                "  { a == b } -> bool;\n"
22900                "};",
22901                Style);
22902   verifyFormat("template <typename T>\n"
22903                "concept EqualityComparable = requires(T a, T b) {\n"
22904                "  { a == b } -> bool;\n"
22905                "  { a != b } -> bool;\n"
22906                "};",
22907                Style);
22908   verifyFormat("template <typename T>\n"
22909                "concept EqualityComparable = requires(T a, T b) {\n"
22910                "  { a == b } -> bool;\n"
22911                "  { a != b } -> bool;\n"
22912                "};",
22913                Style);
22914 
22915   verifyFormat("template <typename It>\n"
22916                "requires Iterator<It>\n"
22917                "void sort(It begin, It end) {\n"
22918                "  //....\n"
22919                "}",
22920                Style);
22921 
22922   verifyFormat("template <typename T>\n"
22923                "concept Large = sizeof(T) > 10;",
22924                Style);
22925 
22926   verifyFormat("template <typename T, typename U>\n"
22927                "concept FooableWith = requires(T t, U u) {\n"
22928                "  typename T::foo_type;\n"
22929                "  { t.foo(u) } -> typename T::foo_type;\n"
22930                "  t++;\n"
22931                "};\n"
22932                "void doFoo(FooableWith<int> auto t) {\n"
22933                "  t.foo(3);\n"
22934                "}",
22935                Style);
22936   verifyFormat("template <typename T>\n"
22937                "concept Context = sizeof(T) == 1;",
22938                Style);
22939   verifyFormat("template <typename T>\n"
22940                "concept Context = is_specialization_of_v<context, T>;",
22941                Style);
22942   verifyFormat("template <typename T>\n"
22943                "concept Node = std::is_object_v<T>;",
22944                Style);
22945   verifyFormat("template <typename T>\n"
22946                "concept Tree = true;",
22947                Style);
22948 
22949   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
22950                "  //...\n"
22951                "}",
22952                Style);
22953 
22954   verifyFormat(
22955       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
22956       "  //...\n"
22957       "}",
22958       Style);
22959 
22960   verifyFormat(
22961       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
22962       "  //...\n"
22963       "}",
22964       Style);
22965 
22966   verifyFormat("template <typename T>\n"
22967                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
22968                "Concept2<I> {\n"
22969                "  //...\n"
22970                "}",
22971                Style);
22972 
22973   verifyFormat("template <typename T>\n"
22974                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
22975                "Concept2<I> {\n"
22976                "  //...\n"
22977                "}",
22978                Style);
22979 
22980   verifyFormat(
22981       "template <typename T>\n"
22982       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
22983       "  //...\n"
22984       "}",
22985       Style);
22986 
22987   verifyFormat(
22988       "template <typename T>\n"
22989       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
22990       "  //...\n"
22991       "}",
22992       Style);
22993 
22994   verifyFormat("template <typename It>\n"
22995                "requires Foo<It>() && Bar<It> {\n"
22996                "  //....\n"
22997                "}",
22998                Style);
22999 
23000   verifyFormat("template <typename It>\n"
23001                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
23002                "  //....\n"
23003                "}",
23004                Style);
23005 
23006   verifyFormat("template <typename It>\n"
23007                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
23008                "  //....\n"
23009                "}",
23010                Style);
23011 
23012   verifyFormat(
23013       "template <typename It>\n"
23014       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
23015       "  //....\n"
23016       "}",
23017       Style);
23018 
23019   Style.IndentRequires = true;
23020   verifyFormat("template <typename It>\n"
23021                "  requires Iterator<It>\n"
23022                "void sort(It begin, It end) {\n"
23023                "  //....\n"
23024                "}",
23025                Style);
23026   verifyFormat("template <std::size index_>\n"
23027                "  requires(index_ < sizeof...(Children_))\n"
23028                "Tree auto &child() {\n"
23029                "  // ...\n"
23030                "}",
23031                Style);
23032 
23033   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
23034   verifyFormat("template <typename T>\n"
23035                "concept Hashable = requires (T a) {\n"
23036                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
23037                "};",
23038                Style);
23039 
23040   verifyFormat("template <class T = void>\n"
23041                "  requires EqualityComparable<T> || Same<T, void>\n"
23042                "struct equal_to;",
23043                Style);
23044 
23045   verifyFormat("template <class T>\n"
23046                "  requires requires {\n"
23047                "    T{};\n"
23048                "    T (int);\n"
23049                "  }\n",
23050                Style);
23051 
23052   Style.ColumnLimit = 78;
23053   verifyFormat("template <typename T>\n"
23054                "concept Context = Traits<typename T::traits_type> and\n"
23055                "    Interface<typename T::interface_type> and\n"
23056                "    Request<typename T::request_type> and\n"
23057                "    Response<typename T::response_type> and\n"
23058                "    ContextExtension<typename T::extension_type> and\n"
23059                "    ::std::is_copy_constructable<T> and "
23060                "::std::is_move_constructable<T> and\n"
23061                "    requires (T c) {\n"
23062                "  { c.response; } -> Response;\n"
23063                "} and requires (T c) {\n"
23064                "  { c.request; } -> Request;\n"
23065                "}\n",
23066                Style);
23067 
23068   verifyFormat("template <typename T>\n"
23069                "concept Context = Traits<typename T::traits_type> or\n"
23070                "    Interface<typename T::interface_type> or\n"
23071                "    Request<typename T::request_type> or\n"
23072                "    Response<typename T::response_type> or\n"
23073                "    ContextExtension<typename T::extension_type> or\n"
23074                "    ::std::is_copy_constructable<T> or "
23075                "::std::is_move_constructable<T> or\n"
23076                "    requires (T c) {\n"
23077                "  { c.response; } -> Response;\n"
23078                "} or requires (T c) {\n"
23079                "  { c.request; } -> Request;\n"
23080                "}\n",
23081                Style);
23082 
23083   verifyFormat("template <typename T>\n"
23084                "concept Context = Traits<typename T::traits_type> &&\n"
23085                "    Interface<typename T::interface_type> &&\n"
23086                "    Request<typename T::request_type> &&\n"
23087                "    Response<typename T::response_type> &&\n"
23088                "    ContextExtension<typename T::extension_type> &&\n"
23089                "    ::std::is_copy_constructable<T> && "
23090                "::std::is_move_constructable<T> &&\n"
23091                "    requires (T c) {\n"
23092                "  { c.response; } -> Response;\n"
23093                "} && requires (T c) {\n"
23094                "  { c.request; } -> Request;\n"
23095                "}\n",
23096                Style);
23097 
23098   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
23099                "Constraint2<T>;");
23100 
23101   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
23102   Style.BraceWrapping.AfterFunction = true;
23103   Style.BraceWrapping.AfterClass = true;
23104   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
23105   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
23106   verifyFormat("void Foo () requires (std::copyable<T>)\n"
23107                "{\n"
23108                "  return\n"
23109                "}\n",
23110                Style);
23111 
23112   verifyFormat("void Foo () requires std::copyable<T>\n"
23113                "{\n"
23114                "  return\n"
23115                "}\n",
23116                Style);
23117 
23118   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
23119                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
23120                "struct constant;",
23121                Style);
23122 
23123   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
23124                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
23125                "struct constant;",
23126                Style);
23127 
23128   verifyFormat("template <class T>\n"
23129                "class plane_with_very_very_very_long_name\n"
23130                "{\n"
23131                "  constexpr plane_with_very_very_very_long_name () requires "
23132                "std::copyable<T>\n"
23133                "      : plane_with_very_very_very_long_name (1)\n"
23134                "  {\n"
23135                "  }\n"
23136                "}\n",
23137                Style);
23138 
23139   verifyFormat("template <class T>\n"
23140                "class plane_with_long_name\n"
23141                "{\n"
23142                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
23143                "      : plane_with_long_name (1)\n"
23144                "  {\n"
23145                "  }\n"
23146                "}\n",
23147                Style);
23148 
23149   Style.BreakBeforeConceptDeclarations = false;
23150   verifyFormat("template <typename T> concept Tree = true;", Style);
23151 
23152   Style.IndentRequires = false;
23153   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
23154                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
23155                "struct constant;",
23156                Style);
23157 }
23158 
23159 TEST_F(FormatTest, StatementAttributeLikeMacros) {
23160   FormatStyle Style = getLLVMStyle();
23161   StringRef Source = "void Foo::slot() {\n"
23162                      "  unsigned char MyChar = 'x';\n"
23163                      "  emit signal(MyChar);\n"
23164                      "  Q_EMIT signal(MyChar);\n"
23165                      "}";
23166 
23167   EXPECT_EQ(Source, format(Source, Style));
23168 
23169   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
23170   EXPECT_EQ("void Foo::slot() {\n"
23171             "  unsigned char MyChar = 'x';\n"
23172             "  emit          signal(MyChar);\n"
23173             "  Q_EMIT signal(MyChar);\n"
23174             "}",
23175             format(Source, Style));
23176 
23177   Style.StatementAttributeLikeMacros.push_back("emit");
23178   EXPECT_EQ(Source, format(Source, Style));
23179 
23180   Style.StatementAttributeLikeMacros = {};
23181   EXPECT_EQ("void Foo::slot() {\n"
23182             "  unsigned char MyChar = 'x';\n"
23183             "  emit          signal(MyChar);\n"
23184             "  Q_EMIT        signal(MyChar);\n"
23185             "}",
23186             format(Source, Style));
23187 }
23188 
23189 TEST_F(FormatTest, IndentAccessModifiers) {
23190   FormatStyle Style = getLLVMStyle();
23191   Style.IndentAccessModifiers = true;
23192   // Members are *two* levels below the record;
23193   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
23194   verifyFormat("class C {\n"
23195                "    int i;\n"
23196                "};\n",
23197                Style);
23198   verifyFormat("union C {\n"
23199                "    int i;\n"
23200                "    unsigned u;\n"
23201                "};\n",
23202                Style);
23203   // Access modifiers should be indented one level below the record.
23204   verifyFormat("class C {\n"
23205                "  public:\n"
23206                "    int i;\n"
23207                "};\n",
23208                Style);
23209   verifyFormat("struct S {\n"
23210                "  private:\n"
23211                "    class C {\n"
23212                "        int j;\n"
23213                "\n"
23214                "      public:\n"
23215                "        C();\n"
23216                "    };\n"
23217                "\n"
23218                "  public:\n"
23219                "    int i;\n"
23220                "};\n",
23221                Style);
23222   // Enumerations are not records and should be unaffected.
23223   Style.AllowShortEnumsOnASingleLine = false;
23224   verifyFormat("enum class E {\n"
23225                "  A,\n"
23226                "  B\n"
23227                "};\n",
23228                Style);
23229   // Test with a different indentation width;
23230   // also proves that the result is Style.AccessModifierOffset agnostic.
23231   Style.IndentWidth = 3;
23232   verifyFormat("class C {\n"
23233                "   public:\n"
23234                "      int i;\n"
23235                "};\n",
23236                Style);
23237 }
23238 
23239 TEST_F(FormatTest, LimitlessStringsAndComments) {
23240   auto Style = getLLVMStyleWithColumns(0);
23241   constexpr StringRef Code =
23242       "/**\n"
23243       " * This is a multiline comment with quite some long lines, at least for "
23244       "the LLVM Style.\n"
23245       " * We will redo this with strings and line comments. Just to  check if "
23246       "everything is working.\n"
23247       " */\n"
23248       "bool foo() {\n"
23249       "  /* Single line multi line comment. */\n"
23250       "  const std::string String = \"This is a multiline string with quite "
23251       "some long lines, at least for the LLVM Style.\"\n"
23252       "                             \"We already did it with multi line "
23253       "comments, and we will do it with line comments. Just to check if "
23254       "everything is working.\";\n"
23255       "  // This is a line comment (block) with quite some long lines, at "
23256       "least for the LLVM Style.\n"
23257       "  // We already did this with multi line comments and strings. Just to "
23258       "check if everything is working.\n"
23259       "  const std::string SmallString = \"Hello World\";\n"
23260       "  // Small line comment\n"
23261       "  return String.size() > SmallString.size();\n"
23262       "}";
23263   EXPECT_EQ(Code, format(Code, Style));
23264 }
23265 
23266 TEST_F(FormatTest, FormatDecayCopy) {
23267   // error cases from unit tests
23268   verifyFormat("foo(auto())");
23269   verifyFormat("foo(auto{})");
23270   verifyFormat("foo(auto({}))");
23271   verifyFormat("foo(auto{{}})");
23272 
23273   verifyFormat("foo(auto(1))");
23274   verifyFormat("foo(auto{1})");
23275   verifyFormat("foo(new auto(1))");
23276   verifyFormat("foo(new auto{1})");
23277   verifyFormat("decltype(auto(1)) x;");
23278   verifyFormat("decltype(auto{1}) x;");
23279   verifyFormat("auto(x);");
23280   verifyFormat("auto{x};");
23281   verifyFormat("new auto{x};");
23282   verifyFormat("auto{x} = y;");
23283   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
23284                                 // the user's own fault
23285   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
23286                                          // clearly the user's own fault
23287   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
23288 }
23289 
23290 TEST_F(FormatTest, Cpp20ModulesSupport) {
23291   FormatStyle Style = getLLVMStyle();
23292   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
23293   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
23294 
23295   verifyFormat("export import foo;", Style);
23296   verifyFormat("export import foo:bar;", Style);
23297   verifyFormat("export import foo.bar;", Style);
23298   verifyFormat("export import foo.bar:baz;", Style);
23299   verifyFormat("export import :bar;", Style);
23300   verifyFormat("export module foo:bar;", Style);
23301   verifyFormat("export module foo;", Style);
23302   verifyFormat("export module foo.bar;", Style);
23303   verifyFormat("export module foo.bar:baz;", Style);
23304   verifyFormat("export import <string_view>;", Style);
23305 
23306   verifyFormat("export type_name var;", Style);
23307   verifyFormat("template <class T> export using A = B<T>;", Style);
23308   verifyFormat("export using A = B;", Style);
23309   verifyFormat("export int func() {\n"
23310                "  foo();\n"
23311                "}",
23312                Style);
23313   verifyFormat("export struct {\n"
23314                "  int foo;\n"
23315                "};",
23316                Style);
23317   verifyFormat("export {\n"
23318                "  int foo;\n"
23319                "};",
23320                Style);
23321   verifyFormat("export export char const *hello() { return \"hello\"; }");
23322 
23323   verifyFormat("import bar;", Style);
23324   verifyFormat("import foo.bar;", Style);
23325   verifyFormat("import foo:bar;", Style);
23326   verifyFormat("import :bar;", Style);
23327   verifyFormat("import <ctime>;", Style);
23328   verifyFormat("import \"header\";", Style);
23329 
23330   verifyFormat("module foo;", Style);
23331   verifyFormat("module foo:bar;", Style);
23332   verifyFormat("module foo.bar;", Style);
23333   verifyFormat("module;", Style);
23334 
23335   verifyFormat("export namespace hi {\n"
23336                "const char *sayhi();\n"
23337                "}",
23338                Style);
23339 
23340   verifyFormat("module :private;", Style);
23341   verifyFormat("import <foo/bar.h>;", Style);
23342   verifyFormat("import foo...bar;", Style);
23343   verifyFormat("import ..........;", Style);
23344   verifyFormat("module foo:private;", Style);
23345   verifyFormat("import a", Style);
23346   verifyFormat("module a", Style);
23347   verifyFormat("export import a", Style);
23348   verifyFormat("export module a", Style);
23349 
23350   verifyFormat("import", Style);
23351   verifyFormat("module", Style);
23352   verifyFormat("export", Style);
23353 }
23354 
23355 TEST_F(FormatTest, CoroutineForCoawait) {
23356   FormatStyle Style = getLLVMStyle();
23357   verifyFormat("for co_await (auto x : range())\n  ;");
23358   verifyFormat("for (auto i : arr) {\n"
23359                "}",
23360                Style);
23361   verifyFormat("for co_await (auto i : arr) {\n"
23362                "}",
23363                Style);
23364   verifyFormat("for co_await (auto i : foo(T{})) {\n"
23365                "}",
23366                Style);
23367 }
23368 
23369 TEST_F(FormatTest, CoroutineCoAwait) {
23370   verifyFormat("int x = co_await foo();");
23371   verifyFormat("int x = (co_await foo());");
23372   verifyFormat("co_await (42);");
23373   verifyFormat("void operator co_await(int);");
23374   verifyFormat("void operator co_await(a);");
23375   verifyFormat("co_await a;");
23376   verifyFormat("co_await missing_await_resume{};");
23377   verifyFormat("co_await a; // comment");
23378   verifyFormat("void test0() { co_await a; }");
23379   verifyFormat("co_await co_await co_await foo();");
23380   verifyFormat("co_await foo().bar();");
23381   verifyFormat("co_await [this]() -> Task { co_return x; }");
23382   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
23383                "foo(); }(x, y);");
23384 
23385   FormatStyle Style = getLLVMStyleWithColumns(40);
23386   verifyFormat("co_await [this](int a, int b) -> Task {\n"
23387                "  co_return co_await foo();\n"
23388                "}(x, y);",
23389                Style);
23390   verifyFormat("co_await;");
23391 }
23392 
23393 TEST_F(FormatTest, CoroutineCoYield) {
23394   verifyFormat("int x = co_yield foo();");
23395   verifyFormat("int x = (co_yield foo());");
23396   verifyFormat("co_yield (42);");
23397   verifyFormat("co_yield {42};");
23398   verifyFormat("co_yield 42;");
23399   verifyFormat("co_yield n++;");
23400   verifyFormat("co_yield ++n;");
23401   verifyFormat("co_yield;");
23402 }
23403 
23404 TEST_F(FormatTest, CoroutineCoReturn) {
23405   verifyFormat("co_return (42);");
23406   verifyFormat("co_return;");
23407   verifyFormat("co_return {};");
23408   verifyFormat("co_return x;");
23409   verifyFormat("co_return co_await foo();");
23410   verifyFormat("co_return co_yield foo();");
23411 }
23412 
23413 TEST_F(FormatTest, EmptyShortBlock) {
23414   auto Style = getLLVMStyle();
23415   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
23416 
23417   verifyFormat("try {\n"
23418                "  doA();\n"
23419                "} catch (Exception &e) {\n"
23420                "  e.printStackTrace();\n"
23421                "}\n",
23422                Style);
23423 
23424   verifyFormat("try {\n"
23425                "  doA();\n"
23426                "} catch (Exception &e) {}\n",
23427                Style);
23428 }
23429 
23430 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
23431   auto Style = getLLVMStyle();
23432 
23433   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
23434   verifyFormat("struct Y<[] { return 0; }> {};", Style);
23435 
23436   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
23437 }
23438 
23439 TEST_F(FormatTest, RemoveBraces) {
23440   FormatStyle Style = getLLVMStyle();
23441   Style.RemoveBracesLLVM = true;
23442 
23443   // The following eight test cases are fully-braced versions of the examples at
23444   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
23445   // statement-bodies-of-if-else-loop-statements".
23446 
23447   // 1. Omit the braces, since the body is simple and clearly associated with
23448   // the if.
23449   verifyFormat("if (isa<FunctionDecl>(D))\n"
23450                "  handleFunctionDecl(D);\n"
23451                "else if (isa<VarDecl>(D))\n"
23452                "  handleVarDecl(D);",
23453                "if (isa<FunctionDecl>(D)) {\n"
23454                "  handleFunctionDecl(D);\n"
23455                "} else if (isa<VarDecl>(D)) {\n"
23456                "  handleVarDecl(D);\n"
23457                "}",
23458                Style);
23459 
23460   // 2. Here we document the condition itself and not the body.
23461   verifyFormat("if (isa<VarDecl>(D)) {\n"
23462                "  // It is necessary that we explain the situation with this\n"
23463                "  // surprisingly long comment, so it would be unclear\n"
23464                "  // without the braces whether the following statement is in\n"
23465                "  // the scope of the `if`.\n"
23466                "  // Because the condition is documented, we can't really\n"
23467                "  // hoist this comment that applies to the body above the\n"
23468                "  // if.\n"
23469                "  handleOtherDecl(D);\n"
23470                "}",
23471                Style);
23472 
23473   // 3. Use braces on the outer `if` to avoid a potential dangling else
23474   // situation.
23475   verifyFormat("if (isa<VarDecl>(D)) {\n"
23476                "  for (auto *A : D.attrs())\n"
23477                "    if (shouldProcessAttr(A))\n"
23478                "      handleAttr(A);\n"
23479                "}",
23480                "if (isa<VarDecl>(D)) {\n"
23481                "  for (auto *A : D.attrs()) {\n"
23482                "    if (shouldProcessAttr(A)) {\n"
23483                "      handleAttr(A);\n"
23484                "    }\n"
23485                "  }\n"
23486                "}",
23487                Style);
23488 
23489   // 4. Use braces for the `if` block to keep it uniform with the else block.
23490   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
23491                "  handleFunctionDecl(D);\n"
23492                "} else {\n"
23493                "  // In this else case, it is necessary that we explain the\n"
23494                "  // situation with this surprisingly long comment, so it\n"
23495                "  // would be unclear without the braces whether the\n"
23496                "  // following statement is in the scope of the `if`.\n"
23497                "  handleOtherDecl(D);\n"
23498                "}",
23499                Style);
23500 
23501   // 5. This should also omit braces.  The `for` loop contains only a single
23502   // statement, so it shouldn't have braces.  The `if` also only contains a
23503   // single simple statement (the for loop), so it also should omit braces.
23504   verifyFormat("if (isa<FunctionDecl>(D))\n"
23505                "  for (auto *A : D.attrs())\n"
23506                "    handleAttr(A);",
23507                "if (isa<FunctionDecl>(D)) {\n"
23508                "  for (auto *A : D.attrs()) {\n"
23509                "    handleAttr(A);\n"
23510                "  }\n"
23511                "}",
23512                Style);
23513 
23514   // 6. Use braces for the outer `if` since the nested `for` is braced.
23515   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
23516                "  for (auto *A : D.attrs()) {\n"
23517                "    // In this for loop body, it is necessary that we explain\n"
23518                "    // the situation with this surprisingly long comment,\n"
23519                "    // forcing braces on the `for` block.\n"
23520                "    handleAttr(A);\n"
23521                "  }\n"
23522                "}",
23523                Style);
23524 
23525   // 7. Use braces on the outer block because there are more than two levels of
23526   // nesting.
23527   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
23528                "  for (auto *A : D.attrs())\n"
23529                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
23530                "      handleAttrOnDecl(D, A, i);\n"
23531                "}",
23532                "if (isa<FunctionDecl>(D)) {\n"
23533                "  for (auto *A : D.attrs()) {\n"
23534                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
23535                "      handleAttrOnDecl(D, A, i);\n"
23536                "    }\n"
23537                "  }\n"
23538                "}",
23539                Style);
23540 
23541   // 8. Use braces on the outer block because of a nested `if`, otherwise the
23542   // compiler would warn: `add explicit braces to avoid dangling else`
23543   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
23544                "  if (shouldProcess(D))\n"
23545                "    handleVarDecl(D);\n"
23546                "  else\n"
23547                "    markAsIgnored(D);\n"
23548                "}",
23549                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
23550                "  if (shouldProcess(D)) {\n"
23551                "    handleVarDecl(D);\n"
23552                "  } else {\n"
23553                "    markAsIgnored(D);\n"
23554                "  }\n"
23555                "}",
23556                Style);
23557 
23558   verifyFormat("if (a)\n"
23559                "  b; // comment\n"
23560                "else if (c)\n"
23561                "  d; /* comment */\n"
23562                "else\n"
23563                "  e;",
23564                "if (a) {\n"
23565                "  b; // comment\n"
23566                "} else if (c) {\n"
23567                "  d; /* comment */\n"
23568                "} else {\n"
23569                "  e;\n"
23570                "}",
23571                Style);
23572 
23573   verifyFormat("if (a) {\n"
23574                "  b;\n"
23575                "  c;\n"
23576                "} else if (d) {\n"
23577                "  e;\n"
23578                "}",
23579                Style);
23580 
23581   verifyFormat("if (a) {\n"
23582                "#undef NDEBUG\n"
23583                "  b;\n"
23584                "} else {\n"
23585                "  c;\n"
23586                "}",
23587                Style);
23588 
23589   verifyFormat("if (a) {\n"
23590                "  // comment\n"
23591                "} else if (b) {\n"
23592                "  c;\n"
23593                "}",
23594                Style);
23595 
23596   verifyFormat("if (a) {\n"
23597                "  b;\n"
23598                "} else {\n"
23599                "  { c; }\n"
23600                "}",
23601                Style);
23602 
23603   verifyFormat("if (a) {\n"
23604                "  if (b) // comment\n"
23605                "    c;\n"
23606                "} else if (d) {\n"
23607                "  e;\n"
23608                "}",
23609                "if (a) {\n"
23610                "  if (b) { // comment\n"
23611                "    c;\n"
23612                "  }\n"
23613                "} else if (d) {\n"
23614                "  e;\n"
23615                "}",
23616                Style);
23617 
23618   verifyFormat("if (a) {\n"
23619                "  if (b) {\n"
23620                "    c;\n"
23621                "    // comment\n"
23622                "  } else if (d) {\n"
23623                "    e;\n"
23624                "  }\n"
23625                "}",
23626                Style);
23627 
23628   verifyFormat("if (a) {\n"
23629                "  if (b)\n"
23630                "    c;\n"
23631                "}",
23632                "if (a) {\n"
23633                "  if (b) {\n"
23634                "    c;\n"
23635                "  }\n"
23636                "}",
23637                Style);
23638 
23639   verifyFormat("if (a)\n"
23640                "  if (b)\n"
23641                "    c;\n"
23642                "  else\n"
23643                "    d;\n"
23644                "else\n"
23645                "  e;",
23646                "if (a) {\n"
23647                "  if (b) {\n"
23648                "    c;\n"
23649                "  } else {\n"
23650                "    d;\n"
23651                "  }\n"
23652                "} else {\n"
23653                "  e;\n"
23654                "}",
23655                Style);
23656 
23657   verifyFormat("if (a) {\n"
23658                "  // comment\n"
23659                "  if (b)\n"
23660                "    c;\n"
23661                "  else if (d)\n"
23662                "    e;\n"
23663                "} else {\n"
23664                "  g;\n"
23665                "}",
23666                "if (a) {\n"
23667                "  // comment\n"
23668                "  if (b) {\n"
23669                "    c;\n"
23670                "  } else if (d) {\n"
23671                "    e;\n"
23672                "  }\n"
23673                "} else {\n"
23674                "  g;\n"
23675                "}",
23676                Style);
23677 
23678   verifyFormat("if (a)\n"
23679                "  b;\n"
23680                "else if (c)\n"
23681                "  d;\n"
23682                "else\n"
23683                "  e;",
23684                "if (a) {\n"
23685                "  b;\n"
23686                "} else {\n"
23687                "  if (c) {\n"
23688                "    d;\n"
23689                "  } else {\n"
23690                "    e;\n"
23691                "  }\n"
23692                "}",
23693                Style);
23694 
23695   verifyFormat("if (a) {\n"
23696                "  if (b)\n"
23697                "    c;\n"
23698                "  else if (d)\n"
23699                "    e;\n"
23700                "} else {\n"
23701                "  g;\n"
23702                "}",
23703                "if (a) {\n"
23704                "  if (b)\n"
23705                "    c;\n"
23706                "  else {\n"
23707                "    if (d)\n"
23708                "      e;\n"
23709                "  }\n"
23710                "} else {\n"
23711                "  g;\n"
23712                "}",
23713                Style);
23714 
23715   verifyFormat("if (a)\n"
23716                "  b;\n"
23717                "else if (c)\n"
23718                "  while (d)\n"
23719                "    e;\n"
23720                "// comment",
23721                "if (a)\n"
23722                "{\n"
23723                "  b;\n"
23724                "} else if (c) {\n"
23725                "  while (d) {\n"
23726                "    e;\n"
23727                "  }\n"
23728                "}\n"
23729                "// comment",
23730                Style);
23731 
23732   verifyFormat("if (a) {\n"
23733                "  b;\n"
23734                "} else if (c) {\n"
23735                "  d;\n"
23736                "} else {\n"
23737                "  e;\n"
23738                "  g;\n"
23739                "}",
23740                Style);
23741 
23742   verifyFormat("if (a) {\n"
23743                "  b;\n"
23744                "} else if (c) {\n"
23745                "  d;\n"
23746                "} else {\n"
23747                "  e;\n"
23748                "} // comment",
23749                Style);
23750 
23751   verifyFormat("int abs = [](int i) {\n"
23752                "  if (i >= 0)\n"
23753                "    return i;\n"
23754                "  return -i;\n"
23755                "};",
23756                "int abs = [](int i) {\n"
23757                "  if (i >= 0) {\n"
23758                "    return i;\n"
23759                "  }\n"
23760                "  return -i;\n"
23761                "};",
23762                Style);
23763 
23764   Style.ColumnLimit = 20;
23765 
23766   verifyFormat("if (a) {\n"
23767                "  b = c + // 1 -\n"
23768                "      d;\n"
23769                "}",
23770                Style);
23771 
23772   verifyFormat("if (a) {\n"
23773                "  b = c >= 0 ? d\n"
23774                "             : e;\n"
23775                "}",
23776                "if (a) {\n"
23777                "  b = c >= 0 ? d : e;\n"
23778                "}",
23779                Style);
23780 
23781   verifyFormat("if (a)\n"
23782                "  b = c > 0 ? d : e;",
23783                "if (a) {\n"
23784                "  b = c > 0 ? d : e;\n"
23785                "}",
23786                Style);
23787 
23788   Style.ColumnLimit = 0;
23789 
23790   verifyFormat("if (a)\n"
23791                "  b234567890223456789032345678904234567890 = "
23792                "c234567890223456789032345678904234567890;",
23793                "if (a) {\n"
23794                "  b234567890223456789032345678904234567890 = "
23795                "c234567890223456789032345678904234567890;\n"
23796                "}",
23797                Style);
23798 }
23799 
23800 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
23801   auto Style = getLLVMStyle();
23802 
23803   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
23804                     "void functionDecl(int a, int b, int c);";
23805 
23806   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
23807                      "paramF, paramG, paramH, paramI);\n"
23808                      "void functionDecl(int argumentA, int argumentB, int "
23809                      "argumentC, int argumentD, int argumentE);";
23810 
23811   verifyFormat(Short, Style);
23812 
23813   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
23814                       "paramF, paramG, paramH,\n"
23815                       "             paramI);\n"
23816                       "void functionDecl(int argumentA, int argumentB, int "
23817                       "argumentC, int argumentD,\n"
23818                       "                  int argumentE);";
23819 
23820   verifyFormat(NoBreak, Medium, Style);
23821   verifyFormat(NoBreak,
23822                "functionCall(\n"
23823                "    paramA,\n"
23824                "    paramB,\n"
23825                "    paramC,\n"
23826                "    paramD,\n"
23827                "    paramE,\n"
23828                "    paramF,\n"
23829                "    paramG,\n"
23830                "    paramH,\n"
23831                "    paramI\n"
23832                ");\n"
23833                "void functionDecl(\n"
23834                "    int argumentA,\n"
23835                "    int argumentB,\n"
23836                "    int argumentC,\n"
23837                "    int argumentD,\n"
23838                "    int argumentE\n"
23839                ");",
23840                Style);
23841 
23842   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
23843                "                  nestedLongFunctionCall(argument1, "
23844                "argument2, argument3,\n"
23845                "                                         argument4, "
23846                "argument5));",
23847                Style);
23848 
23849   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
23850 
23851   verifyFormat(Short, Style);
23852   verifyFormat(
23853       "functionCall(\n"
23854       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
23855       "paramI\n"
23856       ");\n"
23857       "void functionDecl(\n"
23858       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
23859       "argumentE\n"
23860       ");",
23861       Medium, Style);
23862 
23863   Style.AllowAllArgumentsOnNextLine = false;
23864   Style.AllowAllParametersOfDeclarationOnNextLine = false;
23865 
23866   verifyFormat(Short, Style);
23867   verifyFormat(
23868       "functionCall(\n"
23869       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
23870       "paramI\n"
23871       ");\n"
23872       "void functionDecl(\n"
23873       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
23874       "argumentE\n"
23875       ");",
23876       Medium, Style);
23877 
23878   Style.BinPackArguments = false;
23879   Style.BinPackParameters = false;
23880 
23881   verifyFormat(Short, Style);
23882 
23883   verifyFormat("functionCall(\n"
23884                "    paramA,\n"
23885                "    paramB,\n"
23886                "    paramC,\n"
23887                "    paramD,\n"
23888                "    paramE,\n"
23889                "    paramF,\n"
23890                "    paramG,\n"
23891                "    paramH,\n"
23892                "    paramI\n"
23893                ");\n"
23894                "void functionDecl(\n"
23895                "    int argumentA,\n"
23896                "    int argumentB,\n"
23897                "    int argumentC,\n"
23898                "    int argumentD,\n"
23899                "    int argumentE\n"
23900                ");",
23901                Medium, Style);
23902 
23903   verifyFormat("outerFunctionCall(\n"
23904                "    nestedFunctionCall(argument1),\n"
23905                "    nestedLongFunctionCall(\n"
23906                "        argument1,\n"
23907                "        argument2,\n"
23908                "        argument3,\n"
23909                "        argument4,\n"
23910                "        argument5\n"
23911                "    )\n"
23912                ");",
23913                Style);
23914 
23915   verifyFormat("int a = (int)b;", Style);
23916   verifyFormat("int a = (int)b;",
23917                "int a = (\n"
23918                "    int\n"
23919                ") b;",
23920                Style);
23921 
23922   verifyFormat("return (true);", Style);
23923   verifyFormat("return (true);",
23924                "return (\n"
23925                "    true\n"
23926                ");",
23927                Style);
23928 
23929   verifyFormat("void foo();", Style);
23930   verifyFormat("void foo();",
23931                "void foo(\n"
23932                ");",
23933                Style);
23934 
23935   verifyFormat("void foo() {}", Style);
23936   verifyFormat("void foo() {}",
23937                "void foo(\n"
23938                ") {\n"
23939                "}",
23940                Style);
23941 
23942   verifyFormat("auto string = std::string();", Style);
23943   verifyFormat("auto string = std::string();",
23944                "auto string = std::string(\n"
23945                ");",
23946                Style);
23947 
23948   verifyFormat("void (*functionPointer)() = nullptr;", Style);
23949   verifyFormat("void (*functionPointer)() = nullptr;",
23950                "void (\n"
23951                "    *functionPointer\n"
23952                ")\n"
23953                "(\n"
23954                ") = nullptr;",
23955                Style);
23956 }
23957 
23958 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
23959   auto Style = getLLVMStyle();
23960 
23961   verifyFormat("if (foo()) {\n"
23962                "  return;\n"
23963                "}",
23964                Style);
23965 
23966   verifyFormat("if (quitelongarg !=\n"
23967                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
23968                "comment\n"
23969                "  return;\n"
23970                "}",
23971                Style);
23972 
23973   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
23974 
23975   verifyFormat("if (foo()) {\n"
23976                "  return;\n"
23977                "}",
23978                Style);
23979 
23980   verifyFormat("if (quitelongarg !=\n"
23981                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
23982                "comment\n"
23983                "  return;\n"
23984                "}",
23985                Style);
23986 }
23987 
23988 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
23989   auto Style = getLLVMStyle();
23990 
23991   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
23992                "  doSomething();\n"
23993                "}",
23994                Style);
23995 
23996   verifyFormat("for (int myReallyLongCountVariable = 0; "
23997                "myReallyLongCountVariable < count;\n"
23998                "     myReallyLongCountVariable++) {\n"
23999                "  doSomething();\n"
24000                "}",
24001                Style);
24002 
24003   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
24004 
24005   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
24006                "  doSomething();\n"
24007                "}",
24008                Style);
24009 
24010   verifyFormat("for (int myReallyLongCountVariable = 0; "
24011                "myReallyLongCountVariable < count;\n"
24012                "     myReallyLongCountVariable++) {\n"
24013                "  doSomething();\n"
24014                "}",
24015                Style);
24016 }
24017 
24018 } // namespace
24019 } // namespace format
24020 } // namespace clang
24021