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("while (true)\n"
1468                "  ;",
1469                AllowsMergedLoops);
1470   verifyFormat("for (;;)\n"
1471                "  ;",
1472                AllowsMergedLoops);
1473   verifyFormat("for (;;)\n"
1474                "  for (;;) continue;",
1475                AllowsMergedLoops);
1476   verifyFormat("for (;;)\n"
1477                "  while (true) continue;",
1478                AllowsMergedLoops);
1479   verifyFormat("BOOST_FOREACH (int v, vec)\n"
1480                "  for (;;) continue;",
1481                AllowsMergedLoops);
1482   verifyFormat("for (;;) // Can't merge this\n"
1483                "  continue;",
1484                AllowsMergedLoops);
1485   verifyFormat("for (;;) /* still don't merge */\n"
1486                "  continue;",
1487                AllowsMergedLoops);
1488   verifyFormat("do a++;\n"
1489                "while (true);",
1490                AllowsMergedLoops);
1491   verifyFormat("do /* Don't merge */\n"
1492                "  a++;\n"
1493                "while (true);",
1494                AllowsMergedLoops);
1495   verifyFormat("do // Don't merge\n"
1496                "  a++;\n"
1497                "while (true);",
1498                AllowsMergedLoops);
1499   verifyFormat("do\n"
1500                "  // Don't merge\n"
1501                "  a++;\n"
1502                "while (true);",
1503                AllowsMergedLoops);
1504   // Without braces labels are interpreted differently.
1505   verifyFormat("{\n"
1506                "  do\n"
1507                "  label:\n"
1508                "    a++;\n"
1509                "  while (true);\n"
1510                "}",
1511                AllowsMergedLoops);
1512 }
1513 
1514 TEST_F(FormatTest, FormatShortBracedStatements) {
1515   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
1516   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
1517   // Where line-lengths matter, a 2-letter synonym that maintains line length.
1518   // Not IF to avoid any confusion that IF is somehow special.
1519   AllowSimpleBracedStatements.IfMacros.push_back("FI");
1520   AllowSimpleBracedStatements.ColumnLimit = 40;
1521   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1522       FormatStyle::SBS_Always;
1523 
1524   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1525       FormatStyle::SIS_WithoutElse;
1526   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1527 
1528   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1529   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1530   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1531 
1532   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1533   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1534   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1535   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1536   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1537   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1538   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1539   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1540   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1541   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1542   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1543   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1544   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1545   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1546   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1547   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1548   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1549                AllowSimpleBracedStatements);
1550   verifyFormat("if (true) {\n"
1551                "  ffffffffffffffffffffffff();\n"
1552                "}",
1553                AllowSimpleBracedStatements);
1554   verifyFormat("if (true) {\n"
1555                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1556                "}",
1557                AllowSimpleBracedStatements);
1558   verifyFormat("if (true) { //\n"
1559                "  f();\n"
1560                "}",
1561                AllowSimpleBracedStatements);
1562   verifyFormat("if (true) {\n"
1563                "  f();\n"
1564                "  f();\n"
1565                "}",
1566                AllowSimpleBracedStatements);
1567   verifyFormat("if (true) {\n"
1568                "  f();\n"
1569                "} else {\n"
1570                "  f();\n"
1571                "}",
1572                AllowSimpleBracedStatements);
1573   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1574                AllowSimpleBracedStatements);
1575   verifyFormat("MYIF (true) {\n"
1576                "  ffffffffffffffffffffffff();\n"
1577                "}",
1578                AllowSimpleBracedStatements);
1579   verifyFormat("MYIF (true) {\n"
1580                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1581                "}",
1582                AllowSimpleBracedStatements);
1583   verifyFormat("MYIF (true) { //\n"
1584                "  f();\n"
1585                "}",
1586                AllowSimpleBracedStatements);
1587   verifyFormat("MYIF (true) {\n"
1588                "  f();\n"
1589                "  f();\n"
1590                "}",
1591                AllowSimpleBracedStatements);
1592   verifyFormat("MYIF (true) {\n"
1593                "  f();\n"
1594                "} else {\n"
1595                "  f();\n"
1596                "}",
1597                AllowSimpleBracedStatements);
1598 
1599   verifyFormat("struct A2 {\n"
1600                "  int X;\n"
1601                "};",
1602                AllowSimpleBracedStatements);
1603   verifyFormat("typedef struct A2 {\n"
1604                "  int X;\n"
1605                "} A2_t;",
1606                AllowSimpleBracedStatements);
1607   verifyFormat("template <int> struct A2 {\n"
1608                "  struct B {};\n"
1609                "};",
1610                AllowSimpleBracedStatements);
1611 
1612   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1613       FormatStyle::SIS_Never;
1614   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1615   verifyFormat("if (true) {\n"
1616                "  f();\n"
1617                "}",
1618                AllowSimpleBracedStatements);
1619   verifyFormat("if (true) {\n"
1620                "  f();\n"
1621                "} else {\n"
1622                "  f();\n"
1623                "}",
1624                AllowSimpleBracedStatements);
1625   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1626   verifyFormat("MYIF (true) {\n"
1627                "  f();\n"
1628                "}",
1629                AllowSimpleBracedStatements);
1630   verifyFormat("MYIF (true) {\n"
1631                "  f();\n"
1632                "} else {\n"
1633                "  f();\n"
1634                "}",
1635                AllowSimpleBracedStatements);
1636 
1637   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1638   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1639   verifyFormat("while (true) {\n"
1640                "  f();\n"
1641                "}",
1642                AllowSimpleBracedStatements);
1643   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1644   verifyFormat("for (;;) {\n"
1645                "  f();\n"
1646                "}",
1647                AllowSimpleBracedStatements);
1648 
1649   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1650       FormatStyle::SIS_WithoutElse;
1651   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1652   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1653       FormatStyle::BWACS_Always;
1654 
1655   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1656   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1657   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1658   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1659   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1660   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1661   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1662   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1663   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1664   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1665   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1666   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1667   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1668   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1669   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1670   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1671   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1672                AllowSimpleBracedStatements);
1673   verifyFormat("if (true)\n"
1674                "{\n"
1675                "  ffffffffffffffffffffffff();\n"
1676                "}",
1677                AllowSimpleBracedStatements);
1678   verifyFormat("if (true)\n"
1679                "{\n"
1680                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1681                "}",
1682                AllowSimpleBracedStatements);
1683   verifyFormat("if (true)\n"
1684                "{ //\n"
1685                "  f();\n"
1686                "}",
1687                AllowSimpleBracedStatements);
1688   verifyFormat("if (true)\n"
1689                "{\n"
1690                "  f();\n"
1691                "  f();\n"
1692                "}",
1693                AllowSimpleBracedStatements);
1694   verifyFormat("if (true)\n"
1695                "{\n"
1696                "  f();\n"
1697                "} else\n"
1698                "{\n"
1699                "  f();\n"
1700                "}",
1701                AllowSimpleBracedStatements);
1702   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1703                AllowSimpleBracedStatements);
1704   verifyFormat("MYIF (true)\n"
1705                "{\n"
1706                "  ffffffffffffffffffffffff();\n"
1707                "}",
1708                AllowSimpleBracedStatements);
1709   verifyFormat("MYIF (true)\n"
1710                "{\n"
1711                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1712                "}",
1713                AllowSimpleBracedStatements);
1714   verifyFormat("MYIF (true)\n"
1715                "{ //\n"
1716                "  f();\n"
1717                "}",
1718                AllowSimpleBracedStatements);
1719   verifyFormat("MYIF (true)\n"
1720                "{\n"
1721                "  f();\n"
1722                "  f();\n"
1723                "}",
1724                AllowSimpleBracedStatements);
1725   verifyFormat("MYIF (true)\n"
1726                "{\n"
1727                "  f();\n"
1728                "} else\n"
1729                "{\n"
1730                "  f();\n"
1731                "}",
1732                AllowSimpleBracedStatements);
1733 
1734   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1735       FormatStyle::SIS_Never;
1736   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1737   verifyFormat("if (true)\n"
1738                "{\n"
1739                "  f();\n"
1740                "}",
1741                AllowSimpleBracedStatements);
1742   verifyFormat("if (true)\n"
1743                "{\n"
1744                "  f();\n"
1745                "} else\n"
1746                "{\n"
1747                "  f();\n"
1748                "}",
1749                AllowSimpleBracedStatements);
1750   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1751   verifyFormat("MYIF (true)\n"
1752                "{\n"
1753                "  f();\n"
1754                "}",
1755                AllowSimpleBracedStatements);
1756   verifyFormat("MYIF (true)\n"
1757                "{\n"
1758                "  f();\n"
1759                "} else\n"
1760                "{\n"
1761                "  f();\n"
1762                "}",
1763                AllowSimpleBracedStatements);
1764 
1765   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1766   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1767   verifyFormat("while (true)\n"
1768                "{\n"
1769                "  f();\n"
1770                "}",
1771                AllowSimpleBracedStatements);
1772   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1773   verifyFormat("for (;;)\n"
1774                "{\n"
1775                "  f();\n"
1776                "}",
1777                AllowSimpleBracedStatements);
1778 }
1779 
1780 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1781   FormatStyle Style = getLLVMStyleWithColumns(60);
1782   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1783   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1784   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1785   EXPECT_EQ("#define A                                                  \\\n"
1786             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1787             "  {                                                        \\\n"
1788             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1789             "  }\n"
1790             "X;",
1791             format("#define A \\\n"
1792                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1793                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1794                    "   }\n"
1795                    "X;",
1796                    Style));
1797 }
1798 
1799 TEST_F(FormatTest, ParseIfElse) {
1800   verifyFormat("if (true)\n"
1801                "  if (true)\n"
1802                "    if (true)\n"
1803                "      f();\n"
1804                "    else\n"
1805                "      g();\n"
1806                "  else\n"
1807                "    h();\n"
1808                "else\n"
1809                "  i();");
1810   verifyFormat("if (true)\n"
1811                "  if (true)\n"
1812                "    if (true) {\n"
1813                "      if (true)\n"
1814                "        f();\n"
1815                "    } else {\n"
1816                "      g();\n"
1817                "    }\n"
1818                "  else\n"
1819                "    h();\n"
1820                "else {\n"
1821                "  i();\n"
1822                "}");
1823   verifyFormat("if (true)\n"
1824                "  if constexpr (true)\n"
1825                "    if (true) {\n"
1826                "      if constexpr (true)\n"
1827                "        f();\n"
1828                "    } else {\n"
1829                "      g();\n"
1830                "    }\n"
1831                "  else\n"
1832                "    h();\n"
1833                "else {\n"
1834                "  i();\n"
1835                "}");
1836   verifyFormat("if (true)\n"
1837                "  if CONSTEXPR (true)\n"
1838                "    if (true) {\n"
1839                "      if CONSTEXPR (true)\n"
1840                "        f();\n"
1841                "    } else {\n"
1842                "      g();\n"
1843                "    }\n"
1844                "  else\n"
1845                "    h();\n"
1846                "else {\n"
1847                "  i();\n"
1848                "}");
1849   verifyFormat("void f() {\n"
1850                "  if (a) {\n"
1851                "  } else {\n"
1852                "  }\n"
1853                "}");
1854 }
1855 
1856 TEST_F(FormatTest, ElseIf) {
1857   verifyFormat("if (a) {\n} else if (b) {\n}");
1858   verifyFormat("if (a)\n"
1859                "  f();\n"
1860                "else if (b)\n"
1861                "  g();\n"
1862                "else\n"
1863                "  h();");
1864   verifyFormat("if (a)\n"
1865                "  f();\n"
1866                "else // comment\n"
1867                "  if (b) {\n"
1868                "    g();\n"
1869                "    h();\n"
1870                "  }");
1871   verifyFormat("if constexpr (a)\n"
1872                "  f();\n"
1873                "else if constexpr (b)\n"
1874                "  g();\n"
1875                "else\n"
1876                "  h();");
1877   verifyFormat("if CONSTEXPR (a)\n"
1878                "  f();\n"
1879                "else if CONSTEXPR (b)\n"
1880                "  g();\n"
1881                "else\n"
1882                "  h();");
1883   verifyFormat("if (a) {\n"
1884                "  f();\n"
1885                "}\n"
1886                "// or else ..\n"
1887                "else {\n"
1888                "  g()\n"
1889                "}");
1890 
1891   verifyFormat("if (a) {\n"
1892                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1893                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1894                "}");
1895   verifyFormat("if (a) {\n"
1896                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1897                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1898                "}");
1899   verifyFormat("if (a) {\n"
1900                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1901                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1902                "}");
1903   verifyFormat("if (a) {\n"
1904                "} else if (\n"
1905                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1906                "}",
1907                getLLVMStyleWithColumns(62));
1908   verifyFormat("if (a) {\n"
1909                "} else if constexpr (\n"
1910                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1911                "}",
1912                getLLVMStyleWithColumns(62));
1913   verifyFormat("if (a) {\n"
1914                "} else if CONSTEXPR (\n"
1915                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1916                "}",
1917                getLLVMStyleWithColumns(62));
1918 }
1919 
1920 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
1921   FormatStyle Style = getLLVMStyle();
1922   // Check first the default LLVM style
1923   // Style.PointerAlignment = FormatStyle::PAS_Right;
1924   // Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1925   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
1926   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
1927   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
1928   verifyFormat("int *f1(int &a) const &;", Style);
1929   verifyFormat("int *f1(int &a) const & = 0;", Style);
1930   verifyFormat("int *a = f1();", Style);
1931   verifyFormat("int &b = f2();", Style);
1932   verifyFormat("int &&c = f3();", Style);
1933   verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
1934   verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
1935   verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
1936   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
1937   verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
1938   verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
1939   verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
1940   verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
1941   verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
1942   verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
1943   verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
1944   verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
1945   verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
1946   verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
1947   verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
1948   verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
1949 
1950   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1951   verifyFormat("Const unsigned int *c;\n"
1952                "const unsigned int *d;\n"
1953                "Const unsigned int &e;\n"
1954                "const unsigned int &f;\n"
1955                "const unsigned    &&g;\n"
1956                "Const unsigned      h;",
1957                Style);
1958 
1959   Style.PointerAlignment = FormatStyle::PAS_Left;
1960   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1961   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
1962   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
1963   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
1964   verifyFormat("int* f1(int& a) const& = 0;", Style);
1965   verifyFormat("int* a = f1();", Style);
1966   verifyFormat("int& b = f2();", Style);
1967   verifyFormat("int&& c = f3();", Style);
1968   verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
1969   verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
1970   verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
1971   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
1972   verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
1973   verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
1974   verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
1975   verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
1976   verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
1977   verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
1978   verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
1979   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
1980   verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
1981   verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
1982   verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
1983   verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
1984   verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
1985   verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
1986 
1987   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1988   verifyFormat("Const unsigned int* c;\n"
1989                "const unsigned int* d;\n"
1990                "Const unsigned int& e;\n"
1991                "const unsigned int& f;\n"
1992                "const unsigned&&    g;\n"
1993                "Const unsigned      h;",
1994                Style);
1995 
1996   Style.PointerAlignment = FormatStyle::PAS_Right;
1997   Style.ReferenceAlignment = FormatStyle::RAS_Left;
1998   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
1999   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
2000   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
2001   verifyFormat("int *a = f1();", Style);
2002   verifyFormat("int& b = f2();", Style);
2003   verifyFormat("int&& c = f3();", Style);
2004   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2005   verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2006   verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
2007 
2008   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2009   verifyFormat("Const unsigned int *c;\n"
2010                "const unsigned int *d;\n"
2011                "Const unsigned int& e;\n"
2012                "const unsigned int& f;\n"
2013                "const unsigned      g;\n"
2014                "Const unsigned      h;",
2015                Style);
2016 
2017   Style.PointerAlignment = FormatStyle::PAS_Left;
2018   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
2019   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
2020   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
2021   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
2022   verifyFormat("int* a = f1();", Style);
2023   verifyFormat("int & b = f2();", Style);
2024   verifyFormat("int && c = f3();", Style);
2025   verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
2026   verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
2027   verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
2028   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2029   verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
2030   verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
2031   verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
2032   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2033   verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
2034   verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
2035   verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
2036   verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
2037   verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
2038   verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
2039 
2040   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2041   verifyFormat("Const unsigned int*  c;\n"
2042                "const unsigned int*  d;\n"
2043                "Const unsigned int & e;\n"
2044                "const unsigned int & f;\n"
2045                "const unsigned &&    g;\n"
2046                "Const unsigned       h;",
2047                Style);
2048 
2049   Style.PointerAlignment = FormatStyle::PAS_Middle;
2050   Style.ReferenceAlignment = FormatStyle::RAS_Right;
2051   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
2052   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
2053   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
2054   verifyFormat("int * a = f1();", Style);
2055   verifyFormat("int &b = f2();", Style);
2056   verifyFormat("int &&c = f3();", Style);
2057   verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2058   verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2059   verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
2060 
2061   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2062   // specifically handled
2063   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2064 }
2065 
2066 TEST_F(FormatTest, FormatsForLoop) {
2067   verifyFormat(
2068       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2069       "     ++VeryVeryLongLoopVariable)\n"
2070       "  ;");
2071   verifyFormat("for (;;)\n"
2072                "  f();");
2073   verifyFormat("for (;;) {\n}");
2074   verifyFormat("for (;;) {\n"
2075                "  f();\n"
2076                "}");
2077   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2078 
2079   verifyFormat(
2080       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2081       "                                          E = UnwrappedLines.end();\n"
2082       "     I != E; ++I) {\n}");
2083 
2084   verifyFormat(
2085       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2086       "     ++IIIII) {\n}");
2087   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2088                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2089                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2090   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2091                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2092                "         E = FD->getDeclsInPrototypeScope().end();\n"
2093                "     I != E; ++I) {\n}");
2094   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2095                "         I = Container.begin(),\n"
2096                "         E = Container.end();\n"
2097                "     I != E; ++I) {\n}",
2098                getLLVMStyleWithColumns(76));
2099 
2100   verifyFormat(
2101       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2102       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2103       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2104       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2105       "     ++aaaaaaaaaaa) {\n}");
2106   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2107                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2108                "     ++i) {\n}");
2109   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2110                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2111                "}");
2112   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2113                "         aaaaaaaaaa);\n"
2114                "     iter; ++iter) {\n"
2115                "}");
2116   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2117                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2118                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2119                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2120 
2121   // These should not be formatted as Objective-C for-in loops.
2122   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2123   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2124   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2125   verifyFormat(
2126       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2127 
2128   FormatStyle NoBinPacking = getLLVMStyle();
2129   NoBinPacking.BinPackParameters = false;
2130   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2131                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2132                "                                           aaaaaaaaaaaaaaaa,\n"
2133                "                                           aaaaaaaaaaaaaaaa,\n"
2134                "                                           aaaaaaaaaaaaaaaa);\n"
2135                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2136                "}",
2137                NoBinPacking);
2138   verifyFormat(
2139       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2140       "                                          E = UnwrappedLines.end();\n"
2141       "     I != E;\n"
2142       "     ++I) {\n}",
2143       NoBinPacking);
2144 
2145   FormatStyle AlignLeft = getLLVMStyle();
2146   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2147   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2148 }
2149 
2150 TEST_F(FormatTest, RangeBasedForLoops) {
2151   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2152                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2153   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2154                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2155   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2156                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2157   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2158                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2159 }
2160 
2161 TEST_F(FormatTest, ForEachLoops) {
2162   verifyFormat("void f() {\n"
2163                "  foreach (Item *item, itemlist) {}\n"
2164                "  Q_FOREACH (Item *item, itemlist) {}\n"
2165                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
2166                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2167                "}");
2168 
2169   FormatStyle Style = getLLVMStyle();
2170   Style.SpaceBeforeParens =
2171       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2172   verifyFormat("void f() {\n"
2173                "  foreach(Item *item, itemlist) {}\n"
2174                "  Q_FOREACH(Item *item, itemlist) {}\n"
2175                "  BOOST_FOREACH(Item *item, itemlist) {}\n"
2176                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2177                "}",
2178                Style);
2179 
2180   // As function-like macros.
2181   verifyFormat("#define foreach(x, y)\n"
2182                "#define Q_FOREACH(x, y)\n"
2183                "#define BOOST_FOREACH(x, y)\n"
2184                "#define UNKNOWN_FOREACH(x, y)\n");
2185 
2186   // Not as function-like macros.
2187   verifyFormat("#define foreach (x, y)\n"
2188                "#define Q_FOREACH (x, y)\n"
2189                "#define BOOST_FOREACH (x, y)\n"
2190                "#define UNKNOWN_FOREACH (x, y)\n");
2191 
2192   // handle microsoft non standard extension
2193   verifyFormat("for each (char c in x->MyStringProperty)");
2194 }
2195 
2196 TEST_F(FormatTest, FormatsWhileLoop) {
2197   verifyFormat("while (true) {\n}");
2198   verifyFormat("while (true)\n"
2199                "  f();");
2200   verifyFormat("while () {\n}");
2201   verifyFormat("while () {\n"
2202                "  f();\n"
2203                "}");
2204 }
2205 
2206 TEST_F(FormatTest, FormatsDoWhile) {
2207   verifyFormat("do {\n"
2208                "  do_something();\n"
2209                "} while (something());");
2210   verifyFormat("do\n"
2211                "  do_something();\n"
2212                "while (something());");
2213 }
2214 
2215 TEST_F(FormatTest, FormatsSwitchStatement) {
2216   verifyFormat("switch (x) {\n"
2217                "case 1:\n"
2218                "  f();\n"
2219                "  break;\n"
2220                "case kFoo:\n"
2221                "case ns::kBar:\n"
2222                "case kBaz:\n"
2223                "  break;\n"
2224                "default:\n"
2225                "  g();\n"
2226                "  break;\n"
2227                "}");
2228   verifyFormat("switch (x) {\n"
2229                "case 1: {\n"
2230                "  f();\n"
2231                "  break;\n"
2232                "}\n"
2233                "case 2: {\n"
2234                "  break;\n"
2235                "}\n"
2236                "}");
2237   verifyFormat("switch (x) {\n"
2238                "case 1: {\n"
2239                "  f();\n"
2240                "  {\n"
2241                "    g();\n"
2242                "    h();\n"
2243                "  }\n"
2244                "  break;\n"
2245                "}\n"
2246                "}");
2247   verifyFormat("switch (x) {\n"
2248                "case 1: {\n"
2249                "  f();\n"
2250                "  if (foo) {\n"
2251                "    g();\n"
2252                "    h();\n"
2253                "  }\n"
2254                "  break;\n"
2255                "}\n"
2256                "}");
2257   verifyFormat("switch (x) {\n"
2258                "case 1: {\n"
2259                "  f();\n"
2260                "  g();\n"
2261                "} break;\n"
2262                "}");
2263   verifyFormat("switch (test)\n"
2264                "  ;");
2265   verifyFormat("switch (x) {\n"
2266                "default: {\n"
2267                "  // Do nothing.\n"
2268                "}\n"
2269                "}");
2270   verifyFormat("switch (x) {\n"
2271                "// comment\n"
2272                "// if 1, do f()\n"
2273                "case 1:\n"
2274                "  f();\n"
2275                "}");
2276   verifyFormat("switch (x) {\n"
2277                "case 1:\n"
2278                "  // Do amazing stuff\n"
2279                "  {\n"
2280                "    f();\n"
2281                "    g();\n"
2282                "  }\n"
2283                "  break;\n"
2284                "}");
2285   verifyFormat("#define A          \\\n"
2286                "  switch (x) {     \\\n"
2287                "  case a:          \\\n"
2288                "    foo = b;       \\\n"
2289                "  }",
2290                getLLVMStyleWithColumns(20));
2291   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2292                "  case OP_name:                        \\\n"
2293                "    return operations::Operation##name\n",
2294                getLLVMStyleWithColumns(40));
2295   verifyFormat("switch (x) {\n"
2296                "case 1:;\n"
2297                "default:;\n"
2298                "  int i;\n"
2299                "}");
2300 
2301   verifyGoogleFormat("switch (x) {\n"
2302                      "  case 1:\n"
2303                      "    f();\n"
2304                      "    break;\n"
2305                      "  case kFoo:\n"
2306                      "  case ns::kBar:\n"
2307                      "  case kBaz:\n"
2308                      "    break;\n"
2309                      "  default:\n"
2310                      "    g();\n"
2311                      "    break;\n"
2312                      "}");
2313   verifyGoogleFormat("switch (x) {\n"
2314                      "  case 1: {\n"
2315                      "    f();\n"
2316                      "    break;\n"
2317                      "  }\n"
2318                      "}");
2319   verifyGoogleFormat("switch (test)\n"
2320                      "  ;");
2321 
2322   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2323                      "  case OP_name:              \\\n"
2324                      "    return operations::Operation##name\n");
2325   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2326                      "  // Get the correction operation class.\n"
2327                      "  switch (OpCode) {\n"
2328                      "    CASE(Add);\n"
2329                      "    CASE(Subtract);\n"
2330                      "    default:\n"
2331                      "      return operations::Unknown;\n"
2332                      "  }\n"
2333                      "#undef OPERATION_CASE\n"
2334                      "}");
2335   verifyFormat("DEBUG({\n"
2336                "  switch (x) {\n"
2337                "  case A:\n"
2338                "    f();\n"
2339                "    break;\n"
2340                "    // fallthrough\n"
2341                "  case B:\n"
2342                "    g();\n"
2343                "    break;\n"
2344                "  }\n"
2345                "});");
2346   EXPECT_EQ("DEBUG({\n"
2347             "  switch (x) {\n"
2348             "  case A:\n"
2349             "    f();\n"
2350             "    break;\n"
2351             "  // On B:\n"
2352             "  case B:\n"
2353             "    g();\n"
2354             "    break;\n"
2355             "  }\n"
2356             "});",
2357             format("DEBUG({\n"
2358                    "  switch (x) {\n"
2359                    "  case A:\n"
2360                    "    f();\n"
2361                    "    break;\n"
2362                    "  // On B:\n"
2363                    "  case B:\n"
2364                    "    g();\n"
2365                    "    break;\n"
2366                    "  }\n"
2367                    "});",
2368                    getLLVMStyle()));
2369   EXPECT_EQ("switch (n) {\n"
2370             "case 0: {\n"
2371             "  return false;\n"
2372             "}\n"
2373             "default: {\n"
2374             "  return true;\n"
2375             "}\n"
2376             "}",
2377             format("switch (n)\n"
2378                    "{\n"
2379                    "case 0: {\n"
2380                    "  return false;\n"
2381                    "}\n"
2382                    "default: {\n"
2383                    "  return true;\n"
2384                    "}\n"
2385                    "}",
2386                    getLLVMStyle()));
2387   verifyFormat("switch (a) {\n"
2388                "case (b):\n"
2389                "  return;\n"
2390                "}");
2391 
2392   verifyFormat("switch (a) {\n"
2393                "case some_namespace::\n"
2394                "    some_constant:\n"
2395                "  return;\n"
2396                "}",
2397                getLLVMStyleWithColumns(34));
2398 
2399   FormatStyle Style = getLLVMStyle();
2400   Style.IndentCaseLabels = true;
2401   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2402   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2403   Style.BraceWrapping.AfterCaseLabel = true;
2404   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2405   EXPECT_EQ("switch (n)\n"
2406             "{\n"
2407             "  case 0:\n"
2408             "  {\n"
2409             "    return false;\n"
2410             "  }\n"
2411             "  default:\n"
2412             "  {\n"
2413             "    return true;\n"
2414             "  }\n"
2415             "}",
2416             format("switch (n) {\n"
2417                    "  case 0: {\n"
2418                    "    return false;\n"
2419                    "  }\n"
2420                    "  default: {\n"
2421                    "    return true;\n"
2422                    "  }\n"
2423                    "}",
2424                    Style));
2425   Style.BraceWrapping.AfterCaseLabel = false;
2426   EXPECT_EQ("switch (n)\n"
2427             "{\n"
2428             "  case 0: {\n"
2429             "    return false;\n"
2430             "  }\n"
2431             "  default: {\n"
2432             "    return true;\n"
2433             "  }\n"
2434             "}",
2435             format("switch (n) {\n"
2436                    "  case 0:\n"
2437                    "  {\n"
2438                    "    return false;\n"
2439                    "  }\n"
2440                    "  default:\n"
2441                    "  {\n"
2442                    "    return true;\n"
2443                    "  }\n"
2444                    "}",
2445                    Style));
2446   Style.IndentCaseLabels = false;
2447   Style.IndentCaseBlocks = true;
2448   EXPECT_EQ("switch (n)\n"
2449             "{\n"
2450             "case 0:\n"
2451             "  {\n"
2452             "    return false;\n"
2453             "  }\n"
2454             "case 1:\n"
2455             "  break;\n"
2456             "default:\n"
2457             "  {\n"
2458             "    return true;\n"
2459             "  }\n"
2460             "}",
2461             format("switch (n) {\n"
2462                    "case 0: {\n"
2463                    "  return false;\n"
2464                    "}\n"
2465                    "case 1:\n"
2466                    "  break;\n"
2467                    "default: {\n"
2468                    "  return true;\n"
2469                    "}\n"
2470                    "}",
2471                    Style));
2472   Style.IndentCaseLabels = true;
2473   Style.IndentCaseBlocks = true;
2474   EXPECT_EQ("switch (n)\n"
2475             "{\n"
2476             "  case 0:\n"
2477             "    {\n"
2478             "      return false;\n"
2479             "    }\n"
2480             "  case 1:\n"
2481             "    break;\n"
2482             "  default:\n"
2483             "    {\n"
2484             "      return true;\n"
2485             "    }\n"
2486             "}",
2487             format("switch (n) {\n"
2488                    "case 0: {\n"
2489                    "  return false;\n"
2490                    "}\n"
2491                    "case 1:\n"
2492                    "  break;\n"
2493                    "default: {\n"
2494                    "  return true;\n"
2495                    "}\n"
2496                    "}",
2497                    Style));
2498 }
2499 
2500 TEST_F(FormatTest, CaseRanges) {
2501   verifyFormat("switch (x) {\n"
2502                "case 'A' ... 'Z':\n"
2503                "case 1 ... 5:\n"
2504                "case a ... b:\n"
2505                "  break;\n"
2506                "}");
2507 }
2508 
2509 TEST_F(FormatTest, ShortEnums) {
2510   FormatStyle Style = getLLVMStyle();
2511   Style.AllowShortEnumsOnASingleLine = true;
2512   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2513   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2514   Style.AllowShortEnumsOnASingleLine = false;
2515   verifyFormat("enum {\n"
2516                "  A,\n"
2517                "  B,\n"
2518                "  C\n"
2519                "} ShortEnum1, ShortEnum2;",
2520                Style);
2521   verifyFormat("typedef enum {\n"
2522                "  A,\n"
2523                "  B,\n"
2524                "  C\n"
2525                "} ShortEnum1, ShortEnum2;",
2526                Style);
2527   verifyFormat("enum {\n"
2528                "  A,\n"
2529                "} ShortEnum1, ShortEnum2;",
2530                Style);
2531   verifyFormat("typedef enum {\n"
2532                "  A,\n"
2533                "} ShortEnum1, ShortEnum2;",
2534                Style);
2535   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2536   Style.BraceWrapping.AfterEnum = true;
2537   verifyFormat("enum\n"
2538                "{\n"
2539                "  A,\n"
2540                "  B,\n"
2541                "  C\n"
2542                "} ShortEnum1, ShortEnum2;",
2543                Style);
2544   verifyFormat("typedef enum\n"
2545                "{\n"
2546                "  A,\n"
2547                "  B,\n"
2548                "  C\n"
2549                "} ShortEnum1, ShortEnum2;",
2550                Style);
2551 }
2552 
2553 TEST_F(FormatTest, ShortCaseLabels) {
2554   FormatStyle Style = getLLVMStyle();
2555   Style.AllowShortCaseLabelsOnASingleLine = true;
2556   verifyFormat("switch (a) {\n"
2557                "case 1: x = 1; break;\n"
2558                "case 2: return;\n"
2559                "case 3:\n"
2560                "case 4:\n"
2561                "case 5: return;\n"
2562                "case 6: // comment\n"
2563                "  return;\n"
2564                "case 7:\n"
2565                "  // comment\n"
2566                "  return;\n"
2567                "case 8:\n"
2568                "  x = 8; // comment\n"
2569                "  break;\n"
2570                "default: y = 1; break;\n"
2571                "}",
2572                Style);
2573   verifyFormat("switch (a) {\n"
2574                "case 0: return; // comment\n"
2575                "case 1: break;  // comment\n"
2576                "case 2: return;\n"
2577                "// comment\n"
2578                "case 3: return;\n"
2579                "// comment 1\n"
2580                "// comment 2\n"
2581                "// comment 3\n"
2582                "case 4: break; /* comment */\n"
2583                "case 5:\n"
2584                "  // comment\n"
2585                "  break;\n"
2586                "case 6: /* comment */ x = 1; break;\n"
2587                "case 7: x = /* comment */ 1; break;\n"
2588                "case 8:\n"
2589                "  x = 1; /* comment */\n"
2590                "  break;\n"
2591                "case 9:\n"
2592                "  break; // comment line 1\n"
2593                "         // comment line 2\n"
2594                "}",
2595                Style);
2596   EXPECT_EQ("switch (a) {\n"
2597             "case 1:\n"
2598             "  x = 8;\n"
2599             "  // fall through\n"
2600             "case 2: x = 8;\n"
2601             "// comment\n"
2602             "case 3:\n"
2603             "  return; /* comment line 1\n"
2604             "           * comment line 2 */\n"
2605             "case 4: i = 8;\n"
2606             "// something else\n"
2607             "#if FOO\n"
2608             "case 5: break;\n"
2609             "#endif\n"
2610             "}",
2611             format("switch (a) {\n"
2612                    "case 1: x = 8;\n"
2613                    "  // fall through\n"
2614                    "case 2:\n"
2615                    "  x = 8;\n"
2616                    "// comment\n"
2617                    "case 3:\n"
2618                    "  return; /* comment line 1\n"
2619                    "           * comment line 2 */\n"
2620                    "case 4:\n"
2621                    "  i = 8;\n"
2622                    "// something else\n"
2623                    "#if FOO\n"
2624                    "case 5: break;\n"
2625                    "#endif\n"
2626                    "}",
2627                    Style));
2628   EXPECT_EQ("switch (a) {\n"
2629             "case 0:\n"
2630             "  return; // long long long long long long long long long long "
2631             "long long comment\n"
2632             "          // line\n"
2633             "}",
2634             format("switch (a) {\n"
2635                    "case 0: return; // long long long long long long long long "
2636                    "long long long long comment line\n"
2637                    "}",
2638                    Style));
2639   EXPECT_EQ("switch (a) {\n"
2640             "case 0:\n"
2641             "  return; /* long long long long long long long long long long "
2642             "long long comment\n"
2643             "             line */\n"
2644             "}",
2645             format("switch (a) {\n"
2646                    "case 0: return; /* long long long long long long long long "
2647                    "long long long long comment line */\n"
2648                    "}",
2649                    Style));
2650   verifyFormat("switch (a) {\n"
2651                "#if FOO\n"
2652                "case 0: return 0;\n"
2653                "#endif\n"
2654                "}",
2655                Style);
2656   verifyFormat("switch (a) {\n"
2657                "case 1: {\n"
2658                "}\n"
2659                "case 2: {\n"
2660                "  return;\n"
2661                "}\n"
2662                "case 3: {\n"
2663                "  x = 1;\n"
2664                "  return;\n"
2665                "}\n"
2666                "case 4:\n"
2667                "  if (x)\n"
2668                "    return;\n"
2669                "}",
2670                Style);
2671   Style.ColumnLimit = 21;
2672   verifyFormat("switch (a) {\n"
2673                "case 1: x = 1; break;\n"
2674                "case 2: return;\n"
2675                "case 3:\n"
2676                "case 4:\n"
2677                "case 5: return;\n"
2678                "default:\n"
2679                "  y = 1;\n"
2680                "  break;\n"
2681                "}",
2682                Style);
2683   Style.ColumnLimit = 80;
2684   Style.AllowShortCaseLabelsOnASingleLine = false;
2685   Style.IndentCaseLabels = true;
2686   EXPECT_EQ("switch (n) {\n"
2687             "  default /*comments*/:\n"
2688             "    return true;\n"
2689             "  case 0:\n"
2690             "    return false;\n"
2691             "}",
2692             format("switch (n) {\n"
2693                    "default/*comments*/:\n"
2694                    "  return true;\n"
2695                    "case 0:\n"
2696                    "  return false;\n"
2697                    "}",
2698                    Style));
2699   Style.AllowShortCaseLabelsOnASingleLine = true;
2700   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2701   Style.BraceWrapping.AfterCaseLabel = true;
2702   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2703   EXPECT_EQ("switch (n)\n"
2704             "{\n"
2705             "  case 0:\n"
2706             "  {\n"
2707             "    return false;\n"
2708             "  }\n"
2709             "  default:\n"
2710             "  {\n"
2711             "    return true;\n"
2712             "  }\n"
2713             "}",
2714             format("switch (n) {\n"
2715                    "  case 0: {\n"
2716                    "    return false;\n"
2717                    "  }\n"
2718                    "  default:\n"
2719                    "  {\n"
2720                    "    return true;\n"
2721                    "  }\n"
2722                    "}",
2723                    Style));
2724 }
2725 
2726 TEST_F(FormatTest, FormatsLabels) {
2727   verifyFormat("void f() {\n"
2728                "  some_code();\n"
2729                "test_label:\n"
2730                "  some_other_code();\n"
2731                "  {\n"
2732                "    some_more_code();\n"
2733                "  another_label:\n"
2734                "    some_more_code();\n"
2735                "  }\n"
2736                "}");
2737   verifyFormat("{\n"
2738                "  some_code();\n"
2739                "test_label:\n"
2740                "  some_other_code();\n"
2741                "}");
2742   verifyFormat("{\n"
2743                "  some_code();\n"
2744                "test_label:;\n"
2745                "  int i = 0;\n"
2746                "}");
2747   FormatStyle Style = getLLVMStyle();
2748   Style.IndentGotoLabels = false;
2749   verifyFormat("void f() {\n"
2750                "  some_code();\n"
2751                "test_label:\n"
2752                "  some_other_code();\n"
2753                "  {\n"
2754                "    some_more_code();\n"
2755                "another_label:\n"
2756                "    some_more_code();\n"
2757                "  }\n"
2758                "}",
2759                Style);
2760   verifyFormat("{\n"
2761                "  some_code();\n"
2762                "test_label:\n"
2763                "  some_other_code();\n"
2764                "}",
2765                Style);
2766   verifyFormat("{\n"
2767                "  some_code();\n"
2768                "test_label:;\n"
2769                "  int i = 0;\n"
2770                "}");
2771 }
2772 
2773 TEST_F(FormatTest, MultiLineControlStatements) {
2774   FormatStyle Style = getLLVMStyleWithColumns(20);
2775   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2776   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2777   // Short lines should keep opening brace on same line.
2778   EXPECT_EQ("if (foo) {\n"
2779             "  bar();\n"
2780             "}",
2781             format("if(foo){bar();}", Style));
2782   EXPECT_EQ("if (foo) {\n"
2783             "  bar();\n"
2784             "} else {\n"
2785             "  baz();\n"
2786             "}",
2787             format("if(foo){bar();}else{baz();}", Style));
2788   EXPECT_EQ("if (foo && bar) {\n"
2789             "  baz();\n"
2790             "}",
2791             format("if(foo&&bar){baz();}", Style));
2792   EXPECT_EQ("if (foo) {\n"
2793             "  bar();\n"
2794             "} else if (baz) {\n"
2795             "  quux();\n"
2796             "}",
2797             format("if(foo){bar();}else if(baz){quux();}", Style));
2798   EXPECT_EQ(
2799       "if (foo) {\n"
2800       "  bar();\n"
2801       "} else if (baz) {\n"
2802       "  quux();\n"
2803       "} else {\n"
2804       "  foobar();\n"
2805       "}",
2806       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
2807   EXPECT_EQ("for (;;) {\n"
2808             "  foo();\n"
2809             "}",
2810             format("for(;;){foo();}"));
2811   EXPECT_EQ("while (1) {\n"
2812             "  foo();\n"
2813             "}",
2814             format("while(1){foo();}", Style));
2815   EXPECT_EQ("switch (foo) {\n"
2816             "case bar:\n"
2817             "  return;\n"
2818             "}",
2819             format("switch(foo){case bar:return;}", Style));
2820   EXPECT_EQ("try {\n"
2821             "  foo();\n"
2822             "} catch (...) {\n"
2823             "  bar();\n"
2824             "}",
2825             format("try{foo();}catch(...){bar();}", Style));
2826   EXPECT_EQ("do {\n"
2827             "  foo();\n"
2828             "} while (bar &&\n"
2829             "         baz);",
2830             format("do{foo();}while(bar&&baz);", Style));
2831   // Long lines should put opening brace on new line.
2832   EXPECT_EQ("if (foo && bar &&\n"
2833             "    baz)\n"
2834             "{\n"
2835             "  quux();\n"
2836             "}",
2837             format("if(foo&&bar&&baz){quux();}", Style));
2838   EXPECT_EQ("if (foo && bar &&\n"
2839             "    baz)\n"
2840             "{\n"
2841             "  quux();\n"
2842             "}",
2843             format("if (foo && bar &&\n"
2844                    "    baz) {\n"
2845                    "  quux();\n"
2846                    "}",
2847                    Style));
2848   EXPECT_EQ("if (foo) {\n"
2849             "  bar();\n"
2850             "} else if (baz ||\n"
2851             "           quux)\n"
2852             "{\n"
2853             "  foobar();\n"
2854             "}",
2855             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
2856   EXPECT_EQ(
2857       "if (foo) {\n"
2858       "  bar();\n"
2859       "} else if (baz ||\n"
2860       "           quux)\n"
2861       "{\n"
2862       "  foobar();\n"
2863       "} else {\n"
2864       "  barbaz();\n"
2865       "}",
2866       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2867              Style));
2868   EXPECT_EQ("for (int i = 0;\n"
2869             "     i < 10; ++i)\n"
2870             "{\n"
2871             "  foo();\n"
2872             "}",
2873             format("for(int i=0;i<10;++i){foo();}", Style));
2874   EXPECT_EQ("foreach (int i,\n"
2875             "         list)\n"
2876             "{\n"
2877             "  foo();\n"
2878             "}",
2879             format("foreach(int i, list){foo();}", Style));
2880   Style.ColumnLimit =
2881       40; // to concentrate at brace wrapping, not line wrap due to column limit
2882   EXPECT_EQ("foreach (int i, list) {\n"
2883             "  foo();\n"
2884             "}",
2885             format("foreach(int i, list){foo();}", Style));
2886   Style.ColumnLimit =
2887       20; // to concentrate at brace wrapping, not line wrap due to column limit
2888   EXPECT_EQ("while (foo || bar ||\n"
2889             "       baz)\n"
2890             "{\n"
2891             "  quux();\n"
2892             "}",
2893             format("while(foo||bar||baz){quux();}", Style));
2894   EXPECT_EQ("switch (\n"
2895             "    foo = barbaz)\n"
2896             "{\n"
2897             "case quux:\n"
2898             "  return;\n"
2899             "}",
2900             format("switch(foo=barbaz){case quux:return;}", Style));
2901   EXPECT_EQ("try {\n"
2902             "  foo();\n"
2903             "} catch (\n"
2904             "    Exception &bar)\n"
2905             "{\n"
2906             "  baz();\n"
2907             "}",
2908             format("try{foo();}catch(Exception&bar){baz();}", Style));
2909   Style.ColumnLimit =
2910       40; // to concentrate at brace wrapping, not line wrap due to column limit
2911   EXPECT_EQ("try {\n"
2912             "  foo();\n"
2913             "} catch (Exception &bar) {\n"
2914             "  baz();\n"
2915             "}",
2916             format("try{foo();}catch(Exception&bar){baz();}", Style));
2917   Style.ColumnLimit =
2918       20; // to concentrate at brace wrapping, not line wrap due to column limit
2919 
2920   Style.BraceWrapping.BeforeElse = true;
2921   EXPECT_EQ(
2922       "if (foo) {\n"
2923       "  bar();\n"
2924       "}\n"
2925       "else if (baz ||\n"
2926       "         quux)\n"
2927       "{\n"
2928       "  foobar();\n"
2929       "}\n"
2930       "else {\n"
2931       "  barbaz();\n"
2932       "}",
2933       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2934              Style));
2935 
2936   Style.BraceWrapping.BeforeCatch = true;
2937   EXPECT_EQ("try {\n"
2938             "  foo();\n"
2939             "}\n"
2940             "catch (...) {\n"
2941             "  baz();\n"
2942             "}",
2943             format("try{foo();}catch(...){baz();}", Style));
2944 
2945   Style.BraceWrapping.AfterFunction = true;
2946   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2947   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
2948   Style.ColumnLimit = 80;
2949   verifyFormat("void shortfunction() { bar(); }", Style);
2950 
2951   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
2952   verifyFormat("void shortfunction()\n"
2953                "{\n"
2954                "  bar();\n"
2955                "}",
2956                Style);
2957 }
2958 
2959 TEST_F(FormatTest, BeforeWhile) {
2960   FormatStyle Style = getLLVMStyle();
2961   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2962 
2963   verifyFormat("do {\n"
2964                "  foo();\n"
2965                "} while (1);",
2966                Style);
2967   Style.BraceWrapping.BeforeWhile = true;
2968   verifyFormat("do {\n"
2969                "  foo();\n"
2970                "}\n"
2971                "while (1);",
2972                Style);
2973 }
2974 
2975 //===----------------------------------------------------------------------===//
2976 // Tests for classes, namespaces, etc.
2977 //===----------------------------------------------------------------------===//
2978 
2979 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
2980   verifyFormat("class A {};");
2981 }
2982 
2983 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
2984   verifyFormat("class A {\n"
2985                "public:\n"
2986                "public: // comment\n"
2987                "protected:\n"
2988                "private:\n"
2989                "  void f() {}\n"
2990                "};");
2991   verifyFormat("export class A {\n"
2992                "public:\n"
2993                "public: // comment\n"
2994                "protected:\n"
2995                "private:\n"
2996                "  void f() {}\n"
2997                "};");
2998   verifyGoogleFormat("class A {\n"
2999                      " public:\n"
3000                      " protected:\n"
3001                      " private:\n"
3002                      "  void f() {}\n"
3003                      "};");
3004   verifyGoogleFormat("export class A {\n"
3005                      " public:\n"
3006                      " protected:\n"
3007                      " private:\n"
3008                      "  void f() {}\n"
3009                      "};");
3010   verifyFormat("class A {\n"
3011                "public slots:\n"
3012                "  void f1() {}\n"
3013                "public Q_SLOTS:\n"
3014                "  void f2() {}\n"
3015                "protected slots:\n"
3016                "  void f3() {}\n"
3017                "protected Q_SLOTS:\n"
3018                "  void f4() {}\n"
3019                "private slots:\n"
3020                "  void f5() {}\n"
3021                "private Q_SLOTS:\n"
3022                "  void f6() {}\n"
3023                "signals:\n"
3024                "  void g1();\n"
3025                "Q_SIGNALS:\n"
3026                "  void g2();\n"
3027                "};");
3028 
3029   // Don't interpret 'signals' the wrong way.
3030   verifyFormat("signals.set();");
3031   verifyFormat("for (Signals signals : f()) {\n}");
3032   verifyFormat("{\n"
3033                "  signals.set(); // This needs indentation.\n"
3034                "}");
3035   verifyFormat("void f() {\n"
3036                "label:\n"
3037                "  signals.baz();\n"
3038                "}");
3039 }
3040 
3041 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3042   EXPECT_EQ("class A {\n"
3043             "public:\n"
3044             "  void f();\n"
3045             "\n"
3046             "private:\n"
3047             "  void g() {}\n"
3048             "  // test\n"
3049             "protected:\n"
3050             "  int h;\n"
3051             "};",
3052             format("class A {\n"
3053                    "public:\n"
3054                    "void f();\n"
3055                    "private:\n"
3056                    "void g() {}\n"
3057                    "// test\n"
3058                    "protected:\n"
3059                    "int h;\n"
3060                    "};"));
3061   EXPECT_EQ("class A {\n"
3062             "protected:\n"
3063             "public:\n"
3064             "  void f();\n"
3065             "};",
3066             format("class A {\n"
3067                    "protected:\n"
3068                    "\n"
3069                    "public:\n"
3070                    "\n"
3071                    "  void f();\n"
3072                    "};"));
3073 
3074   // Even ensure proper spacing inside macros.
3075   EXPECT_EQ("#define B     \\\n"
3076             "  class A {   \\\n"
3077             "   protected: \\\n"
3078             "   public:    \\\n"
3079             "    void f(); \\\n"
3080             "  };",
3081             format("#define B     \\\n"
3082                    "  class A {   \\\n"
3083                    "   protected: \\\n"
3084                    "              \\\n"
3085                    "   public:    \\\n"
3086                    "              \\\n"
3087                    "    void f(); \\\n"
3088                    "  };",
3089                    getGoogleStyle()));
3090   // But don't remove empty lines after macros ending in access specifiers.
3091   EXPECT_EQ("#define A private:\n"
3092             "\n"
3093             "int i;",
3094             format("#define A         private:\n"
3095                    "\n"
3096                    "int              i;"));
3097 }
3098 
3099 TEST_F(FormatTest, FormatsClasses) {
3100   verifyFormat("class A : public B {};");
3101   verifyFormat("class A : public ::B {};");
3102 
3103   verifyFormat(
3104       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3105       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3106   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3107                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3108                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3109   verifyFormat(
3110       "class A : public B, public C, public D, public E, public F {};");
3111   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3112                "                     public C,\n"
3113                "                     public D,\n"
3114                "                     public E,\n"
3115                "                     public F,\n"
3116                "                     public G {};");
3117 
3118   verifyFormat("class\n"
3119                "    ReallyReallyLongClassName {\n"
3120                "  int i;\n"
3121                "};",
3122                getLLVMStyleWithColumns(32));
3123   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3124                "                           aaaaaaaaaaaaaaaa> {};");
3125   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3126                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3127                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3128   verifyFormat("template <class R, class C>\n"
3129                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3130                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3131   verifyFormat("class ::A::B {};");
3132 }
3133 
3134 TEST_F(FormatTest, BreakInheritanceStyle) {
3135   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3136   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3137       FormatStyle::BILS_BeforeComma;
3138   verifyFormat("class MyClass : public X {};",
3139                StyleWithInheritanceBreakBeforeComma);
3140   verifyFormat("class MyClass\n"
3141                "    : public X\n"
3142                "    , public Y {};",
3143                StyleWithInheritanceBreakBeforeComma);
3144   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3145                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3146                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3147                StyleWithInheritanceBreakBeforeComma);
3148   verifyFormat("struct aaaaaaaaaaaaa\n"
3149                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3150                "          aaaaaaaaaaaaaaaa> {};",
3151                StyleWithInheritanceBreakBeforeComma);
3152 
3153   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3154   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3155       FormatStyle::BILS_AfterColon;
3156   verifyFormat("class MyClass : public X {};",
3157                StyleWithInheritanceBreakAfterColon);
3158   verifyFormat("class MyClass : public X, public Y {};",
3159                StyleWithInheritanceBreakAfterColon);
3160   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3161                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3162                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3163                StyleWithInheritanceBreakAfterColon);
3164   verifyFormat("struct aaaaaaaaaaaaa :\n"
3165                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3166                "        aaaaaaaaaaaaaaaa> {};",
3167                StyleWithInheritanceBreakAfterColon);
3168 
3169   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3170   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3171       FormatStyle::BILS_AfterComma;
3172   verifyFormat("class MyClass : public X {};",
3173                StyleWithInheritanceBreakAfterComma);
3174   verifyFormat("class MyClass : public X,\n"
3175                "                public Y {};",
3176                StyleWithInheritanceBreakAfterComma);
3177   verifyFormat(
3178       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3179       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3180       "{};",
3181       StyleWithInheritanceBreakAfterComma);
3182   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3183                "                           aaaaaaaaaaaaaaaa> {};",
3184                StyleWithInheritanceBreakAfterComma);
3185   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3186                "    : public OnceBreak,\n"
3187                "      public AlwaysBreak,\n"
3188                "      EvenBasesFitInOneLine {};",
3189                StyleWithInheritanceBreakAfterComma);
3190 }
3191 
3192 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
3193   verifyFormat("class A {\n} a, b;");
3194   verifyFormat("struct A {\n} a, b;");
3195   verifyFormat("union A {\n} a;");
3196 }
3197 
3198 TEST_F(FormatTest, FormatsEnum) {
3199   verifyFormat("enum {\n"
3200                "  Zero,\n"
3201                "  One = 1,\n"
3202                "  Two = One + 1,\n"
3203                "  Three = (One + Two),\n"
3204                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3205                "  Five = (One, Two, Three, Four, 5)\n"
3206                "};");
3207   verifyGoogleFormat("enum {\n"
3208                      "  Zero,\n"
3209                      "  One = 1,\n"
3210                      "  Two = One + 1,\n"
3211                      "  Three = (One + Two),\n"
3212                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3213                      "  Five = (One, Two, Three, Four, 5)\n"
3214                      "};");
3215   verifyFormat("enum Enum {};");
3216   verifyFormat("enum {};");
3217   verifyFormat("enum X E {} d;");
3218   verifyFormat("enum __attribute__((...)) E {} d;");
3219   verifyFormat("enum __declspec__((...)) E {} d;");
3220   verifyFormat("enum {\n"
3221                "  Bar = Foo<int, int>::value\n"
3222                "};",
3223                getLLVMStyleWithColumns(30));
3224 
3225   verifyFormat("enum ShortEnum { A, B, C };");
3226   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3227 
3228   EXPECT_EQ("enum KeepEmptyLines {\n"
3229             "  ONE,\n"
3230             "\n"
3231             "  TWO,\n"
3232             "\n"
3233             "  THREE\n"
3234             "}",
3235             format("enum KeepEmptyLines {\n"
3236                    "  ONE,\n"
3237                    "\n"
3238                    "  TWO,\n"
3239                    "\n"
3240                    "\n"
3241                    "  THREE\n"
3242                    "}"));
3243   verifyFormat("enum E { // comment\n"
3244                "  ONE,\n"
3245                "  TWO\n"
3246                "};\n"
3247                "int i;");
3248 
3249   FormatStyle EightIndent = getLLVMStyle();
3250   EightIndent.IndentWidth = 8;
3251   verifyFormat("enum {\n"
3252                "        VOID,\n"
3253                "        CHAR,\n"
3254                "        SHORT,\n"
3255                "        INT,\n"
3256                "        LONG,\n"
3257                "        SIGNED,\n"
3258                "        UNSIGNED,\n"
3259                "        BOOL,\n"
3260                "        FLOAT,\n"
3261                "        DOUBLE,\n"
3262                "        COMPLEX\n"
3263                "};",
3264                EightIndent);
3265 
3266   // Not enums.
3267   verifyFormat("enum X f() {\n"
3268                "  a();\n"
3269                "  return 42;\n"
3270                "}");
3271   verifyFormat("enum X Type::f() {\n"
3272                "  a();\n"
3273                "  return 42;\n"
3274                "}");
3275   verifyFormat("enum ::X f() {\n"
3276                "  a();\n"
3277                "  return 42;\n"
3278                "}");
3279   verifyFormat("enum ns::X f() {\n"
3280                "  a();\n"
3281                "  return 42;\n"
3282                "}");
3283 }
3284 
3285 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3286   verifyFormat("enum Type {\n"
3287                "  One = 0; // These semicolons should be commas.\n"
3288                "  Two = 1;\n"
3289                "};");
3290   verifyFormat("namespace n {\n"
3291                "enum Type {\n"
3292                "  One,\n"
3293                "  Two, // missing };\n"
3294                "  int i;\n"
3295                "}\n"
3296                "void g() {}");
3297 }
3298 
3299 TEST_F(FormatTest, FormatsEnumStruct) {
3300   verifyFormat("enum struct {\n"
3301                "  Zero,\n"
3302                "  One = 1,\n"
3303                "  Two = One + 1,\n"
3304                "  Three = (One + Two),\n"
3305                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3306                "  Five = (One, Two, Three, Four, 5)\n"
3307                "};");
3308   verifyFormat("enum struct Enum {};");
3309   verifyFormat("enum struct {};");
3310   verifyFormat("enum struct X E {} d;");
3311   verifyFormat("enum struct __attribute__((...)) E {} d;");
3312   verifyFormat("enum struct __declspec__((...)) E {} d;");
3313   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3314 }
3315 
3316 TEST_F(FormatTest, FormatsEnumClass) {
3317   verifyFormat("enum class {\n"
3318                "  Zero,\n"
3319                "  One = 1,\n"
3320                "  Two = One + 1,\n"
3321                "  Three = (One + Two),\n"
3322                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3323                "  Five = (One, Two, Three, Four, 5)\n"
3324                "};");
3325   verifyFormat("enum class Enum {};");
3326   verifyFormat("enum class {};");
3327   verifyFormat("enum class X E {} d;");
3328   verifyFormat("enum class __attribute__((...)) E {} d;");
3329   verifyFormat("enum class __declspec__((...)) E {} d;");
3330   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3331 }
3332 
3333 TEST_F(FormatTest, FormatsEnumTypes) {
3334   verifyFormat("enum X : int {\n"
3335                "  A, // Force multiple lines.\n"
3336                "  B\n"
3337                "};");
3338   verifyFormat("enum X : int { A, B };");
3339   verifyFormat("enum X : std::uint32_t { A, B };");
3340 }
3341 
3342 TEST_F(FormatTest, FormatsTypedefEnum) {
3343   FormatStyle Style = getLLVMStyleWithColumns(40);
3344   verifyFormat("typedef enum {} EmptyEnum;");
3345   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3346   verifyFormat("typedef enum {\n"
3347                "  ZERO = 0,\n"
3348                "  ONE = 1,\n"
3349                "  TWO = 2,\n"
3350                "  THREE = 3\n"
3351                "} LongEnum;",
3352                Style);
3353   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3354   Style.BraceWrapping.AfterEnum = true;
3355   verifyFormat("typedef enum {} EmptyEnum;");
3356   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3357   verifyFormat("typedef enum\n"
3358                "{\n"
3359                "  ZERO = 0,\n"
3360                "  ONE = 1,\n"
3361                "  TWO = 2,\n"
3362                "  THREE = 3\n"
3363                "} LongEnum;",
3364                Style);
3365 }
3366 
3367 TEST_F(FormatTest, FormatsNSEnums) {
3368   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3369   verifyGoogleFormat(
3370       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3371   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3372                      "  // Information about someDecentlyLongValue.\n"
3373                      "  someDecentlyLongValue,\n"
3374                      "  // Information about anotherDecentlyLongValue.\n"
3375                      "  anotherDecentlyLongValue,\n"
3376                      "  // Information about aThirdDecentlyLongValue.\n"
3377                      "  aThirdDecentlyLongValue\n"
3378                      "};");
3379   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3380                      "  // Information about someDecentlyLongValue.\n"
3381                      "  someDecentlyLongValue,\n"
3382                      "  // Information about anotherDecentlyLongValue.\n"
3383                      "  anotherDecentlyLongValue,\n"
3384                      "  // Information about aThirdDecentlyLongValue.\n"
3385                      "  aThirdDecentlyLongValue\n"
3386                      "};");
3387   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3388                      "  a = 1,\n"
3389                      "  b = 2,\n"
3390                      "  c = 3,\n"
3391                      "};");
3392   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3393                      "  a = 1,\n"
3394                      "  b = 2,\n"
3395                      "  c = 3,\n"
3396                      "};");
3397   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3398                      "  a = 1,\n"
3399                      "  b = 2,\n"
3400                      "  c = 3,\n"
3401                      "};");
3402   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3403                      "  a = 1,\n"
3404                      "  b = 2,\n"
3405                      "  c = 3,\n"
3406                      "};");
3407 }
3408 
3409 TEST_F(FormatTest, FormatsBitfields) {
3410   verifyFormat("struct Bitfields {\n"
3411                "  unsigned sClass : 8;\n"
3412                "  unsigned ValueKind : 2;\n"
3413                "};");
3414   verifyFormat("struct A {\n"
3415                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3416                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3417                "};");
3418   verifyFormat("struct MyStruct {\n"
3419                "  uchar data;\n"
3420                "  uchar : 8;\n"
3421                "  uchar : 8;\n"
3422                "  uchar other;\n"
3423                "};");
3424   FormatStyle Style = getLLVMStyle();
3425   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3426   verifyFormat("struct Bitfields {\n"
3427                "  unsigned sClass:8;\n"
3428                "  unsigned ValueKind:2;\n"
3429                "  uchar other;\n"
3430                "};",
3431                Style);
3432   verifyFormat("struct A {\n"
3433                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3434                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3435                "};",
3436                Style);
3437   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3438   verifyFormat("struct Bitfields {\n"
3439                "  unsigned sClass :8;\n"
3440                "  unsigned ValueKind :2;\n"
3441                "  uchar other;\n"
3442                "};",
3443                Style);
3444   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3445   verifyFormat("struct Bitfields {\n"
3446                "  unsigned sClass: 8;\n"
3447                "  unsigned ValueKind: 2;\n"
3448                "  uchar other;\n"
3449                "};",
3450                Style);
3451 }
3452 
3453 TEST_F(FormatTest, FormatsNamespaces) {
3454   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3455   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3456 
3457   verifyFormat("namespace some_namespace {\n"
3458                "class A {};\n"
3459                "void f() { f(); }\n"
3460                "}",
3461                LLVMWithNoNamespaceFix);
3462   verifyFormat("namespace N::inline D {\n"
3463                "class A {};\n"
3464                "void f() { f(); }\n"
3465                "}",
3466                LLVMWithNoNamespaceFix);
3467   verifyFormat("namespace N::inline D::E {\n"
3468                "class A {};\n"
3469                "void f() { f(); }\n"
3470                "}",
3471                LLVMWithNoNamespaceFix);
3472   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3473                "class A {};\n"
3474                "void f() { f(); }\n"
3475                "}",
3476                LLVMWithNoNamespaceFix);
3477   verifyFormat("/* something */ namespace some_namespace {\n"
3478                "class A {};\n"
3479                "void f() { f(); }\n"
3480                "}",
3481                LLVMWithNoNamespaceFix);
3482   verifyFormat("namespace {\n"
3483                "class A {};\n"
3484                "void f() { f(); }\n"
3485                "}",
3486                LLVMWithNoNamespaceFix);
3487   verifyFormat("/* something */ namespace {\n"
3488                "class A {};\n"
3489                "void f() { f(); }\n"
3490                "}",
3491                LLVMWithNoNamespaceFix);
3492   verifyFormat("inline namespace X {\n"
3493                "class A {};\n"
3494                "void f() { f(); }\n"
3495                "}",
3496                LLVMWithNoNamespaceFix);
3497   verifyFormat("/* something */ inline namespace X {\n"
3498                "class A {};\n"
3499                "void f() { f(); }\n"
3500                "}",
3501                LLVMWithNoNamespaceFix);
3502   verifyFormat("export namespace X {\n"
3503                "class A {};\n"
3504                "void f() { f(); }\n"
3505                "}",
3506                LLVMWithNoNamespaceFix);
3507   verifyFormat("using namespace some_namespace;\n"
3508                "class A {};\n"
3509                "void f() { f(); }",
3510                LLVMWithNoNamespaceFix);
3511 
3512   // This code is more common than we thought; if we
3513   // layout this correctly the semicolon will go into
3514   // its own line, which is undesirable.
3515   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3516   verifyFormat("namespace {\n"
3517                "class A {};\n"
3518                "};",
3519                LLVMWithNoNamespaceFix);
3520 
3521   verifyFormat("namespace {\n"
3522                "int SomeVariable = 0; // comment\n"
3523                "} // namespace",
3524                LLVMWithNoNamespaceFix);
3525   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3526             "#define HEADER_GUARD\n"
3527             "namespace my_namespace {\n"
3528             "int i;\n"
3529             "} // my_namespace\n"
3530             "#endif // HEADER_GUARD",
3531             format("#ifndef HEADER_GUARD\n"
3532                    " #define HEADER_GUARD\n"
3533                    "   namespace my_namespace {\n"
3534                    "int i;\n"
3535                    "}    // my_namespace\n"
3536                    "#endif    // HEADER_GUARD",
3537                    LLVMWithNoNamespaceFix));
3538 
3539   EXPECT_EQ("namespace A::B {\n"
3540             "class C {};\n"
3541             "}",
3542             format("namespace A::B {\n"
3543                    "class C {};\n"
3544                    "}",
3545                    LLVMWithNoNamespaceFix));
3546 
3547   FormatStyle Style = getLLVMStyle();
3548   Style.NamespaceIndentation = FormatStyle::NI_All;
3549   EXPECT_EQ("namespace out {\n"
3550             "  int i;\n"
3551             "  namespace in {\n"
3552             "    int i;\n"
3553             "  } // namespace in\n"
3554             "} // namespace out",
3555             format("namespace out {\n"
3556                    "int i;\n"
3557                    "namespace in {\n"
3558                    "int i;\n"
3559                    "} // namespace in\n"
3560                    "} // namespace out",
3561                    Style));
3562 
3563   FormatStyle ShortInlineFunctions = getLLVMStyle();
3564   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3565   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3566       FormatStyle::SFS_Inline;
3567   verifyFormat("namespace {\n"
3568                "  void f() {\n"
3569                "    return;\n"
3570                "  }\n"
3571                "} // namespace\n",
3572                ShortInlineFunctions);
3573   verifyFormat("namespace {\n"
3574                "  int some_int;\n"
3575                "  void f() {\n"
3576                "    return;\n"
3577                "  }\n"
3578                "} // namespace\n",
3579                ShortInlineFunctions);
3580   verifyFormat("namespace interface {\n"
3581                "  void f() {\n"
3582                "    return;\n"
3583                "  }\n"
3584                "} // namespace interface\n",
3585                ShortInlineFunctions);
3586   verifyFormat("namespace {\n"
3587                "  class X {\n"
3588                "    void f() { return; }\n"
3589                "  };\n"
3590                "} // namespace\n",
3591                ShortInlineFunctions);
3592   verifyFormat("namespace {\n"
3593                "  struct X {\n"
3594                "    void f() { return; }\n"
3595                "  };\n"
3596                "} // namespace\n",
3597                ShortInlineFunctions);
3598   verifyFormat("namespace {\n"
3599                "  union X {\n"
3600                "    void f() { return; }\n"
3601                "  };\n"
3602                "} // namespace\n",
3603                ShortInlineFunctions);
3604   verifyFormat("extern \"C\" {\n"
3605                "void f() {\n"
3606                "  return;\n"
3607                "}\n"
3608                "} // namespace\n",
3609                ShortInlineFunctions);
3610   verifyFormat("namespace {\n"
3611                "  class X {\n"
3612                "    void f() { return; }\n"
3613                "  } x;\n"
3614                "} // namespace\n",
3615                ShortInlineFunctions);
3616   verifyFormat("namespace {\n"
3617                "  [[nodiscard]] class X {\n"
3618                "    void f() { return; }\n"
3619                "  };\n"
3620                "} // namespace\n",
3621                ShortInlineFunctions);
3622   verifyFormat("namespace {\n"
3623                "  static class X {\n"
3624                "    void f() { return; }\n"
3625                "  } x;\n"
3626                "} // namespace\n",
3627                ShortInlineFunctions);
3628   verifyFormat("namespace {\n"
3629                "  constexpr class X {\n"
3630                "    void f() { return; }\n"
3631                "  } x;\n"
3632                "} // namespace\n",
3633                ShortInlineFunctions);
3634 
3635   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
3636   verifyFormat("extern \"C\" {\n"
3637                "  void f() {\n"
3638                "    return;\n"
3639                "  }\n"
3640                "} // namespace\n",
3641                ShortInlineFunctions);
3642 
3643   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3644   EXPECT_EQ("namespace out {\n"
3645             "int i;\n"
3646             "namespace in {\n"
3647             "  int i;\n"
3648             "} // namespace in\n"
3649             "} // namespace out",
3650             format("namespace out {\n"
3651                    "int i;\n"
3652                    "namespace in {\n"
3653                    "int i;\n"
3654                    "} // namespace in\n"
3655                    "} // namespace out",
3656                    Style));
3657 
3658   Style.NamespaceIndentation = FormatStyle::NI_None;
3659   verifyFormat("template <class T>\n"
3660                "concept a_concept = X<>;\n"
3661                "namespace B {\n"
3662                "struct b_struct {};\n"
3663                "} // namespace B\n",
3664                Style);
3665   verifyFormat("template <int I> constexpr void foo requires(I == 42) {}\n"
3666                "namespace ns {\n"
3667                "void foo() {}\n"
3668                "} // namespace ns\n",
3669                Style);
3670 }
3671 
3672 TEST_F(FormatTest, NamespaceMacros) {
3673   FormatStyle Style = getLLVMStyle();
3674   Style.NamespaceMacros.push_back("TESTSUITE");
3675 
3676   verifyFormat("TESTSUITE(A) {\n"
3677                "int foo();\n"
3678                "} // TESTSUITE(A)",
3679                Style);
3680 
3681   verifyFormat("TESTSUITE(A, B) {\n"
3682                "int foo();\n"
3683                "} // TESTSUITE(A)",
3684                Style);
3685 
3686   // Properly indent according to NamespaceIndentation style
3687   Style.NamespaceIndentation = FormatStyle::NI_All;
3688   verifyFormat("TESTSUITE(A) {\n"
3689                "  int foo();\n"
3690                "} // TESTSUITE(A)",
3691                Style);
3692   verifyFormat("TESTSUITE(A) {\n"
3693                "  namespace B {\n"
3694                "    int foo();\n"
3695                "  } // namespace B\n"
3696                "} // TESTSUITE(A)",
3697                Style);
3698   verifyFormat("namespace A {\n"
3699                "  TESTSUITE(B) {\n"
3700                "    int foo();\n"
3701                "  } // TESTSUITE(B)\n"
3702                "} // namespace A",
3703                Style);
3704 
3705   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3706   verifyFormat("TESTSUITE(A) {\n"
3707                "TESTSUITE(B) {\n"
3708                "  int foo();\n"
3709                "} // TESTSUITE(B)\n"
3710                "} // TESTSUITE(A)",
3711                Style);
3712   verifyFormat("TESTSUITE(A) {\n"
3713                "namespace B {\n"
3714                "  int foo();\n"
3715                "} // namespace B\n"
3716                "} // TESTSUITE(A)",
3717                Style);
3718   verifyFormat("namespace A {\n"
3719                "TESTSUITE(B) {\n"
3720                "  int foo();\n"
3721                "} // TESTSUITE(B)\n"
3722                "} // namespace A",
3723                Style);
3724 
3725   // Properly merge namespace-macros blocks in CompactNamespaces mode
3726   Style.NamespaceIndentation = FormatStyle::NI_None;
3727   Style.CompactNamespaces = true;
3728   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
3729                "}} // TESTSUITE(A::B)",
3730                Style);
3731 
3732   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3733             "}} // TESTSUITE(out::in)",
3734             format("TESTSUITE(out) {\n"
3735                    "TESTSUITE(in) {\n"
3736                    "} // TESTSUITE(in)\n"
3737                    "} // TESTSUITE(out)",
3738                    Style));
3739 
3740   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3741             "}} // TESTSUITE(out::in)",
3742             format("TESTSUITE(out) {\n"
3743                    "TESTSUITE(in) {\n"
3744                    "} // TESTSUITE(in)\n"
3745                    "} // TESTSUITE(out)",
3746                    Style));
3747 
3748   // Do not merge different namespaces/macros
3749   EXPECT_EQ("namespace out {\n"
3750             "TESTSUITE(in) {\n"
3751             "} // TESTSUITE(in)\n"
3752             "} // namespace out",
3753             format("namespace out {\n"
3754                    "TESTSUITE(in) {\n"
3755                    "} // TESTSUITE(in)\n"
3756                    "} // namespace out",
3757                    Style));
3758   EXPECT_EQ("TESTSUITE(out) {\n"
3759             "namespace in {\n"
3760             "} // namespace in\n"
3761             "} // TESTSUITE(out)",
3762             format("TESTSUITE(out) {\n"
3763                    "namespace in {\n"
3764                    "} // namespace in\n"
3765                    "} // TESTSUITE(out)",
3766                    Style));
3767   Style.NamespaceMacros.push_back("FOOBAR");
3768   EXPECT_EQ("TESTSUITE(out) {\n"
3769             "FOOBAR(in) {\n"
3770             "} // FOOBAR(in)\n"
3771             "} // TESTSUITE(out)",
3772             format("TESTSUITE(out) {\n"
3773                    "FOOBAR(in) {\n"
3774                    "} // FOOBAR(in)\n"
3775                    "} // TESTSUITE(out)",
3776                    Style));
3777 }
3778 
3779 TEST_F(FormatTest, FormatsCompactNamespaces) {
3780   FormatStyle Style = getLLVMStyle();
3781   Style.CompactNamespaces = true;
3782   Style.NamespaceMacros.push_back("TESTSUITE");
3783 
3784   verifyFormat("namespace A { namespace B {\n"
3785                "}} // namespace A::B",
3786                Style);
3787 
3788   EXPECT_EQ("namespace out { namespace in {\n"
3789             "}} // namespace out::in",
3790             format("namespace out {\n"
3791                    "namespace in {\n"
3792                    "} // namespace in\n"
3793                    "} // namespace out",
3794                    Style));
3795 
3796   // Only namespaces which have both consecutive opening and end get compacted
3797   EXPECT_EQ("namespace out {\n"
3798             "namespace in1 {\n"
3799             "} // namespace in1\n"
3800             "namespace in2 {\n"
3801             "} // namespace in2\n"
3802             "} // namespace out",
3803             format("namespace out {\n"
3804                    "namespace in1 {\n"
3805                    "} // namespace in1\n"
3806                    "namespace in2 {\n"
3807                    "} // namespace in2\n"
3808                    "} // namespace out",
3809                    Style));
3810 
3811   EXPECT_EQ("namespace out {\n"
3812             "int i;\n"
3813             "namespace in {\n"
3814             "int j;\n"
3815             "} // namespace in\n"
3816             "int k;\n"
3817             "} // namespace out",
3818             format("namespace out { int i;\n"
3819                    "namespace in { int j; } // namespace in\n"
3820                    "int k; } // namespace out",
3821                    Style));
3822 
3823   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
3824             "}}} // namespace A::B::C\n",
3825             format("namespace A { namespace B {\n"
3826                    "namespace C {\n"
3827                    "}} // namespace B::C\n"
3828                    "} // namespace A\n",
3829                    Style));
3830 
3831   Style.ColumnLimit = 40;
3832   EXPECT_EQ("namespace aaaaaaaaaa {\n"
3833             "namespace bbbbbbbbbb {\n"
3834             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
3835             format("namespace aaaaaaaaaa {\n"
3836                    "namespace bbbbbbbbbb {\n"
3837                    "} // namespace bbbbbbbbbb\n"
3838                    "} // namespace aaaaaaaaaa",
3839                    Style));
3840 
3841   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
3842             "namespace cccccc {\n"
3843             "}}} // namespace aaaaaa::bbbbbb::cccccc",
3844             format("namespace aaaaaa {\n"
3845                    "namespace bbbbbb {\n"
3846                    "namespace cccccc {\n"
3847                    "} // namespace cccccc\n"
3848                    "} // namespace bbbbbb\n"
3849                    "} // namespace aaaaaa",
3850                    Style));
3851   Style.ColumnLimit = 80;
3852 
3853   // Extra semicolon after 'inner' closing brace prevents merging
3854   EXPECT_EQ("namespace out { namespace in {\n"
3855             "}; } // namespace out::in",
3856             format("namespace out {\n"
3857                    "namespace in {\n"
3858                    "}; // namespace in\n"
3859                    "} // namespace out",
3860                    Style));
3861 
3862   // Extra semicolon after 'outer' closing brace is conserved
3863   EXPECT_EQ("namespace out { namespace in {\n"
3864             "}}; // namespace out::in",
3865             format("namespace out {\n"
3866                    "namespace in {\n"
3867                    "} // namespace in\n"
3868                    "}; // namespace out",
3869                    Style));
3870 
3871   Style.NamespaceIndentation = FormatStyle::NI_All;
3872   EXPECT_EQ("namespace out { namespace in {\n"
3873             "  int i;\n"
3874             "}} // namespace out::in",
3875             format("namespace out {\n"
3876                    "namespace in {\n"
3877                    "int i;\n"
3878                    "} // namespace in\n"
3879                    "} // namespace out",
3880                    Style));
3881   EXPECT_EQ("namespace out { namespace mid {\n"
3882             "  namespace in {\n"
3883             "    int j;\n"
3884             "  } // namespace in\n"
3885             "  int k;\n"
3886             "}} // namespace out::mid",
3887             format("namespace out { namespace mid {\n"
3888                    "namespace in { int j; } // namespace in\n"
3889                    "int k; }} // namespace out::mid",
3890                    Style));
3891 
3892   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3893   EXPECT_EQ("namespace out { namespace in {\n"
3894             "  int i;\n"
3895             "}} // namespace out::in",
3896             format("namespace out {\n"
3897                    "namespace in {\n"
3898                    "int i;\n"
3899                    "} // namespace in\n"
3900                    "} // namespace out",
3901                    Style));
3902   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
3903             "  int i;\n"
3904             "}}} // namespace out::mid::in",
3905             format("namespace out {\n"
3906                    "namespace mid {\n"
3907                    "namespace in {\n"
3908                    "int i;\n"
3909                    "} // namespace in\n"
3910                    "} // namespace mid\n"
3911                    "} // namespace out",
3912                    Style));
3913 
3914   Style.CompactNamespaces = true;
3915   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
3916   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3917   Style.BraceWrapping.BeforeLambdaBody = true;
3918   verifyFormat("namespace out { namespace in {\n"
3919                "}} // namespace out::in",
3920                Style);
3921   EXPECT_EQ("namespace out { namespace in {\n"
3922             "}} // namespace out::in",
3923             format("namespace out {\n"
3924                    "namespace in {\n"
3925                    "} // namespace in\n"
3926                    "} // namespace out",
3927                    Style));
3928 }
3929 
3930 TEST_F(FormatTest, FormatsExternC) {
3931   verifyFormat("extern \"C\" {\nint a;");
3932   verifyFormat("extern \"C\" {}");
3933   verifyFormat("extern \"C\" {\n"
3934                "int foo();\n"
3935                "}");
3936   verifyFormat("extern \"C\" int foo() {}");
3937   verifyFormat("extern \"C\" int foo();");
3938   verifyFormat("extern \"C\" int foo() {\n"
3939                "  int i = 42;\n"
3940                "  return i;\n"
3941                "}");
3942 
3943   FormatStyle Style = getLLVMStyle();
3944   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3945   Style.BraceWrapping.AfterFunction = true;
3946   verifyFormat("extern \"C\" int foo() {}", Style);
3947   verifyFormat("extern \"C\" int foo();", Style);
3948   verifyFormat("extern \"C\" int foo()\n"
3949                "{\n"
3950                "  int i = 42;\n"
3951                "  return i;\n"
3952                "}",
3953                Style);
3954 
3955   Style.BraceWrapping.AfterExternBlock = true;
3956   Style.BraceWrapping.SplitEmptyRecord = false;
3957   verifyFormat("extern \"C\"\n"
3958                "{}",
3959                Style);
3960   verifyFormat("extern \"C\"\n"
3961                "{\n"
3962                "  int foo();\n"
3963                "}",
3964                Style);
3965 }
3966 
3967 TEST_F(FormatTest, IndentExternBlockStyle) {
3968   FormatStyle Style = getLLVMStyle();
3969   Style.IndentWidth = 2;
3970 
3971   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
3972   verifyFormat("extern \"C\" { /*9*/\n"
3973                "}",
3974                Style);
3975   verifyFormat("extern \"C\" {\n"
3976                "  int foo10();\n"
3977                "}",
3978                Style);
3979 
3980   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
3981   verifyFormat("extern \"C\" { /*11*/\n"
3982                "}",
3983                Style);
3984   verifyFormat("extern \"C\" {\n"
3985                "int foo12();\n"
3986                "}",
3987                Style);
3988 
3989   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3990   Style.BraceWrapping.AfterExternBlock = true;
3991   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
3992   verifyFormat("extern \"C\"\n"
3993                "{ /*13*/\n"
3994                "}",
3995                Style);
3996   verifyFormat("extern \"C\"\n{\n"
3997                "  int foo14();\n"
3998                "}",
3999                Style);
4000 
4001   Style.BraceWrapping.AfterExternBlock = false;
4002   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4003   verifyFormat("extern \"C\" { /*15*/\n"
4004                "}",
4005                Style);
4006   verifyFormat("extern \"C\" {\n"
4007                "int foo16();\n"
4008                "}",
4009                Style);
4010 
4011   Style.BraceWrapping.AfterExternBlock = true;
4012   verifyFormat("extern \"C\"\n"
4013                "{ /*13*/\n"
4014                "}",
4015                Style);
4016   verifyFormat("extern \"C\"\n"
4017                "{\n"
4018                "int foo14();\n"
4019                "}",
4020                Style);
4021 
4022   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4023   verifyFormat("extern \"C\"\n"
4024                "{ /*13*/\n"
4025                "}",
4026                Style);
4027   verifyFormat("extern \"C\"\n"
4028                "{\n"
4029                "  int foo14();\n"
4030                "}",
4031                Style);
4032 }
4033 
4034 TEST_F(FormatTest, FormatsInlineASM) {
4035   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4036   verifyFormat("asm(\"nop\" ::: \"memory\");");
4037   verifyFormat(
4038       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4039       "    \"cpuid\\n\\t\"\n"
4040       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4041       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4042       "    : \"a\"(value));");
4043   EXPECT_EQ(
4044       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4045       "  __asm {\n"
4046       "        mov     edx,[that] // vtable in edx\n"
4047       "        mov     eax,methodIndex\n"
4048       "        call    [edx][eax*4] // stdcall\n"
4049       "  }\n"
4050       "}",
4051       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4052              "    __asm {\n"
4053              "        mov     edx,[that] // vtable in edx\n"
4054              "        mov     eax,methodIndex\n"
4055              "        call    [edx][eax*4] // stdcall\n"
4056              "    }\n"
4057              "}"));
4058   EXPECT_EQ("_asm {\n"
4059             "  xor eax, eax;\n"
4060             "  cpuid;\n"
4061             "}",
4062             format("_asm {\n"
4063                    "  xor eax, eax;\n"
4064                    "  cpuid;\n"
4065                    "}"));
4066   verifyFormat("void function() {\n"
4067                "  // comment\n"
4068                "  asm(\"\");\n"
4069                "}");
4070   EXPECT_EQ("__asm {\n"
4071             "}\n"
4072             "int i;",
4073             format("__asm   {\n"
4074                    "}\n"
4075                    "int   i;"));
4076 }
4077 
4078 TEST_F(FormatTest, FormatTryCatch) {
4079   verifyFormat("try {\n"
4080                "  throw a * b;\n"
4081                "} catch (int a) {\n"
4082                "  // Do nothing.\n"
4083                "} catch (...) {\n"
4084                "  exit(42);\n"
4085                "}");
4086 
4087   // Function-level try statements.
4088   verifyFormat("int f() try { return 4; } catch (...) {\n"
4089                "  return 5;\n"
4090                "}");
4091   verifyFormat("class A {\n"
4092                "  int a;\n"
4093                "  A() try : a(0) {\n"
4094                "  } catch (...) {\n"
4095                "    throw;\n"
4096                "  }\n"
4097                "};\n");
4098   verifyFormat("class A {\n"
4099                "  int a;\n"
4100                "  A() try : a(0), b{1} {\n"
4101                "  } catch (...) {\n"
4102                "    throw;\n"
4103                "  }\n"
4104                "};\n");
4105   verifyFormat("class A {\n"
4106                "  int a;\n"
4107                "  A() try : a(0), b{1}, c{2} {\n"
4108                "  } catch (...) {\n"
4109                "    throw;\n"
4110                "  }\n"
4111                "};\n");
4112   verifyFormat("class A {\n"
4113                "  int a;\n"
4114                "  A() try : a(0), b{1}, c{2} {\n"
4115                "    { // New scope.\n"
4116                "    }\n"
4117                "  } catch (...) {\n"
4118                "    throw;\n"
4119                "  }\n"
4120                "};\n");
4121 
4122   // Incomplete try-catch blocks.
4123   verifyIncompleteFormat("try {} catch (");
4124 }
4125 
4126 TEST_F(FormatTest, FormatTryAsAVariable) {
4127   verifyFormat("int try;");
4128   verifyFormat("int try, size;");
4129   verifyFormat("try = foo();");
4130   verifyFormat("if (try < size) {\n  return true;\n}");
4131 
4132   verifyFormat("int catch;");
4133   verifyFormat("int catch, size;");
4134   verifyFormat("catch = foo();");
4135   verifyFormat("if (catch < size) {\n  return true;\n}");
4136 
4137   FormatStyle Style = getLLVMStyle();
4138   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4139   Style.BraceWrapping.AfterFunction = true;
4140   Style.BraceWrapping.BeforeCatch = true;
4141   verifyFormat("try {\n"
4142                "  int bar = 1;\n"
4143                "}\n"
4144                "catch (...) {\n"
4145                "  int bar = 1;\n"
4146                "}",
4147                Style);
4148   verifyFormat("#if NO_EX\n"
4149                "try\n"
4150                "#endif\n"
4151                "{\n"
4152                "}\n"
4153                "#if NO_EX\n"
4154                "catch (...) {\n"
4155                "}",
4156                Style);
4157   verifyFormat("try /* abc */ {\n"
4158                "  int bar = 1;\n"
4159                "}\n"
4160                "catch (...) {\n"
4161                "  int bar = 1;\n"
4162                "}",
4163                Style);
4164   verifyFormat("try\n"
4165                "// abc\n"
4166                "{\n"
4167                "  int bar = 1;\n"
4168                "}\n"
4169                "catch (...) {\n"
4170                "  int bar = 1;\n"
4171                "}",
4172                Style);
4173 }
4174 
4175 TEST_F(FormatTest, FormatSEHTryCatch) {
4176   verifyFormat("__try {\n"
4177                "  int a = b * c;\n"
4178                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4179                "  // Do nothing.\n"
4180                "}");
4181 
4182   verifyFormat("__try {\n"
4183                "  int a = b * c;\n"
4184                "} __finally {\n"
4185                "  // Do nothing.\n"
4186                "}");
4187 
4188   verifyFormat("DEBUG({\n"
4189                "  __try {\n"
4190                "  } __finally {\n"
4191                "  }\n"
4192                "});\n");
4193 }
4194 
4195 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4196   verifyFormat("try {\n"
4197                "  f();\n"
4198                "} catch {\n"
4199                "  g();\n"
4200                "}");
4201   verifyFormat("try {\n"
4202                "  f();\n"
4203                "} catch (A a) MACRO(x) {\n"
4204                "  g();\n"
4205                "} catch (B b) MACRO(x) {\n"
4206                "  g();\n"
4207                "}");
4208 }
4209 
4210 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4211   FormatStyle Style = getLLVMStyle();
4212   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4213                           FormatStyle::BS_WebKit}) {
4214     Style.BreakBeforeBraces = BraceStyle;
4215     verifyFormat("try {\n"
4216                  "  // something\n"
4217                  "} catch (...) {\n"
4218                  "  // something\n"
4219                  "}",
4220                  Style);
4221   }
4222   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4223   verifyFormat("try {\n"
4224                "  // something\n"
4225                "}\n"
4226                "catch (...) {\n"
4227                "  // something\n"
4228                "}",
4229                Style);
4230   verifyFormat("__try {\n"
4231                "  // something\n"
4232                "}\n"
4233                "__finally {\n"
4234                "  // something\n"
4235                "}",
4236                Style);
4237   verifyFormat("@try {\n"
4238                "  // something\n"
4239                "}\n"
4240                "@finally {\n"
4241                "  // something\n"
4242                "}",
4243                Style);
4244   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4245   verifyFormat("try\n"
4246                "{\n"
4247                "  // something\n"
4248                "}\n"
4249                "catch (...)\n"
4250                "{\n"
4251                "  // something\n"
4252                "}",
4253                Style);
4254   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4255   verifyFormat("try\n"
4256                "  {\n"
4257                "  // something white\n"
4258                "  }\n"
4259                "catch (...)\n"
4260                "  {\n"
4261                "  // something white\n"
4262                "  }",
4263                Style);
4264   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4265   verifyFormat("try\n"
4266                "  {\n"
4267                "    // something\n"
4268                "  }\n"
4269                "catch (...)\n"
4270                "  {\n"
4271                "    // something\n"
4272                "  }",
4273                Style);
4274   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4275   Style.BraceWrapping.BeforeCatch = true;
4276   verifyFormat("try {\n"
4277                "  // something\n"
4278                "}\n"
4279                "catch (...) {\n"
4280                "  // something\n"
4281                "}",
4282                Style);
4283 }
4284 
4285 TEST_F(FormatTest, StaticInitializers) {
4286   verifyFormat("static SomeClass SC = {1, 'a'};");
4287 
4288   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4289                "    100000000, "
4290                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4291 
4292   // Here, everything other than the "}" would fit on a line.
4293   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4294                "    10000000000000000000000000};");
4295   EXPECT_EQ("S s = {a,\n"
4296             "\n"
4297             "       b};",
4298             format("S s = {\n"
4299                    "  a,\n"
4300                    "\n"
4301                    "  b\n"
4302                    "};"));
4303 
4304   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4305   // line. However, the formatting looks a bit off and this probably doesn't
4306   // happen often in practice.
4307   verifyFormat("static int Variable[1] = {\n"
4308                "    {1000000000000000000000000000000000000}};",
4309                getLLVMStyleWithColumns(40));
4310 }
4311 
4312 TEST_F(FormatTest, DesignatedInitializers) {
4313   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4314   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4315                "                    .bbbbbbbbbb = 2,\n"
4316                "                    .cccccccccc = 3,\n"
4317                "                    .dddddddddd = 4,\n"
4318                "                    .eeeeeeeeee = 5};");
4319   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4320                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4321                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4322                "    .ccccccccccccccccccccccccccc = 3,\n"
4323                "    .ddddddddddddddddddddddddddd = 4,\n"
4324                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4325 
4326   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4327 
4328   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4329   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4330                "                    [2] = bbbbbbbbbb,\n"
4331                "                    [3] = cccccccccc,\n"
4332                "                    [4] = dddddddddd,\n"
4333                "                    [5] = eeeeeeeeee};");
4334   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4335                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4336                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4337                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4338                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4339                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4340 }
4341 
4342 TEST_F(FormatTest, NestedStaticInitializers) {
4343   verifyFormat("static A x = {{{}}};\n");
4344   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4345                "               {init1, init2, init3, init4}}};",
4346                getLLVMStyleWithColumns(50));
4347 
4348   verifyFormat("somes Status::global_reps[3] = {\n"
4349                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4350                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4351                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4352                getLLVMStyleWithColumns(60));
4353   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4354                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4355                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4356                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4357   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4358                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4359                "rect.fTop}};");
4360 
4361   verifyFormat(
4362       "SomeArrayOfSomeType a = {\n"
4363       "    {{1, 2, 3},\n"
4364       "     {1, 2, 3},\n"
4365       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4366       "      333333333333333333333333333333},\n"
4367       "     {1, 2, 3},\n"
4368       "     {1, 2, 3}}};");
4369   verifyFormat(
4370       "SomeArrayOfSomeType a = {\n"
4371       "    {{1, 2, 3}},\n"
4372       "    {{1, 2, 3}},\n"
4373       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4374       "      333333333333333333333333333333}},\n"
4375       "    {{1, 2, 3}},\n"
4376       "    {{1, 2, 3}}};");
4377 
4378   verifyFormat("struct {\n"
4379                "  unsigned bit;\n"
4380                "  const char *const name;\n"
4381                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4382                "                 {kOsWin, \"Windows\"},\n"
4383                "                 {kOsLinux, \"Linux\"},\n"
4384                "                 {kOsCrOS, \"Chrome OS\"}};");
4385   verifyFormat("struct {\n"
4386                "  unsigned bit;\n"
4387                "  const char *const name;\n"
4388                "} kBitsToOs[] = {\n"
4389                "    {kOsMac, \"Mac\"},\n"
4390                "    {kOsWin, \"Windows\"},\n"
4391                "    {kOsLinux, \"Linux\"},\n"
4392                "    {kOsCrOS, \"Chrome OS\"},\n"
4393                "};");
4394 }
4395 
4396 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4397   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4398                "                      \\\n"
4399                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4400 }
4401 
4402 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4403   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4404                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4405 
4406   // Do break defaulted and deleted functions.
4407   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4408                "    default;",
4409                getLLVMStyleWithColumns(40));
4410   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4411                "    delete;",
4412                getLLVMStyleWithColumns(40));
4413 }
4414 
4415 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4416   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4417                getLLVMStyleWithColumns(40));
4418   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4419                getLLVMStyleWithColumns(40));
4420   EXPECT_EQ("#define Q                              \\\n"
4421             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4422             "  \"aaaaaaaa.cpp\"",
4423             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4424                    getLLVMStyleWithColumns(40)));
4425 }
4426 
4427 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4428   EXPECT_EQ("# 123 \"A string literal\"",
4429             format("   #     123    \"A string literal\""));
4430 }
4431 
4432 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4433   EXPECT_EQ("#;", format("#;"));
4434   verifyFormat("#\n;\n;\n;");
4435 }
4436 
4437 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4438   EXPECT_EQ("#line 42 \"test\"\n",
4439             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4440   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4441                                     getLLVMStyleWithColumns(12)));
4442 }
4443 
4444 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4445   EXPECT_EQ("#line 42 \"test\"",
4446             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4447   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4448 }
4449 
4450 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4451   verifyFormat("#define A \\x20");
4452   verifyFormat("#define A \\ x20");
4453   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4454   verifyFormat("#define A ''");
4455   verifyFormat("#define A ''qqq");
4456   verifyFormat("#define A `qqq");
4457   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4458   EXPECT_EQ("const char *c = STRINGIFY(\n"
4459             "\\na : b);",
4460             format("const char * c = STRINGIFY(\n"
4461                    "\\na : b);"));
4462 
4463   verifyFormat("a\r\\");
4464   verifyFormat("a\v\\");
4465   verifyFormat("a\f\\");
4466 }
4467 
4468 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4469   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4470   style.IndentWidth = 4;
4471   style.PPIndentWidth = 1;
4472 
4473   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4474   verifyFormat("#ifdef __linux__\n"
4475                "void foo() {\n"
4476                "    int x = 0;\n"
4477                "}\n"
4478                "#define FOO\n"
4479                "#endif\n"
4480                "void bar() {\n"
4481                "    int y = 0;\n"
4482                "}\n",
4483                style);
4484 
4485   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4486   verifyFormat("#ifdef __linux__\n"
4487                "void foo() {\n"
4488                "    int x = 0;\n"
4489                "}\n"
4490                "# define FOO foo\n"
4491                "#endif\n"
4492                "void bar() {\n"
4493                "    int y = 0;\n"
4494                "}\n",
4495                style);
4496 
4497   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4498   verifyFormat("#ifdef __linux__\n"
4499                "void foo() {\n"
4500                "    int x = 0;\n"
4501                "}\n"
4502                " #define FOO foo\n"
4503                "#endif\n"
4504                "void bar() {\n"
4505                "    int y = 0;\n"
4506                "}\n",
4507                style);
4508 }
4509 
4510 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4511   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4512   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4513   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4514   // FIXME: We never break before the macro name.
4515   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4516 
4517   verifyFormat("#define A A\n#define A A");
4518   verifyFormat("#define A(X) A\n#define A A");
4519 
4520   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4521   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4522 }
4523 
4524 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4525   EXPECT_EQ("// somecomment\n"
4526             "#include \"a.h\"\n"
4527             "#define A(  \\\n"
4528             "    A, B)\n"
4529             "#include \"b.h\"\n"
4530             "// somecomment\n",
4531             format("  // somecomment\n"
4532                    "  #include \"a.h\"\n"
4533                    "#define A(A,\\\n"
4534                    "    B)\n"
4535                    "    #include \"b.h\"\n"
4536                    " // somecomment\n",
4537                    getLLVMStyleWithColumns(13)));
4538 }
4539 
4540 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4541 
4542 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4543   EXPECT_EQ("#define A    \\\n"
4544             "  c;         \\\n"
4545             "  e;\n"
4546             "f;",
4547             format("#define A c; e;\n"
4548                    "f;",
4549                    getLLVMStyleWithColumns(14)));
4550 }
4551 
4552 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4553 
4554 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4555   EXPECT_EQ("int x,\n"
4556             "#define A\n"
4557             "    y;",
4558             format("int x,\n#define A\ny;"));
4559 }
4560 
4561 TEST_F(FormatTest, HashInMacroDefinition) {
4562   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4563   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4564   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4565   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4566   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4567   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4568   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4569   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4570   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4571   verifyFormat("#define A  \\\n"
4572                "  {        \\\n"
4573                "    f(#c); \\\n"
4574                "  }",
4575                getLLVMStyleWithColumns(11));
4576 
4577   verifyFormat("#define A(X)         \\\n"
4578                "  void function##X()",
4579                getLLVMStyleWithColumns(22));
4580 
4581   verifyFormat("#define A(a, b, c)   \\\n"
4582                "  void a##b##c()",
4583                getLLVMStyleWithColumns(22));
4584 
4585   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4586 }
4587 
4588 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4589   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4590   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4591 
4592   FormatStyle Style = getLLVMStyle();
4593   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4594   verifyFormat("#define true ((foo)1)", Style);
4595   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4596   verifyFormat("#define false((foo)0)", Style);
4597 }
4598 
4599 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4600   EXPECT_EQ("#define A b;", format("#define A \\\n"
4601                                    "          \\\n"
4602                                    "  b;",
4603                                    getLLVMStyleWithColumns(25)));
4604   EXPECT_EQ("#define A \\\n"
4605             "          \\\n"
4606             "  a;      \\\n"
4607             "  b;",
4608             format("#define A \\\n"
4609                    "          \\\n"
4610                    "  a;      \\\n"
4611                    "  b;",
4612                    getLLVMStyleWithColumns(11)));
4613   EXPECT_EQ("#define A \\\n"
4614             "  a;      \\\n"
4615             "          \\\n"
4616             "  b;",
4617             format("#define A \\\n"
4618                    "  a;      \\\n"
4619                    "          \\\n"
4620                    "  b;",
4621                    getLLVMStyleWithColumns(11)));
4622 }
4623 
4624 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
4625   verifyIncompleteFormat("#define A :");
4626   verifyFormat("#define SOMECASES  \\\n"
4627                "  case 1:          \\\n"
4628                "  case 2\n",
4629                getLLVMStyleWithColumns(20));
4630   verifyFormat("#define MACRO(a) \\\n"
4631                "  if (a)         \\\n"
4632                "    f();         \\\n"
4633                "  else           \\\n"
4634                "    g()",
4635                getLLVMStyleWithColumns(18));
4636   verifyFormat("#define A template <typename T>");
4637   verifyIncompleteFormat("#define STR(x) #x\n"
4638                          "f(STR(this_is_a_string_literal{));");
4639   verifyFormat("#pragma omp threadprivate( \\\n"
4640                "    y)), // expected-warning",
4641                getLLVMStyleWithColumns(28));
4642   verifyFormat("#d, = };");
4643   verifyFormat("#if \"a");
4644   verifyIncompleteFormat("({\n"
4645                          "#define b     \\\n"
4646                          "  }           \\\n"
4647                          "  a\n"
4648                          "a",
4649                          getLLVMStyleWithColumns(15));
4650   verifyFormat("#define A     \\\n"
4651                "  {           \\\n"
4652                "    {\n"
4653                "#define B     \\\n"
4654                "  }           \\\n"
4655                "  }",
4656                getLLVMStyleWithColumns(15));
4657   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
4658   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
4659   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
4660   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
4661 }
4662 
4663 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
4664   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
4665   EXPECT_EQ("class A : public QObject {\n"
4666             "  Q_OBJECT\n"
4667             "\n"
4668             "  A() {}\n"
4669             "};",
4670             format("class A  :  public QObject {\n"
4671                    "     Q_OBJECT\n"
4672                    "\n"
4673                    "  A() {\n}\n"
4674                    "}  ;"));
4675   EXPECT_EQ("MACRO\n"
4676             "/*static*/ int i;",
4677             format("MACRO\n"
4678                    " /*static*/ int   i;"));
4679   EXPECT_EQ("SOME_MACRO\n"
4680             "namespace {\n"
4681             "void f();\n"
4682             "} // namespace",
4683             format("SOME_MACRO\n"
4684                    "  namespace    {\n"
4685                    "void   f(  );\n"
4686                    "} // namespace"));
4687   // Only if the identifier contains at least 5 characters.
4688   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
4689   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
4690   // Only if everything is upper case.
4691   EXPECT_EQ("class A : public QObject {\n"
4692             "  Q_Object A() {}\n"
4693             "};",
4694             format("class A  :  public QObject {\n"
4695                    "     Q_Object\n"
4696                    "  A() {\n}\n"
4697                    "}  ;"));
4698 
4699   // Only if the next line can actually start an unwrapped line.
4700   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
4701             format("SOME_WEIRD_LOG_MACRO\n"
4702                    "<< SomeThing;"));
4703 
4704   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
4705                "(n, buffers))\n",
4706                getChromiumStyle(FormatStyle::LK_Cpp));
4707 
4708   // See PR41483
4709   EXPECT_EQ("/**/ FOO(a)\n"
4710             "FOO(b)",
4711             format("/**/ FOO(a)\n"
4712                    "FOO(b)"));
4713 }
4714 
4715 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
4716   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4717             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4718             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4719             "class X {};\n"
4720             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4721             "int *createScopDetectionPass() { return 0; }",
4722             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4723                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4724                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4725                    "  class X {};\n"
4726                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4727                    "  int *createScopDetectionPass() { return 0; }"));
4728   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
4729   // braces, so that inner block is indented one level more.
4730   EXPECT_EQ("int q() {\n"
4731             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4732             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4733             "  IPC_END_MESSAGE_MAP()\n"
4734             "}",
4735             format("int q() {\n"
4736                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4737                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4738                    "  IPC_END_MESSAGE_MAP()\n"
4739                    "}"));
4740 
4741   // Same inside macros.
4742   EXPECT_EQ("#define LIST(L) \\\n"
4743             "  L(A)          \\\n"
4744             "  L(B)          \\\n"
4745             "  L(C)",
4746             format("#define LIST(L) \\\n"
4747                    "  L(A) \\\n"
4748                    "  L(B) \\\n"
4749                    "  L(C)",
4750                    getGoogleStyle()));
4751 
4752   // These must not be recognized as macros.
4753   EXPECT_EQ("int q() {\n"
4754             "  f(x);\n"
4755             "  f(x) {}\n"
4756             "  f(x)->g();\n"
4757             "  f(x)->*g();\n"
4758             "  f(x).g();\n"
4759             "  f(x) = x;\n"
4760             "  f(x) += x;\n"
4761             "  f(x) -= x;\n"
4762             "  f(x) *= x;\n"
4763             "  f(x) /= x;\n"
4764             "  f(x) %= x;\n"
4765             "  f(x) &= x;\n"
4766             "  f(x) |= x;\n"
4767             "  f(x) ^= x;\n"
4768             "  f(x) >>= x;\n"
4769             "  f(x) <<= x;\n"
4770             "  f(x)[y].z();\n"
4771             "  LOG(INFO) << x;\n"
4772             "  ifstream(x) >> x;\n"
4773             "}\n",
4774             format("int q() {\n"
4775                    "  f(x)\n;\n"
4776                    "  f(x)\n {}\n"
4777                    "  f(x)\n->g();\n"
4778                    "  f(x)\n->*g();\n"
4779                    "  f(x)\n.g();\n"
4780                    "  f(x)\n = x;\n"
4781                    "  f(x)\n += x;\n"
4782                    "  f(x)\n -= x;\n"
4783                    "  f(x)\n *= x;\n"
4784                    "  f(x)\n /= x;\n"
4785                    "  f(x)\n %= x;\n"
4786                    "  f(x)\n &= x;\n"
4787                    "  f(x)\n |= x;\n"
4788                    "  f(x)\n ^= x;\n"
4789                    "  f(x)\n >>= x;\n"
4790                    "  f(x)\n <<= x;\n"
4791                    "  f(x)\n[y].z();\n"
4792                    "  LOG(INFO)\n << x;\n"
4793                    "  ifstream(x)\n >> x;\n"
4794                    "}\n"));
4795   EXPECT_EQ("int q() {\n"
4796             "  F(x)\n"
4797             "  if (1) {\n"
4798             "  }\n"
4799             "  F(x)\n"
4800             "  while (1) {\n"
4801             "  }\n"
4802             "  F(x)\n"
4803             "  G(x);\n"
4804             "  F(x)\n"
4805             "  try {\n"
4806             "    Q();\n"
4807             "  } catch (...) {\n"
4808             "  }\n"
4809             "}\n",
4810             format("int q() {\n"
4811                    "F(x)\n"
4812                    "if (1) {}\n"
4813                    "F(x)\n"
4814                    "while (1) {}\n"
4815                    "F(x)\n"
4816                    "G(x);\n"
4817                    "F(x)\n"
4818                    "try { Q(); } catch (...) {}\n"
4819                    "}\n"));
4820   EXPECT_EQ("class A {\n"
4821             "  A() : t(0) {}\n"
4822             "  A(int i) noexcept() : {}\n"
4823             "  A(X x)\n" // FIXME: function-level try blocks are broken.
4824             "  try : t(0) {\n"
4825             "  } catch (...) {\n"
4826             "  }\n"
4827             "};",
4828             format("class A {\n"
4829                    "  A()\n : t(0) {}\n"
4830                    "  A(int i)\n noexcept() : {}\n"
4831                    "  A(X x)\n"
4832                    "  try : t(0) {} catch (...) {}\n"
4833                    "};"));
4834   FormatStyle Style = getLLVMStyle();
4835   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4836   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
4837   Style.BraceWrapping.AfterFunction = true;
4838   EXPECT_EQ("void f()\n"
4839             "try\n"
4840             "{\n"
4841             "}",
4842             format("void f() try {\n"
4843                    "}",
4844                    Style));
4845   EXPECT_EQ("class SomeClass {\n"
4846             "public:\n"
4847             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4848             "};",
4849             format("class SomeClass {\n"
4850                    "public:\n"
4851                    "  SomeClass()\n"
4852                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4853                    "};"));
4854   EXPECT_EQ("class SomeClass {\n"
4855             "public:\n"
4856             "  SomeClass()\n"
4857             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4858             "};",
4859             format("class SomeClass {\n"
4860                    "public:\n"
4861                    "  SomeClass()\n"
4862                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4863                    "};",
4864                    getLLVMStyleWithColumns(40)));
4865 
4866   verifyFormat("MACRO(>)");
4867 
4868   // Some macros contain an implicit semicolon.
4869   Style = getLLVMStyle();
4870   Style.StatementMacros.push_back("FOO");
4871   verifyFormat("FOO(a) int b = 0;");
4872   verifyFormat("FOO(a)\n"
4873                "int b = 0;",
4874                Style);
4875   verifyFormat("FOO(a);\n"
4876                "int b = 0;",
4877                Style);
4878   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
4879                "int b = 0;",
4880                Style);
4881   verifyFormat("FOO()\n"
4882                "int b = 0;",
4883                Style);
4884   verifyFormat("FOO\n"
4885                "int b = 0;",
4886                Style);
4887   verifyFormat("void f() {\n"
4888                "  FOO(a)\n"
4889                "  return a;\n"
4890                "}",
4891                Style);
4892   verifyFormat("FOO(a)\n"
4893                "FOO(b)",
4894                Style);
4895   verifyFormat("int a = 0;\n"
4896                "FOO(b)\n"
4897                "int c = 0;",
4898                Style);
4899   verifyFormat("int a = 0;\n"
4900                "int x = FOO(a)\n"
4901                "int b = 0;",
4902                Style);
4903   verifyFormat("void foo(int a) { FOO(a) }\n"
4904                "uint32_t bar() {}",
4905                Style);
4906 }
4907 
4908 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
4909   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
4910 
4911   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
4912                ZeroColumn);
4913 }
4914 
4915 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
4916   verifyFormat("#define A \\\n"
4917                "  f({     \\\n"
4918                "    g();  \\\n"
4919                "  });",
4920                getLLVMStyleWithColumns(11));
4921 }
4922 
4923 TEST_F(FormatTest, IndentPreprocessorDirectives) {
4924   FormatStyle Style = getLLVMStyleWithColumns(40);
4925   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
4926   verifyFormat("#ifdef _WIN32\n"
4927                "#define A 0\n"
4928                "#ifdef VAR2\n"
4929                "#define B 1\n"
4930                "#include <someheader.h>\n"
4931                "#define MACRO                          \\\n"
4932                "  some_very_long_func_aaaaaaaaaa();\n"
4933                "#endif\n"
4934                "#else\n"
4935                "#define A 1\n"
4936                "#endif",
4937                Style);
4938   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4939   verifyFormat("#ifdef _WIN32\n"
4940                "#  define A 0\n"
4941                "#  ifdef VAR2\n"
4942                "#    define B 1\n"
4943                "#    include <someheader.h>\n"
4944                "#    define MACRO                      \\\n"
4945                "      some_very_long_func_aaaaaaaaaa();\n"
4946                "#  endif\n"
4947                "#else\n"
4948                "#  define A 1\n"
4949                "#endif",
4950                Style);
4951   verifyFormat("#if A\n"
4952                "#  define MACRO                        \\\n"
4953                "    void a(int x) {                    \\\n"
4954                "      b();                             \\\n"
4955                "      c();                             \\\n"
4956                "      d();                             \\\n"
4957                "      e();                             \\\n"
4958                "      f();                             \\\n"
4959                "    }\n"
4960                "#endif",
4961                Style);
4962   // Comments before include guard.
4963   verifyFormat("// file comment\n"
4964                "// file comment\n"
4965                "#ifndef HEADER_H\n"
4966                "#define HEADER_H\n"
4967                "code();\n"
4968                "#endif",
4969                Style);
4970   // Test with include guards.
4971   verifyFormat("#ifndef HEADER_H\n"
4972                "#define HEADER_H\n"
4973                "code();\n"
4974                "#endif",
4975                Style);
4976   // Include guards must have a #define with the same variable immediately
4977   // after #ifndef.
4978   verifyFormat("#ifndef NOT_GUARD\n"
4979                "#  define FOO\n"
4980                "code();\n"
4981                "#endif",
4982                Style);
4983 
4984   // Include guards must cover the entire file.
4985   verifyFormat("code();\n"
4986                "code();\n"
4987                "#ifndef NOT_GUARD\n"
4988                "#  define NOT_GUARD\n"
4989                "code();\n"
4990                "#endif",
4991                Style);
4992   verifyFormat("#ifndef NOT_GUARD\n"
4993                "#  define NOT_GUARD\n"
4994                "code();\n"
4995                "#endif\n"
4996                "code();",
4997                Style);
4998   // Test with trailing blank lines.
4999   verifyFormat("#ifndef HEADER_H\n"
5000                "#define HEADER_H\n"
5001                "code();\n"
5002                "#endif\n",
5003                Style);
5004   // Include guards don't have #else.
5005   verifyFormat("#ifndef NOT_GUARD\n"
5006                "#  define NOT_GUARD\n"
5007                "code();\n"
5008                "#else\n"
5009                "#endif",
5010                Style);
5011   verifyFormat("#ifndef NOT_GUARD\n"
5012                "#  define NOT_GUARD\n"
5013                "code();\n"
5014                "#elif FOO\n"
5015                "#endif",
5016                Style);
5017   // Non-identifier #define after potential include guard.
5018   verifyFormat("#ifndef FOO\n"
5019                "#  define 1\n"
5020                "#endif\n",
5021                Style);
5022   // #if closes past last non-preprocessor line.
5023   verifyFormat("#ifndef FOO\n"
5024                "#define FOO\n"
5025                "#if 1\n"
5026                "int i;\n"
5027                "#  define A 0\n"
5028                "#endif\n"
5029                "#endif\n",
5030                Style);
5031   // Don't crash if there is an #elif directive without a condition.
5032   verifyFormat("#if 1\n"
5033                "int x;\n"
5034                "#elif\n"
5035                "int y;\n"
5036                "#else\n"
5037                "int z;\n"
5038                "#endif",
5039                Style);
5040   // FIXME: This doesn't handle the case where there's code between the
5041   // #ifndef and #define but all other conditions hold. This is because when
5042   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5043   // previous code line yet, so we can't detect it.
5044   EXPECT_EQ("#ifndef NOT_GUARD\n"
5045             "code();\n"
5046             "#define NOT_GUARD\n"
5047             "code();\n"
5048             "#endif",
5049             format("#ifndef NOT_GUARD\n"
5050                    "code();\n"
5051                    "#  define NOT_GUARD\n"
5052                    "code();\n"
5053                    "#endif",
5054                    Style));
5055   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5056   // be outside an include guard. Examples are #pragma once and
5057   // #pragma GCC diagnostic, or anything else that does not change the meaning
5058   // of the file if it's included multiple times.
5059   EXPECT_EQ("#ifdef WIN32\n"
5060             "#  pragma once\n"
5061             "#endif\n"
5062             "#ifndef HEADER_H\n"
5063             "#  define HEADER_H\n"
5064             "code();\n"
5065             "#endif",
5066             format("#ifdef WIN32\n"
5067                    "#  pragma once\n"
5068                    "#endif\n"
5069                    "#ifndef HEADER_H\n"
5070                    "#define HEADER_H\n"
5071                    "code();\n"
5072                    "#endif",
5073                    Style));
5074   // FIXME: This does not detect when there is a single non-preprocessor line
5075   // in front of an include-guard-like structure where other conditions hold
5076   // because ScopedLineState hides the line.
5077   EXPECT_EQ("code();\n"
5078             "#ifndef HEADER_H\n"
5079             "#define HEADER_H\n"
5080             "code();\n"
5081             "#endif",
5082             format("code();\n"
5083                    "#ifndef HEADER_H\n"
5084                    "#  define HEADER_H\n"
5085                    "code();\n"
5086                    "#endif",
5087                    Style));
5088   // Keep comments aligned with #, otherwise indent comments normally. These
5089   // tests cannot use verifyFormat because messUp manipulates leading
5090   // whitespace.
5091   {
5092     const char *Expected = ""
5093                            "void f() {\n"
5094                            "#if 1\n"
5095                            "// Preprocessor aligned.\n"
5096                            "#  define A 0\n"
5097                            "  // Code. Separated by blank line.\n"
5098                            "\n"
5099                            "#  define B 0\n"
5100                            "  // Code. Not aligned with #\n"
5101                            "#  define C 0\n"
5102                            "#endif";
5103     const char *ToFormat = ""
5104                            "void f() {\n"
5105                            "#if 1\n"
5106                            "// Preprocessor aligned.\n"
5107                            "#  define A 0\n"
5108                            "// Code. Separated by blank line.\n"
5109                            "\n"
5110                            "#  define B 0\n"
5111                            "   // Code. Not aligned with #\n"
5112                            "#  define C 0\n"
5113                            "#endif";
5114     EXPECT_EQ(Expected, format(ToFormat, Style));
5115     EXPECT_EQ(Expected, format(Expected, Style));
5116   }
5117   // Keep block quotes aligned.
5118   {
5119     const char *Expected = ""
5120                            "void f() {\n"
5121                            "#if 1\n"
5122                            "/* Preprocessor aligned. */\n"
5123                            "#  define A 0\n"
5124                            "  /* Code. Separated by blank line. */\n"
5125                            "\n"
5126                            "#  define B 0\n"
5127                            "  /* Code. Not aligned with # */\n"
5128                            "#  define C 0\n"
5129                            "#endif";
5130     const char *ToFormat = ""
5131                            "void f() {\n"
5132                            "#if 1\n"
5133                            "/* Preprocessor aligned. */\n"
5134                            "#  define A 0\n"
5135                            "/* Code. Separated by blank line. */\n"
5136                            "\n"
5137                            "#  define B 0\n"
5138                            "   /* Code. Not aligned with # */\n"
5139                            "#  define C 0\n"
5140                            "#endif";
5141     EXPECT_EQ(Expected, format(ToFormat, Style));
5142     EXPECT_EQ(Expected, format(Expected, Style));
5143   }
5144   // Keep comments aligned with un-indented directives.
5145   {
5146     const char *Expected = ""
5147                            "void f() {\n"
5148                            "// Preprocessor aligned.\n"
5149                            "#define A 0\n"
5150                            "  // Code. Separated by blank line.\n"
5151                            "\n"
5152                            "#define B 0\n"
5153                            "  // Code. Not aligned with #\n"
5154                            "#define C 0\n";
5155     const char *ToFormat = ""
5156                            "void f() {\n"
5157                            "// Preprocessor aligned.\n"
5158                            "#define A 0\n"
5159                            "// Code. Separated by blank line.\n"
5160                            "\n"
5161                            "#define B 0\n"
5162                            "   // Code. Not aligned with #\n"
5163                            "#define C 0\n";
5164     EXPECT_EQ(Expected, format(ToFormat, Style));
5165     EXPECT_EQ(Expected, format(Expected, Style));
5166   }
5167   // Test AfterHash with tabs.
5168   {
5169     FormatStyle Tabbed = Style;
5170     Tabbed.UseTab = FormatStyle::UT_Always;
5171     Tabbed.IndentWidth = 8;
5172     Tabbed.TabWidth = 8;
5173     verifyFormat("#ifdef _WIN32\n"
5174                  "#\tdefine A 0\n"
5175                  "#\tifdef VAR2\n"
5176                  "#\t\tdefine B 1\n"
5177                  "#\t\tinclude <someheader.h>\n"
5178                  "#\t\tdefine MACRO          \\\n"
5179                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5180                  "#\tendif\n"
5181                  "#else\n"
5182                  "#\tdefine A 1\n"
5183                  "#endif",
5184                  Tabbed);
5185   }
5186 
5187   // Regression test: Multiline-macro inside include guards.
5188   verifyFormat("#ifndef HEADER_H\n"
5189                "#define HEADER_H\n"
5190                "#define A()        \\\n"
5191                "  int i;           \\\n"
5192                "  int j;\n"
5193                "#endif // HEADER_H",
5194                getLLVMStyleWithColumns(20));
5195 
5196   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5197   // Basic before hash indent tests
5198   verifyFormat("#ifdef _WIN32\n"
5199                "  #define A 0\n"
5200                "  #ifdef VAR2\n"
5201                "    #define B 1\n"
5202                "    #include <someheader.h>\n"
5203                "    #define MACRO                      \\\n"
5204                "      some_very_long_func_aaaaaaaaaa();\n"
5205                "  #endif\n"
5206                "#else\n"
5207                "  #define A 1\n"
5208                "#endif",
5209                Style);
5210   verifyFormat("#if A\n"
5211                "  #define MACRO                        \\\n"
5212                "    void a(int x) {                    \\\n"
5213                "      b();                             \\\n"
5214                "      c();                             \\\n"
5215                "      d();                             \\\n"
5216                "      e();                             \\\n"
5217                "      f();                             \\\n"
5218                "    }\n"
5219                "#endif",
5220                Style);
5221   // Keep comments aligned with indented directives. These
5222   // tests cannot use verifyFormat because messUp manipulates leading
5223   // whitespace.
5224   {
5225     const char *Expected = "void f() {\n"
5226                            "// Aligned to preprocessor.\n"
5227                            "#if 1\n"
5228                            "  // Aligned to code.\n"
5229                            "  int a;\n"
5230                            "  #if 1\n"
5231                            "    // Aligned to preprocessor.\n"
5232                            "    #define A 0\n"
5233                            "  // Aligned to code.\n"
5234                            "  int b;\n"
5235                            "  #endif\n"
5236                            "#endif\n"
5237                            "}";
5238     const char *ToFormat = "void f() {\n"
5239                            "// Aligned to preprocessor.\n"
5240                            "#if 1\n"
5241                            "// Aligned to code.\n"
5242                            "int a;\n"
5243                            "#if 1\n"
5244                            "// Aligned to preprocessor.\n"
5245                            "#define A 0\n"
5246                            "// Aligned to code.\n"
5247                            "int b;\n"
5248                            "#endif\n"
5249                            "#endif\n"
5250                            "}";
5251     EXPECT_EQ(Expected, format(ToFormat, Style));
5252     EXPECT_EQ(Expected, format(Expected, Style));
5253   }
5254   {
5255     const char *Expected = "void f() {\n"
5256                            "/* Aligned to preprocessor. */\n"
5257                            "#if 1\n"
5258                            "  /* Aligned to code. */\n"
5259                            "  int a;\n"
5260                            "  #if 1\n"
5261                            "    /* Aligned to preprocessor. */\n"
5262                            "    #define A 0\n"
5263                            "  /* Aligned to code. */\n"
5264                            "  int b;\n"
5265                            "  #endif\n"
5266                            "#endif\n"
5267                            "}";
5268     const char *ToFormat = "void f() {\n"
5269                            "/* Aligned to preprocessor. */\n"
5270                            "#if 1\n"
5271                            "/* Aligned to code. */\n"
5272                            "int a;\n"
5273                            "#if 1\n"
5274                            "/* Aligned to preprocessor. */\n"
5275                            "#define A 0\n"
5276                            "/* Aligned to code. */\n"
5277                            "int b;\n"
5278                            "#endif\n"
5279                            "#endif\n"
5280                            "}";
5281     EXPECT_EQ(Expected, format(ToFormat, Style));
5282     EXPECT_EQ(Expected, format(Expected, Style));
5283   }
5284 
5285   // Test single comment before preprocessor
5286   verifyFormat("// Comment\n"
5287                "\n"
5288                "#if 1\n"
5289                "#endif",
5290                Style);
5291 }
5292 
5293 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5294   verifyFormat("{\n  { a #c; }\n}");
5295 }
5296 
5297 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5298   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5299             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5300   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5301             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5302 }
5303 
5304 TEST_F(FormatTest, EscapedNewlines) {
5305   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5306   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5307             format("#define A \\\nint i;\\\n  int j;", Narrow));
5308   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5309   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5310   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5311   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5312 
5313   FormatStyle AlignLeft = getLLVMStyle();
5314   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5315   EXPECT_EQ("#define MACRO(x) \\\n"
5316             "private:         \\\n"
5317             "  int x(int a);\n",
5318             format("#define MACRO(x) \\\n"
5319                    "private:         \\\n"
5320                    "  int x(int a);\n",
5321                    AlignLeft));
5322 
5323   // CRLF line endings
5324   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5325             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5326   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5327   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5328   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5329   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5330   EXPECT_EQ("#define MACRO(x) \\\r\n"
5331             "private:         \\\r\n"
5332             "  int x(int a);\r\n",
5333             format("#define MACRO(x) \\\r\n"
5334                    "private:         \\\r\n"
5335                    "  int x(int a);\r\n",
5336                    AlignLeft));
5337 
5338   FormatStyle DontAlign = getLLVMStyle();
5339   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5340   DontAlign.MaxEmptyLinesToKeep = 3;
5341   // FIXME: can't use verifyFormat here because the newline before
5342   // "public:" is not inserted the first time it's reformatted
5343   EXPECT_EQ("#define A \\\n"
5344             "  class Foo { \\\n"
5345             "    void bar(); \\\n"
5346             "\\\n"
5347             "\\\n"
5348             "\\\n"
5349             "  public: \\\n"
5350             "    void baz(); \\\n"
5351             "  };",
5352             format("#define A \\\n"
5353                    "  class Foo { \\\n"
5354                    "    void bar(); \\\n"
5355                    "\\\n"
5356                    "\\\n"
5357                    "\\\n"
5358                    "  public: \\\n"
5359                    "    void baz(); \\\n"
5360                    "  };",
5361                    DontAlign));
5362 }
5363 
5364 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5365   verifyFormat("#define A \\\n"
5366                "  int v(  \\\n"
5367                "      a); \\\n"
5368                "  int i;",
5369                getLLVMStyleWithColumns(11));
5370 }
5371 
5372 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5373   EXPECT_EQ(
5374       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5375       "                      \\\n"
5376       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5377       "\n"
5378       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5379       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5380       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5381              "\\\n"
5382              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5383              "  \n"
5384              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5385              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5386 }
5387 
5388 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5389   EXPECT_EQ("int\n"
5390             "#define A\n"
5391             "    a;",
5392             format("int\n#define A\na;"));
5393   verifyFormat("functionCallTo(\n"
5394                "    someOtherFunction(\n"
5395                "        withSomeParameters, whichInSequence,\n"
5396                "        areLongerThanALine(andAnotherCall,\n"
5397                "#define A B\n"
5398                "                           withMoreParamters,\n"
5399                "                           whichStronglyInfluenceTheLayout),\n"
5400                "        andMoreParameters),\n"
5401                "    trailing);",
5402                getLLVMStyleWithColumns(69));
5403   verifyFormat("Foo::Foo()\n"
5404                "#ifdef BAR\n"
5405                "    : baz(0)\n"
5406                "#endif\n"
5407                "{\n"
5408                "}");
5409   verifyFormat("void f() {\n"
5410                "  if (true)\n"
5411                "#ifdef A\n"
5412                "    f(42);\n"
5413                "  x();\n"
5414                "#else\n"
5415                "    g();\n"
5416                "  x();\n"
5417                "#endif\n"
5418                "}");
5419   verifyFormat("void f(param1, param2,\n"
5420                "       param3,\n"
5421                "#ifdef A\n"
5422                "       param4(param5,\n"
5423                "#ifdef A1\n"
5424                "              param6,\n"
5425                "#ifdef A2\n"
5426                "              param7),\n"
5427                "#else\n"
5428                "              param8),\n"
5429                "       param9,\n"
5430                "#endif\n"
5431                "       param10,\n"
5432                "#endif\n"
5433                "       param11)\n"
5434                "#else\n"
5435                "       param12)\n"
5436                "#endif\n"
5437                "{\n"
5438                "  x();\n"
5439                "}",
5440                getLLVMStyleWithColumns(28));
5441   verifyFormat("#if 1\n"
5442                "int i;");
5443   verifyFormat("#if 1\n"
5444                "#endif\n"
5445                "#if 1\n"
5446                "#else\n"
5447                "#endif\n");
5448   verifyFormat("DEBUG({\n"
5449                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5450                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5451                "});\n"
5452                "#if a\n"
5453                "#else\n"
5454                "#endif");
5455 
5456   verifyIncompleteFormat("void f(\n"
5457                          "#if A\n"
5458                          ");\n"
5459                          "#else\n"
5460                          "#endif");
5461 }
5462 
5463 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5464   verifyFormat("#endif\n"
5465                "#if B");
5466 }
5467 
5468 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5469   FormatStyle SingleLine = getLLVMStyle();
5470   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5471   verifyFormat("#if 0\n"
5472                "#elif 1\n"
5473                "#endif\n"
5474                "void foo() {\n"
5475                "  if (test) foo2();\n"
5476                "}",
5477                SingleLine);
5478 }
5479 
5480 TEST_F(FormatTest, LayoutBlockInsideParens) {
5481   verifyFormat("functionCall({ int i; });");
5482   verifyFormat("functionCall({\n"
5483                "  int i;\n"
5484                "  int j;\n"
5485                "});");
5486   verifyFormat("functionCall(\n"
5487                "    {\n"
5488                "      int i;\n"
5489                "      int j;\n"
5490                "    },\n"
5491                "    aaaa, bbbb, cccc);");
5492   verifyFormat("functionA(functionB({\n"
5493                "            int i;\n"
5494                "            int j;\n"
5495                "          }),\n"
5496                "          aaaa, bbbb, cccc);");
5497   verifyFormat("functionCall(\n"
5498                "    {\n"
5499                "      int i;\n"
5500                "      int j;\n"
5501                "    },\n"
5502                "    aaaa, bbbb, // comment\n"
5503                "    cccc);");
5504   verifyFormat("functionA(functionB({\n"
5505                "            int i;\n"
5506                "            int j;\n"
5507                "          }),\n"
5508                "          aaaa, bbbb, // comment\n"
5509                "          cccc);");
5510   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5511   verifyFormat("functionCall(aaaa, bbbb, {\n"
5512                "  int i;\n"
5513                "  int j;\n"
5514                "});");
5515   verifyFormat(
5516       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5517       "    {\n"
5518       "      int i; // break\n"
5519       "    },\n"
5520       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5521       "                                     ccccccccccccccccc));");
5522   verifyFormat("DEBUG({\n"
5523                "  if (a)\n"
5524                "    f();\n"
5525                "});");
5526 }
5527 
5528 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5529   EXPECT_EQ("SOME_MACRO { int i; }\n"
5530             "int i;",
5531             format("  SOME_MACRO  {int i;}  int i;"));
5532 }
5533 
5534 TEST_F(FormatTest, LayoutNestedBlocks) {
5535   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5536                "  struct s {\n"
5537                "    int i;\n"
5538                "  };\n"
5539                "  s kBitsToOs[] = {{10}};\n"
5540                "  for (int i = 0; i < 10; ++i)\n"
5541                "    return;\n"
5542                "}");
5543   verifyFormat("call(parameter, {\n"
5544                "  something();\n"
5545                "  // Comment using all columns.\n"
5546                "  somethingelse();\n"
5547                "});",
5548                getLLVMStyleWithColumns(40));
5549   verifyFormat("DEBUG( //\n"
5550                "    { f(); }, a);");
5551   verifyFormat("DEBUG( //\n"
5552                "    {\n"
5553                "      f(); //\n"
5554                "    },\n"
5555                "    a);");
5556 
5557   EXPECT_EQ("call(parameter, {\n"
5558             "  something();\n"
5559             "  // Comment too\n"
5560             "  // looooooooooong.\n"
5561             "  somethingElse();\n"
5562             "});",
5563             format("call(parameter, {\n"
5564                    "  something();\n"
5565                    "  // Comment too looooooooooong.\n"
5566                    "  somethingElse();\n"
5567                    "});",
5568                    getLLVMStyleWithColumns(29)));
5569   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5570   EXPECT_EQ("DEBUG({ // comment\n"
5571             "  int i;\n"
5572             "});",
5573             format("DEBUG({ // comment\n"
5574                    "int  i;\n"
5575                    "});"));
5576   EXPECT_EQ("DEBUG({\n"
5577             "  int i;\n"
5578             "\n"
5579             "  // comment\n"
5580             "  int j;\n"
5581             "});",
5582             format("DEBUG({\n"
5583                    "  int  i;\n"
5584                    "\n"
5585                    "  // comment\n"
5586                    "  int  j;\n"
5587                    "});"));
5588 
5589   verifyFormat("DEBUG({\n"
5590                "  if (a)\n"
5591                "    return;\n"
5592                "});");
5593   verifyGoogleFormat("DEBUG({\n"
5594                      "  if (a) return;\n"
5595                      "});");
5596   FormatStyle Style = getGoogleStyle();
5597   Style.ColumnLimit = 45;
5598   verifyFormat("Debug(\n"
5599                "    aaaaa,\n"
5600                "    {\n"
5601                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5602                "    },\n"
5603                "    a);",
5604                Style);
5605 
5606   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5607 
5608   verifyNoCrash("^{v^{a}}");
5609 }
5610 
5611 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
5612   EXPECT_EQ("#define MACRO()                     \\\n"
5613             "  Debug(aaa, /* force line break */ \\\n"
5614             "        {                           \\\n"
5615             "          int i;                    \\\n"
5616             "          int j;                    \\\n"
5617             "        })",
5618             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
5619                    "          {  int   i;  int  j;   })",
5620                    getGoogleStyle()));
5621 
5622   EXPECT_EQ("#define A                                       \\\n"
5623             "  [] {                                          \\\n"
5624             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
5625             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
5626             "  }",
5627             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
5628                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
5629                    getGoogleStyle()));
5630 }
5631 
5632 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
5633   EXPECT_EQ("{}", format("{}"));
5634   verifyFormat("enum E {};");
5635   verifyFormat("enum E {}");
5636   FormatStyle Style = getLLVMStyle();
5637   Style.SpaceInEmptyBlock = true;
5638   EXPECT_EQ("void f() { }", format("void f() {}", Style));
5639   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
5640   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
5641   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5642   Style.BraceWrapping.BeforeElse = false;
5643   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5644   verifyFormat("if (a)\n"
5645                "{\n"
5646                "} else if (b)\n"
5647                "{\n"
5648                "} else\n"
5649                "{ }",
5650                Style);
5651   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
5652   verifyFormat("if (a) {\n"
5653                "} else if (b) {\n"
5654                "} else {\n"
5655                "}",
5656                Style);
5657   Style.BraceWrapping.BeforeElse = true;
5658   verifyFormat("if (a) { }\n"
5659                "else if (b) { }\n"
5660                "else { }",
5661                Style);
5662 }
5663 
5664 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
5665   FormatStyle Style = getLLVMStyle();
5666   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
5667   Style.MacroBlockEnd = "^[A-Z_]+_END$";
5668   verifyFormat("FOO_BEGIN\n"
5669                "  FOO_ENTRY\n"
5670                "FOO_END",
5671                Style);
5672   verifyFormat("FOO_BEGIN\n"
5673                "  NESTED_FOO_BEGIN\n"
5674                "    NESTED_FOO_ENTRY\n"
5675                "  NESTED_FOO_END\n"
5676                "FOO_END",
5677                Style);
5678   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
5679                "  int x;\n"
5680                "  x = 1;\n"
5681                "FOO_END(Baz)",
5682                Style);
5683 }
5684 
5685 //===----------------------------------------------------------------------===//
5686 // Line break tests.
5687 //===----------------------------------------------------------------------===//
5688 
5689 TEST_F(FormatTest, PreventConfusingIndents) {
5690   verifyFormat(
5691       "void f() {\n"
5692       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
5693       "                         parameter, parameter, parameter)),\n"
5694       "                     SecondLongCall(parameter));\n"
5695       "}");
5696   verifyFormat(
5697       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5698       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5699       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5700       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
5701   verifyFormat(
5702       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5703       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
5704       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5705       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
5706   verifyFormat(
5707       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5708       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
5709       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
5710       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
5711   verifyFormat("int a = bbbb && ccc &&\n"
5712                "        fffff(\n"
5713                "#define A Just forcing a new line\n"
5714                "            ddd);");
5715 }
5716 
5717 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
5718   verifyFormat(
5719       "bool aaaaaaa =\n"
5720       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
5721       "    bbbbbbbb();");
5722   verifyFormat(
5723       "bool aaaaaaa =\n"
5724       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
5725       "    bbbbbbbb();");
5726 
5727   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5728                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
5729                "    ccccccccc == ddddddddddd;");
5730   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5731                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
5732                "    ccccccccc == ddddddddddd;");
5733   verifyFormat(
5734       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
5735       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
5736       "    ccccccccc == ddddddddddd;");
5737 
5738   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5739                "                 aaaaaa) &&\n"
5740                "         bbbbbb && cccccc;");
5741   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5742                "                 aaaaaa) >>\n"
5743                "         bbbbbb;");
5744   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
5745                "    SourceMgr.getSpellingColumnNumber(\n"
5746                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
5747                "    1);");
5748 
5749   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5750                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
5751                "    cccccc) {\n}");
5752   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5753                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5754                "              cccccc) {\n}");
5755   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5756                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5757                "              cccccc) {\n}");
5758   verifyFormat("b = a &&\n"
5759                "    // Comment\n"
5760                "    b.c && d;");
5761 
5762   // If the LHS of a comparison is not a binary expression itself, the
5763   // additional linebreak confuses many people.
5764   verifyFormat(
5765       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5766       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
5767       "}");
5768   verifyFormat(
5769       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5770       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5771       "}");
5772   verifyFormat(
5773       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
5774       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5775       "}");
5776   verifyFormat(
5777       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5778       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
5779       "}");
5780   // Even explicit parentheses stress the precedence enough to make the
5781   // additional break unnecessary.
5782   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5783                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5784                "}");
5785   // This cases is borderline, but with the indentation it is still readable.
5786   verifyFormat(
5787       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5788       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5789       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
5790       "}",
5791       getLLVMStyleWithColumns(75));
5792 
5793   // If the LHS is a binary expression, we should still use the additional break
5794   // as otherwise the formatting hides the operator precedence.
5795   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5796                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5797                "    5) {\n"
5798                "}");
5799   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5800                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
5801                "    5) {\n"
5802                "}");
5803 
5804   FormatStyle OnePerLine = getLLVMStyle();
5805   OnePerLine.BinPackParameters = false;
5806   verifyFormat(
5807       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5808       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5809       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
5810       OnePerLine);
5811 
5812   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
5813                "                .aaa(aaaaaaaaaaaaa) *\n"
5814                "            aaaaaaa +\n"
5815                "        aaaaaaa;",
5816                getLLVMStyleWithColumns(40));
5817 }
5818 
5819 TEST_F(FormatTest, ExpressionIndentation) {
5820   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5821                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5822                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5823                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5824                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
5825                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
5826                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5827                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
5828                "                 ccccccccccccccccccccccccccccccccccccccccc;");
5829   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5830                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5831                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5832                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5833   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5834                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5835                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5836                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5837   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5838                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5839                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5840                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5841   verifyFormat("if () {\n"
5842                "} else if (aaaaa && bbbbb > // break\n"
5843                "                        ccccc) {\n"
5844                "}");
5845   verifyFormat("if () {\n"
5846                "} else if constexpr (aaaaa && bbbbb > // break\n"
5847                "                                  ccccc) {\n"
5848                "}");
5849   verifyFormat("if () {\n"
5850                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
5851                "                                  ccccc) {\n"
5852                "}");
5853   verifyFormat("if () {\n"
5854                "} else if (aaaaa &&\n"
5855                "           bbbbb > // break\n"
5856                "               ccccc &&\n"
5857                "           ddddd) {\n"
5858                "}");
5859 
5860   // Presence of a trailing comment used to change indentation of b.
5861   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
5862                "       b;\n"
5863                "return aaaaaaaaaaaaaaaaaaa +\n"
5864                "       b; //",
5865                getLLVMStyleWithColumns(30));
5866 }
5867 
5868 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
5869   // Not sure what the best system is here. Like this, the LHS can be found
5870   // immediately above an operator (everything with the same or a higher
5871   // indent). The RHS is aligned right of the operator and so compasses
5872   // everything until something with the same indent as the operator is found.
5873   // FIXME: Is this a good system?
5874   FormatStyle Style = getLLVMStyle();
5875   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5876   verifyFormat(
5877       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5878       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5879       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5880       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5881       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5882       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5883       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5884       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5885       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
5886       Style);
5887   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5888                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5889                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5890                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5891                Style);
5892   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5893                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5894                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5895                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5896                Style);
5897   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5898                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5899                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5900                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5901                Style);
5902   verifyFormat("if () {\n"
5903                "} else if (aaaaa\n"
5904                "           && bbbbb // break\n"
5905                "                  > ccccc) {\n"
5906                "}",
5907                Style);
5908   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5909                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5910                Style);
5911   verifyFormat("return (a)\n"
5912                "       // comment\n"
5913                "       + b;",
5914                Style);
5915   verifyFormat(
5916       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5917       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5918       "             + cc;",
5919       Style);
5920 
5921   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5922                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5923                Style);
5924 
5925   // Forced by comments.
5926   verifyFormat(
5927       "unsigned ContentSize =\n"
5928       "    sizeof(int16_t)   // DWARF ARange version number\n"
5929       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5930       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5931       "    + sizeof(int8_t); // Segment Size (in bytes)");
5932 
5933   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
5934                "       == boost::fusion::at_c<1>(iiii).second;",
5935                Style);
5936 
5937   Style.ColumnLimit = 60;
5938   verifyFormat("zzzzzzzzzz\n"
5939                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5940                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
5941                Style);
5942 
5943   Style.ColumnLimit = 80;
5944   Style.IndentWidth = 4;
5945   Style.TabWidth = 4;
5946   Style.UseTab = FormatStyle::UT_Always;
5947   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5948   Style.AlignOperands = FormatStyle::OAS_DontAlign;
5949   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
5950             "\t&& (someOtherLongishConditionPart1\n"
5951             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
5952             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
5953                    "(someOtherLongishConditionPart1 || "
5954                    "someOtherEvenLongerNestedConditionPart2);",
5955                    Style));
5956 }
5957 
5958 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
5959   FormatStyle Style = getLLVMStyle();
5960   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5961   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
5962 
5963   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5964                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5965                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5966                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5967                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5968                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5969                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5970                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5971                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
5972                Style);
5973   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5974                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5975                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5976                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5977                Style);
5978   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5979                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5980                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5981                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5982                Style);
5983   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5984                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5985                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5986                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5987                Style);
5988   verifyFormat("if () {\n"
5989                "} else if (aaaaa\n"
5990                "           && bbbbb // break\n"
5991                "                  > ccccc) {\n"
5992                "}",
5993                Style);
5994   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5995                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5996                Style);
5997   verifyFormat("return (a)\n"
5998                "     // comment\n"
5999                "     + b;",
6000                Style);
6001   verifyFormat(
6002       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6003       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6004       "           + cc;",
6005       Style);
6006   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6007                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6008                "                        : 3333333333333333;",
6009                Style);
6010   verifyFormat(
6011       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6012       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6013       "                                             : eeeeeeeeeeeeeeeeee)\n"
6014       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6015       "                        : 3333333333333333;",
6016       Style);
6017   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6018                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6019                Style);
6020 
6021   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6022                "    == boost::fusion::at_c<1>(iiii).second;",
6023                Style);
6024 
6025   Style.ColumnLimit = 60;
6026   verifyFormat("zzzzzzzzzzzzz\n"
6027                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6028                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6029                Style);
6030 
6031   // Forced by comments.
6032   Style.ColumnLimit = 80;
6033   verifyFormat(
6034       "unsigned ContentSize\n"
6035       "    = sizeof(int16_t) // DWARF ARange version number\n"
6036       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6037       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6038       "    + sizeof(int8_t); // Segment Size (in bytes)",
6039       Style);
6040 
6041   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6042   verifyFormat(
6043       "unsigned ContentSize =\n"
6044       "    sizeof(int16_t)   // DWARF ARange version number\n"
6045       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6046       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6047       "    + sizeof(int8_t); // Segment Size (in bytes)",
6048       Style);
6049 
6050   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6051   verifyFormat(
6052       "unsigned ContentSize =\n"
6053       "    sizeof(int16_t)   // DWARF ARange version number\n"
6054       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6055       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6056       "    + sizeof(int8_t); // Segment Size (in bytes)",
6057       Style);
6058 }
6059 
6060 TEST_F(FormatTest, EnforcedOperatorWraps) {
6061   // Here we'd like to wrap after the || operators, but a comment is forcing an
6062   // earlier wrap.
6063   verifyFormat("bool x = aaaaa //\n"
6064                "         || bbbbb\n"
6065                "         //\n"
6066                "         || cccc;");
6067 }
6068 
6069 TEST_F(FormatTest, NoOperandAlignment) {
6070   FormatStyle Style = getLLVMStyle();
6071   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6072   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6073                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6074                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6075                Style);
6076   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6077   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6078                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6079                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6080                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6081                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6082                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6083                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6084                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6085                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6086                Style);
6087 
6088   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6089                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6090                "    + cc;",
6091                Style);
6092   verifyFormat("int a = aa\n"
6093                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6094                "        * cccccccccccccccccccccccccccccccccccc;\n",
6095                Style);
6096 
6097   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6098   verifyFormat("return (a > b\n"
6099                "    // comment1\n"
6100                "    // comment2\n"
6101                "    || c);",
6102                Style);
6103 }
6104 
6105 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6106   FormatStyle Style = getLLVMStyle();
6107   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6108   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6109                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6110                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6111                Style);
6112 }
6113 
6114 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6115   FormatStyle Style = getLLVMStyleWithColumns(40);
6116   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6117   Style.BinPackArguments = false;
6118   verifyFormat("void test() {\n"
6119                "  someFunction(\n"
6120                "      this + argument + is + quite\n"
6121                "      + long + so + it + gets + wrapped\n"
6122                "      + but + remains + bin - packed);\n"
6123                "}",
6124                Style);
6125   verifyFormat("void test() {\n"
6126                "  someFunction(arg1,\n"
6127                "               this + argument + is\n"
6128                "                   + quite + long + so\n"
6129                "                   + it + gets + wrapped\n"
6130                "                   + but + remains + bin\n"
6131                "                   - packed,\n"
6132                "               arg3);\n"
6133                "}",
6134                Style);
6135   verifyFormat("void test() {\n"
6136                "  someFunction(\n"
6137                "      arg1,\n"
6138                "      this + argument + has\n"
6139                "          + anotherFunc(nested,\n"
6140                "                        calls + whose\n"
6141                "                            + arguments\n"
6142                "                            + are + also\n"
6143                "                            + wrapped,\n"
6144                "                        in + addition)\n"
6145                "          + to + being + bin - packed,\n"
6146                "      arg3);\n"
6147                "}",
6148                Style);
6149 
6150   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6151   verifyFormat("void test() {\n"
6152                "  someFunction(\n"
6153                "      arg1,\n"
6154                "      this + argument + has +\n"
6155                "          anotherFunc(nested,\n"
6156                "                      calls + whose +\n"
6157                "                          arguments +\n"
6158                "                          are + also +\n"
6159                "                          wrapped,\n"
6160                "                      in + addition) +\n"
6161                "          to + being + bin - packed,\n"
6162                "      arg3);\n"
6163                "}",
6164                Style);
6165 }
6166 
6167 TEST_F(FormatTest, ConstructorInitializers) {
6168   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6169   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6170                getLLVMStyleWithColumns(45));
6171   verifyFormat("Constructor()\n"
6172                "    : Inttializer(FitsOnTheLine) {}",
6173                getLLVMStyleWithColumns(44));
6174   verifyFormat("Constructor()\n"
6175                "    : Inttializer(FitsOnTheLine) {}",
6176                getLLVMStyleWithColumns(43));
6177 
6178   verifyFormat("template <typename T>\n"
6179                "Constructor() : Initializer(FitsOnTheLine) {}",
6180                getLLVMStyleWithColumns(45));
6181 
6182   verifyFormat(
6183       "SomeClass::Constructor()\n"
6184       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6185 
6186   verifyFormat(
6187       "SomeClass::Constructor()\n"
6188       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6189       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6190   verifyFormat(
6191       "SomeClass::Constructor()\n"
6192       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6193       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6194   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6195                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6196                "    : aaaaaaaaaa(aaaaaa) {}");
6197 
6198   verifyFormat("Constructor()\n"
6199                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6200                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6201                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6202                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6203 
6204   verifyFormat("Constructor()\n"
6205                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6206                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6207 
6208   verifyFormat("Constructor(int Parameter = 0)\n"
6209                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6210                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6211   verifyFormat("Constructor()\n"
6212                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6213                "}",
6214                getLLVMStyleWithColumns(60));
6215   verifyFormat("Constructor()\n"
6216                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6217                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6218 
6219   // Here a line could be saved by splitting the second initializer onto two
6220   // lines, but that is not desirable.
6221   verifyFormat("Constructor()\n"
6222                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6223                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6224                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6225 
6226   FormatStyle OnePerLine = getLLVMStyle();
6227   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6228   verifyFormat("MyClass::MyClass()\n"
6229                "    : a(a),\n"
6230                "      b(b),\n"
6231                "      c(c) {}",
6232                OnePerLine);
6233   verifyFormat("MyClass::MyClass()\n"
6234                "    : a(a), // comment\n"
6235                "      b(b),\n"
6236                "      c(c) {}",
6237                OnePerLine);
6238   verifyFormat("MyClass::MyClass(int a)\n"
6239                "    : b(a),      // comment\n"
6240                "      c(a + 1) { // lined up\n"
6241                "}",
6242                OnePerLine);
6243   verifyFormat("Constructor()\n"
6244                "    : a(b, b, b) {}",
6245                OnePerLine);
6246   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6247   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6248   verifyFormat("SomeClass::Constructor()\n"
6249                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6250                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6251                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6252                OnePerLine);
6253   verifyFormat("SomeClass::Constructor()\n"
6254                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6255                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6256                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6257                OnePerLine);
6258   verifyFormat("MyClass::MyClass(int var)\n"
6259                "    : some_var_(var),            // 4 space indent\n"
6260                "      some_other_var_(var + 1) { // lined up\n"
6261                "}",
6262                OnePerLine);
6263   verifyFormat("Constructor()\n"
6264                "    : aaaaa(aaaaaa),\n"
6265                "      aaaaa(aaaaaa),\n"
6266                "      aaaaa(aaaaaa),\n"
6267                "      aaaaa(aaaaaa),\n"
6268                "      aaaaa(aaaaaa) {}",
6269                OnePerLine);
6270   verifyFormat("Constructor()\n"
6271                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6272                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6273                OnePerLine);
6274   OnePerLine.BinPackParameters = false;
6275   verifyFormat(
6276       "Constructor()\n"
6277       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6278       "          aaaaaaaaaaa().aaa(),\n"
6279       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6280       OnePerLine);
6281   OnePerLine.ColumnLimit = 60;
6282   verifyFormat("Constructor()\n"
6283                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6284                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6285                OnePerLine);
6286 
6287   EXPECT_EQ("Constructor()\n"
6288             "    : // Comment forcing unwanted break.\n"
6289             "      aaaa(aaaa) {}",
6290             format("Constructor() :\n"
6291                    "    // Comment forcing unwanted break.\n"
6292                    "    aaaa(aaaa) {}"));
6293 }
6294 
6295 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6296   FormatStyle Style = getLLVMStyleWithColumns(60);
6297   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6298   Style.BinPackParameters = false;
6299 
6300   for (int i = 0; i < 4; ++i) {
6301     // Test all combinations of parameters that should not have an effect.
6302     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6303     Style.AllowAllArgumentsOnNextLine = i & 2;
6304 
6305     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6306     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6307     verifyFormat("Constructor()\n"
6308                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6309                  Style);
6310     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6311 
6312     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6313     verifyFormat("Constructor()\n"
6314                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6315                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6316                  Style);
6317     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6318 
6319     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6320     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6321     verifyFormat("Constructor()\n"
6322                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6323                  Style);
6324 
6325     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6326     verifyFormat("Constructor()\n"
6327                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6328                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6329                  Style);
6330 
6331     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6332     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6333     verifyFormat("Constructor() :\n"
6334                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6335                  Style);
6336 
6337     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6338     verifyFormat("Constructor() :\n"
6339                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6340                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6341                  Style);
6342   }
6343 
6344   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6345   // AllowAllConstructorInitializersOnNextLine in all
6346   // BreakConstructorInitializers modes
6347   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6348   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6349   verifyFormat("SomeClassWithALongName::Constructor(\n"
6350                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6351                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6352                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6353                Style);
6354 
6355   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6356   verifyFormat("SomeClassWithALongName::Constructor(\n"
6357                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6358                "    int bbbbbbbbbbbbb,\n"
6359                "    int cccccccccccccccc)\n"
6360                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6361                Style);
6362 
6363   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6364   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6365   verifyFormat("SomeClassWithALongName::Constructor(\n"
6366                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6367                "    int bbbbbbbbbbbbb)\n"
6368                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6369                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6370                Style);
6371 
6372   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6373 
6374   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6375   verifyFormat("SomeClassWithALongName::Constructor(\n"
6376                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6377                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6378                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6379                Style);
6380 
6381   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6382   verifyFormat("SomeClassWithALongName::Constructor(\n"
6383                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6384                "    int bbbbbbbbbbbbb,\n"
6385                "    int cccccccccccccccc)\n"
6386                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6387                Style);
6388 
6389   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6390   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6391   verifyFormat("SomeClassWithALongName::Constructor(\n"
6392                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6393                "    int bbbbbbbbbbbbb)\n"
6394                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6395                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6396                Style);
6397 
6398   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6399   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6400   verifyFormat("SomeClassWithALongName::Constructor(\n"
6401                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6402                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6403                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6404                Style);
6405 
6406   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6407   verifyFormat("SomeClassWithALongName::Constructor(\n"
6408                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6409                "    int bbbbbbbbbbbbb,\n"
6410                "    int cccccccccccccccc) :\n"
6411                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6412                Style);
6413 
6414   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6415   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6416   verifyFormat("SomeClassWithALongName::Constructor(\n"
6417                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6418                "    int bbbbbbbbbbbbb) :\n"
6419                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6420                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6421                Style);
6422 }
6423 
6424 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6425   FormatStyle Style = getLLVMStyleWithColumns(60);
6426   Style.BinPackArguments = false;
6427   for (int i = 0; i < 4; ++i) {
6428     // Test all combinations of parameters that should not have an effect.
6429     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6430     Style.PackConstructorInitializers =
6431         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6432 
6433     Style.AllowAllArgumentsOnNextLine = true;
6434     verifyFormat("void foo() {\n"
6435                  "  FunctionCallWithReallyLongName(\n"
6436                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6437                  "}",
6438                  Style);
6439     Style.AllowAllArgumentsOnNextLine = false;
6440     verifyFormat("void foo() {\n"
6441                  "  FunctionCallWithReallyLongName(\n"
6442                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6443                  "      bbbbbbbbbbbb);\n"
6444                  "}",
6445                  Style);
6446 
6447     Style.AllowAllArgumentsOnNextLine = true;
6448     verifyFormat("void foo() {\n"
6449                  "  auto VariableWithReallyLongName = {\n"
6450                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6451                  "}",
6452                  Style);
6453     Style.AllowAllArgumentsOnNextLine = false;
6454     verifyFormat("void foo() {\n"
6455                  "  auto VariableWithReallyLongName = {\n"
6456                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6457                  "      bbbbbbbbbbbb};\n"
6458                  "}",
6459                  Style);
6460   }
6461 
6462   // This parameter should not affect declarations.
6463   Style.BinPackParameters = false;
6464   Style.AllowAllArgumentsOnNextLine = false;
6465   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6466   verifyFormat("void FunctionCallWithReallyLongName(\n"
6467                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6468                Style);
6469   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6470   verifyFormat("void FunctionCallWithReallyLongName(\n"
6471                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6472                "    int bbbbbbbbbbbb);",
6473                Style);
6474 }
6475 
6476 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6477   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6478   // and BAS_Align.
6479   FormatStyle Style = getLLVMStyleWithColumns(35);
6480   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6481                     "void functionDecl(int A, int B, int C);";
6482   Style.AllowAllArgumentsOnNextLine = false;
6483   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6484   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6485                       "    paramC);\n"
6486                       "void functionDecl(int A, int B,\n"
6487                       "    int C);"),
6488             format(Input, Style));
6489   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6490   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6491                       "             paramC);\n"
6492                       "void functionDecl(int A, int B,\n"
6493                       "                  int C);"),
6494             format(Input, Style));
6495   // However, BAS_AlwaysBreak should take precedence over
6496   // AllowAllArgumentsOnNextLine.
6497   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6498   EXPECT_EQ(StringRef("functionCall(\n"
6499                       "    paramA, paramB, paramC);\n"
6500                       "void functionDecl(\n"
6501                       "    int A, int B, int C);"),
6502             format(Input, Style));
6503 
6504   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6505   // first argument.
6506   Style.AllowAllArgumentsOnNextLine = true;
6507   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6508   EXPECT_EQ(StringRef("functionCall(\n"
6509                       "    paramA, paramB, paramC);\n"
6510                       "void functionDecl(\n"
6511                       "    int A, int B, int C);"),
6512             format(Input, Style));
6513   // It wouldn't fit on one line with aligned parameters so this setting
6514   // doesn't change anything for BAS_Align.
6515   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6516   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6517                       "             paramC);\n"
6518                       "void functionDecl(int A, int B,\n"
6519                       "                  int C);"),
6520             format(Input, Style));
6521   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6522   EXPECT_EQ(StringRef("functionCall(\n"
6523                       "    paramA, paramB, paramC);\n"
6524                       "void functionDecl(\n"
6525                       "    int A, int B, int C);"),
6526             format(Input, Style));
6527 }
6528 
6529 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6530   FormatStyle Style = getLLVMStyle();
6531   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6532 
6533   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6534   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6535                getStyleWithColumns(Style, 45));
6536   verifyFormat("Constructor() :\n"
6537                "    Initializer(FitsOnTheLine) {}",
6538                getStyleWithColumns(Style, 44));
6539   verifyFormat("Constructor() :\n"
6540                "    Initializer(FitsOnTheLine) {}",
6541                getStyleWithColumns(Style, 43));
6542 
6543   verifyFormat("template <typename T>\n"
6544                "Constructor() : Initializer(FitsOnTheLine) {}",
6545                getStyleWithColumns(Style, 50));
6546   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6547   verifyFormat(
6548       "SomeClass::Constructor() :\n"
6549       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6550       Style);
6551 
6552   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6553   verifyFormat(
6554       "SomeClass::Constructor() :\n"
6555       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6556       Style);
6557 
6558   verifyFormat(
6559       "SomeClass::Constructor() :\n"
6560       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6561       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6562       Style);
6563   verifyFormat(
6564       "SomeClass::Constructor() :\n"
6565       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6566       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6567       Style);
6568   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6569                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6570                "    aaaaaaaaaa(aaaaaa) {}",
6571                Style);
6572 
6573   verifyFormat("Constructor() :\n"
6574                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6575                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6576                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6577                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
6578                Style);
6579 
6580   verifyFormat("Constructor() :\n"
6581                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6582                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6583                Style);
6584 
6585   verifyFormat("Constructor(int Parameter = 0) :\n"
6586                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6587                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
6588                Style);
6589   verifyFormat("Constructor() :\n"
6590                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6591                "}",
6592                getStyleWithColumns(Style, 60));
6593   verifyFormat("Constructor() :\n"
6594                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6595                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
6596                Style);
6597 
6598   // Here a line could be saved by splitting the second initializer onto two
6599   // lines, but that is not desirable.
6600   verifyFormat("Constructor() :\n"
6601                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6602                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
6603                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6604                Style);
6605 
6606   FormatStyle OnePerLine = Style;
6607   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6608   verifyFormat("SomeClass::Constructor() :\n"
6609                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6610                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6611                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6612                OnePerLine);
6613   verifyFormat("SomeClass::Constructor() :\n"
6614                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6615                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6616                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6617                OnePerLine);
6618   verifyFormat("MyClass::MyClass(int var) :\n"
6619                "    some_var_(var),            // 4 space indent\n"
6620                "    some_other_var_(var + 1) { // lined up\n"
6621                "}",
6622                OnePerLine);
6623   verifyFormat("Constructor() :\n"
6624                "    aaaaa(aaaaaa),\n"
6625                "    aaaaa(aaaaaa),\n"
6626                "    aaaaa(aaaaaa),\n"
6627                "    aaaaa(aaaaaa),\n"
6628                "    aaaaa(aaaaaa) {}",
6629                OnePerLine);
6630   verifyFormat("Constructor() :\n"
6631                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6632                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
6633                OnePerLine);
6634   OnePerLine.BinPackParameters = false;
6635   verifyFormat("Constructor() :\n"
6636                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6637                "        aaaaaaaaaaa().aaa(),\n"
6638                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6639                OnePerLine);
6640   OnePerLine.ColumnLimit = 60;
6641   verifyFormat("Constructor() :\n"
6642                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6643                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6644                OnePerLine);
6645 
6646   EXPECT_EQ("Constructor() :\n"
6647             "    // Comment forcing unwanted break.\n"
6648             "    aaaa(aaaa) {}",
6649             format("Constructor() :\n"
6650                    "    // Comment forcing unwanted break.\n"
6651                    "    aaaa(aaaa) {}",
6652                    Style));
6653 
6654   Style.ColumnLimit = 0;
6655   verifyFormat("SomeClass::Constructor() :\n"
6656                "    a(a) {}",
6657                Style);
6658   verifyFormat("SomeClass::Constructor() noexcept :\n"
6659                "    a(a) {}",
6660                Style);
6661   verifyFormat("SomeClass::Constructor() :\n"
6662                "    a(a), b(b), c(c) {}",
6663                Style);
6664   verifyFormat("SomeClass::Constructor() :\n"
6665                "    a(a) {\n"
6666                "  foo();\n"
6667                "  bar();\n"
6668                "}",
6669                Style);
6670 
6671   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6672   verifyFormat("SomeClass::Constructor() :\n"
6673                "    a(a), b(b), c(c) {\n"
6674                "}",
6675                Style);
6676   verifyFormat("SomeClass::Constructor() :\n"
6677                "    a(a) {\n"
6678                "}",
6679                Style);
6680 
6681   Style.ColumnLimit = 80;
6682   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
6683   Style.ConstructorInitializerIndentWidth = 2;
6684   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
6685   verifyFormat("SomeClass::Constructor() :\n"
6686                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6687                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
6688                Style);
6689 
6690   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
6691   // well
6692   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
6693   verifyFormat(
6694       "class SomeClass\n"
6695       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6696       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6697       Style);
6698   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
6699   verifyFormat(
6700       "class SomeClass\n"
6701       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6702       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6703       Style);
6704   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
6705   verifyFormat(
6706       "class SomeClass :\n"
6707       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6708       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6709       Style);
6710   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
6711   verifyFormat(
6712       "class SomeClass\n"
6713       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6714       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6715       Style);
6716 }
6717 
6718 #ifndef EXPENSIVE_CHECKS
6719 // Expensive checks enables libstdc++ checking which includes validating the
6720 // state of ranges used in std::priority_queue - this blows out the
6721 // runtime/scalability of the function and makes this test unacceptably slow.
6722 TEST_F(FormatTest, MemoizationTests) {
6723   // This breaks if the memoization lookup does not take \c Indent and
6724   // \c LastSpace into account.
6725   verifyFormat(
6726       "extern CFRunLoopTimerRef\n"
6727       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
6728       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
6729       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
6730       "                     CFRunLoopTimerContext *context) {}");
6731 
6732   // Deep nesting somewhat works around our memoization.
6733   verifyFormat(
6734       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6735       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6736       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6737       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6738       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
6739       getLLVMStyleWithColumns(65));
6740   verifyFormat(
6741       "aaaaa(\n"
6742       "    aaaaa,\n"
6743       "    aaaaa(\n"
6744       "        aaaaa,\n"
6745       "        aaaaa(\n"
6746       "            aaaaa,\n"
6747       "            aaaaa(\n"
6748       "                aaaaa,\n"
6749       "                aaaaa(\n"
6750       "                    aaaaa,\n"
6751       "                    aaaaa(\n"
6752       "                        aaaaa,\n"
6753       "                        aaaaa(\n"
6754       "                            aaaaa,\n"
6755       "                            aaaaa(\n"
6756       "                                aaaaa,\n"
6757       "                                aaaaa(\n"
6758       "                                    aaaaa,\n"
6759       "                                    aaaaa(\n"
6760       "                                        aaaaa,\n"
6761       "                                        aaaaa(\n"
6762       "                                            aaaaa,\n"
6763       "                                            aaaaa(\n"
6764       "                                                aaaaa,\n"
6765       "                                                aaaaa))))))))))));",
6766       getLLVMStyleWithColumns(65));
6767   verifyFormat(
6768       "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"
6769       "                                  a),\n"
6770       "                                a),\n"
6771       "                              a),\n"
6772       "                            a),\n"
6773       "                          a),\n"
6774       "                        a),\n"
6775       "                      a),\n"
6776       "                    a),\n"
6777       "                  a),\n"
6778       "                a),\n"
6779       "              a),\n"
6780       "            a),\n"
6781       "          a),\n"
6782       "        a),\n"
6783       "      a),\n"
6784       "    a),\n"
6785       "  a)",
6786       getLLVMStyleWithColumns(65));
6787 
6788   // This test takes VERY long when memoization is broken.
6789   FormatStyle OnePerLine = getLLVMStyle();
6790   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6791   OnePerLine.BinPackParameters = false;
6792   std::string input = "Constructor()\n"
6793                       "    : aaaa(a,\n";
6794   for (unsigned i = 0, e = 80; i != e; ++i) {
6795     input += "           a,\n";
6796   }
6797   input += "           a) {}";
6798   verifyFormat(input, OnePerLine);
6799 }
6800 #endif
6801 
6802 TEST_F(FormatTest, BreaksAsHighAsPossible) {
6803   verifyFormat(
6804       "void f() {\n"
6805       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
6806       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
6807       "    f();\n"
6808       "}");
6809   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
6810                "    Intervals[i - 1].getRange().getLast()) {\n}");
6811 }
6812 
6813 TEST_F(FormatTest, BreaksFunctionDeclarations) {
6814   // Principially, we break function declarations in a certain order:
6815   // 1) break amongst arguments.
6816   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
6817                "                              Cccccccccccccc cccccccccccccc);");
6818   verifyFormat("template <class TemplateIt>\n"
6819                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
6820                "                            TemplateIt *stop) {}");
6821 
6822   // 2) break after return type.
6823   verifyFormat(
6824       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6825       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
6826       getGoogleStyle());
6827 
6828   // 3) break after (.
6829   verifyFormat(
6830       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
6831       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
6832       getGoogleStyle());
6833 
6834   // 4) break before after nested name specifiers.
6835   verifyFormat(
6836       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6837       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
6838       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
6839       getGoogleStyle());
6840 
6841   // However, there are exceptions, if a sufficient amount of lines can be
6842   // saved.
6843   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
6844   // more adjusting.
6845   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6846                "                                  Cccccccccccccc cccccccccc,\n"
6847                "                                  Cccccccccccccc cccccccccc,\n"
6848                "                                  Cccccccccccccc cccccccccc,\n"
6849                "                                  Cccccccccccccc cccccccccc);");
6850   verifyFormat(
6851       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6852       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6853       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6854       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
6855       getGoogleStyle());
6856   verifyFormat(
6857       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6858       "                                          Cccccccccccccc cccccccccc,\n"
6859       "                                          Cccccccccccccc cccccccccc,\n"
6860       "                                          Cccccccccccccc cccccccccc,\n"
6861       "                                          Cccccccccccccc cccccccccc,\n"
6862       "                                          Cccccccccccccc cccccccccc,\n"
6863       "                                          Cccccccccccccc cccccccccc);");
6864   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6865                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6866                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6867                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6868                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
6869 
6870   // Break after multi-line parameters.
6871   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6872                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6873                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6874                "    bbbb bbbb);");
6875   verifyFormat("void SomeLoooooooooooongFunction(\n"
6876                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
6877                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6878                "    int bbbbbbbbbbbbb);");
6879 
6880   // Treat overloaded operators like other functions.
6881   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6882                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
6883   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6884                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
6885   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6886                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
6887   verifyGoogleFormat(
6888       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
6889       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6890   verifyGoogleFormat(
6891       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
6892       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6893   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6894                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6895   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
6896                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6897   verifyGoogleFormat(
6898       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
6899       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6900       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
6901   verifyGoogleFormat("template <typename T>\n"
6902                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6903                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
6904                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
6905 
6906   FormatStyle Style = getLLVMStyle();
6907   Style.PointerAlignment = FormatStyle::PAS_Left;
6908   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6909                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
6910                Style);
6911   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
6912                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6913                Style);
6914 }
6915 
6916 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
6917   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
6918   // Prefer keeping `::` followed by `operator` together.
6919   EXPECT_EQ("const aaaa::bbbbbbb &\n"
6920             "ccccccccc::operator++() {\n"
6921             "  stuff();\n"
6922             "}",
6923             format("const aaaa::bbbbbbb\n"
6924                    "&ccccccccc::operator++() { stuff(); }",
6925                    getLLVMStyleWithColumns(40)));
6926 }
6927 
6928 TEST_F(FormatTest, TrailingReturnType) {
6929   verifyFormat("auto foo() -> int;\n");
6930   // correct trailing return type spacing
6931   verifyFormat("auto operator->() -> int;\n");
6932   verifyFormat("auto operator++(int) -> int;\n");
6933 
6934   verifyFormat("struct S {\n"
6935                "  auto bar() const -> int;\n"
6936                "};");
6937   verifyFormat("template <size_t Order, typename T>\n"
6938                "auto load_img(const std::string &filename)\n"
6939                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
6940   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
6941                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
6942   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
6943   verifyFormat("template <typename T>\n"
6944                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
6945                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
6946 
6947   // Not trailing return types.
6948   verifyFormat("void f() { auto a = b->c(); }");
6949   verifyFormat("auto a = p->foo();");
6950   verifyFormat("int a = p->foo();");
6951   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
6952 }
6953 
6954 TEST_F(FormatTest, DeductionGuides) {
6955   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
6956   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
6957   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
6958   verifyFormat(
6959       "template <class... T>\n"
6960       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
6961   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
6962   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
6963   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
6964   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
6965   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
6966   verifyFormat("template <class T> x() -> x<1>;");
6967   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
6968 
6969   // Ensure not deduction guides.
6970   verifyFormat("c()->f<int>();");
6971   verifyFormat("x()->foo<1>;");
6972   verifyFormat("x = p->foo<3>();");
6973   verifyFormat("x()->x<1>();");
6974   verifyFormat("x()->x<1>;");
6975 }
6976 
6977 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
6978   // Avoid breaking before trailing 'const' or other trailing annotations, if
6979   // they are not function-like.
6980   FormatStyle Style = getGoogleStyleWithColumns(47);
6981   verifyFormat("void someLongFunction(\n"
6982                "    int someLoooooooooooooongParameter) const {\n}",
6983                getLLVMStyleWithColumns(47));
6984   verifyFormat("LoooooongReturnType\n"
6985                "someLoooooooongFunction() const {}",
6986                getLLVMStyleWithColumns(47));
6987   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
6988                "    const {}",
6989                Style);
6990   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6991                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
6992   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6993                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
6994   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6995                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
6996   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
6997                "                   aaaaaaaaaaa aaaaa) const override;");
6998   verifyGoogleFormat(
6999       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7000       "    const override;");
7001 
7002   // Even if the first parameter has to be wrapped.
7003   verifyFormat("void someLongFunction(\n"
7004                "    int someLongParameter) const {}",
7005                getLLVMStyleWithColumns(46));
7006   verifyFormat("void someLongFunction(\n"
7007                "    int someLongParameter) const {}",
7008                Style);
7009   verifyFormat("void someLongFunction(\n"
7010                "    int someLongParameter) override {}",
7011                Style);
7012   verifyFormat("void someLongFunction(\n"
7013                "    int someLongParameter) OVERRIDE {}",
7014                Style);
7015   verifyFormat("void someLongFunction(\n"
7016                "    int someLongParameter) final {}",
7017                Style);
7018   verifyFormat("void someLongFunction(\n"
7019                "    int someLongParameter) FINAL {}",
7020                Style);
7021   verifyFormat("void someLongFunction(\n"
7022                "    int parameter) const override {}",
7023                Style);
7024 
7025   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
7026   verifyFormat("void someLongFunction(\n"
7027                "    int someLongParameter) const\n"
7028                "{\n"
7029                "}",
7030                Style);
7031 
7032   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
7033   verifyFormat("void someLongFunction(\n"
7034                "    int someLongParameter) const\n"
7035                "  {\n"
7036                "  }",
7037                Style);
7038 
7039   // Unless these are unknown annotations.
7040   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
7041                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7042                "    LONG_AND_UGLY_ANNOTATION;");
7043 
7044   // Breaking before function-like trailing annotations is fine to keep them
7045   // close to their arguments.
7046   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7047                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7048   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7049                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7050   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7051                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
7052   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
7053                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
7054   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
7055 
7056   verifyFormat(
7057       "void aaaaaaaaaaaaaaaaaa()\n"
7058       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
7059       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
7060   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7061                "    __attribute__((unused));");
7062   verifyGoogleFormat(
7063       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7064       "    GUARDED_BY(aaaaaaaaaaaa);");
7065   verifyGoogleFormat(
7066       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7067       "    GUARDED_BY(aaaaaaaaaaaa);");
7068   verifyGoogleFormat(
7069       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7070       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7071   verifyGoogleFormat(
7072       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7073       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
7074 }
7075 
7076 TEST_F(FormatTest, FunctionAnnotations) {
7077   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7078                "int OldFunction(const string &parameter) {}");
7079   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7080                "string OldFunction(const string &parameter) {}");
7081   verifyFormat("template <typename T>\n"
7082                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7083                "string OldFunction(const string &parameter) {}");
7084 
7085   // Not function annotations.
7086   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7087                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
7088   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
7089                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
7090   verifyFormat("MACRO(abc).function() // wrap\n"
7091                "    << abc;");
7092   verifyFormat("MACRO(abc)->function() // wrap\n"
7093                "    << abc;");
7094   verifyFormat("MACRO(abc)::function() // wrap\n"
7095                "    << abc;");
7096 }
7097 
7098 TEST_F(FormatTest, BreaksDesireably) {
7099   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7100                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7101                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
7102   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7103                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
7104                "}");
7105 
7106   verifyFormat(
7107       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7108       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7109 
7110   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7111                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7112                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7113 
7114   verifyFormat(
7115       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7116       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7117       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7118       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7119       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7120 
7121   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7122                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7123 
7124   verifyFormat(
7125       "void f() {\n"
7126       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7127       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7128       "}");
7129   verifyFormat(
7130       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7131       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7132   verifyFormat(
7133       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7134       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7135   verifyFormat(
7136       "aaaaaa(aaa,\n"
7137       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7138       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7139       "       aaaa);");
7140   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7141                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7142                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7143 
7144   // Indent consistently independent of call expression and unary operator.
7145   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7146                "    dddddddddddddddddddddddddddddd));");
7147   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7148                "    dddddddddddddddddddddddddddddd));");
7149   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7150                "    dddddddddddddddddddddddddddddd));");
7151 
7152   // This test case breaks on an incorrect memoization, i.e. an optimization not
7153   // taking into account the StopAt value.
7154   verifyFormat(
7155       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7156       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7157       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7158       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7159 
7160   verifyFormat("{\n  {\n    {\n"
7161                "      Annotation.SpaceRequiredBefore =\n"
7162                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7163                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7164                "    }\n  }\n}");
7165 
7166   // Break on an outer level if there was a break on an inner level.
7167   EXPECT_EQ("f(g(h(a, // comment\n"
7168             "      b, c),\n"
7169             "    d, e),\n"
7170             "  x, y);",
7171             format("f(g(h(a, // comment\n"
7172                    "    b, c), d, e), x, y);"));
7173 
7174   // Prefer breaking similar line breaks.
7175   verifyFormat(
7176       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7177       "                             NSTrackingMouseEnteredAndExited |\n"
7178       "                             NSTrackingActiveAlways;");
7179 }
7180 
7181 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7182   FormatStyle NoBinPacking = getGoogleStyle();
7183   NoBinPacking.BinPackParameters = false;
7184   NoBinPacking.BinPackArguments = true;
7185   verifyFormat("void f() {\n"
7186                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7187                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7188                "}",
7189                NoBinPacking);
7190   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7191                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7192                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7193                NoBinPacking);
7194 
7195   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7196   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7197                "                        vector<int> bbbbbbbbbbbbbbb);",
7198                NoBinPacking);
7199   // FIXME: This behavior difference is probably not wanted. However, currently
7200   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7201   // template arguments from BreakBeforeParameter being set because of the
7202   // one-per-line formatting.
7203   verifyFormat(
7204       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7205       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7206       NoBinPacking);
7207   verifyFormat(
7208       "void fffffffffff(\n"
7209       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7210       "        aaaaaaaaaa);");
7211 }
7212 
7213 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7214   FormatStyle NoBinPacking = getGoogleStyle();
7215   NoBinPacking.BinPackParameters = false;
7216   NoBinPacking.BinPackArguments = false;
7217   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7218                "  aaaaaaaaaaaaaaaaaaaa,\n"
7219                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7220                NoBinPacking);
7221   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7222                "        aaaaaaaaaaaaa,\n"
7223                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7224                NoBinPacking);
7225   verifyFormat(
7226       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7227       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7228       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7229       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7230       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7231       NoBinPacking);
7232   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7233                "    .aaaaaaaaaaaaaaaaaa();",
7234                NoBinPacking);
7235   verifyFormat("void f() {\n"
7236                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7237                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7238                "}",
7239                NoBinPacking);
7240 
7241   verifyFormat(
7242       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7243       "             aaaaaaaaaaaa,\n"
7244       "             aaaaaaaaaaaa);",
7245       NoBinPacking);
7246   verifyFormat(
7247       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7248       "                               ddddddddddddddddddddddddddddd),\n"
7249       "             test);",
7250       NoBinPacking);
7251 
7252   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7253                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7254                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7255                "    aaaaaaaaaaaaaaaaaa;",
7256                NoBinPacking);
7257   verifyFormat("a(\"a\"\n"
7258                "  \"a\",\n"
7259                "  a);");
7260 
7261   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7262   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7263                "                aaaaaaaaa,\n"
7264                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7265                NoBinPacking);
7266   verifyFormat(
7267       "void f() {\n"
7268       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7269       "      .aaaaaaa();\n"
7270       "}",
7271       NoBinPacking);
7272   verifyFormat(
7273       "template <class SomeType, class SomeOtherType>\n"
7274       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7275       NoBinPacking);
7276 }
7277 
7278 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7279   FormatStyle Style = getLLVMStyleWithColumns(15);
7280   Style.ExperimentalAutoDetectBinPacking = true;
7281   EXPECT_EQ("aaa(aaaa,\n"
7282             "    aaaa,\n"
7283             "    aaaa);\n"
7284             "aaa(aaaa,\n"
7285             "    aaaa,\n"
7286             "    aaaa);",
7287             format("aaa(aaaa,\n" // one-per-line
7288                    "  aaaa,\n"
7289                    "    aaaa  );\n"
7290                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7291                    Style));
7292   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7293             "    aaaa);\n"
7294             "aaa(aaaa, aaaa,\n"
7295             "    aaaa);",
7296             format("aaa(aaaa,  aaaa,\n" // bin-packed
7297                    "    aaaa  );\n"
7298                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7299                    Style));
7300 }
7301 
7302 TEST_F(FormatTest, FormatsBuilderPattern) {
7303   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7304                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7305                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7306                "    .StartsWith(\".init\", ORDER_INIT)\n"
7307                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7308                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7309                "    .Default(ORDER_TEXT);\n");
7310 
7311   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7312                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7313   verifyFormat("aaaaaaa->aaaaaaa\n"
7314                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7315                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7316                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7317   verifyFormat(
7318       "aaaaaaa->aaaaaaa\n"
7319       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7320       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7321   verifyFormat(
7322       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7323       "    aaaaaaaaaaaaaa);");
7324   verifyFormat(
7325       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7326       "    aaaaaa->aaaaaaaaaaaa()\n"
7327       "        ->aaaaaaaaaaaaaaaa(\n"
7328       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7329       "        ->aaaaaaaaaaaaaaaaa();");
7330   verifyGoogleFormat(
7331       "void f() {\n"
7332       "  someo->Add((new util::filetools::Handler(dir))\n"
7333       "                 ->OnEvent1(NewPermanentCallback(\n"
7334       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7335       "                 ->OnEvent2(NewPermanentCallback(\n"
7336       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7337       "                 ->OnEvent3(NewPermanentCallback(\n"
7338       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7339       "                 ->OnEvent5(NewPermanentCallback(\n"
7340       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7341       "                 ->OnEvent6(NewPermanentCallback(\n"
7342       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7343       "}");
7344 
7345   verifyFormat(
7346       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7347   verifyFormat("aaaaaaaaaaaaaaa()\n"
7348                "    .aaaaaaaaaaaaaaa()\n"
7349                "    .aaaaaaaaaaaaaaa()\n"
7350                "    .aaaaaaaaaaaaaaa()\n"
7351                "    .aaaaaaaaaaaaaaa();");
7352   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7353                "    .aaaaaaaaaaaaaaa()\n"
7354                "    .aaaaaaaaaaaaaaa()\n"
7355                "    .aaaaaaaaaaaaaaa();");
7356   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7357                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7358                "    .aaaaaaaaaaaaaaa();");
7359   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7360                "    ->aaaaaaaaaaaaaae(0)\n"
7361                "    ->aaaaaaaaaaaaaaa();");
7362 
7363   // Don't linewrap after very short segments.
7364   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7365                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7366                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7367   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7368                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7369                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7370   verifyFormat("aaa()\n"
7371                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7372                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7373                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7374 
7375   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7376                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7377                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7378   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7379                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7380                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7381 
7382   // Prefer not to break after empty parentheses.
7383   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7384                "    First->LastNewlineOffset);");
7385 
7386   // Prefer not to create "hanging" indents.
7387   verifyFormat(
7388       "return !soooooooooooooome_map\n"
7389       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7390       "            .second;");
7391   verifyFormat(
7392       "return aaaaaaaaaaaaaaaa\n"
7393       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7394       "    .aaaa(aaaaaaaaaaaaaa);");
7395   // No hanging indent here.
7396   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7397                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7398   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7399                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7400   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7401                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7402                getLLVMStyleWithColumns(60));
7403   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7404                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7405                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7406                getLLVMStyleWithColumns(59));
7407   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7408                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7409                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7410 
7411   // Dont break if only closing statements before member call
7412   verifyFormat("test() {\n"
7413                "  ([]() -> {\n"
7414                "    int b = 32;\n"
7415                "    return 3;\n"
7416                "  }).foo();\n"
7417                "}");
7418   verifyFormat("test() {\n"
7419                "  (\n"
7420                "      []() -> {\n"
7421                "        int b = 32;\n"
7422                "        return 3;\n"
7423                "      },\n"
7424                "      foo, bar)\n"
7425                "      .foo();\n"
7426                "}");
7427   verifyFormat("test() {\n"
7428                "  ([]() -> {\n"
7429                "    int b = 32;\n"
7430                "    return 3;\n"
7431                "  })\n"
7432                "      .foo()\n"
7433                "      .bar();\n"
7434                "}");
7435   verifyFormat("test() {\n"
7436                "  ([]() -> {\n"
7437                "    int b = 32;\n"
7438                "    return 3;\n"
7439                "  })\n"
7440                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7441                "           \"bbbb\");\n"
7442                "}",
7443                getLLVMStyleWithColumns(30));
7444 }
7445 
7446 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7447   verifyFormat(
7448       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7449       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7450   verifyFormat(
7451       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7452       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7453 
7454   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7455                "    ccccccccccccccccccccccccc) {\n}");
7456   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7457                "    ccccccccccccccccccccccccc) {\n}");
7458 
7459   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7460                "    ccccccccccccccccccccccccc) {\n}");
7461   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7462                "    ccccccccccccccccccccccccc) {\n}");
7463 
7464   verifyFormat(
7465       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7466       "    ccccccccccccccccccccccccc) {\n}");
7467   verifyFormat(
7468       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7469       "    ccccccccccccccccccccccccc) {\n}");
7470 
7471   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7472                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7473                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7474                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7475   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7476                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7477                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7478                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7479 
7480   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7481                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7482                "    aaaaaaaaaaaaaaa != aa) {\n}");
7483   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7484                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7485                "    aaaaaaaaaaaaaaa != aa) {\n}");
7486 }
7487 
7488 TEST_F(FormatTest, BreaksAfterAssignments) {
7489   verifyFormat(
7490       "unsigned Cost =\n"
7491       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7492       "                        SI->getPointerAddressSpaceee());\n");
7493   verifyFormat(
7494       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7495       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7496 
7497   verifyFormat(
7498       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7499       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7500   verifyFormat("unsigned OriginalStartColumn =\n"
7501                "    SourceMgr.getSpellingColumnNumber(\n"
7502                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7503                "    1;");
7504 }
7505 
7506 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7507   FormatStyle Style = getLLVMStyle();
7508   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7509                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7510                Style);
7511 
7512   Style.PenaltyBreakAssignment = 20;
7513   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7514                "                                 cccccccccccccccccccccccccc;",
7515                Style);
7516 }
7517 
7518 TEST_F(FormatTest, AlignsAfterAssignments) {
7519   verifyFormat(
7520       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7521       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7522   verifyFormat(
7523       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7524       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7525   verifyFormat(
7526       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7527       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7528   verifyFormat(
7529       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7530       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7531   verifyFormat(
7532       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7533       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7534       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7535 }
7536 
7537 TEST_F(FormatTest, AlignsAfterReturn) {
7538   verifyFormat(
7539       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7540       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7541   verifyFormat(
7542       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7543       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7544   verifyFormat(
7545       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7546       "       aaaaaaaaaaaaaaaaaaaaaa();");
7547   verifyFormat(
7548       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7549       "        aaaaaaaaaaaaaaaaaaaaaa());");
7550   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7551                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7552   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7553                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7554                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7555   verifyFormat("return\n"
7556                "    // true if code is one of a or b.\n"
7557                "    code == a || code == b;");
7558 }
7559 
7560 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7561   verifyFormat(
7562       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7563       "                                                aaaaaaaaa aaaaaaa) {}");
7564   verifyFormat(
7565       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7566       "                                               aaaaaaaaaaa aaaaaaaaa);");
7567   verifyFormat(
7568       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7569       "                                             aaaaaaaaaaaaaaaaaaaaa));");
7570   FormatStyle Style = getLLVMStyle();
7571   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7572   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7573                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
7574                Style);
7575   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7576                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
7577                Style);
7578   verifyFormat("SomeLongVariableName->someFunction(\n"
7579                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
7580                Style);
7581   verifyFormat(
7582       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7583       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7584       Style);
7585   verifyFormat(
7586       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7587       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7588       Style);
7589   verifyFormat(
7590       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7591       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7592       Style);
7593 
7594   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
7595                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
7596                "        b));",
7597                Style);
7598 
7599   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7600   Style.BinPackArguments = false;
7601   Style.BinPackParameters = false;
7602   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7603                "    aaaaaaaaaaa aaaaaaaa,\n"
7604                "    aaaaaaaaa aaaaaaa,\n"
7605                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7606                Style);
7607   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7608                "    aaaaaaaaaaa aaaaaaaaa,\n"
7609                "    aaaaaaaaaaa aaaaaaaaa,\n"
7610                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7611                Style);
7612   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
7613                "    aaaaaaaaaaaaaaa,\n"
7614                "    aaaaaaaaaaaaaaaaaaaaa,\n"
7615                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7616                Style);
7617   verifyFormat(
7618       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
7619       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7620       Style);
7621   verifyFormat(
7622       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
7623       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7624       Style);
7625   verifyFormat(
7626       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7627       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7628       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
7629       "    aaaaaaaaaaaaaaaa);",
7630       Style);
7631   verifyFormat(
7632       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7633       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7634       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
7635       "    aaaaaaaaaaaaaaaa);",
7636       Style);
7637 }
7638 
7639 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
7640   FormatStyle Style = getLLVMStyleWithColumns(40);
7641   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7642                "          bbbbbbbbbbbbbbbbbbbbbb);",
7643                Style);
7644   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7645   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7646   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7647                "          bbbbbbbbbbbbbbbbbbbbbb);",
7648                Style);
7649   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7650   Style.AlignOperands = FormatStyle::OAS_Align;
7651   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7652                "          bbbbbbbbbbbbbbbbbbbbbb);",
7653                Style);
7654   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7655   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7656   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7657                "    bbbbbbbbbbbbbbbbbbbbbb);",
7658                Style);
7659 }
7660 
7661 TEST_F(FormatTest, BreaksConditionalExpressions) {
7662   verifyFormat(
7663       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7664       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7665       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7666   verifyFormat(
7667       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7668       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7669       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7670   verifyFormat(
7671       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7672       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7673   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
7674                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7675                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7676   verifyFormat(
7677       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
7678       "                                                    : aaaaaaaaaaaaa);");
7679   verifyFormat(
7680       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7681       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7682       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7683       "                   aaaaaaaaaaaaa);");
7684   verifyFormat(
7685       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7686       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7687       "                   aaaaaaaaaaaaa);");
7688   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7689                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7690                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7691                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7692                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7693   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7694                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7695                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7696                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7697                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7698                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7699                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7700   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7701                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7702                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7703                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7704                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7705   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7706                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7707                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7708   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7709                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7710                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7711                "        : aaaaaaaaaaaaaaaa;");
7712   verifyFormat(
7713       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7714       "    ? aaaaaaaaaaaaaaa\n"
7715       "    : aaaaaaaaaaaaaaa;");
7716   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7717                "          aaaaaaaaa\n"
7718                "      ? b\n"
7719                "      : c);");
7720   verifyFormat("return aaaa == bbbb\n"
7721                "           // comment\n"
7722                "           ? aaaa\n"
7723                "           : bbbb;");
7724   verifyFormat("unsigned Indent =\n"
7725                "    format(TheLine.First,\n"
7726                "           IndentForLevel[TheLine.Level] >= 0\n"
7727                "               ? IndentForLevel[TheLine.Level]\n"
7728                "               : TheLine * 2,\n"
7729                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
7730                getLLVMStyleWithColumns(60));
7731   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7732                "                  ? aaaaaaaaaaaaaaa\n"
7733                "                  : bbbbbbbbbbbbbbb //\n"
7734                "                        ? ccccccccccccccc\n"
7735                "                        : ddddddddddddddd;");
7736   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7737                "                  ? aaaaaaaaaaaaaaa\n"
7738                "                  : (bbbbbbbbbbbbbbb //\n"
7739                "                         ? ccccccccccccccc\n"
7740                "                         : ddddddddddddddd);");
7741   verifyFormat(
7742       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7743       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7744       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
7745       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
7746       "                                      : aaaaaaaaaa;");
7747   verifyFormat(
7748       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7749       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
7750       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7751 
7752   FormatStyle NoBinPacking = getLLVMStyle();
7753   NoBinPacking.BinPackArguments = false;
7754   verifyFormat(
7755       "void f() {\n"
7756       "  g(aaa,\n"
7757       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7758       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7759       "        ? aaaaaaaaaaaaaaa\n"
7760       "        : aaaaaaaaaaaaaaa);\n"
7761       "}",
7762       NoBinPacking);
7763   verifyFormat(
7764       "void f() {\n"
7765       "  g(aaa,\n"
7766       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7767       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7768       "        ?: aaaaaaaaaaaaaaa);\n"
7769       "}",
7770       NoBinPacking);
7771 
7772   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
7773                "             // comment.\n"
7774                "             ccccccccccccccccccccccccccccccccccccccc\n"
7775                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7776                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
7777 
7778   // Assignments in conditional expressions. Apparently not uncommon :-(.
7779   verifyFormat("return a != b\n"
7780                "           // comment\n"
7781                "           ? a = b\n"
7782                "           : a = b;");
7783   verifyFormat("return a != b\n"
7784                "           // comment\n"
7785                "           ? a = a != b\n"
7786                "                     // comment\n"
7787                "                     ? a = b\n"
7788                "                     : a\n"
7789                "           : a;\n");
7790   verifyFormat("return a != b\n"
7791                "           // comment\n"
7792                "           ? a\n"
7793                "           : a = a != b\n"
7794                "                     // comment\n"
7795                "                     ? a = b\n"
7796                "                     : a;");
7797 
7798   // Chained conditionals
7799   FormatStyle Style = getLLVMStyleWithColumns(70);
7800   Style.AlignOperands = FormatStyle::OAS_Align;
7801   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7802                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7803                "                        : 3333333333333333;",
7804                Style);
7805   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7806                "       : bbbbbbbbbb     ? 2222222222222222\n"
7807                "                        : 3333333333333333;",
7808                Style);
7809   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
7810                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
7811                "                          : 3333333333333333;",
7812                Style);
7813   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7814                "       : bbbbbbbbbbbbbb ? 222222\n"
7815                "                        : 333333;",
7816                Style);
7817   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7818                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7819                "       : cccccccccccccc ? 3333333333333333\n"
7820                "                        : 4444444444444444;",
7821                Style);
7822   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
7823                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7824                "                        : 3333333333333333;",
7825                Style);
7826   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7827                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7828                "                        : (aaa ? bbb : ccc);",
7829                Style);
7830   verifyFormat(
7831       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7832       "                                             : cccccccccccccccccc)\n"
7833       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7834       "                        : 3333333333333333;",
7835       Style);
7836   verifyFormat(
7837       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7838       "                                             : cccccccccccccccccc)\n"
7839       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7840       "                        : 3333333333333333;",
7841       Style);
7842   verifyFormat(
7843       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7844       "                                             : dddddddddddddddddd)\n"
7845       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7846       "                        : 3333333333333333;",
7847       Style);
7848   verifyFormat(
7849       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7850       "                                             : dddddddddddddddddd)\n"
7851       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7852       "                        : 3333333333333333;",
7853       Style);
7854   verifyFormat(
7855       "return aaaaaaaaa        ? 1111111111111111\n"
7856       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7857       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7858       "                                             : dddddddddddddddddd)\n",
7859       Style);
7860   verifyFormat(
7861       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7862       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7863       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7864       "                                             : cccccccccccccccccc);",
7865       Style);
7866   verifyFormat(
7867       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7868       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7869       "                                             : eeeeeeeeeeeeeeeeee)\n"
7870       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7871       "                        : 3333333333333333;",
7872       Style);
7873   verifyFormat(
7874       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
7875       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7876       "                                             : eeeeeeeeeeeeeeeeee)\n"
7877       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7878       "                        : 3333333333333333;",
7879       Style);
7880   verifyFormat(
7881       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7882       "                           : cccccccccccc    ? dddddddddddddddddd\n"
7883       "                                             : eeeeeeeeeeeeeeeeee)\n"
7884       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7885       "                        : 3333333333333333;",
7886       Style);
7887   verifyFormat(
7888       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7889       "                                             : cccccccccccccccccc\n"
7890       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7891       "                        : 3333333333333333;",
7892       Style);
7893   verifyFormat(
7894       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7895       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
7896       "                                             : eeeeeeeeeeeeeeeeee\n"
7897       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7898       "                        : 3333333333333333;",
7899       Style);
7900   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
7901                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
7902                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
7903                "                                   : eeeeeeeeeeeeeeeeee)\n"
7904                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7905                "                             : 3333333333333333;",
7906                Style);
7907   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
7908                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7909                "             : cccccccccccccccc ? dddddddddddddddddd\n"
7910                "                                : eeeeeeeeeeeeeeeeee\n"
7911                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7912                "                                 : 3333333333333333;",
7913                Style);
7914 
7915   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7916   Style.BreakBeforeTernaryOperators = false;
7917   // FIXME: Aligning the question marks is weird given DontAlign.
7918   // Consider disabling this alignment in this case. Also check whether this
7919   // will render the adjustment from https://reviews.llvm.org/D82199
7920   // unnecessary.
7921   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
7922                "    bbbb                ? cccccccccccccccccc :\n"
7923                "                          ddddd;\n",
7924                Style);
7925 
7926   EXPECT_EQ(
7927       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7928       "    /*\n"
7929       "     */\n"
7930       "    function() {\n"
7931       "      try {\n"
7932       "        return JJJJJJJJJJJJJJ(\n"
7933       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7934       "      }\n"
7935       "    } :\n"
7936       "    function() {};",
7937       format(
7938           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7939           "     /*\n"
7940           "      */\n"
7941           "     function() {\n"
7942           "      try {\n"
7943           "        return JJJJJJJJJJJJJJ(\n"
7944           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7945           "      }\n"
7946           "    } :\n"
7947           "    function() {};",
7948           getGoogleStyle(FormatStyle::LK_JavaScript)));
7949 }
7950 
7951 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
7952   FormatStyle Style = getLLVMStyleWithColumns(70);
7953   Style.BreakBeforeTernaryOperators = false;
7954   verifyFormat(
7955       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7956       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7957       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7958       Style);
7959   verifyFormat(
7960       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7961       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7962       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7963       Style);
7964   verifyFormat(
7965       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7966       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7967       Style);
7968   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
7969                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7970                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7971                Style);
7972   verifyFormat(
7973       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
7974       "                                                      aaaaaaaaaaaaa);",
7975       Style);
7976   verifyFormat(
7977       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7978       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7979       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7980       "                   aaaaaaaaaaaaa);",
7981       Style);
7982   verifyFormat(
7983       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7984       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7985       "                   aaaaaaaaaaaaa);",
7986       Style);
7987   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7988                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7989                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7990                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7991                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7992                Style);
7993   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7994                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7995                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7996                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7997                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7998                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7999                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8000                Style);
8001   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8002                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
8003                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8004                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8005                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8006                Style);
8007   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8008                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8009                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8010                Style);
8011   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8012                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8013                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8014                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8015                Style);
8016   verifyFormat(
8017       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8018       "    aaaaaaaaaaaaaaa :\n"
8019       "    aaaaaaaaaaaaaaa;",
8020       Style);
8021   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8022                "          aaaaaaaaa ?\n"
8023                "      b :\n"
8024                "      c);",
8025                Style);
8026   verifyFormat("unsigned Indent =\n"
8027                "    format(TheLine.First,\n"
8028                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
8029                "               IndentForLevel[TheLine.Level] :\n"
8030                "               TheLine * 2,\n"
8031                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8032                Style);
8033   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8034                "                  aaaaaaaaaaaaaaa :\n"
8035                "                  bbbbbbbbbbbbbbb ? //\n"
8036                "                      ccccccccccccccc :\n"
8037                "                      ddddddddddddddd;",
8038                Style);
8039   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8040                "                  aaaaaaaaaaaaaaa :\n"
8041                "                  (bbbbbbbbbbbbbbb ? //\n"
8042                "                       ccccccccccccccc :\n"
8043                "                       ddddddddddddddd);",
8044                Style);
8045   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8046                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
8047                "            ccccccccccccccccccccccccccc;",
8048                Style);
8049   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8050                "           aaaaa :\n"
8051                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
8052                Style);
8053 
8054   // Chained conditionals
8055   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8056                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8057                "                          3333333333333333;",
8058                Style);
8059   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8060                "       bbbbbbbbbb       ? 2222222222222222 :\n"
8061                "                          3333333333333333;",
8062                Style);
8063   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
8064                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8065                "                          3333333333333333;",
8066                Style);
8067   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8068                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
8069                "                          333333;",
8070                Style);
8071   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8072                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8073                "       cccccccccccccccc ? 3333333333333333 :\n"
8074                "                          4444444444444444;",
8075                Style);
8076   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
8077                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8078                "                          3333333333333333;",
8079                Style);
8080   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8081                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8082                "                          (aaa ? bbb : ccc);",
8083                Style);
8084   verifyFormat(
8085       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8086       "                                               cccccccccccccccccc) :\n"
8087       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8088       "                          3333333333333333;",
8089       Style);
8090   verifyFormat(
8091       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8092       "                                               cccccccccccccccccc) :\n"
8093       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8094       "                          3333333333333333;",
8095       Style);
8096   verifyFormat(
8097       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8098       "                                               dddddddddddddddddd) :\n"
8099       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8100       "                          3333333333333333;",
8101       Style);
8102   verifyFormat(
8103       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8104       "                                               dddddddddddddddddd) :\n"
8105       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8106       "                          3333333333333333;",
8107       Style);
8108   verifyFormat(
8109       "return aaaaaaaaa        ? 1111111111111111 :\n"
8110       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8111       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8112       "                                               dddddddddddddddddd)\n",
8113       Style);
8114   verifyFormat(
8115       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8116       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8117       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8118       "                                               cccccccccccccccccc);",
8119       Style);
8120   verifyFormat(
8121       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8122       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8123       "                                               eeeeeeeeeeeeeeeeee) :\n"
8124       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8125       "                          3333333333333333;",
8126       Style);
8127   verifyFormat(
8128       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8129       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8130       "                                               eeeeeeeeeeeeeeeeee) :\n"
8131       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8132       "                          3333333333333333;",
8133       Style);
8134   verifyFormat(
8135       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8136       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8137       "                                               eeeeeeeeeeeeeeeeee) :\n"
8138       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8139       "                          3333333333333333;",
8140       Style);
8141   verifyFormat(
8142       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8143       "                                               cccccccccccccccccc :\n"
8144       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8145       "                          3333333333333333;",
8146       Style);
8147   verifyFormat(
8148       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8149       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8150       "                                               eeeeeeeeeeeeeeeeee :\n"
8151       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8152       "                          3333333333333333;",
8153       Style);
8154   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8155                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8156                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8157                "                                 eeeeeeeeeeeeeeeeee) :\n"
8158                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8159                "                               3333333333333333;",
8160                Style);
8161   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8162                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8163                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8164                "                                  eeeeeeeeeeeeeeeeee :\n"
8165                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8166                "                               3333333333333333;",
8167                Style);
8168 }
8169 
8170 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8171   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8172                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8173   verifyFormat("bool a = true, b = false;");
8174 
8175   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8176                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8177                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8178                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8179   verifyFormat(
8180       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8181       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8182       "     d = e && f;");
8183   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8184                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8185   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8186                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8187   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8188                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8189 
8190   FormatStyle Style = getGoogleStyle();
8191   Style.PointerAlignment = FormatStyle::PAS_Left;
8192   Style.DerivePointerAlignment = false;
8193   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8194                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8195                "    *b = bbbbbbbbbbbbbbbbbbb;",
8196                Style);
8197   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8198                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8199                Style);
8200   verifyFormat("vector<int*> a, b;", Style);
8201   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8202 }
8203 
8204 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8205   verifyFormat("arr[foo ? bar : baz];");
8206   verifyFormat("f()[foo ? bar : baz];");
8207   verifyFormat("(a + b)[foo ? bar : baz];");
8208   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8209 }
8210 
8211 TEST_F(FormatTest, AlignsStringLiterals) {
8212   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8213                "                                      \"short literal\");");
8214   verifyFormat(
8215       "looooooooooooooooooooooooongFunction(\n"
8216       "    \"short literal\"\n"
8217       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8218   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8219                "             \" string literals\",\n"
8220                "             and, other, parameters);");
8221   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8222             "      \"5678\";",
8223             format("fun + \"1243\" /* comment */\n"
8224                    "    \"5678\";",
8225                    getLLVMStyleWithColumns(28)));
8226   EXPECT_EQ(
8227       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8228       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8229       "         \"aaaaaaaaaaaaaaaa\";",
8230       format("aaaaaa ="
8231              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8232              "aaaaaaaaaaaaaaaaaaaaa\" "
8233              "\"aaaaaaaaaaaaaaaa\";"));
8234   verifyFormat("a = a + \"a\"\n"
8235                "        \"a\"\n"
8236                "        \"a\";");
8237   verifyFormat("f(\"a\", \"b\"\n"
8238                "       \"c\");");
8239 
8240   verifyFormat(
8241       "#define LL_FORMAT \"ll\"\n"
8242       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8243       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8244 
8245   verifyFormat("#define A(X)          \\\n"
8246                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8247                "  \"ccccc\"",
8248                getLLVMStyleWithColumns(23));
8249   verifyFormat("#define A \"def\"\n"
8250                "f(\"abc\" A \"ghi\"\n"
8251                "  \"jkl\");");
8252 
8253   verifyFormat("f(L\"a\"\n"
8254                "  L\"b\");");
8255   verifyFormat("#define A(X)            \\\n"
8256                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8257                "  L\"ccccc\"",
8258                getLLVMStyleWithColumns(25));
8259 
8260   verifyFormat("f(@\"a\"\n"
8261                "  @\"b\");");
8262   verifyFormat("NSString s = @\"a\"\n"
8263                "             @\"b\"\n"
8264                "             @\"c\";");
8265   verifyFormat("NSString s = @\"a\"\n"
8266                "              \"b\"\n"
8267                "              \"c\";");
8268 }
8269 
8270 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8271   FormatStyle Style = getLLVMStyle();
8272   // No declarations or definitions should be moved to own line.
8273   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8274   verifyFormat("class A {\n"
8275                "  int f() { return 1; }\n"
8276                "  int g();\n"
8277                "};\n"
8278                "int f() { return 1; }\n"
8279                "int g();\n",
8280                Style);
8281 
8282   // All declarations and definitions should have the return type moved to its
8283   // own line.
8284   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8285   Style.TypenameMacros = {"LIST"};
8286   verifyFormat("SomeType\n"
8287                "funcdecl(LIST(uint64_t));",
8288                Style);
8289   verifyFormat("class E {\n"
8290                "  int\n"
8291                "  f() {\n"
8292                "    return 1;\n"
8293                "  }\n"
8294                "  int\n"
8295                "  g();\n"
8296                "};\n"
8297                "int\n"
8298                "f() {\n"
8299                "  return 1;\n"
8300                "}\n"
8301                "int\n"
8302                "g();\n",
8303                Style);
8304 
8305   // Top-level definitions, and no kinds of declarations should have the
8306   // return type moved to its own line.
8307   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8308   verifyFormat("class B {\n"
8309                "  int f() { return 1; }\n"
8310                "  int g();\n"
8311                "};\n"
8312                "int\n"
8313                "f() {\n"
8314                "  return 1;\n"
8315                "}\n"
8316                "int g();\n",
8317                Style);
8318 
8319   // Top-level definitions and declarations should have the return type moved
8320   // to its own line.
8321   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8322   verifyFormat("class C {\n"
8323                "  int f() { return 1; }\n"
8324                "  int g();\n"
8325                "};\n"
8326                "int\n"
8327                "f() {\n"
8328                "  return 1;\n"
8329                "}\n"
8330                "int\n"
8331                "g();\n",
8332                Style);
8333 
8334   // All definitions should have the return type moved to its own line, but no
8335   // kinds of declarations.
8336   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8337   verifyFormat("class D {\n"
8338                "  int\n"
8339                "  f() {\n"
8340                "    return 1;\n"
8341                "  }\n"
8342                "  int g();\n"
8343                "};\n"
8344                "int\n"
8345                "f() {\n"
8346                "  return 1;\n"
8347                "}\n"
8348                "int g();\n",
8349                Style);
8350   verifyFormat("const char *\n"
8351                "f(void) {\n" // Break here.
8352                "  return \"\";\n"
8353                "}\n"
8354                "const char *bar(void);\n", // No break here.
8355                Style);
8356   verifyFormat("template <class T>\n"
8357                "T *\n"
8358                "f(T &c) {\n" // Break here.
8359                "  return NULL;\n"
8360                "}\n"
8361                "template <class T> T *f(T &c);\n", // No break here.
8362                Style);
8363   verifyFormat("class C {\n"
8364                "  int\n"
8365                "  operator+() {\n"
8366                "    return 1;\n"
8367                "  }\n"
8368                "  int\n"
8369                "  operator()() {\n"
8370                "    return 1;\n"
8371                "  }\n"
8372                "};\n",
8373                Style);
8374   verifyFormat("void\n"
8375                "A::operator()() {}\n"
8376                "void\n"
8377                "A::operator>>() {}\n"
8378                "void\n"
8379                "A::operator+() {}\n"
8380                "void\n"
8381                "A::operator*() {}\n"
8382                "void\n"
8383                "A::operator->() {}\n"
8384                "void\n"
8385                "A::operator void *() {}\n"
8386                "void\n"
8387                "A::operator void &() {}\n"
8388                "void\n"
8389                "A::operator void &&() {}\n"
8390                "void\n"
8391                "A::operator char *() {}\n"
8392                "void\n"
8393                "A::operator[]() {}\n"
8394                "void\n"
8395                "A::operator!() {}\n"
8396                "void\n"
8397                "A::operator**() {}\n"
8398                "void\n"
8399                "A::operator<Foo> *() {}\n"
8400                "void\n"
8401                "A::operator<Foo> **() {}\n"
8402                "void\n"
8403                "A::operator<Foo> &() {}\n"
8404                "void\n"
8405                "A::operator void **() {}\n",
8406                Style);
8407   verifyFormat("constexpr auto\n"
8408                "operator()() const -> reference {}\n"
8409                "constexpr auto\n"
8410                "operator>>() const -> reference {}\n"
8411                "constexpr auto\n"
8412                "operator+() const -> reference {}\n"
8413                "constexpr auto\n"
8414                "operator*() const -> reference {}\n"
8415                "constexpr auto\n"
8416                "operator->() const -> reference {}\n"
8417                "constexpr auto\n"
8418                "operator++() const -> reference {}\n"
8419                "constexpr auto\n"
8420                "operator void *() const -> reference {}\n"
8421                "constexpr auto\n"
8422                "operator void **() const -> reference {}\n"
8423                "constexpr auto\n"
8424                "operator void *() const -> reference {}\n"
8425                "constexpr auto\n"
8426                "operator void &() const -> reference {}\n"
8427                "constexpr auto\n"
8428                "operator void &&() const -> reference {}\n"
8429                "constexpr auto\n"
8430                "operator char *() const -> reference {}\n"
8431                "constexpr auto\n"
8432                "operator!() const -> reference {}\n"
8433                "constexpr auto\n"
8434                "operator[]() const -> reference {}\n",
8435                Style);
8436   verifyFormat("void *operator new(std::size_t s);", // No break here.
8437                Style);
8438   verifyFormat("void *\n"
8439                "operator new(std::size_t s) {}",
8440                Style);
8441   verifyFormat("void *\n"
8442                "operator delete[](void *ptr) {}",
8443                Style);
8444   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8445   verifyFormat("const char *\n"
8446                "f(void)\n" // Break here.
8447                "{\n"
8448                "  return \"\";\n"
8449                "}\n"
8450                "const char *bar(void);\n", // No break here.
8451                Style);
8452   verifyFormat("template <class T>\n"
8453                "T *\n"     // Problem here: no line break
8454                "f(T &c)\n" // Break here.
8455                "{\n"
8456                "  return NULL;\n"
8457                "}\n"
8458                "template <class T> T *f(T &c);\n", // No break here.
8459                Style);
8460   verifyFormat("int\n"
8461                "foo(A<bool> a)\n"
8462                "{\n"
8463                "  return a;\n"
8464                "}\n",
8465                Style);
8466   verifyFormat("int\n"
8467                "foo(A<8> a)\n"
8468                "{\n"
8469                "  return a;\n"
8470                "}\n",
8471                Style);
8472   verifyFormat("int\n"
8473                "foo(A<B<bool>, 8> a)\n"
8474                "{\n"
8475                "  return a;\n"
8476                "}\n",
8477                Style);
8478   verifyFormat("int\n"
8479                "foo(A<B<8>, bool> a)\n"
8480                "{\n"
8481                "  return a;\n"
8482                "}\n",
8483                Style);
8484   verifyFormat("int\n"
8485                "foo(A<B<bool>, bool> a)\n"
8486                "{\n"
8487                "  return a;\n"
8488                "}\n",
8489                Style);
8490   verifyFormat("int\n"
8491                "foo(A<B<8>, 8> a)\n"
8492                "{\n"
8493                "  return a;\n"
8494                "}\n",
8495                Style);
8496 
8497   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8498   Style.BraceWrapping.AfterFunction = true;
8499   verifyFormat("int f(i);\n" // No break here.
8500                "int\n"       // Break here.
8501                "f(i)\n"
8502                "{\n"
8503                "  return i + 1;\n"
8504                "}\n"
8505                "int\n" // Break here.
8506                "f(i)\n"
8507                "{\n"
8508                "  return i + 1;\n"
8509                "};",
8510                Style);
8511   verifyFormat("int f(a, b, c);\n" // No break here.
8512                "int\n"             // Break here.
8513                "f(a, b, c)\n"      // Break here.
8514                "short a, b;\n"
8515                "float c;\n"
8516                "{\n"
8517                "  return a + b < c;\n"
8518                "}\n"
8519                "int\n"        // Break here.
8520                "f(a, b, c)\n" // Break here.
8521                "short a, b;\n"
8522                "float c;\n"
8523                "{\n"
8524                "  return a + b < c;\n"
8525                "};",
8526                Style);
8527   verifyFormat("byte *\n" // Break here.
8528                "f(a)\n"   // Break here.
8529                "byte a[];\n"
8530                "{\n"
8531                "  return a;\n"
8532                "}",
8533                Style);
8534   verifyFormat("bool f(int a, int) override;\n"
8535                "Bar g(int a, Bar) final;\n"
8536                "Bar h(a, Bar) final;",
8537                Style);
8538   verifyFormat("int\n"
8539                "f(a)",
8540                Style);
8541   verifyFormat("bool\n"
8542                "f(size_t = 0, bool b = false)\n"
8543                "{\n"
8544                "  return !b;\n"
8545                "}",
8546                Style);
8547 
8548   // The return breaking style doesn't affect:
8549   // * function and object definitions with attribute-like macros
8550   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8551                "    ABSL_GUARDED_BY(mutex) = {};",
8552                getGoogleStyleWithColumns(40));
8553   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8554                "    ABSL_GUARDED_BY(mutex);  // comment",
8555                getGoogleStyleWithColumns(40));
8556   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8557                "    ABSL_GUARDED_BY(mutex1)\n"
8558                "        ABSL_GUARDED_BY(mutex2);",
8559                getGoogleStyleWithColumns(40));
8560   verifyFormat("Tttttt f(int a, int b)\n"
8561                "    ABSL_GUARDED_BY(mutex1)\n"
8562                "        ABSL_GUARDED_BY(mutex2);",
8563                getGoogleStyleWithColumns(40));
8564   // * typedefs
8565   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
8566 
8567   Style = getGNUStyle();
8568 
8569   // Test for comments at the end of function declarations.
8570   verifyFormat("void\n"
8571                "foo (int a, /*abc*/ int b) // def\n"
8572                "{\n"
8573                "}\n",
8574                Style);
8575 
8576   verifyFormat("void\n"
8577                "foo (int a, /* abc */ int b) /* def */\n"
8578                "{\n"
8579                "}\n",
8580                Style);
8581 
8582   // Definitions that should not break after return type
8583   verifyFormat("void foo (int a, int b); // def\n", Style);
8584   verifyFormat("void foo (int a, int b); /* def */\n", Style);
8585   verifyFormat("void foo (int a, int b);\n", Style);
8586 }
8587 
8588 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
8589   FormatStyle NoBreak = getLLVMStyle();
8590   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
8591   FormatStyle Break = getLLVMStyle();
8592   Break.AlwaysBreakBeforeMultilineStrings = true;
8593   verifyFormat("aaaa = \"bbbb\"\n"
8594                "       \"cccc\";",
8595                NoBreak);
8596   verifyFormat("aaaa =\n"
8597                "    \"bbbb\"\n"
8598                "    \"cccc\";",
8599                Break);
8600   verifyFormat("aaaa(\"bbbb\"\n"
8601                "     \"cccc\");",
8602                NoBreak);
8603   verifyFormat("aaaa(\n"
8604                "    \"bbbb\"\n"
8605                "    \"cccc\");",
8606                Break);
8607   verifyFormat("aaaa(qqq, \"bbbb\"\n"
8608                "          \"cccc\");",
8609                NoBreak);
8610   verifyFormat("aaaa(qqq,\n"
8611                "     \"bbbb\"\n"
8612                "     \"cccc\");",
8613                Break);
8614   verifyFormat("aaaa(qqq,\n"
8615                "     L\"bbbb\"\n"
8616                "     L\"cccc\");",
8617                Break);
8618   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
8619                "                      \"bbbb\"));",
8620                Break);
8621   verifyFormat("string s = someFunction(\n"
8622                "    \"abc\"\n"
8623                "    \"abc\");",
8624                Break);
8625 
8626   // As we break before unary operators, breaking right after them is bad.
8627   verifyFormat("string foo = abc ? \"x\"\n"
8628                "                   \"blah blah blah blah blah blah\"\n"
8629                "                 : \"y\";",
8630                Break);
8631 
8632   // Don't break if there is no column gain.
8633   verifyFormat("f(\"aaaa\"\n"
8634                "  \"bbbb\");",
8635                Break);
8636 
8637   // Treat literals with escaped newlines like multi-line string literals.
8638   EXPECT_EQ("x = \"a\\\n"
8639             "b\\\n"
8640             "c\";",
8641             format("x = \"a\\\n"
8642                    "b\\\n"
8643                    "c\";",
8644                    NoBreak));
8645   EXPECT_EQ("xxxx =\n"
8646             "    \"a\\\n"
8647             "b\\\n"
8648             "c\";",
8649             format("xxxx = \"a\\\n"
8650                    "b\\\n"
8651                    "c\";",
8652                    Break));
8653 
8654   EXPECT_EQ("NSString *const kString =\n"
8655             "    @\"aaaa\"\n"
8656             "    @\"bbbb\";",
8657             format("NSString *const kString = @\"aaaa\"\n"
8658                    "@\"bbbb\";",
8659                    Break));
8660 
8661   Break.ColumnLimit = 0;
8662   verifyFormat("const char *hello = \"hello llvm\";", Break);
8663 }
8664 
8665 TEST_F(FormatTest, AlignsPipes) {
8666   verifyFormat(
8667       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8668       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8669       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8670   verifyFormat(
8671       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
8672       "                     << aaaaaaaaaaaaaaaaaaaa;");
8673   verifyFormat(
8674       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8675       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8676   verifyFormat(
8677       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
8678       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8679   verifyFormat(
8680       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
8681       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
8682       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
8683   verifyFormat(
8684       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8685       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8686       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8687   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8688                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8689                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8690                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8691   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
8692                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
8693   verifyFormat(
8694       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8695       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8696   verifyFormat(
8697       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
8698       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
8699 
8700   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
8701                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
8702   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8703                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8704                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
8705                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
8706   verifyFormat("LOG_IF(aaa == //\n"
8707                "       bbb)\n"
8708                "    << a << b;");
8709 
8710   // But sometimes, breaking before the first "<<" is desirable.
8711   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8712                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
8713   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
8714                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8715                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8716   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
8717                "    << BEF << IsTemplate << Description << E->getType();");
8718   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8719                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8720                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8721   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8722                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8723                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8724                "    << aaa;");
8725 
8726   verifyFormat(
8727       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8728       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8729 
8730   // Incomplete string literal.
8731   EXPECT_EQ("llvm::errs() << \"\n"
8732             "             << a;",
8733             format("llvm::errs() << \"\n<<a;"));
8734 
8735   verifyFormat("void f() {\n"
8736                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
8737                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
8738                "}");
8739 
8740   // Handle 'endl'.
8741   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
8742                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8743   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8744 
8745   // Handle '\n'.
8746   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
8747                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8748   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
8749                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
8750   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
8751                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
8752   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8753 }
8754 
8755 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
8756   verifyFormat("return out << \"somepacket = {\\n\"\n"
8757                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
8758                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
8759                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
8760                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
8761                "           << \"}\";");
8762 
8763   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8764                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8765                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
8766   verifyFormat(
8767       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
8768       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
8769       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
8770       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
8771       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
8772   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
8773                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8774   verifyFormat(
8775       "void f() {\n"
8776       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
8777       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
8778       "}");
8779 
8780   // Breaking before the first "<<" is generally not desirable.
8781   verifyFormat(
8782       "llvm::errs()\n"
8783       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8784       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8785       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8786       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8787       getLLVMStyleWithColumns(70));
8788   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8789                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8790                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8791                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8792                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8793                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8794                getLLVMStyleWithColumns(70));
8795 
8796   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8797                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8798                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
8799   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8800                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8801                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
8802   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
8803                "           (aaaa + aaaa);",
8804                getLLVMStyleWithColumns(40));
8805   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
8806                "                  (aaaaaaa + aaaaa));",
8807                getLLVMStyleWithColumns(40));
8808   verifyFormat(
8809       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
8810       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
8811       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
8812 }
8813 
8814 TEST_F(FormatTest, UnderstandsEquals) {
8815   verifyFormat(
8816       "aaaaaaaaaaaaaaaaa =\n"
8817       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8818   verifyFormat(
8819       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8820       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8821   verifyFormat(
8822       "if (a) {\n"
8823       "  f();\n"
8824       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8825       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
8826       "}");
8827 
8828   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8829                "        100000000 + 10000000) {\n}");
8830 }
8831 
8832 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
8833   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8834                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
8835 
8836   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8837                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
8838 
8839   verifyFormat(
8840       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
8841       "                                                          Parameter2);");
8842 
8843   verifyFormat(
8844       "ShortObject->shortFunction(\n"
8845       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
8846       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
8847 
8848   verifyFormat("loooooooooooooongFunction(\n"
8849                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
8850 
8851   verifyFormat(
8852       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
8853       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
8854 
8855   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8856                "    .WillRepeatedly(Return(SomeValue));");
8857   verifyFormat("void f() {\n"
8858                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8859                "      .Times(2)\n"
8860                "      .WillRepeatedly(Return(SomeValue));\n"
8861                "}");
8862   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
8863                "    ccccccccccccccccccccccc);");
8864   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8865                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8866                "          .aaaaa(aaaaa),\n"
8867                "      aaaaaaaaaaaaaaaaaaaaa);");
8868   verifyFormat("void f() {\n"
8869                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8870                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
8871                "}");
8872   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8873                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8874                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8875                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8876                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
8877   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8878                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8879                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8880                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
8881                "}");
8882 
8883   // Here, it is not necessary to wrap at "." or "->".
8884   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
8885                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8886   verifyFormat(
8887       "aaaaaaaaaaa->aaaaaaaaa(\n"
8888       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8889       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
8890 
8891   verifyFormat(
8892       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8893       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
8894   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
8895                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8896   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
8897                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8898 
8899   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8900                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8901                "    .a();");
8902 
8903   FormatStyle NoBinPacking = getLLVMStyle();
8904   NoBinPacking.BinPackParameters = false;
8905   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8906                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8907                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
8908                "                         aaaaaaaaaaaaaaaaaaa,\n"
8909                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8910                NoBinPacking);
8911 
8912   // If there is a subsequent call, change to hanging indentation.
8913   verifyFormat(
8914       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8915       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
8916       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8917   verifyFormat(
8918       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8919       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
8920   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8921                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8922                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8923   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8924                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8925                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
8926 }
8927 
8928 TEST_F(FormatTest, WrapsTemplateDeclarations) {
8929   verifyFormat("template <typename T>\n"
8930                "virtual void loooooooooooongFunction(int Param1, int Param2);");
8931   verifyFormat("template <typename T>\n"
8932                "// T should be one of {A, B}.\n"
8933                "virtual void loooooooooooongFunction(int Param1, int Param2);");
8934   verifyFormat(
8935       "template <typename T>\n"
8936       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
8937   verifyFormat("template <typename T>\n"
8938                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
8939                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
8940   verifyFormat(
8941       "template <typename T>\n"
8942       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
8943       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
8944   verifyFormat(
8945       "template <typename T>\n"
8946       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
8947       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
8948       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8949   verifyFormat("template <typename T>\n"
8950                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8951                "    int aaaaaaaaaaaaaaaaaaaaaa);");
8952   verifyFormat(
8953       "template <typename T1, typename T2 = char, typename T3 = char,\n"
8954       "          typename T4 = char>\n"
8955       "void f();");
8956   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
8957                "          template <typename> class cccccccccccccccccccccc,\n"
8958                "          typename ddddddddddddd>\n"
8959                "class C {};");
8960   verifyFormat(
8961       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
8962       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8963 
8964   verifyFormat("void f() {\n"
8965                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
8966                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
8967                "}");
8968 
8969   verifyFormat("template <typename T> class C {};");
8970   verifyFormat("template <typename T> void f();");
8971   verifyFormat("template <typename T> void f() {}");
8972   verifyFormat(
8973       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8974       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8975       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
8976       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8977       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8978       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
8979       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
8980       getLLVMStyleWithColumns(72));
8981   EXPECT_EQ("static_cast<A< //\n"
8982             "    B> *>(\n"
8983             "\n"
8984             ");",
8985             format("static_cast<A<//\n"
8986                    "    B>*>(\n"
8987                    "\n"
8988                    "    );"));
8989   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8990                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
8991 
8992   FormatStyle AlwaysBreak = getLLVMStyle();
8993   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
8994   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
8995   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
8996   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
8997   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8998                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
8999                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
9000   verifyFormat("template <template <typename> class Fooooooo,\n"
9001                "          template <typename> class Baaaaaaar>\n"
9002                "struct C {};",
9003                AlwaysBreak);
9004   verifyFormat("template <typename T> // T can be A, B or C.\n"
9005                "struct C {};",
9006                AlwaysBreak);
9007   verifyFormat("template <enum E> class A {\n"
9008                "public:\n"
9009                "  E *f();\n"
9010                "};");
9011 
9012   FormatStyle NeverBreak = getLLVMStyle();
9013   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
9014   verifyFormat("template <typename T> class C {};", NeverBreak);
9015   verifyFormat("template <typename T> void f();", NeverBreak);
9016   verifyFormat("template <typename T> void f() {}", NeverBreak);
9017   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9018                "bbbbbbbbbbbbbbbbbbbb) {}",
9019                NeverBreak);
9020   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9021                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9022                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
9023                NeverBreak);
9024   verifyFormat("template <template <typename> class Fooooooo,\n"
9025                "          template <typename> class Baaaaaaar>\n"
9026                "struct C {};",
9027                NeverBreak);
9028   verifyFormat("template <typename T> // T can be A, B or C.\n"
9029                "struct C {};",
9030                NeverBreak);
9031   verifyFormat("template <enum E> class A {\n"
9032                "public:\n"
9033                "  E *f();\n"
9034                "};",
9035                NeverBreak);
9036   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
9037   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9038                "bbbbbbbbbbbbbbbbbbbb) {}",
9039                NeverBreak);
9040 }
9041 
9042 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
9043   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9044   Style.ColumnLimit = 60;
9045   EXPECT_EQ("// Baseline - no comments.\n"
9046             "template <\n"
9047             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9048             "void f() {}",
9049             format("// Baseline - no comments.\n"
9050                    "template <\n"
9051                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9052                    "void f() {}",
9053                    Style));
9054 
9055   EXPECT_EQ("template <\n"
9056             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9057             "void f() {}",
9058             format("template <\n"
9059                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9060                    "void f() {}",
9061                    Style));
9062 
9063   EXPECT_EQ(
9064       "template <\n"
9065       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
9066       "void f() {}",
9067       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
9068              "void f() {}",
9069              Style));
9070 
9071   EXPECT_EQ(
9072       "template <\n"
9073       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9074       "                                               // multiline\n"
9075       "void f() {}",
9076       format("template <\n"
9077              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9078              "                                              // multiline\n"
9079              "void f() {}",
9080              Style));
9081 
9082   EXPECT_EQ(
9083       "template <typename aaaaaaaaaa<\n"
9084       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
9085       "void f() {}",
9086       format(
9087           "template <\n"
9088           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
9089           "void f() {}",
9090           Style));
9091 }
9092 
9093 TEST_F(FormatTest, WrapsTemplateParameters) {
9094   FormatStyle Style = getLLVMStyle();
9095   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9096   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9097   verifyFormat(
9098       "template <typename... a> struct q {};\n"
9099       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9100       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9101       "    y;",
9102       Style);
9103   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9104   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9105   verifyFormat(
9106       "template <typename... a> struct r {};\n"
9107       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9108       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9109       "    y;",
9110       Style);
9111   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9112   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9113   verifyFormat("template <typename... a> struct s {};\n"
9114                "extern s<\n"
9115                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9116                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9117                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9118                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9119                "    y;",
9120                Style);
9121   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9122   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9123   verifyFormat("template <typename... a> struct t {};\n"
9124                "extern t<\n"
9125                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9126                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9127                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9128                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9129                "    y;",
9130                Style);
9131 }
9132 
9133 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9134   verifyFormat(
9135       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9136       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9137   verifyFormat(
9138       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9139       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9140       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9141 
9142   // FIXME: Should we have the extra indent after the second break?
9143   verifyFormat(
9144       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9145       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9146       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9147 
9148   verifyFormat(
9149       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9150       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9151 
9152   // Breaking at nested name specifiers is generally not desirable.
9153   verifyFormat(
9154       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9155       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9156 
9157   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9158                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9159                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9160                "                   aaaaaaaaaaaaaaaaaaaaa);",
9161                getLLVMStyleWithColumns(74));
9162 
9163   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9164                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9165                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9166 }
9167 
9168 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9169   verifyFormat("A<int> a;");
9170   verifyFormat("A<A<A<int>>> a;");
9171   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9172   verifyFormat("bool x = a < 1 || 2 > a;");
9173   verifyFormat("bool x = 5 < f<int>();");
9174   verifyFormat("bool x = f<int>() > 5;");
9175   verifyFormat("bool x = 5 < a<int>::x;");
9176   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9177   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9178 
9179   verifyGoogleFormat("A<A<int>> a;");
9180   verifyGoogleFormat("A<A<A<int>>> a;");
9181   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9182   verifyGoogleFormat("A<A<int> > a;");
9183   verifyGoogleFormat("A<A<A<int> > > a;");
9184   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9185   verifyGoogleFormat("A<::A<int>> a;");
9186   verifyGoogleFormat("A<::A> a;");
9187   verifyGoogleFormat("A< ::A> a;");
9188   verifyGoogleFormat("A< ::A<int> > a;");
9189   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9190   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9191   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9192   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9193   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9194             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9195 
9196   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9197 
9198   // template closer followed by a token that starts with > or =
9199   verifyFormat("bool b = a<1> > 1;");
9200   verifyFormat("bool b = a<1> >= 1;");
9201   verifyFormat("int i = a<1> >> 1;");
9202   FormatStyle Style = getLLVMStyle();
9203   Style.SpaceBeforeAssignmentOperators = false;
9204   verifyFormat("bool b= a<1> == 1;", Style);
9205   verifyFormat("a<int> = 1;", Style);
9206   verifyFormat("a<int> >>= 1;", Style);
9207 
9208   verifyFormat("test < a | b >> c;");
9209   verifyFormat("test<test<a | b>> c;");
9210   verifyFormat("test >> a >> b;");
9211   verifyFormat("test << a >> b;");
9212 
9213   verifyFormat("f<int>();");
9214   verifyFormat("template <typename T> void f() {}");
9215   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9216   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9217                "sizeof(char)>::type>;");
9218   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9219   verifyFormat("f(a.operator()<A>());");
9220   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9221                "      .template operator()<A>());",
9222                getLLVMStyleWithColumns(35));
9223 
9224   // Not template parameters.
9225   verifyFormat("return a < b && c > d;");
9226   verifyFormat("void f() {\n"
9227                "  while (a < b && c > d) {\n"
9228                "  }\n"
9229                "}");
9230   verifyFormat("template <typename... Types>\n"
9231                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9232 
9233   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9234                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9235                getLLVMStyleWithColumns(60));
9236   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9237   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9238   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9239   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9240 }
9241 
9242 TEST_F(FormatTest, UnderstandsShiftOperators) {
9243   verifyFormat("if (i < x >> 1)");
9244   verifyFormat("while (i < x >> 1)");
9245   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9246   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9247   verifyFormat(
9248       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9249   verifyFormat("Foo.call<Bar<Function>>()");
9250   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9251   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9252                "++i, v = v >> 1)");
9253   verifyFormat("if (w<u<v<x>>, 1>::t)");
9254 }
9255 
9256 TEST_F(FormatTest, BitshiftOperatorWidth) {
9257   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9258             "                   bar */",
9259             format("int    a=1<<2;  /* foo\n"
9260                    "                   bar */"));
9261 
9262   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9263             "                     bar */",
9264             format("int  b  =256>>1 ;  /* foo\n"
9265                    "                      bar */"));
9266 }
9267 
9268 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9269   verifyFormat("COMPARE(a, ==, b);");
9270   verifyFormat("auto s = sizeof...(Ts) - 1;");
9271 }
9272 
9273 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9274   verifyFormat("int A::*x;");
9275   verifyFormat("int (S::*func)(void *);");
9276   verifyFormat("void f() { int (S::*func)(void *); }");
9277   verifyFormat("typedef bool *(Class::*Member)() const;");
9278   verifyFormat("void f() {\n"
9279                "  (a->*f)();\n"
9280                "  a->*x;\n"
9281                "  (a.*f)();\n"
9282                "  ((*a).*f)();\n"
9283                "  a.*x;\n"
9284                "}");
9285   verifyFormat("void f() {\n"
9286                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9287                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9288                "}");
9289   verifyFormat(
9290       "(aaaaaaaaaa->*bbbbbbb)(\n"
9291       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9292   FormatStyle Style = getLLVMStyle();
9293   Style.PointerAlignment = FormatStyle::PAS_Left;
9294   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9295 }
9296 
9297 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9298   verifyFormat("int a = -2;");
9299   verifyFormat("f(-1, -2, -3);");
9300   verifyFormat("a[-1] = 5;");
9301   verifyFormat("int a = 5 + -2;");
9302   verifyFormat("if (i == -1) {\n}");
9303   verifyFormat("if (i != -1) {\n}");
9304   verifyFormat("if (i > -1) {\n}");
9305   verifyFormat("if (i < -1) {\n}");
9306   verifyFormat("++(a->f());");
9307   verifyFormat("--(a->f());");
9308   verifyFormat("(a->f())++;");
9309   verifyFormat("a[42]++;");
9310   verifyFormat("if (!(a->f())) {\n}");
9311   verifyFormat("if (!+i) {\n}");
9312   verifyFormat("~&a;");
9313 
9314   verifyFormat("a-- > b;");
9315   verifyFormat("b ? -a : c;");
9316   verifyFormat("n * sizeof char16;");
9317   verifyFormat("n * alignof char16;", getGoogleStyle());
9318   verifyFormat("sizeof(char);");
9319   verifyFormat("alignof(char);", getGoogleStyle());
9320 
9321   verifyFormat("return -1;");
9322   verifyFormat("throw -1;");
9323   verifyFormat("switch (a) {\n"
9324                "case -1:\n"
9325                "  break;\n"
9326                "}");
9327   verifyFormat("#define X -1");
9328   verifyFormat("#define X -kConstant");
9329 
9330   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9331   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9332 
9333   verifyFormat("int a = /* confusing comment */ -1;");
9334   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9335   verifyFormat("int a = i /* confusing comment */++;");
9336 
9337   verifyFormat("co_yield -1;");
9338   verifyFormat("co_return -1;");
9339 
9340   // Check that * is not treated as a binary operator when we set
9341   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9342   FormatStyle PASLeftStyle = getLLVMStyle();
9343   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9344   verifyFormat("co_return *a;", PASLeftStyle);
9345   verifyFormat("co_await *a;", PASLeftStyle);
9346   verifyFormat("co_yield *a", PASLeftStyle);
9347   verifyFormat("return *a;", PASLeftStyle);
9348 }
9349 
9350 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9351   verifyFormat("if (!aaaaaaaaaa( // break\n"
9352                "        aaaaa)) {\n"
9353                "}");
9354   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9355                "    aaaaa));");
9356   verifyFormat("*aaa = aaaaaaa( // break\n"
9357                "    bbbbbb);");
9358 }
9359 
9360 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9361   verifyFormat("bool operator<();");
9362   verifyFormat("bool operator>();");
9363   verifyFormat("bool operator=();");
9364   verifyFormat("bool operator==();");
9365   verifyFormat("bool operator!=();");
9366   verifyFormat("int operator+();");
9367   verifyFormat("int operator++();");
9368   verifyFormat("int operator++(int) volatile noexcept;");
9369   verifyFormat("bool operator,();");
9370   verifyFormat("bool operator();");
9371   verifyFormat("bool operator()();");
9372   verifyFormat("bool operator[]();");
9373   verifyFormat("operator bool();");
9374   verifyFormat("operator int();");
9375   verifyFormat("operator void *();");
9376   verifyFormat("operator SomeType<int>();");
9377   verifyFormat("operator SomeType<int, int>();");
9378   verifyFormat("operator SomeType<SomeType<int>>();");
9379   verifyFormat("void *operator new(std::size_t size);");
9380   verifyFormat("void *operator new[](std::size_t size);");
9381   verifyFormat("void operator delete(void *ptr);");
9382   verifyFormat("void operator delete[](void *ptr);");
9383   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9384                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9385   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9386                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9387 
9388   verifyFormat(
9389       "ostream &operator<<(ostream &OutputStream,\n"
9390       "                    SomeReallyLongType WithSomeReallyLongValue);");
9391   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9392                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9393                "  return left.group < right.group;\n"
9394                "}");
9395   verifyFormat("SomeType &operator=(const SomeType &S);");
9396   verifyFormat("f.template operator()<int>();");
9397 
9398   verifyGoogleFormat("operator void*();");
9399   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9400   verifyGoogleFormat("operator ::A();");
9401 
9402   verifyFormat("using A::operator+;");
9403   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9404                "int i;");
9405 
9406   // Calling an operator as a member function.
9407   verifyFormat("void f() { a.operator*(); }");
9408   verifyFormat("void f() { a.operator*(b & b); }");
9409   verifyFormat("void f() { a->operator&(a * b); }");
9410   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9411   // TODO: Calling an operator as a non-member function is hard to distinguish.
9412   // https://llvm.org/PR50629
9413   // verifyFormat("void f() { operator*(a & a); }");
9414   // verifyFormat("void f() { operator&(a, b * b); }");
9415 
9416   verifyFormat("::operator delete(foo);");
9417   verifyFormat("::operator new(n * sizeof(foo));");
9418   verifyFormat("foo() { ::operator delete(foo); }");
9419   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9420 }
9421 
9422 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9423   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9424   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9425   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9426   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9427   verifyFormat("Deleted &operator=(const Deleted &) &;");
9428   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9429   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9430   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9431   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9432   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9433   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9434   verifyFormat("void Fn(T const &) const &;");
9435   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9436   verifyFormat("template <typename T>\n"
9437                "void F(T) && = delete;",
9438                getGoogleStyle());
9439 
9440   FormatStyle AlignLeft = getLLVMStyle();
9441   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9442   verifyFormat("void A::b() && {}", AlignLeft);
9443   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9444   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9445                AlignLeft);
9446   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9447   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9448   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9449   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9450   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9451   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9452   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9453   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9454 
9455   FormatStyle Spaces = getLLVMStyle();
9456   Spaces.SpacesInCStyleCastParentheses = true;
9457   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9458   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9459   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9460   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9461 
9462   Spaces.SpacesInCStyleCastParentheses = false;
9463   Spaces.SpacesInParentheses = true;
9464   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9465   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9466                Spaces);
9467   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9468   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9469 
9470   FormatStyle BreakTemplate = getLLVMStyle();
9471   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9472 
9473   verifyFormat("struct f {\n"
9474                "  template <class T>\n"
9475                "  int &foo(const std::string &str) &noexcept {}\n"
9476                "};",
9477                BreakTemplate);
9478 
9479   verifyFormat("struct f {\n"
9480                "  template <class T>\n"
9481                "  int &foo(const std::string &str) &&noexcept {}\n"
9482                "};",
9483                BreakTemplate);
9484 
9485   verifyFormat("struct f {\n"
9486                "  template <class T>\n"
9487                "  int &foo(const std::string &str) const &noexcept {}\n"
9488                "};",
9489                BreakTemplate);
9490 
9491   verifyFormat("struct f {\n"
9492                "  template <class T>\n"
9493                "  int &foo(const std::string &str) const &noexcept {}\n"
9494                "};",
9495                BreakTemplate);
9496 
9497   verifyFormat("struct f {\n"
9498                "  template <class T>\n"
9499                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
9500                "};",
9501                BreakTemplate);
9502 
9503   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
9504   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
9505       FormatStyle::BTDS_Yes;
9506   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
9507 
9508   verifyFormat("struct f {\n"
9509                "  template <class T>\n"
9510                "  int& foo(const std::string& str) & noexcept {}\n"
9511                "};",
9512                AlignLeftBreakTemplate);
9513 
9514   verifyFormat("struct f {\n"
9515                "  template <class T>\n"
9516                "  int& foo(const std::string& str) && noexcept {}\n"
9517                "};",
9518                AlignLeftBreakTemplate);
9519 
9520   verifyFormat("struct f {\n"
9521                "  template <class T>\n"
9522                "  int& foo(const std::string& str) const& noexcept {}\n"
9523                "};",
9524                AlignLeftBreakTemplate);
9525 
9526   verifyFormat("struct f {\n"
9527                "  template <class T>\n"
9528                "  int& foo(const std::string& str) const&& noexcept {}\n"
9529                "};",
9530                AlignLeftBreakTemplate);
9531 
9532   verifyFormat("struct f {\n"
9533                "  template <class T>\n"
9534                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
9535                "};",
9536                AlignLeftBreakTemplate);
9537 
9538   // The `&` in `Type&` should not be confused with a trailing `&` of
9539   // DEPRECATED(reason) member function.
9540   verifyFormat("struct f {\n"
9541                "  template <class T>\n"
9542                "  DEPRECATED(reason)\n"
9543                "  Type &foo(arguments) {}\n"
9544                "};",
9545                BreakTemplate);
9546 
9547   verifyFormat("struct f {\n"
9548                "  template <class T>\n"
9549                "  DEPRECATED(reason)\n"
9550                "  Type& foo(arguments) {}\n"
9551                "};",
9552                AlignLeftBreakTemplate);
9553 
9554   verifyFormat("void (*foopt)(int) = &func;");
9555 }
9556 
9557 TEST_F(FormatTest, UnderstandsNewAndDelete) {
9558   verifyFormat("void f() {\n"
9559                "  A *a = new A;\n"
9560                "  A *a = new (placement) A;\n"
9561                "  delete a;\n"
9562                "  delete (A *)a;\n"
9563                "}");
9564   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9565                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9566   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9567                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9568                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9569   verifyFormat("delete[] h->p;");
9570 
9571   verifyFormat("void operator delete(void *foo) ATTRIB;");
9572   verifyFormat("void operator new(void *foo) ATTRIB;");
9573   verifyFormat("void operator delete[](void *foo) ATTRIB;");
9574   verifyFormat("void operator delete(void *ptr) noexcept;");
9575 }
9576 
9577 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
9578   verifyFormat("int *f(int *a) {}");
9579   verifyFormat("int main(int argc, char **argv) {}");
9580   verifyFormat("Test::Test(int b) : a(b * b) {}");
9581   verifyIndependentOfContext("f(a, *a);");
9582   verifyFormat("void g() { f(*a); }");
9583   verifyIndependentOfContext("int a = b * 10;");
9584   verifyIndependentOfContext("int a = 10 * b;");
9585   verifyIndependentOfContext("int a = b * c;");
9586   verifyIndependentOfContext("int a += b * c;");
9587   verifyIndependentOfContext("int a -= b * c;");
9588   verifyIndependentOfContext("int a *= b * c;");
9589   verifyIndependentOfContext("int a /= b * c;");
9590   verifyIndependentOfContext("int a = *b;");
9591   verifyIndependentOfContext("int a = *b * c;");
9592   verifyIndependentOfContext("int a = b * *c;");
9593   verifyIndependentOfContext("int a = b * (10);");
9594   verifyIndependentOfContext("S << b * (10);");
9595   verifyIndependentOfContext("return 10 * b;");
9596   verifyIndependentOfContext("return *b * *c;");
9597   verifyIndependentOfContext("return a & ~b;");
9598   verifyIndependentOfContext("f(b ? *c : *d);");
9599   verifyIndependentOfContext("int a = b ? *c : *d;");
9600   verifyIndependentOfContext("*b = a;");
9601   verifyIndependentOfContext("a * ~b;");
9602   verifyIndependentOfContext("a * !b;");
9603   verifyIndependentOfContext("a * +b;");
9604   verifyIndependentOfContext("a * -b;");
9605   verifyIndependentOfContext("a * ++b;");
9606   verifyIndependentOfContext("a * --b;");
9607   verifyIndependentOfContext("a[4] * b;");
9608   verifyIndependentOfContext("a[a * a] = 1;");
9609   verifyIndependentOfContext("f() * b;");
9610   verifyIndependentOfContext("a * [self dostuff];");
9611   verifyIndependentOfContext("int x = a * (a + b);");
9612   verifyIndependentOfContext("(a *)(a + b);");
9613   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
9614   verifyIndependentOfContext("int *pa = (int *)&a;");
9615   verifyIndependentOfContext("return sizeof(int **);");
9616   verifyIndependentOfContext("return sizeof(int ******);");
9617   verifyIndependentOfContext("return (int **&)a;");
9618   verifyIndependentOfContext("f((*PointerToArray)[10]);");
9619   verifyFormat("void f(Type (*parameter)[10]) {}");
9620   verifyFormat("void f(Type (&parameter)[10]) {}");
9621   verifyGoogleFormat("return sizeof(int**);");
9622   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
9623   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
9624   verifyFormat("auto a = [](int **&, int ***) {};");
9625   verifyFormat("auto PointerBinding = [](const char *S) {};");
9626   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
9627   verifyFormat("[](const decltype(*a) &value) {}");
9628   verifyFormat("[](const typeof(*a) &value) {}");
9629   verifyFormat("[](const _Atomic(a *) &value) {}");
9630   verifyFormat("[](const __underlying_type(a) &value) {}");
9631   verifyFormat("decltype(a * b) F();");
9632   verifyFormat("typeof(a * b) F();");
9633   verifyFormat("#define MACRO() [](A *a) { return 1; }");
9634   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
9635   verifyIndependentOfContext("typedef void (*f)(int *a);");
9636   verifyIndependentOfContext("int i{a * b};");
9637   verifyIndependentOfContext("aaa && aaa->f();");
9638   verifyIndependentOfContext("int x = ~*p;");
9639   verifyFormat("Constructor() : a(a), area(width * height) {}");
9640   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
9641   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
9642   verifyFormat("void f() { f(a, c * d); }");
9643   verifyFormat("void f() { f(new a(), c * d); }");
9644   verifyFormat("void f(const MyOverride &override);");
9645   verifyFormat("void f(const MyFinal &final);");
9646   verifyIndependentOfContext("bool a = f() && override.f();");
9647   verifyIndependentOfContext("bool a = f() && final.f();");
9648 
9649   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
9650 
9651   verifyIndependentOfContext("A<int *> a;");
9652   verifyIndependentOfContext("A<int **> a;");
9653   verifyIndependentOfContext("A<int *, int *> a;");
9654   verifyIndependentOfContext("A<int *[]> a;");
9655   verifyIndependentOfContext(
9656       "const char *const p = reinterpret_cast<const char *const>(q);");
9657   verifyIndependentOfContext("A<int **, int **> a;");
9658   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
9659   verifyFormat("for (char **a = b; *a; ++a) {\n}");
9660   verifyFormat("for (; a && b;) {\n}");
9661   verifyFormat("bool foo = true && [] { return false; }();");
9662 
9663   verifyFormat(
9664       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9665       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9666 
9667   verifyGoogleFormat("int const* a = &b;");
9668   verifyGoogleFormat("**outparam = 1;");
9669   verifyGoogleFormat("*outparam = a * b;");
9670   verifyGoogleFormat("int main(int argc, char** argv) {}");
9671   verifyGoogleFormat("A<int*> a;");
9672   verifyGoogleFormat("A<int**> a;");
9673   verifyGoogleFormat("A<int*, int*> a;");
9674   verifyGoogleFormat("A<int**, int**> a;");
9675   verifyGoogleFormat("f(b ? *c : *d);");
9676   verifyGoogleFormat("int a = b ? *c : *d;");
9677   verifyGoogleFormat("Type* t = **x;");
9678   verifyGoogleFormat("Type* t = *++*x;");
9679   verifyGoogleFormat("*++*x;");
9680   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
9681   verifyGoogleFormat("Type* t = x++ * y;");
9682   verifyGoogleFormat(
9683       "const char* const p = reinterpret_cast<const char* const>(q);");
9684   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
9685   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
9686   verifyGoogleFormat("template <typename T>\n"
9687                      "void f(int i = 0, SomeType** temps = NULL);");
9688 
9689   FormatStyle Left = getLLVMStyle();
9690   Left.PointerAlignment = FormatStyle::PAS_Left;
9691   verifyFormat("x = *a(x) = *a(y);", Left);
9692   verifyFormat("for (;; *a = b) {\n}", Left);
9693   verifyFormat("return *this += 1;", Left);
9694   verifyFormat("throw *x;", Left);
9695   verifyFormat("delete *x;", Left);
9696   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
9697   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
9698   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
9699   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
9700   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
9701   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
9702   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
9703   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
9704   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
9705 
9706   verifyIndependentOfContext("a = *(x + y);");
9707   verifyIndependentOfContext("a = &(x + y);");
9708   verifyIndependentOfContext("*(x + y).call();");
9709   verifyIndependentOfContext("&(x + y)->call();");
9710   verifyFormat("void f() { &(*I).first; }");
9711 
9712   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
9713   verifyFormat("f(* /* confusing comment */ foo);");
9714   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
9715   verifyFormat("void foo(int * // this is the first paramters\n"
9716                "         ,\n"
9717                "         int second);");
9718   verifyFormat("double term = a * // first\n"
9719                "              b;");
9720   verifyFormat(
9721       "int *MyValues = {\n"
9722       "    *A, // Operator detection might be confused by the '{'\n"
9723       "    *BB // Operator detection might be confused by previous comment\n"
9724       "};");
9725 
9726   verifyIndependentOfContext("if (int *a = &b)");
9727   verifyIndependentOfContext("if (int &a = *b)");
9728   verifyIndependentOfContext("if (a & b[i])");
9729   verifyIndependentOfContext("if constexpr (a & b[i])");
9730   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
9731   verifyIndependentOfContext("if (a * (b * c))");
9732   verifyIndependentOfContext("if constexpr (a * (b * c))");
9733   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
9734   verifyIndependentOfContext("if (a::b::c::d & b[i])");
9735   verifyIndependentOfContext("if (*b[i])");
9736   verifyIndependentOfContext("if (int *a = (&b))");
9737   verifyIndependentOfContext("while (int *a = &b)");
9738   verifyIndependentOfContext("while (a * (b * c))");
9739   verifyIndependentOfContext("size = sizeof *a;");
9740   verifyIndependentOfContext("if (a && (b = c))");
9741   verifyFormat("void f() {\n"
9742                "  for (const int &v : Values) {\n"
9743                "  }\n"
9744                "}");
9745   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
9746   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
9747   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
9748 
9749   verifyFormat("#define A (!a * b)");
9750   verifyFormat("#define MACRO     \\\n"
9751                "  int *i = a * b; \\\n"
9752                "  void f(a *b);",
9753                getLLVMStyleWithColumns(19));
9754 
9755   verifyIndependentOfContext("A = new SomeType *[Length];");
9756   verifyIndependentOfContext("A = new SomeType *[Length]();");
9757   verifyIndependentOfContext("T **t = new T *;");
9758   verifyIndependentOfContext("T **t = new T *();");
9759   verifyGoogleFormat("A = new SomeType*[Length]();");
9760   verifyGoogleFormat("A = new SomeType*[Length];");
9761   verifyGoogleFormat("T** t = new T*;");
9762   verifyGoogleFormat("T** t = new T*();");
9763 
9764   verifyFormat("STATIC_ASSERT((a & b) == 0);");
9765   verifyFormat("STATIC_ASSERT(0 == (a & b));");
9766   verifyFormat("template <bool a, bool b> "
9767                "typename t::if<x && y>::type f() {}");
9768   verifyFormat("template <int *y> f() {}");
9769   verifyFormat("vector<int *> v;");
9770   verifyFormat("vector<int *const> v;");
9771   verifyFormat("vector<int *const **const *> v;");
9772   verifyFormat("vector<int *volatile> v;");
9773   verifyFormat("vector<a *_Nonnull> v;");
9774   verifyFormat("vector<a *_Nullable> v;");
9775   verifyFormat("vector<a *_Null_unspecified> v;");
9776   verifyFormat("vector<a *__ptr32> v;");
9777   verifyFormat("vector<a *__ptr64> v;");
9778   verifyFormat("vector<a *__capability> v;");
9779   FormatStyle TypeMacros = getLLVMStyle();
9780   TypeMacros.TypenameMacros = {"LIST"};
9781   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
9782   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
9783   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
9784   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
9785   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
9786 
9787   FormatStyle CustomQualifier = getLLVMStyle();
9788   // Add identifiers that should not be parsed as a qualifier by default.
9789   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9790   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
9791   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
9792   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
9793   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
9794   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
9795   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
9796   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
9797   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
9798   verifyFormat("vector<a * _NotAQualifier> v;");
9799   verifyFormat("vector<a * __not_a_qualifier> v;");
9800   verifyFormat("vector<a * b> v;");
9801   verifyFormat("foo<b && false>();");
9802   verifyFormat("foo<b & 1>();");
9803   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
9804   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
9805   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
9806   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
9807   verifyFormat(
9808       "template <class T, class = typename std::enable_if<\n"
9809       "                       std::is_integral<T>::value &&\n"
9810       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
9811       "void F();",
9812       getLLVMStyleWithColumns(70));
9813   verifyFormat("template <class T,\n"
9814                "          class = typename std::enable_if<\n"
9815                "              std::is_integral<T>::value &&\n"
9816                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
9817                "          class U>\n"
9818                "void F();",
9819                getLLVMStyleWithColumns(70));
9820   verifyFormat(
9821       "template <class T,\n"
9822       "          class = typename ::std::enable_if<\n"
9823       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
9824       "void F();",
9825       getGoogleStyleWithColumns(68));
9826 
9827   verifyIndependentOfContext("MACRO(int *i);");
9828   verifyIndependentOfContext("MACRO(auto *a);");
9829   verifyIndependentOfContext("MACRO(const A *a);");
9830   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
9831   verifyIndependentOfContext("MACRO(decltype(A) *a);");
9832   verifyIndependentOfContext("MACRO(typeof(A) *a);");
9833   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
9834   verifyIndependentOfContext("MACRO(A *const a);");
9835   verifyIndependentOfContext("MACRO(A *restrict a);");
9836   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
9837   verifyIndependentOfContext("MACRO(A *__restrict a);");
9838   verifyIndependentOfContext("MACRO(A *volatile a);");
9839   verifyIndependentOfContext("MACRO(A *__volatile a);");
9840   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
9841   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
9842   verifyIndependentOfContext("MACRO(A *_Nullable a);");
9843   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
9844   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
9845   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
9846   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
9847   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
9848   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
9849   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
9850   verifyIndependentOfContext("MACRO(A *__capability);");
9851   verifyIndependentOfContext("MACRO(A &__capability);");
9852   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
9853   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
9854   // If we add __my_qualifier to AttributeMacros it should always be parsed as
9855   // a type declaration:
9856   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
9857   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
9858   // Also check that TypenameMacros prevents parsing it as multiplication:
9859   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
9860   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
9861 
9862   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
9863   verifyFormat("void f() { f(float{1}, a * a); }");
9864   verifyFormat("void f() { f(float(1), a * a); }");
9865 
9866   verifyFormat("f((void (*)(int))g);");
9867   verifyFormat("f((void (&)(int))g);");
9868   verifyFormat("f((void (^)(int))g);");
9869 
9870   // FIXME: Is there a way to make this work?
9871   // verifyIndependentOfContext("MACRO(A *a);");
9872   verifyFormat("MACRO(A &B);");
9873   verifyFormat("MACRO(A *B);");
9874   verifyFormat("void f() { MACRO(A * B); }");
9875   verifyFormat("void f() { MACRO(A & B); }");
9876 
9877   // This lambda was mis-formatted after D88956 (treating it as a binop):
9878   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
9879   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
9880   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
9881   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
9882 
9883   verifyFormat("DatumHandle const *operator->() const { return input_; }");
9884   verifyFormat("return options != nullptr && operator==(*options);");
9885 
9886   EXPECT_EQ("#define OP(x)                                    \\\n"
9887             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
9888             "    return s << a.DebugString();                 \\\n"
9889             "  }",
9890             format("#define OP(x) \\\n"
9891                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
9892                    "    return s << a.DebugString(); \\\n"
9893                    "  }",
9894                    getLLVMStyleWithColumns(50)));
9895 
9896   // FIXME: We cannot handle this case yet; we might be able to figure out that
9897   // foo<x> d > v; doesn't make sense.
9898   verifyFormat("foo<a<b && c> d> v;");
9899 
9900   FormatStyle PointerMiddle = getLLVMStyle();
9901   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9902   verifyFormat("delete *x;", PointerMiddle);
9903   verifyFormat("int * x;", PointerMiddle);
9904   verifyFormat("int *[] x;", PointerMiddle);
9905   verifyFormat("template <int * y> f() {}", PointerMiddle);
9906   verifyFormat("int * f(int * a) {}", PointerMiddle);
9907   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
9908   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
9909   verifyFormat("A<int *> a;", PointerMiddle);
9910   verifyFormat("A<int **> a;", PointerMiddle);
9911   verifyFormat("A<int *, int *> a;", PointerMiddle);
9912   verifyFormat("A<int *[]> a;", PointerMiddle);
9913   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
9914   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
9915   verifyFormat("T ** t = new T *;", PointerMiddle);
9916 
9917   // Member function reference qualifiers aren't binary operators.
9918   verifyFormat("string // break\n"
9919                "operator()() & {}");
9920   verifyFormat("string // break\n"
9921                "operator()() && {}");
9922   verifyGoogleFormat("template <typename T>\n"
9923                      "auto x() & -> int {}");
9924 
9925   // Should be binary operators when used as an argument expression (overloaded
9926   // operator invoked as a member function).
9927   verifyFormat("void f() { a.operator()(a * a); }");
9928   verifyFormat("void f() { a->operator()(a & a); }");
9929   verifyFormat("void f() { a.operator()(*a & *a); }");
9930   verifyFormat("void f() { a->operator()(*a * *a); }");
9931 
9932   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
9933   verifyFormat("int operator()(T (&)[N]) { return 0; }");
9934 }
9935 
9936 TEST_F(FormatTest, UnderstandsAttributes) {
9937   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
9938   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
9939                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
9940   FormatStyle AfterType = getLLVMStyle();
9941   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
9942   verifyFormat("__attribute__((nodebug)) void\n"
9943                "foo() {}\n",
9944                AfterType);
9945   verifyFormat("__unused void\n"
9946                "foo() {}",
9947                AfterType);
9948 
9949   FormatStyle CustomAttrs = getLLVMStyle();
9950   CustomAttrs.AttributeMacros.push_back("__unused");
9951   CustomAttrs.AttributeMacros.push_back("__attr1");
9952   CustomAttrs.AttributeMacros.push_back("__attr2");
9953   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
9954   verifyFormat("vector<SomeType *__attribute((foo))> v;");
9955   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
9956   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
9957   // Check that it is parsed as a multiplication without AttributeMacros and
9958   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
9959   verifyFormat("vector<SomeType * __attr1> v;");
9960   verifyFormat("vector<SomeType __attr1 *> v;");
9961   verifyFormat("vector<SomeType __attr1 *const> v;");
9962   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
9963   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
9964   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
9965   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
9966   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
9967   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
9968   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
9969   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
9970 
9971   // Check that these are not parsed as function declarations:
9972   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9973   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
9974   verifyFormat("SomeType s(InitValue);", CustomAttrs);
9975   verifyFormat("SomeType s{InitValue};", CustomAttrs);
9976   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
9977   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
9978   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
9979   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
9980   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
9981   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
9982 }
9983 
9984 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
9985   // Check that qualifiers on pointers don't break parsing of casts.
9986   verifyFormat("x = (foo *const)*v;");
9987   verifyFormat("x = (foo *volatile)*v;");
9988   verifyFormat("x = (foo *restrict)*v;");
9989   verifyFormat("x = (foo *__attribute__((foo)))*v;");
9990   verifyFormat("x = (foo *_Nonnull)*v;");
9991   verifyFormat("x = (foo *_Nullable)*v;");
9992   verifyFormat("x = (foo *_Null_unspecified)*v;");
9993   verifyFormat("x = (foo *_Nonnull)*v;");
9994   verifyFormat("x = (foo *[[clang::attr]])*v;");
9995   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
9996   verifyFormat("x = (foo *__ptr32)*v;");
9997   verifyFormat("x = (foo *__ptr64)*v;");
9998   verifyFormat("x = (foo *__capability)*v;");
9999 
10000   // Check that we handle multiple trailing qualifiers and skip them all to
10001   // determine that the expression is a cast to a pointer type.
10002   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10003   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10004   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10005   StringRef AllQualifiers =
10006       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10007       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10008   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10009   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10010 
10011   // Also check that address-of is not parsed as a binary bitwise-and:
10012   verifyFormat("x = (foo *const)&v;");
10013   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10014   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10015 
10016   // Check custom qualifiers:
10017   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10018   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10019   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10020   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10021   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10022                CustomQualifier);
10023   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10024                CustomQualifier);
10025 
10026   // Check that unknown identifiers result in binary operator parsing:
10027   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10028   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10029 }
10030 
10031 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10032   verifyFormat("SomeType s [[unused]] (InitValue);");
10033   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10034   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10035   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10036   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10037   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10038                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10039   verifyFormat("[[nodiscard]] bool f() { return false; }");
10040   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10041   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10042   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10043 
10044   // Make sure we do not mistake attributes for array subscripts.
10045   verifyFormat("int a() {}\n"
10046                "[[unused]] int b() {}\n");
10047   verifyFormat("NSArray *arr;\n"
10048                "arr[[Foo() bar]];");
10049 
10050   // On the other hand, we still need to correctly find array subscripts.
10051   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10052 
10053   // Make sure that we do not mistake Objective-C method inside array literals
10054   // as attributes, even if those method names are also keywords.
10055   verifyFormat("@[ [foo bar] ];");
10056   verifyFormat("@[ [NSArray class] ];");
10057   verifyFormat("@[ [foo enum] ];");
10058 
10059   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10060 
10061   // Make sure we do not parse attributes as lambda introducers.
10062   FormatStyle MultiLineFunctions = getLLVMStyle();
10063   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10064   verifyFormat("[[unused]] int b() {\n"
10065                "  return 42;\n"
10066                "}\n",
10067                MultiLineFunctions);
10068 }
10069 
10070 TEST_F(FormatTest, AttributeClass) {
10071   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10072   verifyFormat("class S {\n"
10073                "  S(S&&) = default;\n"
10074                "};",
10075                Style);
10076   verifyFormat("class [[nodiscard]] S {\n"
10077                "  S(S&&) = default;\n"
10078                "};",
10079                Style);
10080   verifyFormat("class __attribute((maybeunused)) S {\n"
10081                "  S(S&&) = default;\n"
10082                "};",
10083                Style);
10084   verifyFormat("struct S {\n"
10085                "  S(S&&) = default;\n"
10086                "};",
10087                Style);
10088   verifyFormat("struct [[nodiscard]] S {\n"
10089                "  S(S&&) = default;\n"
10090                "};",
10091                Style);
10092 }
10093 
10094 TEST_F(FormatTest, AttributesAfterMacro) {
10095   FormatStyle Style = getLLVMStyle();
10096   verifyFormat("MACRO;\n"
10097                "__attribute__((maybe_unused)) int foo() {\n"
10098                "  //...\n"
10099                "}");
10100 
10101   verifyFormat("MACRO;\n"
10102                "[[nodiscard]] int foo() {\n"
10103                "  //...\n"
10104                "}");
10105 
10106   EXPECT_EQ("MACRO\n\n"
10107             "__attribute__((maybe_unused)) int foo() {\n"
10108             "  //...\n"
10109             "}",
10110             format("MACRO\n\n"
10111                    "__attribute__((maybe_unused)) int foo() {\n"
10112                    "  //...\n"
10113                    "}"));
10114 
10115   EXPECT_EQ("MACRO\n\n"
10116             "[[nodiscard]] int foo() {\n"
10117             "  //...\n"
10118             "}",
10119             format("MACRO\n\n"
10120                    "[[nodiscard]] int foo() {\n"
10121                    "  //...\n"
10122                    "}"));
10123 }
10124 
10125 TEST_F(FormatTest, AttributePenaltyBreaking) {
10126   FormatStyle Style = getLLVMStyle();
10127   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10128                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10129                Style);
10130   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10131                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10132                Style);
10133   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10134                "shared_ptr<ALongTypeName> &C d) {\n}",
10135                Style);
10136 }
10137 
10138 TEST_F(FormatTest, UnderstandsEllipsis) {
10139   FormatStyle Style = getLLVMStyle();
10140   verifyFormat("int printf(const char *fmt, ...);");
10141   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10142   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10143 
10144   verifyFormat("template <int *...PP> a;", Style);
10145 
10146   Style.PointerAlignment = FormatStyle::PAS_Left;
10147   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10148 
10149   verifyFormat("template <int*... PP> a;", Style);
10150 
10151   Style.PointerAlignment = FormatStyle::PAS_Middle;
10152   verifyFormat("template <int *... PP> a;", Style);
10153 }
10154 
10155 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10156   EXPECT_EQ("int *a;\n"
10157             "int *a;\n"
10158             "int *a;",
10159             format("int *a;\n"
10160                    "int* a;\n"
10161                    "int *a;",
10162                    getGoogleStyle()));
10163   EXPECT_EQ("int* a;\n"
10164             "int* a;\n"
10165             "int* a;",
10166             format("int* a;\n"
10167                    "int* a;\n"
10168                    "int *a;",
10169                    getGoogleStyle()));
10170   EXPECT_EQ("int *a;\n"
10171             "int *a;\n"
10172             "int *a;",
10173             format("int *a;\n"
10174                    "int * a;\n"
10175                    "int *  a;",
10176                    getGoogleStyle()));
10177   EXPECT_EQ("auto x = [] {\n"
10178             "  int *a;\n"
10179             "  int *a;\n"
10180             "  int *a;\n"
10181             "};",
10182             format("auto x=[]{int *a;\n"
10183                    "int * a;\n"
10184                    "int *  a;};",
10185                    getGoogleStyle()));
10186 }
10187 
10188 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10189   verifyFormat("int f(int &&a) {}");
10190   verifyFormat("int f(int a, char &&b) {}");
10191   verifyFormat("void f() { int &&a = b; }");
10192   verifyGoogleFormat("int f(int a, char&& b) {}");
10193   verifyGoogleFormat("void f() { int&& a = b; }");
10194 
10195   verifyIndependentOfContext("A<int &&> a;");
10196   verifyIndependentOfContext("A<int &&, int &&> a;");
10197   verifyGoogleFormat("A<int&&> a;");
10198   verifyGoogleFormat("A<int&&, int&&> a;");
10199 
10200   // Not rvalue references:
10201   verifyFormat("template <bool B, bool C> class A {\n"
10202                "  static_assert(B && C, \"Something is wrong\");\n"
10203                "};");
10204   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10205   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10206   verifyFormat("#define A(a, b) (a && b)");
10207 }
10208 
10209 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10210   verifyFormat("void f() {\n"
10211                "  x[aaaaaaaaa -\n"
10212                "    b] = 23;\n"
10213                "}",
10214                getLLVMStyleWithColumns(15));
10215 }
10216 
10217 TEST_F(FormatTest, FormatsCasts) {
10218   verifyFormat("Type *A = static_cast<Type *>(P);");
10219   verifyFormat("Type *A = (Type *)P;");
10220   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10221   verifyFormat("int a = (int)(2.0f);");
10222   verifyFormat("int a = (int)2.0f;");
10223   verifyFormat("x[(int32)y];");
10224   verifyFormat("x = (int32)y;");
10225   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10226   verifyFormat("int a = (int)*b;");
10227   verifyFormat("int a = (int)2.0f;");
10228   verifyFormat("int a = (int)~0;");
10229   verifyFormat("int a = (int)++a;");
10230   verifyFormat("int a = (int)sizeof(int);");
10231   verifyFormat("int a = (int)+2;");
10232   verifyFormat("my_int a = (my_int)2.0f;");
10233   verifyFormat("my_int a = (my_int)sizeof(int);");
10234   verifyFormat("return (my_int)aaa;");
10235   verifyFormat("#define x ((int)-1)");
10236   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10237   verifyFormat("#define p(q) ((int *)&q)");
10238   verifyFormat("fn(a)(b) + 1;");
10239 
10240   verifyFormat("void f() { my_int a = (my_int)*b; }");
10241   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10242   verifyFormat("my_int a = (my_int)~0;");
10243   verifyFormat("my_int a = (my_int)++a;");
10244   verifyFormat("my_int a = (my_int)-2;");
10245   verifyFormat("my_int a = (my_int)1;");
10246   verifyFormat("my_int a = (my_int *)1;");
10247   verifyFormat("my_int a = (const my_int)-1;");
10248   verifyFormat("my_int a = (const my_int *)-1;");
10249   verifyFormat("my_int a = (my_int)(my_int)-1;");
10250   verifyFormat("my_int a = (ns::my_int)-2;");
10251   verifyFormat("case (my_int)ONE:");
10252   verifyFormat("auto x = (X)this;");
10253   // Casts in Obj-C style calls used to not be recognized as such.
10254   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10255 
10256   // FIXME: single value wrapped with paren will be treated as cast.
10257   verifyFormat("void f(int i = (kValue)*kMask) {}");
10258 
10259   verifyFormat("{ (void)F; }");
10260 
10261   // Don't break after a cast's
10262   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10263                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10264                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10265 
10266   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10267   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10268   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10269   verifyFormat("bool *y = (bool *)(void *)(x);");
10270   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10271   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10272   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10273   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10274 
10275   // These are not casts.
10276   verifyFormat("void f(int *) {}");
10277   verifyFormat("f(foo)->b;");
10278   verifyFormat("f(foo).b;");
10279   verifyFormat("f(foo)(b);");
10280   verifyFormat("f(foo)[b];");
10281   verifyFormat("[](foo) { return 4; }(bar);");
10282   verifyFormat("(*funptr)(foo)[4];");
10283   verifyFormat("funptrs[4](foo)[4];");
10284   verifyFormat("void f(int *);");
10285   verifyFormat("void f(int *) = 0;");
10286   verifyFormat("void f(SmallVector<int>) {}");
10287   verifyFormat("void f(SmallVector<int>);");
10288   verifyFormat("void f(SmallVector<int>) = 0;");
10289   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10290   verifyFormat("int a = sizeof(int) * b;");
10291   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10292   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10293   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10294   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10295 
10296   // These are not casts, but at some point were confused with casts.
10297   verifyFormat("virtual void foo(int *) override;");
10298   verifyFormat("virtual void foo(char &) const;");
10299   verifyFormat("virtual void foo(int *a, char *) const;");
10300   verifyFormat("int a = sizeof(int *) + b;");
10301   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10302   verifyFormat("bool b = f(g<int>) && c;");
10303   verifyFormat("typedef void (*f)(int i) func;");
10304   verifyFormat("void operator++(int) noexcept;");
10305   verifyFormat("void operator++(int &) noexcept;");
10306   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10307                "&) noexcept;");
10308   verifyFormat(
10309       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10310   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10311   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10312   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10313   verifyFormat("void operator delete(foo &) noexcept;");
10314   verifyFormat("void operator delete(foo) noexcept;");
10315   verifyFormat("void operator delete(int) noexcept;");
10316   verifyFormat("void operator delete(int &) noexcept;");
10317   verifyFormat("void operator delete(int &) volatile noexcept;");
10318   verifyFormat("void operator delete(int &) const");
10319   verifyFormat("void operator delete(int &) = default");
10320   verifyFormat("void operator delete(int &) = delete");
10321   verifyFormat("void operator delete(int &) [[noreturn]]");
10322   verifyFormat("void operator delete(int &) throw();");
10323   verifyFormat("void operator delete(int &) throw(int);");
10324   verifyFormat("auto operator delete(int &) -> int;");
10325   verifyFormat("auto operator delete(int &) override");
10326   verifyFormat("auto operator delete(int &) final");
10327 
10328   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10329                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10330   // FIXME: The indentation here is not ideal.
10331   verifyFormat(
10332       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10333       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10334       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10335 }
10336 
10337 TEST_F(FormatTest, FormatsFunctionTypes) {
10338   verifyFormat("A<bool()> a;");
10339   verifyFormat("A<SomeType()> a;");
10340   verifyFormat("A<void (*)(int, std::string)> a;");
10341   verifyFormat("A<void *(int)>;");
10342   verifyFormat("void *(*a)(int *, SomeType *);");
10343   verifyFormat("int (*func)(void *);");
10344   verifyFormat("void f() { int (*func)(void *); }");
10345   verifyFormat("template <class CallbackClass>\n"
10346                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10347 
10348   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10349   verifyGoogleFormat("void* (*a)(int);");
10350   verifyGoogleFormat(
10351       "template <class CallbackClass>\n"
10352       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10353 
10354   // Other constructs can look somewhat like function types:
10355   verifyFormat("A<sizeof(*x)> a;");
10356   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10357   verifyFormat("some_var = function(*some_pointer_var)[0];");
10358   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10359   verifyFormat("int x = f(&h)();");
10360   verifyFormat("returnsFunction(&param1, &param2)(param);");
10361   verifyFormat("std::function<\n"
10362                "    LooooooooooongTemplatedType<\n"
10363                "        SomeType>*(\n"
10364                "        LooooooooooooooooongType type)>\n"
10365                "    function;",
10366                getGoogleStyleWithColumns(40));
10367 }
10368 
10369 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10370   verifyFormat("A (*foo_)[6];");
10371   verifyFormat("vector<int> (*foo_)[6];");
10372 }
10373 
10374 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10375   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10376                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10377   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10378                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10379   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10380                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10381 
10382   // Different ways of ()-initializiation.
10383   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10384                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10385   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10386                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10387   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10388                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10389   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10390                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10391 
10392   // Lambdas should not confuse the variable declaration heuristic.
10393   verifyFormat("LooooooooooooooooongType\n"
10394                "    variable(nullptr, [](A *a) {});",
10395                getLLVMStyleWithColumns(40));
10396 }
10397 
10398 TEST_F(FormatTest, BreaksLongDeclarations) {
10399   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10400                "    AnotherNameForTheLongType;");
10401   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10402                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10403   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10404                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10405   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10406                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10407   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10408                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10409   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10410                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10411   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10412                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10413   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10414                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10415   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10416                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10417   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10418                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10419   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10420                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10421   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10422                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10423   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10424                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10425   FormatStyle Indented = getLLVMStyle();
10426   Indented.IndentWrappedFunctionNames = true;
10427   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10428                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10429                Indented);
10430   verifyFormat(
10431       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10432       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10433       Indented);
10434   verifyFormat(
10435       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10436       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10437       Indented);
10438   verifyFormat(
10439       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10440       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10441       Indented);
10442 
10443   // FIXME: Without the comment, this breaks after "(".
10444   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10445                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10446                getGoogleStyle());
10447 
10448   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
10449                "                  int LoooooooooooooooooooongParam2) {}");
10450   verifyFormat(
10451       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
10452       "                                   SourceLocation L, IdentifierIn *II,\n"
10453       "                                   Type *T) {}");
10454   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
10455                "ReallyReaaallyLongFunctionName(\n"
10456                "    const std::string &SomeParameter,\n"
10457                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10458                "        &ReallyReallyLongParameterName,\n"
10459                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10460                "        &AnotherLongParameterName) {}");
10461   verifyFormat("template <typename A>\n"
10462                "SomeLoooooooooooooooooooooongType<\n"
10463                "    typename some_namespace::SomeOtherType<A>::Type>\n"
10464                "Function() {}");
10465 
10466   verifyGoogleFormat(
10467       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
10468       "    aaaaaaaaaaaaaaaaaaaaaaa;");
10469   verifyGoogleFormat(
10470       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
10471       "                                   SourceLocation L) {}");
10472   verifyGoogleFormat(
10473       "some_namespace::LongReturnType\n"
10474       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
10475       "    int first_long_parameter, int second_parameter) {}");
10476 
10477   verifyGoogleFormat("template <typename T>\n"
10478                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10479                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
10480   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10481                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
10482 
10483   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
10484                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10485                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10486   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10487                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10488                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
10489   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10490                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
10491                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
10492                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10493 
10494   verifyFormat("template <typename T> // Templates on own line.\n"
10495                "static int            // Some comment.\n"
10496                "MyFunction(int a);",
10497                getLLVMStyle());
10498 }
10499 
10500 TEST_F(FormatTest, FormatsAccessModifiers) {
10501   FormatStyle Style = getLLVMStyle();
10502   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
10503             FormatStyle::ELBAMS_LogicalBlock);
10504   verifyFormat("struct foo {\n"
10505                "private:\n"
10506                "  void f() {}\n"
10507                "\n"
10508                "private:\n"
10509                "  int i;\n"
10510                "\n"
10511                "protected:\n"
10512                "  int j;\n"
10513                "};\n",
10514                Style);
10515   verifyFormat("struct foo {\n"
10516                "private:\n"
10517                "  void f() {}\n"
10518                "\n"
10519                "private:\n"
10520                "  int i;\n"
10521                "\n"
10522                "protected:\n"
10523                "  int j;\n"
10524                "};\n",
10525                "struct foo {\n"
10526                "private:\n"
10527                "  void f() {}\n"
10528                "private:\n"
10529                "  int i;\n"
10530                "protected:\n"
10531                "  int j;\n"
10532                "};\n",
10533                Style);
10534   verifyFormat("struct foo { /* comment */\n"
10535                "private:\n"
10536                "  int i;\n"
10537                "  // comment\n"
10538                "private:\n"
10539                "  int j;\n"
10540                "};\n",
10541                Style);
10542   verifyFormat("struct foo {\n"
10543                "#ifdef FOO\n"
10544                "#endif\n"
10545                "private:\n"
10546                "  int i;\n"
10547                "#ifdef FOO\n"
10548                "private:\n"
10549                "#endif\n"
10550                "  int j;\n"
10551                "};\n",
10552                Style);
10553   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10554   verifyFormat("struct foo {\n"
10555                "private:\n"
10556                "  void f() {}\n"
10557                "private:\n"
10558                "  int i;\n"
10559                "protected:\n"
10560                "  int j;\n"
10561                "};\n",
10562                Style);
10563   verifyFormat("struct foo {\n"
10564                "private:\n"
10565                "  void f() {}\n"
10566                "private:\n"
10567                "  int i;\n"
10568                "protected:\n"
10569                "  int j;\n"
10570                "};\n",
10571                "struct foo {\n"
10572                "\n"
10573                "private:\n"
10574                "  void f() {}\n"
10575                "\n"
10576                "private:\n"
10577                "  int i;\n"
10578                "\n"
10579                "protected:\n"
10580                "  int j;\n"
10581                "};\n",
10582                Style);
10583   verifyFormat("struct foo { /* comment */\n"
10584                "private:\n"
10585                "  int i;\n"
10586                "  // comment\n"
10587                "private:\n"
10588                "  int j;\n"
10589                "};\n",
10590                "struct foo { /* comment */\n"
10591                "\n"
10592                "private:\n"
10593                "  int i;\n"
10594                "  // comment\n"
10595                "\n"
10596                "private:\n"
10597                "  int j;\n"
10598                "};\n",
10599                Style);
10600   verifyFormat("struct foo {\n"
10601                "#ifdef FOO\n"
10602                "#endif\n"
10603                "private:\n"
10604                "  int i;\n"
10605                "#ifdef FOO\n"
10606                "private:\n"
10607                "#endif\n"
10608                "  int j;\n"
10609                "};\n",
10610                "struct foo {\n"
10611                "#ifdef FOO\n"
10612                "#endif\n"
10613                "\n"
10614                "private:\n"
10615                "  int i;\n"
10616                "#ifdef FOO\n"
10617                "\n"
10618                "private:\n"
10619                "#endif\n"
10620                "  int j;\n"
10621                "};\n",
10622                Style);
10623   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10624   verifyFormat("struct foo {\n"
10625                "private:\n"
10626                "  void f() {}\n"
10627                "\n"
10628                "private:\n"
10629                "  int i;\n"
10630                "\n"
10631                "protected:\n"
10632                "  int j;\n"
10633                "};\n",
10634                Style);
10635   verifyFormat("struct foo {\n"
10636                "private:\n"
10637                "  void f() {}\n"
10638                "\n"
10639                "private:\n"
10640                "  int i;\n"
10641                "\n"
10642                "protected:\n"
10643                "  int j;\n"
10644                "};\n",
10645                "struct foo {\n"
10646                "private:\n"
10647                "  void f() {}\n"
10648                "private:\n"
10649                "  int i;\n"
10650                "protected:\n"
10651                "  int j;\n"
10652                "};\n",
10653                Style);
10654   verifyFormat("struct foo { /* comment */\n"
10655                "private:\n"
10656                "  int i;\n"
10657                "  // comment\n"
10658                "\n"
10659                "private:\n"
10660                "  int j;\n"
10661                "};\n",
10662                "struct foo { /* comment */\n"
10663                "private:\n"
10664                "  int i;\n"
10665                "  // comment\n"
10666                "\n"
10667                "private:\n"
10668                "  int j;\n"
10669                "};\n",
10670                Style);
10671   verifyFormat("struct foo {\n"
10672                "#ifdef FOO\n"
10673                "#endif\n"
10674                "\n"
10675                "private:\n"
10676                "  int i;\n"
10677                "#ifdef FOO\n"
10678                "\n"
10679                "private:\n"
10680                "#endif\n"
10681                "  int j;\n"
10682                "};\n",
10683                "struct foo {\n"
10684                "#ifdef FOO\n"
10685                "#endif\n"
10686                "private:\n"
10687                "  int i;\n"
10688                "#ifdef FOO\n"
10689                "private:\n"
10690                "#endif\n"
10691                "  int j;\n"
10692                "};\n",
10693                Style);
10694   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10695   EXPECT_EQ("struct foo {\n"
10696             "\n"
10697             "private:\n"
10698             "  void f() {}\n"
10699             "\n"
10700             "private:\n"
10701             "  int i;\n"
10702             "\n"
10703             "protected:\n"
10704             "  int j;\n"
10705             "};\n",
10706             format("struct foo {\n"
10707                    "\n"
10708                    "private:\n"
10709                    "  void f() {}\n"
10710                    "\n"
10711                    "private:\n"
10712                    "  int i;\n"
10713                    "\n"
10714                    "protected:\n"
10715                    "  int j;\n"
10716                    "};\n",
10717                    Style));
10718   verifyFormat("struct foo {\n"
10719                "private:\n"
10720                "  void f() {}\n"
10721                "private:\n"
10722                "  int i;\n"
10723                "protected:\n"
10724                "  int j;\n"
10725                "};\n",
10726                Style);
10727   EXPECT_EQ("struct foo { /* comment */\n"
10728             "\n"
10729             "private:\n"
10730             "  int i;\n"
10731             "  // comment\n"
10732             "\n"
10733             "private:\n"
10734             "  int j;\n"
10735             "};\n",
10736             format("struct foo { /* comment */\n"
10737                    "\n"
10738                    "private:\n"
10739                    "  int i;\n"
10740                    "  // comment\n"
10741                    "\n"
10742                    "private:\n"
10743                    "  int j;\n"
10744                    "};\n",
10745                    Style));
10746   verifyFormat("struct foo { /* comment */\n"
10747                "private:\n"
10748                "  int i;\n"
10749                "  // comment\n"
10750                "private:\n"
10751                "  int j;\n"
10752                "};\n",
10753                Style);
10754   EXPECT_EQ("struct foo {\n"
10755             "#ifdef FOO\n"
10756             "#endif\n"
10757             "\n"
10758             "private:\n"
10759             "  int i;\n"
10760             "#ifdef FOO\n"
10761             "\n"
10762             "private:\n"
10763             "#endif\n"
10764             "  int j;\n"
10765             "};\n",
10766             format("struct foo {\n"
10767                    "#ifdef FOO\n"
10768                    "#endif\n"
10769                    "\n"
10770                    "private:\n"
10771                    "  int i;\n"
10772                    "#ifdef FOO\n"
10773                    "\n"
10774                    "private:\n"
10775                    "#endif\n"
10776                    "  int j;\n"
10777                    "};\n",
10778                    Style));
10779   verifyFormat("struct foo {\n"
10780                "#ifdef FOO\n"
10781                "#endif\n"
10782                "private:\n"
10783                "  int i;\n"
10784                "#ifdef FOO\n"
10785                "private:\n"
10786                "#endif\n"
10787                "  int j;\n"
10788                "};\n",
10789                Style);
10790 
10791   FormatStyle NoEmptyLines = getLLVMStyle();
10792   NoEmptyLines.MaxEmptyLinesToKeep = 0;
10793   verifyFormat("struct foo {\n"
10794                "private:\n"
10795                "  void f() {}\n"
10796                "\n"
10797                "private:\n"
10798                "  int i;\n"
10799                "\n"
10800                "public:\n"
10801                "protected:\n"
10802                "  int j;\n"
10803                "};\n",
10804                NoEmptyLines);
10805 
10806   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10807   verifyFormat("struct foo {\n"
10808                "private:\n"
10809                "  void f() {}\n"
10810                "private:\n"
10811                "  int i;\n"
10812                "public:\n"
10813                "protected:\n"
10814                "  int j;\n"
10815                "};\n",
10816                NoEmptyLines);
10817 
10818   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10819   verifyFormat("struct foo {\n"
10820                "private:\n"
10821                "  void f() {}\n"
10822                "\n"
10823                "private:\n"
10824                "  int i;\n"
10825                "\n"
10826                "public:\n"
10827                "\n"
10828                "protected:\n"
10829                "  int j;\n"
10830                "};\n",
10831                NoEmptyLines);
10832 }
10833 
10834 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
10835 
10836   FormatStyle Style = getLLVMStyle();
10837   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
10838   verifyFormat("struct foo {\n"
10839                "private:\n"
10840                "  void f() {}\n"
10841                "\n"
10842                "private:\n"
10843                "  int i;\n"
10844                "\n"
10845                "protected:\n"
10846                "  int j;\n"
10847                "};\n",
10848                Style);
10849 
10850   // Check if lines are removed.
10851   verifyFormat("struct foo {\n"
10852                "private:\n"
10853                "  void f() {}\n"
10854                "\n"
10855                "private:\n"
10856                "  int i;\n"
10857                "\n"
10858                "protected:\n"
10859                "  int j;\n"
10860                "};\n",
10861                "struct foo {\n"
10862                "private:\n"
10863                "\n"
10864                "  void f() {}\n"
10865                "\n"
10866                "private:\n"
10867                "\n"
10868                "  int i;\n"
10869                "\n"
10870                "protected:\n"
10871                "\n"
10872                "  int j;\n"
10873                "};\n",
10874                Style);
10875 
10876   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10877   verifyFormat("struct foo {\n"
10878                "private:\n"
10879                "\n"
10880                "  void f() {}\n"
10881                "\n"
10882                "private:\n"
10883                "\n"
10884                "  int i;\n"
10885                "\n"
10886                "protected:\n"
10887                "\n"
10888                "  int j;\n"
10889                "};\n",
10890                Style);
10891 
10892   // Check if lines are added.
10893   verifyFormat("struct foo {\n"
10894                "private:\n"
10895                "\n"
10896                "  void f() {}\n"
10897                "\n"
10898                "private:\n"
10899                "\n"
10900                "  int i;\n"
10901                "\n"
10902                "protected:\n"
10903                "\n"
10904                "  int j;\n"
10905                "};\n",
10906                "struct foo {\n"
10907                "private:\n"
10908                "  void f() {}\n"
10909                "\n"
10910                "private:\n"
10911                "  int i;\n"
10912                "\n"
10913                "protected:\n"
10914                "  int j;\n"
10915                "};\n",
10916                Style);
10917 
10918   // Leave tests rely on the code layout, test::messUp can not be used.
10919   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10920   Style.MaxEmptyLinesToKeep = 0u;
10921   verifyFormat("struct foo {\n"
10922                "private:\n"
10923                "  void f() {}\n"
10924                "\n"
10925                "private:\n"
10926                "  int i;\n"
10927                "\n"
10928                "protected:\n"
10929                "  int j;\n"
10930                "};\n",
10931                Style);
10932 
10933   // Check if MaxEmptyLinesToKeep is respected.
10934   EXPECT_EQ("struct foo {\n"
10935             "private:\n"
10936             "  void f() {}\n"
10937             "\n"
10938             "private:\n"
10939             "  int i;\n"
10940             "\n"
10941             "protected:\n"
10942             "  int j;\n"
10943             "};\n",
10944             format("struct foo {\n"
10945                    "private:\n"
10946                    "\n\n\n"
10947                    "  void f() {}\n"
10948                    "\n"
10949                    "private:\n"
10950                    "\n\n\n"
10951                    "  int i;\n"
10952                    "\n"
10953                    "protected:\n"
10954                    "\n\n\n"
10955                    "  int j;\n"
10956                    "};\n",
10957                    Style));
10958 
10959   Style.MaxEmptyLinesToKeep = 1u;
10960   EXPECT_EQ("struct foo {\n"
10961             "private:\n"
10962             "\n"
10963             "  void f() {}\n"
10964             "\n"
10965             "private:\n"
10966             "\n"
10967             "  int i;\n"
10968             "\n"
10969             "protected:\n"
10970             "\n"
10971             "  int j;\n"
10972             "};\n",
10973             format("struct foo {\n"
10974                    "private:\n"
10975                    "\n"
10976                    "  void f() {}\n"
10977                    "\n"
10978                    "private:\n"
10979                    "\n"
10980                    "  int i;\n"
10981                    "\n"
10982                    "protected:\n"
10983                    "\n"
10984                    "  int j;\n"
10985                    "};\n",
10986                    Style));
10987   // Check if no lines are kept.
10988   EXPECT_EQ("struct foo {\n"
10989             "private:\n"
10990             "  void f() {}\n"
10991             "\n"
10992             "private:\n"
10993             "  int i;\n"
10994             "\n"
10995             "protected:\n"
10996             "  int j;\n"
10997             "};\n",
10998             format("struct foo {\n"
10999                    "private:\n"
11000                    "  void f() {}\n"
11001                    "\n"
11002                    "private:\n"
11003                    "  int i;\n"
11004                    "\n"
11005                    "protected:\n"
11006                    "  int j;\n"
11007                    "};\n",
11008                    Style));
11009   // Check if MaxEmptyLinesToKeep is respected.
11010   EXPECT_EQ("struct foo {\n"
11011             "private:\n"
11012             "\n"
11013             "  void f() {}\n"
11014             "\n"
11015             "private:\n"
11016             "\n"
11017             "  int i;\n"
11018             "\n"
11019             "protected:\n"
11020             "\n"
11021             "  int j;\n"
11022             "};\n",
11023             format("struct foo {\n"
11024                    "private:\n"
11025                    "\n\n\n"
11026                    "  void f() {}\n"
11027                    "\n"
11028                    "private:\n"
11029                    "\n\n\n"
11030                    "  int i;\n"
11031                    "\n"
11032                    "protected:\n"
11033                    "\n\n\n"
11034                    "  int j;\n"
11035                    "};\n",
11036                    Style));
11037 
11038   Style.MaxEmptyLinesToKeep = 10u;
11039   EXPECT_EQ("struct foo {\n"
11040             "private:\n"
11041             "\n\n\n"
11042             "  void f() {}\n"
11043             "\n"
11044             "private:\n"
11045             "\n\n\n"
11046             "  int i;\n"
11047             "\n"
11048             "protected:\n"
11049             "\n\n\n"
11050             "  int j;\n"
11051             "};\n",
11052             format("struct foo {\n"
11053                    "private:\n"
11054                    "\n\n\n"
11055                    "  void f() {}\n"
11056                    "\n"
11057                    "private:\n"
11058                    "\n\n\n"
11059                    "  int i;\n"
11060                    "\n"
11061                    "protected:\n"
11062                    "\n\n\n"
11063                    "  int j;\n"
11064                    "};\n",
11065                    Style));
11066 
11067   // Test with comments.
11068   Style = getLLVMStyle();
11069   verifyFormat("struct foo {\n"
11070                "private:\n"
11071                "  // comment\n"
11072                "  void f() {}\n"
11073                "\n"
11074                "private: /* comment */\n"
11075                "  int i;\n"
11076                "};\n",
11077                Style);
11078   verifyFormat("struct foo {\n"
11079                "private:\n"
11080                "  // comment\n"
11081                "  void f() {}\n"
11082                "\n"
11083                "private: /* comment */\n"
11084                "  int i;\n"
11085                "};\n",
11086                "struct foo {\n"
11087                "private:\n"
11088                "\n"
11089                "  // comment\n"
11090                "  void f() {}\n"
11091                "\n"
11092                "private: /* comment */\n"
11093                "\n"
11094                "  int i;\n"
11095                "};\n",
11096                Style);
11097 
11098   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11099   verifyFormat("struct foo {\n"
11100                "private:\n"
11101                "\n"
11102                "  // comment\n"
11103                "  void f() {}\n"
11104                "\n"
11105                "private: /* comment */\n"
11106                "\n"
11107                "  int i;\n"
11108                "};\n",
11109                "struct foo {\n"
11110                "private:\n"
11111                "  // comment\n"
11112                "  void f() {}\n"
11113                "\n"
11114                "private: /* comment */\n"
11115                "  int i;\n"
11116                "};\n",
11117                Style);
11118   verifyFormat("struct foo {\n"
11119                "private:\n"
11120                "\n"
11121                "  // comment\n"
11122                "  void f() {}\n"
11123                "\n"
11124                "private: /* comment */\n"
11125                "\n"
11126                "  int i;\n"
11127                "};\n",
11128                Style);
11129 
11130   // Test with preprocessor defines.
11131   Style = getLLVMStyle();
11132   verifyFormat("struct foo {\n"
11133                "private:\n"
11134                "#ifdef FOO\n"
11135                "#endif\n"
11136                "  void f() {}\n"
11137                "};\n",
11138                Style);
11139   verifyFormat("struct foo {\n"
11140                "private:\n"
11141                "#ifdef FOO\n"
11142                "#endif\n"
11143                "  void f() {}\n"
11144                "};\n",
11145                "struct foo {\n"
11146                "private:\n"
11147                "\n"
11148                "#ifdef FOO\n"
11149                "#endif\n"
11150                "  void f() {}\n"
11151                "};\n",
11152                Style);
11153 
11154   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11155   verifyFormat("struct foo {\n"
11156                "private:\n"
11157                "\n"
11158                "#ifdef FOO\n"
11159                "#endif\n"
11160                "  void f() {}\n"
11161                "};\n",
11162                "struct foo {\n"
11163                "private:\n"
11164                "#ifdef FOO\n"
11165                "#endif\n"
11166                "  void f() {}\n"
11167                "};\n",
11168                Style);
11169   verifyFormat("struct foo {\n"
11170                "private:\n"
11171                "\n"
11172                "#ifdef FOO\n"
11173                "#endif\n"
11174                "  void f() {}\n"
11175                "};\n",
11176                Style);
11177 }
11178 
11179 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11180   // Combined tests of EmptyLineAfterAccessModifier and
11181   // EmptyLineBeforeAccessModifier.
11182   FormatStyle Style = getLLVMStyle();
11183   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11184   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11185   verifyFormat("struct foo {\n"
11186                "private:\n"
11187                "\n"
11188                "protected:\n"
11189                "};\n",
11190                Style);
11191 
11192   Style.MaxEmptyLinesToKeep = 10u;
11193   // Both remove all new lines.
11194   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11195   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11196   verifyFormat("struct foo {\n"
11197                "private:\n"
11198                "protected:\n"
11199                "};\n",
11200                "struct foo {\n"
11201                "private:\n"
11202                "\n\n\n"
11203                "protected:\n"
11204                "};\n",
11205                Style);
11206 
11207   // Leave tests rely on the code layout, test::messUp can not be used.
11208   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11209   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11210   Style.MaxEmptyLinesToKeep = 10u;
11211   EXPECT_EQ("struct foo {\n"
11212             "private:\n"
11213             "\n\n\n"
11214             "protected:\n"
11215             "};\n",
11216             format("struct foo {\n"
11217                    "private:\n"
11218                    "\n\n\n"
11219                    "protected:\n"
11220                    "};\n",
11221                    Style));
11222   Style.MaxEmptyLinesToKeep = 3u;
11223   EXPECT_EQ("struct foo {\n"
11224             "private:\n"
11225             "\n\n\n"
11226             "protected:\n"
11227             "};\n",
11228             format("struct foo {\n"
11229                    "private:\n"
11230                    "\n\n\n"
11231                    "protected:\n"
11232                    "};\n",
11233                    Style));
11234   Style.MaxEmptyLinesToKeep = 1u;
11235   EXPECT_EQ("struct foo {\n"
11236             "private:\n"
11237             "\n\n\n"
11238             "protected:\n"
11239             "};\n",
11240             format("struct foo {\n"
11241                    "private:\n"
11242                    "\n\n\n"
11243                    "protected:\n"
11244                    "};\n",
11245                    Style)); // Based on new lines in original document and not
11246                             // on the setting.
11247 
11248   Style.MaxEmptyLinesToKeep = 10u;
11249   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11250   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11251   // Newlines are kept if they are greater than zero,
11252   // test::messUp removes all new lines which changes the logic
11253   EXPECT_EQ("struct foo {\n"
11254             "private:\n"
11255             "\n\n\n"
11256             "protected:\n"
11257             "};\n",
11258             format("struct foo {\n"
11259                    "private:\n"
11260                    "\n\n\n"
11261                    "protected:\n"
11262                    "};\n",
11263                    Style));
11264 
11265   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11266   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11267   // test::messUp removes all new lines which changes the logic
11268   EXPECT_EQ("struct foo {\n"
11269             "private:\n"
11270             "\n\n\n"
11271             "protected:\n"
11272             "};\n",
11273             format("struct foo {\n"
11274                    "private:\n"
11275                    "\n\n\n"
11276                    "protected:\n"
11277                    "};\n",
11278                    Style));
11279 
11280   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11281   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11282   EXPECT_EQ("struct foo {\n"
11283             "private:\n"
11284             "\n\n\n"
11285             "protected:\n"
11286             "};\n",
11287             format("struct foo {\n"
11288                    "private:\n"
11289                    "\n\n\n"
11290                    "protected:\n"
11291                    "};\n",
11292                    Style)); // test::messUp removes all new lines which changes
11293                             // the logic.
11294 
11295   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11296   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11297   verifyFormat("struct foo {\n"
11298                "private:\n"
11299                "protected:\n"
11300                "};\n",
11301                "struct foo {\n"
11302                "private:\n"
11303                "\n\n\n"
11304                "protected:\n"
11305                "};\n",
11306                Style);
11307 
11308   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11309   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
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)); // test::messUp removes all new lines which changes
11321                             // the logic.
11322 
11323   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11324   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11325   verifyFormat("struct foo {\n"
11326                "private:\n"
11327                "protected:\n"
11328                "};\n",
11329                "struct foo {\n"
11330                "private:\n"
11331                "\n\n\n"
11332                "protected:\n"
11333                "};\n",
11334                Style);
11335 
11336   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11337   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11338   verifyFormat("struct foo {\n"
11339                "private:\n"
11340                "protected:\n"
11341                "};\n",
11342                "struct foo {\n"
11343                "private:\n"
11344                "\n\n\n"
11345                "protected:\n"
11346                "};\n",
11347                Style);
11348 
11349   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11350   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11351   verifyFormat("struct foo {\n"
11352                "private:\n"
11353                "protected:\n"
11354                "};\n",
11355                "struct foo {\n"
11356                "private:\n"
11357                "\n\n\n"
11358                "protected:\n"
11359                "};\n",
11360                Style);
11361 
11362   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11363   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11364   verifyFormat("struct foo {\n"
11365                "private:\n"
11366                "protected:\n"
11367                "};\n",
11368                "struct foo {\n"
11369                "private:\n"
11370                "\n\n\n"
11371                "protected:\n"
11372                "};\n",
11373                Style);
11374 }
11375 
11376 TEST_F(FormatTest, FormatsArrays) {
11377   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11378                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11379   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11380                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11381   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11382                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11383   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11384                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11385   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11386                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11387   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11388                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11389                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11390   verifyFormat(
11391       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11392       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11393       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11394   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11395                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11396 
11397   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11398                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11399   verifyFormat(
11400       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11401       "                                  .aaaaaaa[0]\n"
11402       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11403   verifyFormat("a[::b::c];");
11404 
11405   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11406 
11407   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11408   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11409 }
11410 
11411 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11412   verifyFormat("(a)->b();");
11413   verifyFormat("--a;");
11414 }
11415 
11416 TEST_F(FormatTest, HandlesIncludeDirectives) {
11417   verifyFormat("#include <string>\n"
11418                "#include <a/b/c.h>\n"
11419                "#include \"a/b/string\"\n"
11420                "#include \"string.h\"\n"
11421                "#include \"string.h\"\n"
11422                "#include <a-a>\n"
11423                "#include < path with space >\n"
11424                "#include_next <test.h>"
11425                "#include \"abc.h\" // this is included for ABC\n"
11426                "#include \"some long include\" // with a comment\n"
11427                "#include \"some very long include path\"\n"
11428                "#include <some/very/long/include/path>\n",
11429                getLLVMStyleWithColumns(35));
11430   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11431   EXPECT_EQ("#include <a>", format("#include<a>"));
11432 
11433   verifyFormat("#import <string>");
11434   verifyFormat("#import <a/b/c.h>");
11435   verifyFormat("#import \"a/b/string\"");
11436   verifyFormat("#import \"string.h\"");
11437   verifyFormat("#import \"string.h\"");
11438   verifyFormat("#if __has_include(<strstream>)\n"
11439                "#include <strstream>\n"
11440                "#endif");
11441 
11442   verifyFormat("#define MY_IMPORT <a/b>");
11443 
11444   verifyFormat("#if __has_include(<a/b>)");
11445   verifyFormat("#if __has_include_next(<a/b>)");
11446   verifyFormat("#define F __has_include(<a/b>)");
11447   verifyFormat("#define F __has_include_next(<a/b>)");
11448 
11449   // Protocol buffer definition or missing "#".
11450   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
11451                getLLVMStyleWithColumns(30));
11452 
11453   FormatStyle Style = getLLVMStyle();
11454   Style.AlwaysBreakBeforeMultilineStrings = true;
11455   Style.ColumnLimit = 0;
11456   verifyFormat("#import \"abc.h\"", Style);
11457 
11458   // But 'import' might also be a regular C++ namespace.
11459   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11460                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11461 }
11462 
11463 //===----------------------------------------------------------------------===//
11464 // Error recovery tests.
11465 //===----------------------------------------------------------------------===//
11466 
11467 TEST_F(FormatTest, IncompleteParameterLists) {
11468   FormatStyle NoBinPacking = getLLVMStyle();
11469   NoBinPacking.BinPackParameters = false;
11470   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
11471                "                        double *min_x,\n"
11472                "                        double *max_x,\n"
11473                "                        double *min_y,\n"
11474                "                        double *max_y,\n"
11475                "                        double *min_z,\n"
11476                "                        double *max_z, ) {}",
11477                NoBinPacking);
11478 }
11479 
11480 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
11481   verifyFormat("void f() { return; }\n42");
11482   verifyFormat("void f() {\n"
11483                "  if (0)\n"
11484                "    return;\n"
11485                "}\n"
11486                "42");
11487   verifyFormat("void f() { return }\n42");
11488   verifyFormat("void f() {\n"
11489                "  if (0)\n"
11490                "    return\n"
11491                "}\n"
11492                "42");
11493 }
11494 
11495 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
11496   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
11497   EXPECT_EQ("void f() {\n"
11498             "  if (a)\n"
11499             "    return\n"
11500             "}",
11501             format("void  f  (  )  {  if  ( a )  return  }"));
11502   EXPECT_EQ("namespace N {\n"
11503             "void f()\n"
11504             "}",
11505             format("namespace  N  {  void f()  }"));
11506   EXPECT_EQ("namespace N {\n"
11507             "void f() {}\n"
11508             "void g()\n"
11509             "} // namespace N",
11510             format("namespace N  { void f( ) { } void g( ) }"));
11511 }
11512 
11513 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
11514   verifyFormat("int aaaaaaaa =\n"
11515                "    // Overlylongcomment\n"
11516                "    b;",
11517                getLLVMStyleWithColumns(20));
11518   verifyFormat("function(\n"
11519                "    ShortArgument,\n"
11520                "    LoooooooooooongArgument);\n",
11521                getLLVMStyleWithColumns(20));
11522 }
11523 
11524 TEST_F(FormatTest, IncorrectAccessSpecifier) {
11525   verifyFormat("public:");
11526   verifyFormat("class A {\n"
11527                "public\n"
11528                "  void f() {}\n"
11529                "};");
11530   verifyFormat("public\n"
11531                "int qwerty;");
11532   verifyFormat("public\n"
11533                "B {}");
11534   verifyFormat("public\n"
11535                "{}");
11536   verifyFormat("public\n"
11537                "B { int x; }");
11538 }
11539 
11540 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
11541   verifyFormat("{");
11542   verifyFormat("#})");
11543   verifyNoCrash("(/**/[:!] ?[).");
11544 }
11545 
11546 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
11547   // Found by oss-fuzz:
11548   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
11549   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
11550   Style.ColumnLimit = 60;
11551   verifyNoCrash(
11552       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
11553       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
11554       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
11555       Style);
11556 }
11557 
11558 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
11559   verifyFormat("do {\n}");
11560   verifyFormat("do {\n}\n"
11561                "f();");
11562   verifyFormat("do {\n}\n"
11563                "wheeee(fun);");
11564   verifyFormat("do {\n"
11565                "  f();\n"
11566                "}");
11567 }
11568 
11569 TEST_F(FormatTest, IncorrectCodeMissingParens) {
11570   verifyFormat("if {\n  foo;\n  foo();\n}");
11571   verifyFormat("switch {\n  foo;\n  foo();\n}");
11572   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
11573   verifyFormat("while {\n  foo;\n  foo();\n}");
11574   verifyFormat("do {\n  foo;\n  foo();\n} while;");
11575 }
11576 
11577 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
11578   verifyIncompleteFormat("namespace {\n"
11579                          "class Foo { Foo (\n"
11580                          "};\n"
11581                          "} // namespace");
11582 }
11583 
11584 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
11585   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
11586   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
11587   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
11588   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
11589 
11590   EXPECT_EQ("{\n"
11591             "  {\n"
11592             "    breakme(\n"
11593             "        qwe);\n"
11594             "  }\n",
11595             format("{\n"
11596                    "    {\n"
11597                    " breakme(qwe);\n"
11598                    "}\n",
11599                    getLLVMStyleWithColumns(10)));
11600 }
11601 
11602 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
11603   verifyFormat("int x = {\n"
11604                "    avariable,\n"
11605                "    b(alongervariable)};",
11606                getLLVMStyleWithColumns(25));
11607 }
11608 
11609 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
11610   verifyFormat("return (a)(b){1, 2, 3};");
11611 }
11612 
11613 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
11614   verifyFormat("vector<int> x{1, 2, 3, 4};");
11615   verifyFormat("vector<int> x{\n"
11616                "    1,\n"
11617                "    2,\n"
11618                "    3,\n"
11619                "    4,\n"
11620                "};");
11621   verifyFormat("vector<T> x{{}, {}, {}, {}};");
11622   verifyFormat("f({1, 2});");
11623   verifyFormat("auto v = Foo{-1};");
11624   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
11625   verifyFormat("Class::Class : member{1, 2, 3} {}");
11626   verifyFormat("new vector<int>{1, 2, 3};");
11627   verifyFormat("new int[3]{1, 2, 3};");
11628   verifyFormat("new int{1};");
11629   verifyFormat("return {arg1, arg2};");
11630   verifyFormat("return {arg1, SomeType{parameter}};");
11631   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
11632   verifyFormat("new T{arg1, arg2};");
11633   verifyFormat("f(MyMap[{composite, key}]);");
11634   verifyFormat("class Class {\n"
11635                "  T member = {arg1, arg2};\n"
11636                "};");
11637   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
11638   verifyFormat("const struct A a = {.a = 1, .b = 2};");
11639   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
11640   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
11641   verifyFormat("int a = std::is_integral<int>{} + 0;");
11642 
11643   verifyFormat("int foo(int i) { return fo1{}(i); }");
11644   verifyFormat("int foo(int i) { return fo1{}(i); }");
11645   verifyFormat("auto i = decltype(x){};");
11646   verifyFormat("auto i = typeof(x){};");
11647   verifyFormat("auto i = _Atomic(x){};");
11648   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
11649   verifyFormat("Node n{1, Node{1000}, //\n"
11650                "       2};");
11651   verifyFormat("Aaaa aaaaaaa{\n"
11652                "    {\n"
11653                "        aaaa,\n"
11654                "    },\n"
11655                "};");
11656   verifyFormat("class C : public D {\n"
11657                "  SomeClass SC{2};\n"
11658                "};");
11659   verifyFormat("class C : public A {\n"
11660                "  class D : public B {\n"
11661                "    void f() { int i{2}; }\n"
11662                "  };\n"
11663                "};");
11664   verifyFormat("#define A {a, a},");
11665   // Don't confuse braced list initializers with compound statements.
11666   verifyFormat(
11667       "class A {\n"
11668       "  A() : a{} {}\n"
11669       "  A(int b) : b(b) {}\n"
11670       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
11671       "  int a, b;\n"
11672       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
11673       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
11674       "{}\n"
11675       "};");
11676 
11677   // Avoid breaking between equal sign and opening brace
11678   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
11679   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
11680   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
11681                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
11682                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
11683                "     {\"ccccccccccccccccccccc\", 2}};",
11684                AvoidBreakingFirstArgument);
11685 
11686   // Binpacking only if there is no trailing comma
11687   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
11688                "                      cccccccccc, dddddddddd};",
11689                getLLVMStyleWithColumns(50));
11690   verifyFormat("const Aaaaaa aaaaa = {\n"
11691                "    aaaaaaaaaaa,\n"
11692                "    bbbbbbbbbbb,\n"
11693                "    ccccccccccc,\n"
11694                "    ddddddddddd,\n"
11695                "};",
11696                getLLVMStyleWithColumns(50));
11697 
11698   // Cases where distinguising braced lists and blocks is hard.
11699   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
11700   verifyFormat("void f() {\n"
11701                "  return; // comment\n"
11702                "}\n"
11703                "SomeType t;");
11704   verifyFormat("void f() {\n"
11705                "  if (a) {\n"
11706                "    f();\n"
11707                "  }\n"
11708                "}\n"
11709                "SomeType t;");
11710 
11711   // In combination with BinPackArguments = false.
11712   FormatStyle NoBinPacking = getLLVMStyle();
11713   NoBinPacking.BinPackArguments = false;
11714   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
11715                "                      bbbbb,\n"
11716                "                      ccccc,\n"
11717                "                      ddddd,\n"
11718                "                      eeeee,\n"
11719                "                      ffffff,\n"
11720                "                      ggggg,\n"
11721                "                      hhhhhh,\n"
11722                "                      iiiiii,\n"
11723                "                      jjjjjj,\n"
11724                "                      kkkkkk};",
11725                NoBinPacking);
11726   verifyFormat("const Aaaaaa aaaaa = {\n"
11727                "    aaaaa,\n"
11728                "    bbbbb,\n"
11729                "    ccccc,\n"
11730                "    ddddd,\n"
11731                "    eeeee,\n"
11732                "    ffffff,\n"
11733                "    ggggg,\n"
11734                "    hhhhhh,\n"
11735                "    iiiiii,\n"
11736                "    jjjjjj,\n"
11737                "    kkkkkk,\n"
11738                "};",
11739                NoBinPacking);
11740   verifyFormat(
11741       "const Aaaaaa aaaaa = {\n"
11742       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
11743       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
11744       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
11745       "};",
11746       NoBinPacking);
11747 
11748   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11749   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
11750             "    CDDDP83848_BMCR_REGISTER,\n"
11751             "    CDDDP83848_BMSR_REGISTER,\n"
11752             "    CDDDP83848_RBR_REGISTER};",
11753             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
11754                    "                                CDDDP83848_BMSR_REGISTER,\n"
11755                    "                                CDDDP83848_RBR_REGISTER};",
11756                    NoBinPacking));
11757 
11758   // FIXME: The alignment of these trailing comments might be bad. Then again,
11759   // this might be utterly useless in real code.
11760   verifyFormat("Constructor::Constructor()\n"
11761                "    : some_value{         //\n"
11762                "                 aaaaaaa, //\n"
11763                "                 bbbbbbb} {}");
11764 
11765   // In braced lists, the first comment is always assumed to belong to the
11766   // first element. Thus, it can be moved to the next or previous line as
11767   // appropriate.
11768   EXPECT_EQ("function({// First element:\n"
11769             "          1,\n"
11770             "          // Second element:\n"
11771             "          2});",
11772             format("function({\n"
11773                    "    // First element:\n"
11774                    "    1,\n"
11775                    "    // Second element:\n"
11776                    "    2});"));
11777   EXPECT_EQ("std::vector<int> MyNumbers{\n"
11778             "    // First element:\n"
11779             "    1,\n"
11780             "    // Second element:\n"
11781             "    2};",
11782             format("std::vector<int> MyNumbers{// First element:\n"
11783                    "                           1,\n"
11784                    "                           // Second element:\n"
11785                    "                           2};",
11786                    getLLVMStyleWithColumns(30)));
11787   // A trailing comma should still lead to an enforced line break and no
11788   // binpacking.
11789   EXPECT_EQ("vector<int> SomeVector = {\n"
11790             "    // aaa\n"
11791             "    1,\n"
11792             "    2,\n"
11793             "};",
11794             format("vector<int> SomeVector = { // aaa\n"
11795                    "    1, 2, };"));
11796 
11797   // C++11 brace initializer list l-braces should not be treated any differently
11798   // when breaking before lambda bodies is enabled
11799   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
11800   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
11801   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
11802   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
11803   verifyFormat(
11804       "std::runtime_error{\n"
11805       "    \"Long string which will force a break onto the next line...\"};",
11806       BreakBeforeLambdaBody);
11807 
11808   FormatStyle ExtraSpaces = getLLVMStyle();
11809   ExtraSpaces.Cpp11BracedListStyle = false;
11810   ExtraSpaces.ColumnLimit = 75;
11811   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
11812   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
11813   verifyFormat("f({ 1, 2 });", ExtraSpaces);
11814   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
11815   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
11816   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
11817   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
11818   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
11819   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
11820   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
11821   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
11822   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
11823   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
11824   verifyFormat("class Class {\n"
11825                "  T member = { arg1, arg2 };\n"
11826                "};",
11827                ExtraSpaces);
11828   verifyFormat(
11829       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11830       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
11831       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
11832       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
11833       ExtraSpaces);
11834   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
11835   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
11836                ExtraSpaces);
11837   verifyFormat(
11838       "someFunction(OtherParam,\n"
11839       "             BracedList{ // comment 1 (Forcing interesting break)\n"
11840       "                         param1, param2,\n"
11841       "                         // comment 2\n"
11842       "                         param3, param4 });",
11843       ExtraSpaces);
11844   verifyFormat(
11845       "std::this_thread::sleep_for(\n"
11846       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
11847       ExtraSpaces);
11848   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
11849                "    aaaaaaa,\n"
11850                "    aaaaaaaaaa,\n"
11851                "    aaaaa,\n"
11852                "    aaaaaaaaaaaaaaa,\n"
11853                "    aaa,\n"
11854                "    aaaaaaaaaa,\n"
11855                "    a,\n"
11856                "    aaaaaaaaaaaaaaaaaaaaa,\n"
11857                "    aaaaaaaaaaaa,\n"
11858                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
11859                "    aaaaaaa,\n"
11860                "    a};");
11861   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
11862   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
11863   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
11864 
11865   // Avoid breaking between initializer/equal sign and opening brace
11866   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
11867   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
11868                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11869                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11870                "  { \"ccccccccccccccccccccc\", 2 }\n"
11871                "};",
11872                ExtraSpaces);
11873   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
11874                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11875                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11876                "  { \"ccccccccccccccccccccc\", 2 }\n"
11877                "};",
11878                ExtraSpaces);
11879 
11880   FormatStyle SpaceBeforeBrace = getLLVMStyle();
11881   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
11882   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
11883   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
11884 
11885   FormatStyle SpaceBetweenBraces = getLLVMStyle();
11886   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
11887   SpaceBetweenBraces.SpacesInParentheses = true;
11888   SpaceBetweenBraces.SpacesInSquareBrackets = true;
11889   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
11890   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
11891   verifyFormat("vector< int > x{ // comment 1\n"
11892                "                 1, 2, 3, 4 };",
11893                SpaceBetweenBraces);
11894   SpaceBetweenBraces.ColumnLimit = 20;
11895   EXPECT_EQ("vector< int > x{\n"
11896             "    1, 2, 3, 4 };",
11897             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11898   SpaceBetweenBraces.ColumnLimit = 24;
11899   EXPECT_EQ("vector< int > x{ 1, 2,\n"
11900             "                 3, 4 };",
11901             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11902   EXPECT_EQ("vector< int > x{\n"
11903             "    1,\n"
11904             "    2,\n"
11905             "    3,\n"
11906             "    4,\n"
11907             "};",
11908             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
11909   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
11910   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
11911   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
11912 }
11913 
11914 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
11915   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11916                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11917                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11918                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11919                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11920                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
11921   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
11922                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11923                "                 1, 22, 333, 4444, 55555, //\n"
11924                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11925                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
11926   verifyFormat(
11927       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
11928       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
11929       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
11930       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11931       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11932       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11933       "                 7777777};");
11934   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11935                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11936                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
11937   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11938                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11939                "    // Separating comment.\n"
11940                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
11941   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11942                "    // Leading comment\n"
11943                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11944                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
11945   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11946                "                 1, 1, 1, 1};",
11947                getLLVMStyleWithColumns(39));
11948   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11949                "                 1, 1, 1, 1};",
11950                getLLVMStyleWithColumns(38));
11951   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
11952                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
11953                getLLVMStyleWithColumns(43));
11954   verifyFormat(
11955       "static unsigned SomeValues[10][3] = {\n"
11956       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
11957       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
11958   verifyFormat("static auto fields = new vector<string>{\n"
11959                "    \"aaaaaaaaaaaaa\",\n"
11960                "    \"aaaaaaaaaaaaa\",\n"
11961                "    \"aaaaaaaaaaaa\",\n"
11962                "    \"aaaaaaaaaaaaaa\",\n"
11963                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11964                "    \"aaaaaaaaaaaa\",\n"
11965                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11966                "};");
11967   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
11968   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
11969                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
11970                "                 3, cccccccccccccccccccccc};",
11971                getLLVMStyleWithColumns(60));
11972 
11973   // Trailing commas.
11974   verifyFormat("vector<int> x = {\n"
11975                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
11976                "};",
11977                getLLVMStyleWithColumns(39));
11978   verifyFormat("vector<int> x = {\n"
11979                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
11980                "};",
11981                getLLVMStyleWithColumns(39));
11982   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11983                "                 1, 1, 1, 1,\n"
11984                "                 /**/ /**/};",
11985                getLLVMStyleWithColumns(39));
11986 
11987   // Trailing comment in the first line.
11988   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
11989                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
11990                "    111111111,  222222222,  3333333333,  444444444,  //\n"
11991                "    11111111,   22222222,   333333333,   44444444};");
11992   // Trailing comment in the last line.
11993   verifyFormat("int aaaaa[] = {\n"
11994                "    1, 2, 3, // comment\n"
11995                "    4, 5, 6  // comment\n"
11996                "};");
11997 
11998   // With nested lists, we should either format one item per line or all nested
11999   // lists one on line.
12000   // FIXME: For some nested lists, we can do better.
12001   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12002                "        {aaaaaaaaaaaaaaaaaaa},\n"
12003                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12004                "        {aaaaaaaaaaaaaaaaa}};",
12005                getLLVMStyleWithColumns(60));
12006   verifyFormat(
12007       "SomeStruct my_struct_array = {\n"
12008       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12009       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12010       "    {aaa, aaa},\n"
12011       "    {aaa, aaa},\n"
12012       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12013       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12014       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12015 
12016   // No column layout should be used here.
12017   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12018                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12019 
12020   verifyNoCrash("a<,");
12021 
12022   // No braced initializer here.
12023   verifyFormat("void f() {\n"
12024                "  struct Dummy {};\n"
12025                "  f(v);\n"
12026                "}");
12027 
12028   // Long lists should be formatted in columns even if they are nested.
12029   verifyFormat(
12030       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12031       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12032       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12033       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12034       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12035       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12036 
12037   // Allow "single-column" layout even if that violates the column limit. There
12038   // isn't going to be a better way.
12039   verifyFormat("std::vector<int> a = {\n"
12040                "    aaaaaaaa,\n"
12041                "    aaaaaaaa,\n"
12042                "    aaaaaaaa,\n"
12043                "    aaaaaaaa,\n"
12044                "    aaaaaaaaaa,\n"
12045                "    aaaaaaaa,\n"
12046                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12047                getLLVMStyleWithColumns(30));
12048   verifyFormat("vector<int> aaaa = {\n"
12049                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12050                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12051                "    aaaaaa.aaaaaaa,\n"
12052                "    aaaaaa.aaaaaaa,\n"
12053                "    aaaaaa.aaaaaaa,\n"
12054                "    aaaaaa.aaaaaaa,\n"
12055                "};");
12056 
12057   // Don't create hanging lists.
12058   verifyFormat("someFunction(Param, {List1, List2,\n"
12059                "                     List3});",
12060                getLLVMStyleWithColumns(35));
12061   verifyFormat("someFunction(Param, Param,\n"
12062                "             {List1, List2,\n"
12063                "              List3});",
12064                getLLVMStyleWithColumns(35));
12065   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12066                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12067 }
12068 
12069 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12070   FormatStyle DoNotMerge = getLLVMStyle();
12071   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12072 
12073   verifyFormat("void f() { return 42; }");
12074   verifyFormat("void f() {\n"
12075                "  return 42;\n"
12076                "}",
12077                DoNotMerge);
12078   verifyFormat("void f() {\n"
12079                "  // Comment\n"
12080                "}");
12081   verifyFormat("{\n"
12082                "#error {\n"
12083                "  int a;\n"
12084                "}");
12085   verifyFormat("{\n"
12086                "  int a;\n"
12087                "#error {\n"
12088                "}");
12089   verifyFormat("void f() {} // comment");
12090   verifyFormat("void f() { int a; } // comment");
12091   verifyFormat("void f() {\n"
12092                "} // comment",
12093                DoNotMerge);
12094   verifyFormat("void f() {\n"
12095                "  int a;\n"
12096                "} // comment",
12097                DoNotMerge);
12098   verifyFormat("void f() {\n"
12099                "} // comment",
12100                getLLVMStyleWithColumns(15));
12101 
12102   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12103   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12104 
12105   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12106   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12107   verifyFormat("class C {\n"
12108                "  C()\n"
12109                "      : iiiiiiii(nullptr),\n"
12110                "        kkkkkkk(nullptr),\n"
12111                "        mmmmmmm(nullptr),\n"
12112                "        nnnnnnn(nullptr) {}\n"
12113                "};",
12114                getGoogleStyle());
12115 
12116   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12117   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12118   EXPECT_EQ("class C {\n"
12119             "  A() : b(0) {}\n"
12120             "};",
12121             format("class C{A():b(0){}};", NoColumnLimit));
12122   EXPECT_EQ("A()\n"
12123             "    : b(0) {\n"
12124             "}",
12125             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12126 
12127   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12128   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12129       FormatStyle::SFS_None;
12130   EXPECT_EQ("A()\n"
12131             "    : b(0) {\n"
12132             "}",
12133             format("A():b(0){}", DoNotMergeNoColumnLimit));
12134   EXPECT_EQ("A()\n"
12135             "    : b(0) {\n"
12136             "}",
12137             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12138 
12139   verifyFormat("#define A          \\\n"
12140                "  void f() {       \\\n"
12141                "    int i;         \\\n"
12142                "  }",
12143                getLLVMStyleWithColumns(20));
12144   verifyFormat("#define A           \\\n"
12145                "  void f() { int i; }",
12146                getLLVMStyleWithColumns(21));
12147   verifyFormat("#define A            \\\n"
12148                "  void f() {         \\\n"
12149                "    int i;           \\\n"
12150                "  }                  \\\n"
12151                "  int j;",
12152                getLLVMStyleWithColumns(22));
12153   verifyFormat("#define A             \\\n"
12154                "  void f() { int i; } \\\n"
12155                "  int j;",
12156                getLLVMStyleWithColumns(23));
12157 }
12158 
12159 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12160   FormatStyle MergeEmptyOnly = getLLVMStyle();
12161   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12162   verifyFormat("class C {\n"
12163                "  int f() {}\n"
12164                "};",
12165                MergeEmptyOnly);
12166   verifyFormat("class C {\n"
12167                "  int f() {\n"
12168                "    return 42;\n"
12169                "  }\n"
12170                "};",
12171                MergeEmptyOnly);
12172   verifyFormat("int f() {}", MergeEmptyOnly);
12173   verifyFormat("int f() {\n"
12174                "  return 42;\n"
12175                "}",
12176                MergeEmptyOnly);
12177 
12178   // Also verify behavior when BraceWrapping.AfterFunction = true
12179   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12180   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12181   verifyFormat("int f() {}", MergeEmptyOnly);
12182   verifyFormat("class C {\n"
12183                "  int f() {}\n"
12184                "};",
12185                MergeEmptyOnly);
12186 }
12187 
12188 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12189   FormatStyle MergeInlineOnly = getLLVMStyle();
12190   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12191   verifyFormat("class C {\n"
12192                "  int f() { return 42; }\n"
12193                "};",
12194                MergeInlineOnly);
12195   verifyFormat("int f() {\n"
12196                "  return 42;\n"
12197                "}",
12198                MergeInlineOnly);
12199 
12200   // SFS_Inline implies SFS_Empty
12201   verifyFormat("class C {\n"
12202                "  int f() {}\n"
12203                "};",
12204                MergeInlineOnly);
12205   verifyFormat("int f() {}", MergeInlineOnly);
12206 
12207   // Also verify behavior when BraceWrapping.AfterFunction = true
12208   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12209   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12210   verifyFormat("class C {\n"
12211                "  int f() { return 42; }\n"
12212                "};",
12213                MergeInlineOnly);
12214   verifyFormat("int f()\n"
12215                "{\n"
12216                "  return 42;\n"
12217                "}",
12218                MergeInlineOnly);
12219 
12220   // SFS_Inline implies SFS_Empty
12221   verifyFormat("int f() {}", MergeInlineOnly);
12222   verifyFormat("class C {\n"
12223                "  int f() {}\n"
12224                "};",
12225                MergeInlineOnly);
12226 }
12227 
12228 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12229   FormatStyle MergeInlineOnly = getLLVMStyle();
12230   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12231       FormatStyle::SFS_InlineOnly;
12232   verifyFormat("class C {\n"
12233                "  int f() { return 42; }\n"
12234                "};",
12235                MergeInlineOnly);
12236   verifyFormat("int f() {\n"
12237                "  return 42;\n"
12238                "}",
12239                MergeInlineOnly);
12240 
12241   // SFS_InlineOnly does not imply SFS_Empty
12242   verifyFormat("class C {\n"
12243                "  int f() {}\n"
12244                "};",
12245                MergeInlineOnly);
12246   verifyFormat("int f() {\n"
12247                "}",
12248                MergeInlineOnly);
12249 
12250   // Also verify behavior when BraceWrapping.AfterFunction = true
12251   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12252   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12253   verifyFormat("class C {\n"
12254                "  int f() { return 42; }\n"
12255                "};",
12256                MergeInlineOnly);
12257   verifyFormat("int f()\n"
12258                "{\n"
12259                "  return 42;\n"
12260                "}",
12261                MergeInlineOnly);
12262 
12263   // SFS_InlineOnly does not imply SFS_Empty
12264   verifyFormat("int f()\n"
12265                "{\n"
12266                "}",
12267                MergeInlineOnly);
12268   verifyFormat("class C {\n"
12269                "  int f() {}\n"
12270                "};",
12271                MergeInlineOnly);
12272 }
12273 
12274 TEST_F(FormatTest, SplitEmptyFunction) {
12275   FormatStyle Style = getLLVMStyleWithColumns(40);
12276   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12277   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12278   Style.BraceWrapping.AfterFunction = true;
12279   Style.BraceWrapping.SplitEmptyFunction = false;
12280 
12281   verifyFormat("int f()\n"
12282                "{}",
12283                Style);
12284   verifyFormat("int f()\n"
12285                "{\n"
12286                "  return 42;\n"
12287                "}",
12288                Style);
12289   verifyFormat("int f()\n"
12290                "{\n"
12291                "  // some comment\n"
12292                "}",
12293                Style);
12294 
12295   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12296   verifyFormat("int f() {}", Style);
12297   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12298                "{}",
12299                Style);
12300   verifyFormat("int f()\n"
12301                "{\n"
12302                "  return 0;\n"
12303                "}",
12304                Style);
12305 
12306   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12307   verifyFormat("class Foo {\n"
12308                "  int f() {}\n"
12309                "};\n",
12310                Style);
12311   verifyFormat("class Foo {\n"
12312                "  int f() { return 0; }\n"
12313                "};\n",
12314                Style);
12315   verifyFormat("class Foo {\n"
12316                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12317                "  {}\n"
12318                "};\n",
12319                Style);
12320   verifyFormat("class Foo {\n"
12321                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12322                "  {\n"
12323                "    return 0;\n"
12324                "  }\n"
12325                "};\n",
12326                Style);
12327 
12328   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12329   verifyFormat("int f() {}", Style);
12330   verifyFormat("int f() { return 0; }", Style);
12331   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12332                "{}",
12333                Style);
12334   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12335                "{\n"
12336                "  return 0;\n"
12337                "}",
12338                Style);
12339 }
12340 
12341 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12342   FormatStyle Style = getLLVMStyleWithColumns(40);
12343   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12344   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12345   Style.BraceWrapping.AfterFunction = true;
12346   Style.BraceWrapping.SplitEmptyFunction = true;
12347   Style.BraceWrapping.SplitEmptyRecord = false;
12348 
12349   verifyFormat("class C {};", Style);
12350   verifyFormat("struct C {};", Style);
12351   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12352                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12353                "{\n"
12354                "}",
12355                Style);
12356   verifyFormat("class C {\n"
12357                "  C()\n"
12358                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12359                "        bbbbbbbbbbbbbbbbbbb()\n"
12360                "  {\n"
12361                "  }\n"
12362                "  void\n"
12363                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12364                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12365                "  {\n"
12366                "  }\n"
12367                "};",
12368                Style);
12369 }
12370 
12371 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12372   FormatStyle Style = getLLVMStyle();
12373   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12374   verifyFormat("#ifdef A\n"
12375                "int f() {}\n"
12376                "#else\n"
12377                "int g() {}\n"
12378                "#endif",
12379                Style);
12380 }
12381 
12382 TEST_F(FormatTest, SplitEmptyClass) {
12383   FormatStyle Style = getLLVMStyle();
12384   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12385   Style.BraceWrapping.AfterClass = true;
12386   Style.BraceWrapping.SplitEmptyRecord = false;
12387 
12388   verifyFormat("class Foo\n"
12389                "{};",
12390                Style);
12391   verifyFormat("/* something */ class Foo\n"
12392                "{};",
12393                Style);
12394   verifyFormat("template <typename X> class Foo\n"
12395                "{};",
12396                Style);
12397   verifyFormat("class Foo\n"
12398                "{\n"
12399                "  Foo();\n"
12400                "};",
12401                Style);
12402   verifyFormat("typedef class Foo\n"
12403                "{\n"
12404                "} Foo_t;",
12405                Style);
12406 
12407   Style.BraceWrapping.SplitEmptyRecord = true;
12408   Style.BraceWrapping.AfterStruct = true;
12409   verifyFormat("class rep\n"
12410                "{\n"
12411                "};",
12412                Style);
12413   verifyFormat("struct rep\n"
12414                "{\n"
12415                "};",
12416                Style);
12417   verifyFormat("template <typename T> class rep\n"
12418                "{\n"
12419                "};",
12420                Style);
12421   verifyFormat("template <typename T> struct rep\n"
12422                "{\n"
12423                "};",
12424                Style);
12425   verifyFormat("class rep\n"
12426                "{\n"
12427                "  int x;\n"
12428                "};",
12429                Style);
12430   verifyFormat("struct rep\n"
12431                "{\n"
12432                "  int x;\n"
12433                "};",
12434                Style);
12435   verifyFormat("template <typename T> class rep\n"
12436                "{\n"
12437                "  int x;\n"
12438                "};",
12439                Style);
12440   verifyFormat("template <typename T> struct rep\n"
12441                "{\n"
12442                "  int x;\n"
12443                "};",
12444                Style);
12445   verifyFormat("template <typename T> class rep // Foo\n"
12446                "{\n"
12447                "  int x;\n"
12448                "};",
12449                Style);
12450   verifyFormat("template <typename T> struct rep // Bar\n"
12451                "{\n"
12452                "  int x;\n"
12453                "};",
12454                Style);
12455 
12456   verifyFormat("template <typename T> class rep<T>\n"
12457                "{\n"
12458                "  int x;\n"
12459                "};",
12460                Style);
12461 
12462   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12463                "{\n"
12464                "  int x;\n"
12465                "};",
12466                Style);
12467   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12468                "{\n"
12469                "};",
12470                Style);
12471 
12472   verifyFormat("#include \"stdint.h\"\n"
12473                "namespace rep {}",
12474                Style);
12475   verifyFormat("#include <stdint.h>\n"
12476                "namespace rep {}",
12477                Style);
12478   verifyFormat("#include <stdint.h>\n"
12479                "namespace rep {}",
12480                "#include <stdint.h>\n"
12481                "namespace rep {\n"
12482                "\n"
12483                "\n"
12484                "}",
12485                Style);
12486 }
12487 
12488 TEST_F(FormatTest, SplitEmptyStruct) {
12489   FormatStyle Style = getLLVMStyle();
12490   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12491   Style.BraceWrapping.AfterStruct = true;
12492   Style.BraceWrapping.SplitEmptyRecord = false;
12493 
12494   verifyFormat("struct Foo\n"
12495                "{};",
12496                Style);
12497   verifyFormat("/* something */ struct Foo\n"
12498                "{};",
12499                Style);
12500   verifyFormat("template <typename X> struct Foo\n"
12501                "{};",
12502                Style);
12503   verifyFormat("struct Foo\n"
12504                "{\n"
12505                "  Foo();\n"
12506                "};",
12507                Style);
12508   verifyFormat("typedef struct Foo\n"
12509                "{\n"
12510                "} Foo_t;",
12511                Style);
12512   // typedef struct Bar {} Bar_t;
12513 }
12514 
12515 TEST_F(FormatTest, SplitEmptyUnion) {
12516   FormatStyle Style = getLLVMStyle();
12517   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12518   Style.BraceWrapping.AfterUnion = true;
12519   Style.BraceWrapping.SplitEmptyRecord = false;
12520 
12521   verifyFormat("union Foo\n"
12522                "{};",
12523                Style);
12524   verifyFormat("/* something */ union Foo\n"
12525                "{};",
12526                Style);
12527   verifyFormat("union Foo\n"
12528                "{\n"
12529                "  A,\n"
12530                "};",
12531                Style);
12532   verifyFormat("typedef union Foo\n"
12533                "{\n"
12534                "} Foo_t;",
12535                Style);
12536 }
12537 
12538 TEST_F(FormatTest, SplitEmptyNamespace) {
12539   FormatStyle Style = getLLVMStyle();
12540   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12541   Style.BraceWrapping.AfterNamespace = true;
12542   Style.BraceWrapping.SplitEmptyNamespace = false;
12543 
12544   verifyFormat("namespace Foo\n"
12545                "{};",
12546                Style);
12547   verifyFormat("/* something */ namespace Foo\n"
12548                "{};",
12549                Style);
12550   verifyFormat("inline namespace Foo\n"
12551                "{};",
12552                Style);
12553   verifyFormat("/* something */ inline namespace Foo\n"
12554                "{};",
12555                Style);
12556   verifyFormat("export namespace Foo\n"
12557                "{};",
12558                Style);
12559   verifyFormat("namespace Foo\n"
12560                "{\n"
12561                "void Bar();\n"
12562                "};",
12563                Style);
12564 }
12565 
12566 TEST_F(FormatTest, NeverMergeShortRecords) {
12567   FormatStyle Style = getLLVMStyle();
12568 
12569   verifyFormat("class Foo {\n"
12570                "  Foo();\n"
12571                "};",
12572                Style);
12573   verifyFormat("typedef class Foo {\n"
12574                "  Foo();\n"
12575                "} Foo_t;",
12576                Style);
12577   verifyFormat("struct Foo {\n"
12578                "  Foo();\n"
12579                "};",
12580                Style);
12581   verifyFormat("typedef struct Foo {\n"
12582                "  Foo();\n"
12583                "} Foo_t;",
12584                Style);
12585   verifyFormat("union Foo {\n"
12586                "  A,\n"
12587                "};",
12588                Style);
12589   verifyFormat("typedef union Foo {\n"
12590                "  A,\n"
12591                "} Foo_t;",
12592                Style);
12593   verifyFormat("namespace Foo {\n"
12594                "void Bar();\n"
12595                "};",
12596                Style);
12597 
12598   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12599   Style.BraceWrapping.AfterClass = true;
12600   Style.BraceWrapping.AfterStruct = true;
12601   Style.BraceWrapping.AfterUnion = true;
12602   Style.BraceWrapping.AfterNamespace = true;
12603   verifyFormat("class Foo\n"
12604                "{\n"
12605                "  Foo();\n"
12606                "};",
12607                Style);
12608   verifyFormat("typedef class Foo\n"
12609                "{\n"
12610                "  Foo();\n"
12611                "} Foo_t;",
12612                Style);
12613   verifyFormat("struct Foo\n"
12614                "{\n"
12615                "  Foo();\n"
12616                "};",
12617                Style);
12618   verifyFormat("typedef struct Foo\n"
12619                "{\n"
12620                "  Foo();\n"
12621                "} Foo_t;",
12622                Style);
12623   verifyFormat("union Foo\n"
12624                "{\n"
12625                "  A,\n"
12626                "};",
12627                Style);
12628   verifyFormat("typedef union Foo\n"
12629                "{\n"
12630                "  A,\n"
12631                "} Foo_t;",
12632                Style);
12633   verifyFormat("namespace Foo\n"
12634                "{\n"
12635                "void Bar();\n"
12636                "};",
12637                Style);
12638 }
12639 
12640 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
12641   // Elaborate type variable declarations.
12642   verifyFormat("struct foo a = {bar};\nint n;");
12643   verifyFormat("class foo a = {bar};\nint n;");
12644   verifyFormat("union foo a = {bar};\nint n;");
12645 
12646   // Elaborate types inside function definitions.
12647   verifyFormat("struct foo f() {}\nint n;");
12648   verifyFormat("class foo f() {}\nint n;");
12649   verifyFormat("union foo f() {}\nint n;");
12650 
12651   // Templates.
12652   verifyFormat("template <class X> void f() {}\nint n;");
12653   verifyFormat("template <struct X> void f() {}\nint n;");
12654   verifyFormat("template <union X> void f() {}\nint n;");
12655 
12656   // Actual definitions...
12657   verifyFormat("struct {\n} n;");
12658   verifyFormat(
12659       "template <template <class T, class Y>, class Z> class X {\n} n;");
12660   verifyFormat("union Z {\n  int n;\n} x;");
12661   verifyFormat("class MACRO Z {\n} n;");
12662   verifyFormat("class MACRO(X) Z {\n} n;");
12663   verifyFormat("class __attribute__(X) Z {\n} n;");
12664   verifyFormat("class __declspec(X) Z {\n} n;");
12665   verifyFormat("class A##B##C {\n} n;");
12666   verifyFormat("class alignas(16) Z {\n} n;");
12667   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
12668   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
12669 
12670   // Redefinition from nested context:
12671   verifyFormat("class A::B::C {\n} n;");
12672 
12673   // Template definitions.
12674   verifyFormat(
12675       "template <typename F>\n"
12676       "Matcher(const Matcher<F> &Other,\n"
12677       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
12678       "                             !is_same<F, T>::value>::type * = 0)\n"
12679       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
12680 
12681   // FIXME: This is still incorrectly handled at the formatter side.
12682   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
12683   verifyFormat("int i = SomeFunction(a<b, a> b);");
12684 
12685   // FIXME:
12686   // This now gets parsed incorrectly as class definition.
12687   // verifyFormat("class A<int> f() {\n}\nint n;");
12688 
12689   // Elaborate types where incorrectly parsing the structural element would
12690   // break the indent.
12691   verifyFormat("if (true)\n"
12692                "  class X x;\n"
12693                "else\n"
12694                "  f();\n");
12695 
12696   // This is simply incomplete. Formatting is not important, but must not crash.
12697   verifyFormat("class A:");
12698 }
12699 
12700 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
12701   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
12702             format("#error Leave     all         white!!!!! space* alone!\n"));
12703   EXPECT_EQ(
12704       "#warning Leave     all         white!!!!! space* alone!\n",
12705       format("#warning Leave     all         white!!!!! space* alone!\n"));
12706   EXPECT_EQ("#error 1", format("  #  error   1"));
12707   EXPECT_EQ("#warning 1", format("  #  warning 1"));
12708 }
12709 
12710 TEST_F(FormatTest, FormatHashIfExpressions) {
12711   verifyFormat("#if AAAA && BBBB");
12712   verifyFormat("#if (AAAA && BBBB)");
12713   verifyFormat("#elif (AAAA && BBBB)");
12714   // FIXME: Come up with a better indentation for #elif.
12715   verifyFormat(
12716       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
12717       "    defined(BBBBBBBB)\n"
12718       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
12719       "    defined(BBBBBBBB)\n"
12720       "#endif",
12721       getLLVMStyleWithColumns(65));
12722 }
12723 
12724 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
12725   FormatStyle AllowsMergedIf = getGoogleStyle();
12726   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
12727       FormatStyle::SIS_WithoutElse;
12728   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
12729   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
12730   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
12731   EXPECT_EQ("if (true) return 42;",
12732             format("if (true)\nreturn 42;", AllowsMergedIf));
12733   FormatStyle ShortMergedIf = AllowsMergedIf;
12734   ShortMergedIf.ColumnLimit = 25;
12735   verifyFormat("#define A \\\n"
12736                "  if (true) return 42;",
12737                ShortMergedIf);
12738   verifyFormat("#define A \\\n"
12739                "  f();    \\\n"
12740                "  if (true)\n"
12741                "#define B",
12742                ShortMergedIf);
12743   verifyFormat("#define A \\\n"
12744                "  f();    \\\n"
12745                "  if (true)\n"
12746                "g();",
12747                ShortMergedIf);
12748   verifyFormat("{\n"
12749                "#ifdef A\n"
12750                "  // Comment\n"
12751                "  if (true) continue;\n"
12752                "#endif\n"
12753                "  // Comment\n"
12754                "  if (true) continue;\n"
12755                "}",
12756                ShortMergedIf);
12757   ShortMergedIf.ColumnLimit = 33;
12758   verifyFormat("#define A \\\n"
12759                "  if constexpr (true) return 42;",
12760                ShortMergedIf);
12761   verifyFormat("#define A \\\n"
12762                "  if CONSTEXPR (true) return 42;",
12763                ShortMergedIf);
12764   ShortMergedIf.ColumnLimit = 29;
12765   verifyFormat("#define A                   \\\n"
12766                "  if (aaaaaaaaaa) return 1; \\\n"
12767                "  return 2;",
12768                ShortMergedIf);
12769   ShortMergedIf.ColumnLimit = 28;
12770   verifyFormat("#define A         \\\n"
12771                "  if (aaaaaaaaaa) \\\n"
12772                "    return 1;     \\\n"
12773                "  return 2;",
12774                ShortMergedIf);
12775   verifyFormat("#define A                \\\n"
12776                "  if constexpr (aaaaaaa) \\\n"
12777                "    return 1;            \\\n"
12778                "  return 2;",
12779                ShortMergedIf);
12780   verifyFormat("#define A                \\\n"
12781                "  if CONSTEXPR (aaaaaaa) \\\n"
12782                "    return 1;            \\\n"
12783                "  return 2;",
12784                ShortMergedIf);
12785 }
12786 
12787 TEST_F(FormatTest, FormatStarDependingOnContext) {
12788   verifyFormat("void f(int *a);");
12789   verifyFormat("void f() { f(fint * b); }");
12790   verifyFormat("class A {\n  void f(int *a);\n};");
12791   verifyFormat("class A {\n  int *a;\n};");
12792   verifyFormat("namespace a {\n"
12793                "namespace b {\n"
12794                "class A {\n"
12795                "  void f() {}\n"
12796                "  int *a;\n"
12797                "};\n"
12798                "} // namespace b\n"
12799                "} // namespace a");
12800 }
12801 
12802 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
12803   verifyFormat("while");
12804   verifyFormat("operator");
12805 }
12806 
12807 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
12808   // This code would be painfully slow to format if we didn't skip it.
12809   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
12810                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12811                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12812                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12813                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12814                    "A(1, 1)\n"
12815                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
12816                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12817                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12818                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12819                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12820                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12821                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12822                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12823                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12824                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
12825   // Deeply nested part is untouched, rest is formatted.
12826   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
12827             format(std::string("int    i;\n") + Code + "int    j;\n",
12828                    getLLVMStyle(), SC_ExpectIncomplete));
12829 }
12830 
12831 //===----------------------------------------------------------------------===//
12832 // Objective-C tests.
12833 //===----------------------------------------------------------------------===//
12834 
12835 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
12836   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
12837   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
12838             format("-(NSUInteger)indexOfObject:(id)anObject;"));
12839   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
12840   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
12841   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
12842             format("-(NSInteger)Method3:(id)anObject;"));
12843   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
12844             format("-(NSInteger)Method4:(id)anObject;"));
12845   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
12846             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
12847   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
12848             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
12849   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12850             "forAllCells:(BOOL)flag;",
12851             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12852                    "forAllCells:(BOOL)flag;"));
12853 
12854   // Very long objectiveC method declaration.
12855   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
12856                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
12857   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
12858                "                    inRange:(NSRange)range\n"
12859                "                   outRange:(NSRange)out_range\n"
12860                "                  outRange1:(NSRange)out_range1\n"
12861                "                  outRange2:(NSRange)out_range2\n"
12862                "                  outRange3:(NSRange)out_range3\n"
12863                "                  outRange4:(NSRange)out_range4\n"
12864                "                  outRange5:(NSRange)out_range5\n"
12865                "                  outRange6:(NSRange)out_range6\n"
12866                "                  outRange7:(NSRange)out_range7\n"
12867                "                  outRange8:(NSRange)out_range8\n"
12868                "                  outRange9:(NSRange)out_range9;");
12869 
12870   // When the function name has to be wrapped.
12871   FormatStyle Style = getLLVMStyle();
12872   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
12873   // and always indents instead.
12874   Style.IndentWrappedFunctionNames = false;
12875   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12876                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
12877                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
12878                "}",
12879                Style);
12880   Style.IndentWrappedFunctionNames = true;
12881   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12882                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
12883                "               anotherName:(NSString)dddddddddddddd {\n"
12884                "}",
12885                Style);
12886 
12887   verifyFormat("- (int)sum:(vector<int>)numbers;");
12888   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
12889   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
12890   // protocol lists (but not for template classes):
12891   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
12892 
12893   verifyFormat("- (int (*)())foo:(int (*)())f;");
12894   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
12895 
12896   // If there's no return type (very rare in practice!), LLVM and Google style
12897   // agree.
12898   verifyFormat("- foo;");
12899   verifyFormat("- foo:(int)f;");
12900   verifyGoogleFormat("- foo:(int)foo;");
12901 }
12902 
12903 TEST_F(FormatTest, BreaksStringLiterals) {
12904   EXPECT_EQ("\"some text \"\n"
12905             "\"other\";",
12906             format("\"some text other\";", getLLVMStyleWithColumns(12)));
12907   EXPECT_EQ("\"some text \"\n"
12908             "\"other\";",
12909             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
12910   EXPECT_EQ(
12911       "#define A  \\\n"
12912       "  \"some \"  \\\n"
12913       "  \"text \"  \\\n"
12914       "  \"other\";",
12915       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
12916   EXPECT_EQ(
12917       "#define A  \\\n"
12918       "  \"so \"    \\\n"
12919       "  \"text \"  \\\n"
12920       "  \"other\";",
12921       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
12922 
12923   EXPECT_EQ("\"some text\"",
12924             format("\"some text\"", getLLVMStyleWithColumns(1)));
12925   EXPECT_EQ("\"some text\"",
12926             format("\"some text\"", getLLVMStyleWithColumns(11)));
12927   EXPECT_EQ("\"some \"\n"
12928             "\"text\"",
12929             format("\"some text\"", getLLVMStyleWithColumns(10)));
12930   EXPECT_EQ("\"some \"\n"
12931             "\"text\"",
12932             format("\"some text\"", getLLVMStyleWithColumns(7)));
12933   EXPECT_EQ("\"some\"\n"
12934             "\" tex\"\n"
12935             "\"t\"",
12936             format("\"some text\"", getLLVMStyleWithColumns(6)));
12937   EXPECT_EQ("\"some\"\n"
12938             "\" tex\"\n"
12939             "\" and\"",
12940             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
12941   EXPECT_EQ("\"some\"\n"
12942             "\"/tex\"\n"
12943             "\"/and\"",
12944             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
12945 
12946   EXPECT_EQ("variable =\n"
12947             "    \"long string \"\n"
12948             "    \"literal\";",
12949             format("variable = \"long string literal\";",
12950                    getLLVMStyleWithColumns(20)));
12951 
12952   EXPECT_EQ("variable = f(\n"
12953             "    \"long string \"\n"
12954             "    \"literal\",\n"
12955             "    short,\n"
12956             "    loooooooooooooooooooong);",
12957             format("variable = f(\"long string literal\", short, "
12958                    "loooooooooooooooooooong);",
12959                    getLLVMStyleWithColumns(20)));
12960 
12961   EXPECT_EQ(
12962       "f(g(\"long string \"\n"
12963       "    \"literal\"),\n"
12964       "  b);",
12965       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
12966   EXPECT_EQ("f(g(\"long string \"\n"
12967             "    \"literal\",\n"
12968             "    a),\n"
12969             "  b);",
12970             format("f(g(\"long string literal\", a), b);",
12971                    getLLVMStyleWithColumns(20)));
12972   EXPECT_EQ(
12973       "f(\"one two\".split(\n"
12974       "    variable));",
12975       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
12976   EXPECT_EQ("f(\"one two three four five six \"\n"
12977             "  \"seven\".split(\n"
12978             "      really_looooong_variable));",
12979             format("f(\"one two three four five six seven\"."
12980                    "split(really_looooong_variable));",
12981                    getLLVMStyleWithColumns(33)));
12982 
12983   EXPECT_EQ("f(\"some \"\n"
12984             "  \"text\",\n"
12985             "  other);",
12986             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
12987 
12988   // Only break as a last resort.
12989   verifyFormat(
12990       "aaaaaaaaaaaaaaaaaaaa(\n"
12991       "    aaaaaaaaaaaaaaaaaaaa,\n"
12992       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
12993 
12994   EXPECT_EQ("\"splitmea\"\n"
12995             "\"trandomp\"\n"
12996             "\"oint\"",
12997             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
12998 
12999   EXPECT_EQ("\"split/\"\n"
13000             "\"pathat/\"\n"
13001             "\"slashes\"",
13002             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13003 
13004   EXPECT_EQ("\"split/\"\n"
13005             "\"pathat/\"\n"
13006             "\"slashes\"",
13007             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13008   EXPECT_EQ("\"split at \"\n"
13009             "\"spaces/at/\"\n"
13010             "\"slashes.at.any$\"\n"
13011             "\"non-alphanumeric%\"\n"
13012             "\"1111111111characte\"\n"
13013             "\"rs\"",
13014             format("\"split at "
13015                    "spaces/at/"
13016                    "slashes.at."
13017                    "any$non-"
13018                    "alphanumeric%"
13019                    "1111111111characte"
13020                    "rs\"",
13021                    getLLVMStyleWithColumns(20)));
13022 
13023   // Verify that splitting the strings understands
13024   // Style::AlwaysBreakBeforeMultilineStrings.
13025   EXPECT_EQ("aaaaaaaaaaaa(\n"
13026             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13027             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13028             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13029                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13030                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13031                    getGoogleStyle()));
13032   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13033             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13034             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13035                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13036                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13037                    getGoogleStyle()));
13038   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13039             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13040             format("llvm::outs() << "
13041                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13042                    "aaaaaaaaaaaaaaaaaaa\";"));
13043   EXPECT_EQ("ffff(\n"
13044             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13045             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13046             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13047                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13048                    getGoogleStyle()));
13049 
13050   FormatStyle Style = getLLVMStyleWithColumns(12);
13051   Style.BreakStringLiterals = false;
13052   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13053 
13054   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13055   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13056   EXPECT_EQ("#define A \\\n"
13057             "  \"some \" \\\n"
13058             "  \"text \" \\\n"
13059             "  \"other\";",
13060             format("#define A \"some text other\";", AlignLeft));
13061 }
13062 
13063 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13064   EXPECT_EQ("C a = \"some more \"\n"
13065             "      \"text\";",
13066             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13067 }
13068 
13069 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13070   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13071   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13072   EXPECT_EQ("int i = a(b());",
13073             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13074 }
13075 
13076 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13077   EXPECT_EQ(
13078       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13079       "(\n"
13080       "    \"x\t\");",
13081       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13082              "aaaaaaa("
13083              "\"x\t\");"));
13084 }
13085 
13086 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13087   EXPECT_EQ(
13088       "u8\"utf8 string \"\n"
13089       "u8\"literal\";",
13090       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13091   EXPECT_EQ(
13092       "u\"utf16 string \"\n"
13093       "u\"literal\";",
13094       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13095   EXPECT_EQ(
13096       "U\"utf32 string \"\n"
13097       "U\"literal\";",
13098       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13099   EXPECT_EQ("L\"wide string \"\n"
13100             "L\"literal\";",
13101             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13102   EXPECT_EQ("@\"NSString \"\n"
13103             "@\"literal\";",
13104             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13105   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13106 
13107   // This input makes clang-format try to split the incomplete unicode escape
13108   // sequence, which used to lead to a crasher.
13109   verifyNoCrash(
13110       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13111       getLLVMStyleWithColumns(60));
13112 }
13113 
13114 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13115   FormatStyle Style = getGoogleStyleWithColumns(15);
13116   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13117   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13118   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13119   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13120   EXPECT_EQ("u8R\"x(raw literal)x\";",
13121             format("u8R\"x(raw literal)x\";", Style));
13122 }
13123 
13124 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13125   FormatStyle Style = getLLVMStyleWithColumns(20);
13126   EXPECT_EQ(
13127       "_T(\"aaaaaaaaaaaaaa\")\n"
13128       "_T(\"aaaaaaaaaaaaaa\")\n"
13129       "_T(\"aaaaaaaaaaaa\")",
13130       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13131   EXPECT_EQ("f(x,\n"
13132             "  _T(\"aaaaaaaaaaaa\")\n"
13133             "  _T(\"aaa\"),\n"
13134             "  z);",
13135             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13136 
13137   // FIXME: Handle embedded spaces in one iteration.
13138   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13139   //            "_T(\"aaaaaaaaaaaaa\")\n"
13140   //            "_T(\"aaaaaaaaaaaaa\")\n"
13141   //            "_T(\"a\")",
13142   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13143   //                   getLLVMStyleWithColumns(20)));
13144   EXPECT_EQ(
13145       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13146       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13147   EXPECT_EQ("f(\n"
13148             "#if !TEST\n"
13149             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13150             "#endif\n"
13151             ");",
13152             format("f(\n"
13153                    "#if !TEST\n"
13154                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13155                    "#endif\n"
13156                    ");"));
13157   EXPECT_EQ("f(\n"
13158             "\n"
13159             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13160             format("f(\n"
13161                    "\n"
13162                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13163   // Regression test for accessing tokens past the end of a vector in the
13164   // TokenLexer.
13165   verifyNoCrash(R"(_T(
13166 "
13167 )
13168 )");
13169 }
13170 
13171 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13172   // In a function call with two operands, the second can be broken with no line
13173   // break before it.
13174   EXPECT_EQ(
13175       "func(a, \"long long \"\n"
13176       "        \"long long\");",
13177       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13178   // In a function call with three operands, the second must be broken with a
13179   // line break before it.
13180   EXPECT_EQ("func(a,\n"
13181             "     \"long long long \"\n"
13182             "     \"long\",\n"
13183             "     c);",
13184             format("func(a, \"long long long long\", c);",
13185                    getLLVMStyleWithColumns(24)));
13186   // In a function call with three operands, the third must be broken with a
13187   // line break before it.
13188   EXPECT_EQ("func(a, b,\n"
13189             "     \"long long long \"\n"
13190             "     \"long\");",
13191             format("func(a, b, \"long long long long\");",
13192                    getLLVMStyleWithColumns(24)));
13193   // In a function call with three operands, both the second and the third must
13194   // be broken with a line break before them.
13195   EXPECT_EQ("func(a,\n"
13196             "     \"long long long \"\n"
13197             "     \"long\",\n"
13198             "     \"long long long \"\n"
13199             "     \"long\");",
13200             format("func(a, \"long long long long\", \"long long long long\");",
13201                    getLLVMStyleWithColumns(24)));
13202   // In a chain of << with two operands, the second can be broken with no line
13203   // break before it.
13204   EXPECT_EQ("a << \"line line \"\n"
13205             "     \"line\";",
13206             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13207   // In a chain of << with three operands, the second can be broken with no line
13208   // break before it.
13209   EXPECT_EQ(
13210       "abcde << \"line \"\n"
13211       "         \"line line\"\n"
13212       "      << c;",
13213       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13214   // In a chain of << with three operands, the third must be broken with a line
13215   // break before it.
13216   EXPECT_EQ(
13217       "a << b\n"
13218       "  << \"line line \"\n"
13219       "     \"line\";",
13220       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13221   // In a chain of << with three operands, the second can be broken with no line
13222   // break before it and the third must be broken with a line break before it.
13223   EXPECT_EQ("abcd << \"line line \"\n"
13224             "        \"line\"\n"
13225             "     << \"line line \"\n"
13226             "        \"line\";",
13227             format("abcd << \"line line line\" << \"line line line\";",
13228                    getLLVMStyleWithColumns(20)));
13229   // In a chain of binary operators with two operands, the second can be broken
13230   // with no line break before it.
13231   EXPECT_EQ(
13232       "abcd + \"line line \"\n"
13233       "       \"line line\";",
13234       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13235   // In a chain of binary operators with three operands, the second must be
13236   // broken with a line break before it.
13237   EXPECT_EQ("abcd +\n"
13238             "    \"line line \"\n"
13239             "    \"line line\" +\n"
13240             "    e;",
13241             format("abcd + \"line line line line\" + e;",
13242                    getLLVMStyleWithColumns(20)));
13243   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13244   // the first must be broken with a line break before it.
13245   FormatStyle Style = getLLVMStyleWithColumns(25);
13246   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13247   EXPECT_EQ("someFunction(\n"
13248             "    \"long long long \"\n"
13249             "    \"long\",\n"
13250             "    a);",
13251             format("someFunction(\"long long long long\", a);", Style));
13252 }
13253 
13254 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13255   EXPECT_EQ(
13256       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13257       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13258       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13259       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13260              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13261              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13262 }
13263 
13264 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13265   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13266             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13267   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13268             "multiline raw string literal xxxxxxxxxxxxxx\n"
13269             ")x\",\n"
13270             "              a),\n"
13271             "            b);",
13272             format("fffffffffff(g(R\"x(\n"
13273                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13274                    ")x\", a), b);",
13275                    getGoogleStyleWithColumns(20)));
13276   EXPECT_EQ("fffffffffff(\n"
13277             "    g(R\"x(qqq\n"
13278             "multiline raw string literal xxxxxxxxxxxxxx\n"
13279             ")x\",\n"
13280             "      a),\n"
13281             "    b);",
13282             format("fffffffffff(g(R\"x(qqq\n"
13283                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13284                    ")x\", a), b);",
13285                    getGoogleStyleWithColumns(20)));
13286 
13287   EXPECT_EQ("fffffffffff(R\"x(\n"
13288             "multiline raw string literal xxxxxxxxxxxxxx\n"
13289             ")x\");",
13290             format("fffffffffff(R\"x(\n"
13291                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13292                    ")x\");",
13293                    getGoogleStyleWithColumns(20)));
13294   EXPECT_EQ("fffffffffff(R\"x(\n"
13295             "multiline raw string literal xxxxxxxxxxxxxx\n"
13296             ")x\" + bbbbbb);",
13297             format("fffffffffff(R\"x(\n"
13298                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13299                    ")x\" +   bbbbbb);",
13300                    getGoogleStyleWithColumns(20)));
13301   EXPECT_EQ("fffffffffff(\n"
13302             "    R\"x(\n"
13303             "multiline raw string literal xxxxxxxxxxxxxx\n"
13304             ")x\" +\n"
13305             "    bbbbbb);",
13306             format("fffffffffff(\n"
13307                    " R\"x(\n"
13308                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13309                    ")x\" + bbbbbb);",
13310                    getGoogleStyleWithColumns(20)));
13311   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13312             format("fffffffffff(\n"
13313                    " R\"(single line raw string)\" + bbbbbb);"));
13314 }
13315 
13316 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13317   verifyFormat("string a = \"unterminated;");
13318   EXPECT_EQ("function(\"unterminated,\n"
13319             "         OtherParameter);",
13320             format("function(  \"unterminated,\n"
13321                    "    OtherParameter);"));
13322 }
13323 
13324 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13325   FormatStyle Style = getLLVMStyle();
13326   Style.Standard = FormatStyle::LS_Cpp03;
13327   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13328             format("#define x(_a) printf(\"foo\"_a);", Style));
13329 }
13330 
13331 TEST_F(FormatTest, CppLexVersion) {
13332   FormatStyle Style = getLLVMStyle();
13333   // Formatting of x * y differs if x is a type.
13334   verifyFormat("void foo() { MACRO(a * b); }", Style);
13335   verifyFormat("void foo() { MACRO(int *b); }", Style);
13336 
13337   // LLVM style uses latest lexer.
13338   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13339   Style.Standard = FormatStyle::LS_Cpp17;
13340   // But in c++17, char8_t isn't a keyword.
13341   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13342 }
13343 
13344 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13345 
13346 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13347   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13348             "             \"ddeeefff\");",
13349             format("someFunction(\"aaabbbcccdddeeefff\");",
13350                    getLLVMStyleWithColumns(25)));
13351   EXPECT_EQ("someFunction1234567890(\n"
13352             "    \"aaabbbcccdddeeefff\");",
13353             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13354                    getLLVMStyleWithColumns(26)));
13355   EXPECT_EQ("someFunction1234567890(\n"
13356             "    \"aaabbbcccdddeeeff\"\n"
13357             "    \"f\");",
13358             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13359                    getLLVMStyleWithColumns(25)));
13360   EXPECT_EQ("someFunction1234567890(\n"
13361             "    \"aaabbbcccdddeeeff\"\n"
13362             "    \"f\");",
13363             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13364                    getLLVMStyleWithColumns(24)));
13365   EXPECT_EQ("someFunction(\n"
13366             "    \"aaabbbcc ddde \"\n"
13367             "    \"efff\");",
13368             format("someFunction(\"aaabbbcc ddde efff\");",
13369                    getLLVMStyleWithColumns(25)));
13370   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13371             "             \"ddeeefff\");",
13372             format("someFunction(\"aaabbbccc ddeeefff\");",
13373                    getLLVMStyleWithColumns(25)));
13374   EXPECT_EQ("someFunction1234567890(\n"
13375             "    \"aaabb \"\n"
13376             "    \"cccdddeeefff\");",
13377             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13378                    getLLVMStyleWithColumns(25)));
13379   EXPECT_EQ("#define A          \\\n"
13380             "  string s =       \\\n"
13381             "      \"123456789\"  \\\n"
13382             "      \"0\";         \\\n"
13383             "  int i;",
13384             format("#define A string s = \"1234567890\"; int i;",
13385                    getLLVMStyleWithColumns(20)));
13386   EXPECT_EQ("someFunction(\n"
13387             "    \"aaabbbcc \"\n"
13388             "    \"dddeeefff\");",
13389             format("someFunction(\"aaabbbcc dddeeefff\");",
13390                    getLLVMStyleWithColumns(25)));
13391 }
13392 
13393 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13394   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13395   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13396   EXPECT_EQ("\"test\"\n"
13397             "\"\\n\"",
13398             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
13399   EXPECT_EQ("\"tes\\\\\"\n"
13400             "\"n\"",
13401             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
13402   EXPECT_EQ("\"\\\\\\\\\"\n"
13403             "\"\\n\"",
13404             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
13405   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
13406   EXPECT_EQ("\"\\uff01\"\n"
13407             "\"test\"",
13408             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
13409   EXPECT_EQ("\"\\Uff01ff02\"",
13410             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
13411   EXPECT_EQ("\"\\x000000000001\"\n"
13412             "\"next\"",
13413             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
13414   EXPECT_EQ("\"\\x000000000001next\"",
13415             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
13416   EXPECT_EQ("\"\\x000000000001\"",
13417             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
13418   EXPECT_EQ("\"test\"\n"
13419             "\"\\000000\"\n"
13420             "\"000001\"",
13421             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
13422   EXPECT_EQ("\"test\\000\"\n"
13423             "\"00000000\"\n"
13424             "\"1\"",
13425             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
13426 }
13427 
13428 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
13429   verifyFormat("void f() {\n"
13430                "  return g() {}\n"
13431                "  void h() {}");
13432   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
13433                "g();\n"
13434                "}");
13435 }
13436 
13437 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
13438   verifyFormat(
13439       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
13440 }
13441 
13442 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
13443   verifyFormat("class X {\n"
13444                "  void f() {\n"
13445                "  }\n"
13446                "};",
13447                getLLVMStyleWithColumns(12));
13448 }
13449 
13450 TEST_F(FormatTest, ConfigurableIndentWidth) {
13451   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
13452   EightIndent.IndentWidth = 8;
13453   EightIndent.ContinuationIndentWidth = 8;
13454   verifyFormat("void f() {\n"
13455                "        someFunction();\n"
13456                "        if (true) {\n"
13457                "                f();\n"
13458                "        }\n"
13459                "}",
13460                EightIndent);
13461   verifyFormat("class X {\n"
13462                "        void f() {\n"
13463                "        }\n"
13464                "};",
13465                EightIndent);
13466   verifyFormat("int x[] = {\n"
13467                "        call(),\n"
13468                "        call()};",
13469                EightIndent);
13470 }
13471 
13472 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
13473   verifyFormat("double\n"
13474                "f();",
13475                getLLVMStyleWithColumns(8));
13476 }
13477 
13478 TEST_F(FormatTest, ConfigurableUseOfTab) {
13479   FormatStyle Tab = getLLVMStyleWithColumns(42);
13480   Tab.IndentWidth = 8;
13481   Tab.UseTab = FormatStyle::UT_Always;
13482   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13483 
13484   EXPECT_EQ("if (aaaaaaaa && // q\n"
13485             "    bb)\t\t// w\n"
13486             "\t;",
13487             format("if (aaaaaaaa &&// q\n"
13488                    "bb)// w\n"
13489                    ";",
13490                    Tab));
13491   EXPECT_EQ("if (aaa && bbb) // w\n"
13492             "\t;",
13493             format("if(aaa&&bbb)// w\n"
13494                    ";",
13495                    Tab));
13496 
13497   verifyFormat("class X {\n"
13498                "\tvoid f() {\n"
13499                "\t\tsomeFunction(parameter1,\n"
13500                "\t\t\t     parameter2);\n"
13501                "\t}\n"
13502                "};",
13503                Tab);
13504   verifyFormat("#define A                        \\\n"
13505                "\tvoid f() {               \\\n"
13506                "\t\tsomeFunction(    \\\n"
13507                "\t\t    parameter1,  \\\n"
13508                "\t\t    parameter2); \\\n"
13509                "\t}",
13510                Tab);
13511   verifyFormat("int a;\t      // x\n"
13512                "int bbbbbbbb; // x\n",
13513                Tab);
13514 
13515   Tab.TabWidth = 4;
13516   Tab.IndentWidth = 8;
13517   verifyFormat("class TabWidth4Indent8 {\n"
13518                "\t\tvoid f() {\n"
13519                "\t\t\t\tsomeFunction(parameter1,\n"
13520                "\t\t\t\t\t\t\t parameter2);\n"
13521                "\t\t}\n"
13522                "};",
13523                Tab);
13524 
13525   Tab.TabWidth = 4;
13526   Tab.IndentWidth = 4;
13527   verifyFormat("class TabWidth4Indent4 {\n"
13528                "\tvoid f() {\n"
13529                "\t\tsomeFunction(parameter1,\n"
13530                "\t\t\t\t\t parameter2);\n"
13531                "\t}\n"
13532                "};",
13533                Tab);
13534 
13535   Tab.TabWidth = 8;
13536   Tab.IndentWidth = 4;
13537   verifyFormat("class TabWidth8Indent4 {\n"
13538                "    void f() {\n"
13539                "\tsomeFunction(parameter1,\n"
13540                "\t\t     parameter2);\n"
13541                "    }\n"
13542                "};",
13543                Tab);
13544 
13545   Tab.TabWidth = 8;
13546   Tab.IndentWidth = 8;
13547   EXPECT_EQ("/*\n"
13548             "\t      a\t\tcomment\n"
13549             "\t      in multiple lines\n"
13550             "       */",
13551             format("   /*\t \t \n"
13552                    " \t \t a\t\tcomment\t \t\n"
13553                    " \t \t in multiple lines\t\n"
13554                    " \t  */",
13555                    Tab));
13556 
13557   Tab.UseTab = FormatStyle::UT_ForIndentation;
13558   verifyFormat("{\n"
13559                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13560                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13561                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13562                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13563                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13564                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13565                "};",
13566                Tab);
13567   verifyFormat("enum AA {\n"
13568                "\ta1, // Force multiple lines\n"
13569                "\ta2,\n"
13570                "\ta3\n"
13571                "};",
13572                Tab);
13573   EXPECT_EQ("if (aaaaaaaa && // q\n"
13574             "    bb)         // w\n"
13575             "\t;",
13576             format("if (aaaaaaaa &&// q\n"
13577                    "bb)// w\n"
13578                    ";",
13579                    Tab));
13580   verifyFormat("class X {\n"
13581                "\tvoid f() {\n"
13582                "\t\tsomeFunction(parameter1,\n"
13583                "\t\t             parameter2);\n"
13584                "\t}\n"
13585                "};",
13586                Tab);
13587   verifyFormat("{\n"
13588                "\tQ(\n"
13589                "\t    {\n"
13590                "\t\t    int a;\n"
13591                "\t\t    someFunction(aaaaaaaa,\n"
13592                "\t\t                 bbbbbbb);\n"
13593                "\t    },\n"
13594                "\t    p);\n"
13595                "}",
13596                Tab);
13597   EXPECT_EQ("{\n"
13598             "\t/* aaaa\n"
13599             "\t   bbbb */\n"
13600             "}",
13601             format("{\n"
13602                    "/* aaaa\n"
13603                    "   bbbb */\n"
13604                    "}",
13605                    Tab));
13606   EXPECT_EQ("{\n"
13607             "\t/*\n"
13608             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13609             "\t  bbbbbbbbbbbbb\n"
13610             "\t*/\n"
13611             "}",
13612             format("{\n"
13613                    "/*\n"
13614                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13615                    "*/\n"
13616                    "}",
13617                    Tab));
13618   EXPECT_EQ("{\n"
13619             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13620             "\t// bbbbbbbbbbbbb\n"
13621             "}",
13622             format("{\n"
13623                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13624                    "}",
13625                    Tab));
13626   EXPECT_EQ("{\n"
13627             "\t/*\n"
13628             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13629             "\t  bbbbbbbbbbbbb\n"
13630             "\t*/\n"
13631             "}",
13632             format("{\n"
13633                    "\t/*\n"
13634                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13635                    "\t*/\n"
13636                    "}",
13637                    Tab));
13638   EXPECT_EQ("{\n"
13639             "\t/*\n"
13640             "\n"
13641             "\t*/\n"
13642             "}",
13643             format("{\n"
13644                    "\t/*\n"
13645                    "\n"
13646                    "\t*/\n"
13647                    "}",
13648                    Tab));
13649   EXPECT_EQ("{\n"
13650             "\t/*\n"
13651             " asdf\n"
13652             "\t*/\n"
13653             "}",
13654             format("{\n"
13655                    "\t/*\n"
13656                    " asdf\n"
13657                    "\t*/\n"
13658                    "}",
13659                    Tab));
13660 
13661   verifyFormat("void f() {\n"
13662                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
13663                "\t            : bbbbbbbbbbbbbbbbbb\n"
13664                "}",
13665                Tab);
13666   FormatStyle TabNoBreak = Tab;
13667   TabNoBreak.BreakBeforeTernaryOperators = false;
13668   verifyFormat("void f() {\n"
13669                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
13670                "\t              bbbbbbbbbbbbbbbbbb\n"
13671                "}",
13672                TabNoBreak);
13673   verifyFormat("void f() {\n"
13674                "\treturn true ?\n"
13675                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
13676                "\t           bbbbbbbbbbbbbbbbbbbb\n"
13677                "}",
13678                TabNoBreak);
13679 
13680   Tab.UseTab = FormatStyle::UT_Never;
13681   EXPECT_EQ("/*\n"
13682             "              a\t\tcomment\n"
13683             "              in multiple lines\n"
13684             "       */",
13685             format("   /*\t \t \n"
13686                    " \t \t a\t\tcomment\t \t\n"
13687                    " \t \t in multiple lines\t\n"
13688                    " \t  */",
13689                    Tab));
13690   EXPECT_EQ("/* some\n"
13691             "   comment */",
13692             format(" \t \t /* some\n"
13693                    " \t \t    comment */",
13694                    Tab));
13695   EXPECT_EQ("int a; /* some\n"
13696             "   comment */",
13697             format(" \t \t int a; /* some\n"
13698                    " \t \t    comment */",
13699                    Tab));
13700 
13701   EXPECT_EQ("int a; /* some\n"
13702             "comment */",
13703             format(" \t \t int\ta; /* some\n"
13704                    " \t \t    comment */",
13705                    Tab));
13706   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13707             "    comment */",
13708             format(" \t \t f(\"\t\t\"); /* some\n"
13709                    " \t \t    comment */",
13710                    Tab));
13711   EXPECT_EQ("{\n"
13712             "        /*\n"
13713             "         * Comment\n"
13714             "         */\n"
13715             "        int i;\n"
13716             "}",
13717             format("{\n"
13718                    "\t/*\n"
13719                    "\t * Comment\n"
13720                    "\t */\n"
13721                    "\t int i;\n"
13722                    "}",
13723                    Tab));
13724 
13725   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13726   Tab.TabWidth = 8;
13727   Tab.IndentWidth = 8;
13728   EXPECT_EQ("if (aaaaaaaa && // q\n"
13729             "    bb)         // w\n"
13730             "\t;",
13731             format("if (aaaaaaaa &&// q\n"
13732                    "bb)// w\n"
13733                    ";",
13734                    Tab));
13735   EXPECT_EQ("if (aaa && bbb) // w\n"
13736             "\t;",
13737             format("if(aaa&&bbb)// w\n"
13738                    ";",
13739                    Tab));
13740   verifyFormat("class X {\n"
13741                "\tvoid f() {\n"
13742                "\t\tsomeFunction(parameter1,\n"
13743                "\t\t\t     parameter2);\n"
13744                "\t}\n"
13745                "};",
13746                Tab);
13747   verifyFormat("#define A                        \\\n"
13748                "\tvoid f() {               \\\n"
13749                "\t\tsomeFunction(    \\\n"
13750                "\t\t    parameter1,  \\\n"
13751                "\t\t    parameter2); \\\n"
13752                "\t}",
13753                Tab);
13754   Tab.TabWidth = 4;
13755   Tab.IndentWidth = 8;
13756   verifyFormat("class TabWidth4Indent8 {\n"
13757                "\t\tvoid f() {\n"
13758                "\t\t\t\tsomeFunction(parameter1,\n"
13759                "\t\t\t\t\t\t\t parameter2);\n"
13760                "\t\t}\n"
13761                "};",
13762                Tab);
13763   Tab.TabWidth = 4;
13764   Tab.IndentWidth = 4;
13765   verifyFormat("class TabWidth4Indent4 {\n"
13766                "\tvoid f() {\n"
13767                "\t\tsomeFunction(parameter1,\n"
13768                "\t\t\t\t\t parameter2);\n"
13769                "\t}\n"
13770                "};",
13771                Tab);
13772   Tab.TabWidth = 8;
13773   Tab.IndentWidth = 4;
13774   verifyFormat("class TabWidth8Indent4 {\n"
13775                "    void f() {\n"
13776                "\tsomeFunction(parameter1,\n"
13777                "\t\t     parameter2);\n"
13778                "    }\n"
13779                "};",
13780                Tab);
13781   Tab.TabWidth = 8;
13782   Tab.IndentWidth = 8;
13783   EXPECT_EQ("/*\n"
13784             "\t      a\t\tcomment\n"
13785             "\t      in multiple lines\n"
13786             "       */",
13787             format("   /*\t \t \n"
13788                    " \t \t a\t\tcomment\t \t\n"
13789                    " \t \t in multiple lines\t\n"
13790                    " \t  */",
13791                    Tab));
13792   verifyFormat("{\n"
13793                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13794                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13795                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13796                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13797                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13798                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13799                "};",
13800                Tab);
13801   verifyFormat("enum AA {\n"
13802                "\ta1, // Force multiple lines\n"
13803                "\ta2,\n"
13804                "\ta3\n"
13805                "};",
13806                Tab);
13807   EXPECT_EQ("if (aaaaaaaa && // q\n"
13808             "    bb)         // w\n"
13809             "\t;",
13810             format("if (aaaaaaaa &&// q\n"
13811                    "bb)// w\n"
13812                    ";",
13813                    Tab));
13814   verifyFormat("class X {\n"
13815                "\tvoid f() {\n"
13816                "\t\tsomeFunction(parameter1,\n"
13817                "\t\t\t     parameter2);\n"
13818                "\t}\n"
13819                "};",
13820                Tab);
13821   verifyFormat("{\n"
13822                "\tQ(\n"
13823                "\t    {\n"
13824                "\t\t    int a;\n"
13825                "\t\t    someFunction(aaaaaaaa,\n"
13826                "\t\t\t\t bbbbbbb);\n"
13827                "\t    },\n"
13828                "\t    p);\n"
13829                "}",
13830                Tab);
13831   EXPECT_EQ("{\n"
13832             "\t/* aaaa\n"
13833             "\t   bbbb */\n"
13834             "}",
13835             format("{\n"
13836                    "/* aaaa\n"
13837                    "   bbbb */\n"
13838                    "}",
13839                    Tab));
13840   EXPECT_EQ("{\n"
13841             "\t/*\n"
13842             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13843             "\t  bbbbbbbbbbbbb\n"
13844             "\t*/\n"
13845             "}",
13846             format("{\n"
13847                    "/*\n"
13848                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13849                    "*/\n"
13850                    "}",
13851                    Tab));
13852   EXPECT_EQ("{\n"
13853             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13854             "\t// bbbbbbbbbbbbb\n"
13855             "}",
13856             format("{\n"
13857                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13858                    "}",
13859                    Tab));
13860   EXPECT_EQ("{\n"
13861             "\t/*\n"
13862             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13863             "\t  bbbbbbbbbbbbb\n"
13864             "\t*/\n"
13865             "}",
13866             format("{\n"
13867                    "\t/*\n"
13868                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13869                    "\t*/\n"
13870                    "}",
13871                    Tab));
13872   EXPECT_EQ("{\n"
13873             "\t/*\n"
13874             "\n"
13875             "\t*/\n"
13876             "}",
13877             format("{\n"
13878                    "\t/*\n"
13879                    "\n"
13880                    "\t*/\n"
13881                    "}",
13882                    Tab));
13883   EXPECT_EQ("{\n"
13884             "\t/*\n"
13885             " asdf\n"
13886             "\t*/\n"
13887             "}",
13888             format("{\n"
13889                    "\t/*\n"
13890                    " asdf\n"
13891                    "\t*/\n"
13892                    "}",
13893                    Tab));
13894   EXPECT_EQ("/* some\n"
13895             "   comment */",
13896             format(" \t \t /* some\n"
13897                    " \t \t    comment */",
13898                    Tab));
13899   EXPECT_EQ("int a; /* some\n"
13900             "   comment */",
13901             format(" \t \t int a; /* some\n"
13902                    " \t \t    comment */",
13903                    Tab));
13904   EXPECT_EQ("int a; /* some\n"
13905             "comment */",
13906             format(" \t \t int\ta; /* some\n"
13907                    " \t \t    comment */",
13908                    Tab));
13909   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13910             "    comment */",
13911             format(" \t \t f(\"\t\t\"); /* some\n"
13912                    " \t \t    comment */",
13913                    Tab));
13914   EXPECT_EQ("{\n"
13915             "\t/*\n"
13916             "\t * Comment\n"
13917             "\t */\n"
13918             "\tint i;\n"
13919             "}",
13920             format("{\n"
13921                    "\t/*\n"
13922                    "\t * Comment\n"
13923                    "\t */\n"
13924                    "\t int i;\n"
13925                    "}",
13926                    Tab));
13927   Tab.TabWidth = 2;
13928   Tab.IndentWidth = 2;
13929   EXPECT_EQ("{\n"
13930             "\t/* aaaa\n"
13931             "\t\t bbbb */\n"
13932             "}",
13933             format("{\n"
13934                    "/* aaaa\n"
13935                    "\t bbbb */\n"
13936                    "}",
13937                    Tab));
13938   EXPECT_EQ("{\n"
13939             "\t/*\n"
13940             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13941             "\t\tbbbbbbbbbbbbb\n"
13942             "\t*/\n"
13943             "}",
13944             format("{\n"
13945                    "/*\n"
13946                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13947                    "*/\n"
13948                    "}",
13949                    Tab));
13950   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13951   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13952   Tab.TabWidth = 4;
13953   Tab.IndentWidth = 4;
13954   verifyFormat("class Assign {\n"
13955                "\tvoid f() {\n"
13956                "\t\tint         x      = 123;\n"
13957                "\t\tint         random = 4;\n"
13958                "\t\tstd::string alphabet =\n"
13959                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
13960                "\t}\n"
13961                "};",
13962                Tab);
13963 
13964   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
13965   Tab.TabWidth = 8;
13966   Tab.IndentWidth = 8;
13967   EXPECT_EQ("if (aaaaaaaa && // q\n"
13968             "    bb)         // w\n"
13969             "\t;",
13970             format("if (aaaaaaaa &&// q\n"
13971                    "bb)// w\n"
13972                    ";",
13973                    Tab));
13974   EXPECT_EQ("if (aaa && bbb) // w\n"
13975             "\t;",
13976             format("if(aaa&&bbb)// w\n"
13977                    ";",
13978                    Tab));
13979   verifyFormat("class X {\n"
13980                "\tvoid f() {\n"
13981                "\t\tsomeFunction(parameter1,\n"
13982                "\t\t             parameter2);\n"
13983                "\t}\n"
13984                "};",
13985                Tab);
13986   verifyFormat("#define A                        \\\n"
13987                "\tvoid f() {               \\\n"
13988                "\t\tsomeFunction(    \\\n"
13989                "\t\t    parameter1,  \\\n"
13990                "\t\t    parameter2); \\\n"
13991                "\t}",
13992                Tab);
13993   Tab.TabWidth = 4;
13994   Tab.IndentWidth = 8;
13995   verifyFormat("class TabWidth4Indent8 {\n"
13996                "\t\tvoid f() {\n"
13997                "\t\t\t\tsomeFunction(parameter1,\n"
13998                "\t\t\t\t             parameter2);\n"
13999                "\t\t}\n"
14000                "};",
14001                Tab);
14002   Tab.TabWidth = 4;
14003   Tab.IndentWidth = 4;
14004   verifyFormat("class TabWidth4Indent4 {\n"
14005                "\tvoid f() {\n"
14006                "\t\tsomeFunction(parameter1,\n"
14007                "\t\t             parameter2);\n"
14008                "\t}\n"
14009                "};",
14010                Tab);
14011   Tab.TabWidth = 8;
14012   Tab.IndentWidth = 4;
14013   verifyFormat("class TabWidth8Indent4 {\n"
14014                "    void f() {\n"
14015                "\tsomeFunction(parameter1,\n"
14016                "\t             parameter2);\n"
14017                "    }\n"
14018                "};",
14019                Tab);
14020   Tab.TabWidth = 8;
14021   Tab.IndentWidth = 8;
14022   EXPECT_EQ("/*\n"
14023             "              a\t\tcomment\n"
14024             "              in multiple lines\n"
14025             "       */",
14026             format("   /*\t \t \n"
14027                    " \t \t a\t\tcomment\t \t\n"
14028                    " \t \t in multiple lines\t\n"
14029                    " \t  */",
14030                    Tab));
14031   verifyFormat("{\n"
14032                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14033                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14034                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14035                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14036                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14037                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14038                "};",
14039                Tab);
14040   verifyFormat("enum AA {\n"
14041                "\ta1, // Force multiple lines\n"
14042                "\ta2,\n"
14043                "\ta3\n"
14044                "};",
14045                Tab);
14046   EXPECT_EQ("if (aaaaaaaa && // q\n"
14047             "    bb)         // w\n"
14048             "\t;",
14049             format("if (aaaaaaaa &&// q\n"
14050                    "bb)// w\n"
14051                    ";",
14052                    Tab));
14053   verifyFormat("class X {\n"
14054                "\tvoid f() {\n"
14055                "\t\tsomeFunction(parameter1,\n"
14056                "\t\t             parameter2);\n"
14057                "\t}\n"
14058                "};",
14059                Tab);
14060   verifyFormat("{\n"
14061                "\tQ(\n"
14062                "\t    {\n"
14063                "\t\t    int a;\n"
14064                "\t\t    someFunction(aaaaaaaa,\n"
14065                "\t\t                 bbbbbbb);\n"
14066                "\t    },\n"
14067                "\t    p);\n"
14068                "}",
14069                Tab);
14070   EXPECT_EQ("{\n"
14071             "\t/* aaaa\n"
14072             "\t   bbbb */\n"
14073             "}",
14074             format("{\n"
14075                    "/* aaaa\n"
14076                    "   bbbb */\n"
14077                    "}",
14078                    Tab));
14079   EXPECT_EQ("{\n"
14080             "\t/*\n"
14081             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14082             "\t  bbbbbbbbbbbbb\n"
14083             "\t*/\n"
14084             "}",
14085             format("{\n"
14086                    "/*\n"
14087                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14088                    "*/\n"
14089                    "}",
14090                    Tab));
14091   EXPECT_EQ("{\n"
14092             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14093             "\t// bbbbbbbbbbbbb\n"
14094             "}",
14095             format("{\n"
14096                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14097                    "}",
14098                    Tab));
14099   EXPECT_EQ("{\n"
14100             "\t/*\n"
14101             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14102             "\t  bbbbbbbbbbbbb\n"
14103             "\t*/\n"
14104             "}",
14105             format("{\n"
14106                    "\t/*\n"
14107                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14108                    "\t*/\n"
14109                    "}",
14110                    Tab));
14111   EXPECT_EQ("{\n"
14112             "\t/*\n"
14113             "\n"
14114             "\t*/\n"
14115             "}",
14116             format("{\n"
14117                    "\t/*\n"
14118                    "\n"
14119                    "\t*/\n"
14120                    "}",
14121                    Tab));
14122   EXPECT_EQ("{\n"
14123             "\t/*\n"
14124             " asdf\n"
14125             "\t*/\n"
14126             "}",
14127             format("{\n"
14128                    "\t/*\n"
14129                    " asdf\n"
14130                    "\t*/\n"
14131                    "}",
14132                    Tab));
14133   EXPECT_EQ("/* some\n"
14134             "   comment */",
14135             format(" \t \t /* some\n"
14136                    " \t \t    comment */",
14137                    Tab));
14138   EXPECT_EQ("int a; /* some\n"
14139             "   comment */",
14140             format(" \t \t int a; /* some\n"
14141                    " \t \t    comment */",
14142                    Tab));
14143   EXPECT_EQ("int a; /* some\n"
14144             "comment */",
14145             format(" \t \t int\ta; /* some\n"
14146                    " \t \t    comment */",
14147                    Tab));
14148   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14149             "    comment */",
14150             format(" \t \t f(\"\t\t\"); /* some\n"
14151                    " \t \t    comment */",
14152                    Tab));
14153   EXPECT_EQ("{\n"
14154             "\t/*\n"
14155             "\t * Comment\n"
14156             "\t */\n"
14157             "\tint i;\n"
14158             "}",
14159             format("{\n"
14160                    "\t/*\n"
14161                    "\t * Comment\n"
14162                    "\t */\n"
14163                    "\t int i;\n"
14164                    "}",
14165                    Tab));
14166   Tab.TabWidth = 2;
14167   Tab.IndentWidth = 2;
14168   EXPECT_EQ("{\n"
14169             "\t/* aaaa\n"
14170             "\t   bbbb */\n"
14171             "}",
14172             format("{\n"
14173                    "/* aaaa\n"
14174                    "   bbbb */\n"
14175                    "}",
14176                    Tab));
14177   EXPECT_EQ("{\n"
14178             "\t/*\n"
14179             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14180             "\t  bbbbbbbbbbbbb\n"
14181             "\t*/\n"
14182             "}",
14183             format("{\n"
14184                    "/*\n"
14185                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14186                    "*/\n"
14187                    "}",
14188                    Tab));
14189   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14190   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14191   Tab.TabWidth = 4;
14192   Tab.IndentWidth = 4;
14193   verifyFormat("class Assign {\n"
14194                "\tvoid f() {\n"
14195                "\t\tint         x      = 123;\n"
14196                "\t\tint         random = 4;\n"
14197                "\t\tstd::string alphabet =\n"
14198                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14199                "\t}\n"
14200                "};",
14201                Tab);
14202   Tab.AlignOperands = FormatStyle::OAS_Align;
14203   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14204                "                 cccccccccccccccccccc;",
14205                Tab);
14206   // no alignment
14207   verifyFormat("int aaaaaaaaaa =\n"
14208                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14209                Tab);
14210   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14211                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14212                "                        : 333333333333333;",
14213                Tab);
14214   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14215   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14216   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14217                "               + cccccccccccccccccccc;",
14218                Tab);
14219 }
14220 
14221 TEST_F(FormatTest, ZeroTabWidth) {
14222   FormatStyle Tab = getLLVMStyleWithColumns(42);
14223   Tab.IndentWidth = 8;
14224   Tab.UseTab = FormatStyle::UT_Never;
14225   Tab.TabWidth = 0;
14226   EXPECT_EQ("void a(){\n"
14227             "    // line starts with '\t'\n"
14228             "};",
14229             format("void a(){\n"
14230                    "\t// line starts with '\t'\n"
14231                    "};",
14232                    Tab));
14233 
14234   EXPECT_EQ("void a(){\n"
14235             "    // line starts with '\t'\n"
14236             "};",
14237             format("void a(){\n"
14238                    "\t\t// line starts with '\t'\n"
14239                    "};",
14240                    Tab));
14241 
14242   Tab.UseTab = FormatStyle::UT_ForIndentation;
14243   EXPECT_EQ("void a(){\n"
14244             "    // line starts with '\t'\n"
14245             "};",
14246             format("void a(){\n"
14247                    "\t// line starts with '\t'\n"
14248                    "};",
14249                    Tab));
14250 
14251   EXPECT_EQ("void a(){\n"
14252             "    // line starts with '\t'\n"
14253             "};",
14254             format("void a(){\n"
14255                    "\t\t// line starts with '\t'\n"
14256                    "};",
14257                    Tab));
14258 
14259   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14260   EXPECT_EQ("void a(){\n"
14261             "    // line starts with '\t'\n"
14262             "};",
14263             format("void a(){\n"
14264                    "\t// line starts with '\t'\n"
14265                    "};",
14266                    Tab));
14267 
14268   EXPECT_EQ("void a(){\n"
14269             "    // line starts with '\t'\n"
14270             "};",
14271             format("void a(){\n"
14272                    "\t\t// line starts with '\t'\n"
14273                    "};",
14274                    Tab));
14275 
14276   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14277   EXPECT_EQ("void a(){\n"
14278             "    // line starts with '\t'\n"
14279             "};",
14280             format("void a(){\n"
14281                    "\t// line starts with '\t'\n"
14282                    "};",
14283                    Tab));
14284 
14285   EXPECT_EQ("void a(){\n"
14286             "    // line starts with '\t'\n"
14287             "};",
14288             format("void a(){\n"
14289                    "\t\t// line starts with '\t'\n"
14290                    "};",
14291                    Tab));
14292 
14293   Tab.UseTab = FormatStyle::UT_Always;
14294   EXPECT_EQ("void a(){\n"
14295             "// line starts with '\t'\n"
14296             "};",
14297             format("void a(){\n"
14298                    "\t// line starts with '\t'\n"
14299                    "};",
14300                    Tab));
14301 
14302   EXPECT_EQ("void a(){\n"
14303             "// line starts with '\t'\n"
14304             "};",
14305             format("void a(){\n"
14306                    "\t\t// line starts with '\t'\n"
14307                    "};",
14308                    Tab));
14309 }
14310 
14311 TEST_F(FormatTest, CalculatesOriginalColumn) {
14312   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14313             "q\"; /* some\n"
14314             "       comment */",
14315             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14316                    "q\"; /* some\n"
14317                    "       comment */",
14318                    getLLVMStyle()));
14319   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14320             "/* some\n"
14321             "   comment */",
14322             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14323                    " /* some\n"
14324                    "    comment */",
14325                    getLLVMStyle()));
14326   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14327             "qqq\n"
14328             "/* some\n"
14329             "   comment */",
14330             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14331                    "qqq\n"
14332                    " /* some\n"
14333                    "    comment */",
14334                    getLLVMStyle()));
14335   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14336             "wwww; /* some\n"
14337             "         comment */",
14338             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14339                    "wwww; /* some\n"
14340                    "         comment */",
14341                    getLLVMStyle()));
14342 }
14343 
14344 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14345   FormatStyle NoSpace = getLLVMStyle();
14346   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14347 
14348   verifyFormat("while(true)\n"
14349                "  continue;",
14350                NoSpace);
14351   verifyFormat("for(;;)\n"
14352                "  continue;",
14353                NoSpace);
14354   verifyFormat("if(true)\n"
14355                "  f();\n"
14356                "else if(true)\n"
14357                "  f();",
14358                NoSpace);
14359   verifyFormat("do {\n"
14360                "  do_something();\n"
14361                "} while(something());",
14362                NoSpace);
14363   verifyFormat("switch(x) {\n"
14364                "default:\n"
14365                "  break;\n"
14366                "}",
14367                NoSpace);
14368   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14369   verifyFormat("size_t x = sizeof(x);", NoSpace);
14370   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14371   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14372   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14373   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14374   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14375   verifyFormat("alignas(128) char a[128];", NoSpace);
14376   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14377   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14378   verifyFormat("int f() throw(Deprecated);", NoSpace);
14379   verifyFormat("typedef void (*cb)(int);", NoSpace);
14380   verifyFormat("T A::operator()();", NoSpace);
14381   verifyFormat("X A::operator++(T);", NoSpace);
14382   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14383 
14384   FormatStyle Space = getLLVMStyle();
14385   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14386 
14387   verifyFormat("int f ();", Space);
14388   verifyFormat("void f (int a, T b) {\n"
14389                "  while (true)\n"
14390                "    continue;\n"
14391                "}",
14392                Space);
14393   verifyFormat("if (true)\n"
14394                "  f ();\n"
14395                "else if (true)\n"
14396                "  f ();",
14397                Space);
14398   verifyFormat("do {\n"
14399                "  do_something ();\n"
14400                "} while (something ());",
14401                Space);
14402   verifyFormat("switch (x) {\n"
14403                "default:\n"
14404                "  break;\n"
14405                "}",
14406                Space);
14407   verifyFormat("A::A () : a (1) {}", Space);
14408   verifyFormat("void f () __attribute__ ((asdf));", Space);
14409   verifyFormat("*(&a + 1);\n"
14410                "&((&a)[1]);\n"
14411                "a[(b + c) * d];\n"
14412                "(((a + 1) * 2) + 3) * 4;",
14413                Space);
14414   verifyFormat("#define A(x) x", Space);
14415   verifyFormat("#define A (x) x", Space);
14416   verifyFormat("#if defined(x)\n"
14417                "#endif",
14418                Space);
14419   verifyFormat("auto i = std::make_unique<int> (5);", Space);
14420   verifyFormat("size_t x = sizeof (x);", Space);
14421   verifyFormat("auto f (int x) -> decltype (x);", Space);
14422   verifyFormat("auto f (int x) -> typeof (x);", Space);
14423   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
14424   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
14425   verifyFormat("int f (T x) noexcept (x.create ());", Space);
14426   verifyFormat("alignas (128) char a[128];", Space);
14427   verifyFormat("size_t x = alignof (MyType);", Space);
14428   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
14429   verifyFormat("int f () throw (Deprecated);", Space);
14430   verifyFormat("typedef void (*cb) (int);", Space);
14431   // FIXME these tests regressed behaviour.
14432   // verifyFormat("T A::operator() ();", Space);
14433   // verifyFormat("X A::operator++ (T);", Space);
14434   verifyFormat("auto lambda = [] () { return 0; };", Space);
14435   verifyFormat("int x = int (y);", Space);
14436 
14437   FormatStyle SomeSpace = getLLVMStyle();
14438   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
14439 
14440   verifyFormat("[]() -> float {}", SomeSpace);
14441   verifyFormat("[] (auto foo) {}", SomeSpace);
14442   verifyFormat("[foo]() -> int {}", SomeSpace);
14443   verifyFormat("int f();", SomeSpace);
14444   verifyFormat("void f (int a, T b) {\n"
14445                "  while (true)\n"
14446                "    continue;\n"
14447                "}",
14448                SomeSpace);
14449   verifyFormat("if (true)\n"
14450                "  f();\n"
14451                "else if (true)\n"
14452                "  f();",
14453                SomeSpace);
14454   verifyFormat("do {\n"
14455                "  do_something();\n"
14456                "} while (something());",
14457                SomeSpace);
14458   verifyFormat("switch (x) {\n"
14459                "default:\n"
14460                "  break;\n"
14461                "}",
14462                SomeSpace);
14463   verifyFormat("A::A() : a (1) {}", SomeSpace);
14464   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
14465   verifyFormat("*(&a + 1);\n"
14466                "&((&a)[1]);\n"
14467                "a[(b + c) * d];\n"
14468                "(((a + 1) * 2) + 3) * 4;",
14469                SomeSpace);
14470   verifyFormat("#define A(x) x", SomeSpace);
14471   verifyFormat("#define A (x) x", SomeSpace);
14472   verifyFormat("#if defined(x)\n"
14473                "#endif",
14474                SomeSpace);
14475   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
14476   verifyFormat("size_t x = sizeof (x);", SomeSpace);
14477   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
14478   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
14479   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
14480   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
14481   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
14482   verifyFormat("alignas (128) char a[128];", SomeSpace);
14483   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
14484   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14485                SomeSpace);
14486   verifyFormat("int f() throw (Deprecated);", SomeSpace);
14487   verifyFormat("typedef void (*cb) (int);", SomeSpace);
14488   verifyFormat("T A::operator()();", SomeSpace);
14489   // FIXME these tests regressed behaviour.
14490   // verifyFormat("X A::operator++ (T);", SomeSpace);
14491   verifyFormat("int x = int (y);", SomeSpace);
14492   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
14493 
14494   FormatStyle SpaceControlStatements = getLLVMStyle();
14495   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14496   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
14497 
14498   verifyFormat("while (true)\n"
14499                "  continue;",
14500                SpaceControlStatements);
14501   verifyFormat("if (true)\n"
14502                "  f();\n"
14503                "else if (true)\n"
14504                "  f();",
14505                SpaceControlStatements);
14506   verifyFormat("for (;;) {\n"
14507                "  do_something();\n"
14508                "}",
14509                SpaceControlStatements);
14510   verifyFormat("do {\n"
14511                "  do_something();\n"
14512                "} while (something());",
14513                SpaceControlStatements);
14514   verifyFormat("switch (x) {\n"
14515                "default:\n"
14516                "  break;\n"
14517                "}",
14518                SpaceControlStatements);
14519 
14520   FormatStyle SpaceFuncDecl = getLLVMStyle();
14521   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14522   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
14523 
14524   verifyFormat("int f ();", SpaceFuncDecl);
14525   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
14526   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
14527   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
14528   verifyFormat("#define A(x) x", SpaceFuncDecl);
14529   verifyFormat("#define A (x) x", SpaceFuncDecl);
14530   verifyFormat("#if defined(x)\n"
14531                "#endif",
14532                SpaceFuncDecl);
14533   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
14534   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
14535   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
14536   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
14537   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
14538   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
14539   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
14540   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
14541   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
14542   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14543                SpaceFuncDecl);
14544   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
14545   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
14546   // FIXME these tests regressed behaviour.
14547   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
14548   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
14549   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
14550   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
14551   verifyFormat("int x = int(y);", SpaceFuncDecl);
14552   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14553                SpaceFuncDecl);
14554 
14555   FormatStyle SpaceFuncDef = getLLVMStyle();
14556   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14557   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
14558 
14559   verifyFormat("int f();", SpaceFuncDef);
14560   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
14561   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
14562   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
14563   verifyFormat("#define A(x) x", SpaceFuncDef);
14564   verifyFormat("#define A (x) x", SpaceFuncDef);
14565   verifyFormat("#if defined(x)\n"
14566                "#endif",
14567                SpaceFuncDef);
14568   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
14569   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
14570   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
14571   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
14572   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
14573   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
14574   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
14575   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
14576   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
14577   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14578                SpaceFuncDef);
14579   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
14580   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
14581   verifyFormat("T A::operator()();", SpaceFuncDef);
14582   verifyFormat("X A::operator++(T);", SpaceFuncDef);
14583   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
14584   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
14585   verifyFormat("int x = int(y);", SpaceFuncDef);
14586   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14587                SpaceFuncDef);
14588 
14589   FormatStyle SpaceIfMacros = getLLVMStyle();
14590   SpaceIfMacros.IfMacros.clear();
14591   SpaceIfMacros.IfMacros.push_back("MYIF");
14592   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14593   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
14594   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
14595   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
14596   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
14597 
14598   FormatStyle SpaceForeachMacros = getLLVMStyle();
14599   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14600   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
14601   verifyFormat("foreach (Item *item, itemlist) {}", SpaceForeachMacros);
14602   verifyFormat("Q_FOREACH (Item *item, itemlist) {}", SpaceForeachMacros);
14603   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {}", SpaceForeachMacros);
14604   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
14605 
14606   FormatStyle SomeSpace2 = getLLVMStyle();
14607   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14608   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
14609   verifyFormat("[]() -> float {}", SomeSpace2);
14610   verifyFormat("[] (auto foo) {}", SomeSpace2);
14611   verifyFormat("[foo]() -> int {}", SomeSpace2);
14612   verifyFormat("int f();", SomeSpace2);
14613   verifyFormat("void f (int a, T b) {\n"
14614                "  while (true)\n"
14615                "    continue;\n"
14616                "}",
14617                SomeSpace2);
14618   verifyFormat("if (true)\n"
14619                "  f();\n"
14620                "else if (true)\n"
14621                "  f();",
14622                SomeSpace2);
14623   verifyFormat("do {\n"
14624                "  do_something();\n"
14625                "} while (something());",
14626                SomeSpace2);
14627   verifyFormat("switch (x) {\n"
14628                "default:\n"
14629                "  break;\n"
14630                "}",
14631                SomeSpace2);
14632   verifyFormat("A::A() : a (1) {}", SomeSpace2);
14633   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
14634   verifyFormat("*(&a + 1);\n"
14635                "&((&a)[1]);\n"
14636                "a[(b + c) * d];\n"
14637                "(((a + 1) * 2) + 3) * 4;",
14638                SomeSpace2);
14639   verifyFormat("#define A(x) x", SomeSpace2);
14640   verifyFormat("#define A (x) x", SomeSpace2);
14641   verifyFormat("#if defined(x)\n"
14642                "#endif",
14643                SomeSpace2);
14644   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
14645   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
14646   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
14647   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
14648   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
14649   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
14650   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
14651   verifyFormat("alignas (128) char a[128];", SomeSpace2);
14652   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
14653   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14654                SomeSpace2);
14655   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
14656   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
14657   verifyFormat("T A::operator()();", SomeSpace2);
14658   // verifyFormat("X A::operator++ (T);", SomeSpace2);
14659   verifyFormat("int x = int (y);", SomeSpace2);
14660   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
14661 
14662   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
14663   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14664   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
14665       .AfterOverloadedOperator = true;
14666 
14667   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
14668   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
14669   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
14670   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
14671 
14672   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
14673       .AfterOverloadedOperator = false;
14674 
14675   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
14676   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
14677   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
14678   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
14679 }
14680 
14681 TEST_F(FormatTest, SpaceAfterLogicalNot) {
14682   FormatStyle Spaces = getLLVMStyle();
14683   Spaces.SpaceAfterLogicalNot = true;
14684 
14685   verifyFormat("bool x = ! y", Spaces);
14686   verifyFormat("if (! isFailure())", Spaces);
14687   verifyFormat("if (! (a && b))", Spaces);
14688   verifyFormat("\"Error!\"", Spaces);
14689   verifyFormat("! ! x", Spaces);
14690 }
14691 
14692 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
14693   FormatStyle Spaces = getLLVMStyle();
14694 
14695   Spaces.SpacesInParentheses = true;
14696   verifyFormat("do_something( ::globalVar );", Spaces);
14697   verifyFormat("call( x, y, z );", Spaces);
14698   verifyFormat("call();", Spaces);
14699   verifyFormat("std::function<void( int, int )> callback;", Spaces);
14700   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
14701                Spaces);
14702   verifyFormat("while ( (bool)1 )\n"
14703                "  continue;",
14704                Spaces);
14705   verifyFormat("for ( ;; )\n"
14706                "  continue;",
14707                Spaces);
14708   verifyFormat("if ( true )\n"
14709                "  f();\n"
14710                "else if ( true )\n"
14711                "  f();",
14712                Spaces);
14713   verifyFormat("do {\n"
14714                "  do_something( (int)i );\n"
14715                "} while ( something() );",
14716                Spaces);
14717   verifyFormat("switch ( x ) {\n"
14718                "default:\n"
14719                "  break;\n"
14720                "}",
14721                Spaces);
14722 
14723   Spaces.SpacesInParentheses = false;
14724   Spaces.SpacesInCStyleCastParentheses = true;
14725   verifyFormat("Type *A = ( Type * )P;", Spaces);
14726   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
14727   verifyFormat("x = ( int32 )y;", Spaces);
14728   verifyFormat("int a = ( int )(2.0f);", Spaces);
14729   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
14730   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
14731   verifyFormat("#define x (( int )-1)", Spaces);
14732 
14733   // Run the first set of tests again with:
14734   Spaces.SpacesInParentheses = false;
14735   Spaces.SpaceInEmptyParentheses = true;
14736   Spaces.SpacesInCStyleCastParentheses = true;
14737   verifyFormat("call(x, y, z);", Spaces);
14738   verifyFormat("call( );", Spaces);
14739   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14740   verifyFormat("while (( bool )1)\n"
14741                "  continue;",
14742                Spaces);
14743   verifyFormat("for (;;)\n"
14744                "  continue;",
14745                Spaces);
14746   verifyFormat("if (true)\n"
14747                "  f( );\n"
14748                "else if (true)\n"
14749                "  f( );",
14750                Spaces);
14751   verifyFormat("do {\n"
14752                "  do_something(( int )i);\n"
14753                "} while (something( ));",
14754                Spaces);
14755   verifyFormat("switch (x) {\n"
14756                "default:\n"
14757                "  break;\n"
14758                "}",
14759                Spaces);
14760 
14761   // Run the first set of tests again with:
14762   Spaces.SpaceAfterCStyleCast = true;
14763   verifyFormat("call(x, y, z);", Spaces);
14764   verifyFormat("call( );", Spaces);
14765   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14766   verifyFormat("while (( bool ) 1)\n"
14767                "  continue;",
14768                Spaces);
14769   verifyFormat("for (;;)\n"
14770                "  continue;",
14771                Spaces);
14772   verifyFormat("if (true)\n"
14773                "  f( );\n"
14774                "else if (true)\n"
14775                "  f( );",
14776                Spaces);
14777   verifyFormat("do {\n"
14778                "  do_something(( int ) i);\n"
14779                "} while (something( ));",
14780                Spaces);
14781   verifyFormat("switch (x) {\n"
14782                "default:\n"
14783                "  break;\n"
14784                "}",
14785                Spaces);
14786   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
14787   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
14788   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
14789   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
14790   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
14791 
14792   // Run subset of tests again with:
14793   Spaces.SpacesInCStyleCastParentheses = false;
14794   Spaces.SpaceAfterCStyleCast = true;
14795   verifyFormat("while ((bool) 1)\n"
14796                "  continue;",
14797                Spaces);
14798   verifyFormat("do {\n"
14799                "  do_something((int) i);\n"
14800                "} while (something( ));",
14801                Spaces);
14802 
14803   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
14804   verifyFormat("size_t idx = (size_t) a;", Spaces);
14805   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
14806   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14807   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14808   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14809   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14810   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
14811   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
14812   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
14813   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
14814   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
14815   Spaces.ColumnLimit = 80;
14816   Spaces.IndentWidth = 4;
14817   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14818   verifyFormat("void foo( ) {\n"
14819                "    size_t foo = (*(function))(\n"
14820                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14821                "BarrrrrrrrrrrrLong,\n"
14822                "        FoooooooooLooooong);\n"
14823                "}",
14824                Spaces);
14825   Spaces.SpaceAfterCStyleCast = false;
14826   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
14827   verifyFormat("size_t idx = (size_t)a;", Spaces);
14828   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
14829   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14830   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14831   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14832   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14833 
14834   verifyFormat("void foo( ) {\n"
14835                "    size_t foo = (*(function))(\n"
14836                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14837                "BarrrrrrrrrrrrLong,\n"
14838                "        FoooooooooLooooong);\n"
14839                "}",
14840                Spaces);
14841 }
14842 
14843 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
14844   verifyFormat("int a[5];");
14845   verifyFormat("a[3] += 42;");
14846 
14847   FormatStyle Spaces = getLLVMStyle();
14848   Spaces.SpacesInSquareBrackets = true;
14849   // Not lambdas.
14850   verifyFormat("int a[ 5 ];", Spaces);
14851   verifyFormat("a[ 3 ] += 42;", Spaces);
14852   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
14853   verifyFormat("double &operator[](int i) { return 0; }\n"
14854                "int i;",
14855                Spaces);
14856   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
14857   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
14858   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
14859   // Lambdas.
14860   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
14861   verifyFormat("return [ i, args... ] {};", Spaces);
14862   verifyFormat("int foo = [ &bar ]() {};", Spaces);
14863   verifyFormat("int foo = [ = ]() {};", Spaces);
14864   verifyFormat("int foo = [ & ]() {};", Spaces);
14865   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
14866   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
14867 }
14868 
14869 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
14870   FormatStyle NoSpaceStyle = getLLVMStyle();
14871   verifyFormat("int a[5];", NoSpaceStyle);
14872   verifyFormat("a[3] += 42;", NoSpaceStyle);
14873 
14874   verifyFormat("int a[1];", NoSpaceStyle);
14875   verifyFormat("int 1 [a];", NoSpaceStyle);
14876   verifyFormat("int a[1][2];", NoSpaceStyle);
14877   verifyFormat("a[7] = 5;", NoSpaceStyle);
14878   verifyFormat("int a = (f())[23];", NoSpaceStyle);
14879   verifyFormat("f([] {})", NoSpaceStyle);
14880 
14881   FormatStyle Space = getLLVMStyle();
14882   Space.SpaceBeforeSquareBrackets = true;
14883   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
14884   verifyFormat("return [i, args...] {};", Space);
14885 
14886   verifyFormat("int a [5];", Space);
14887   verifyFormat("a [3] += 42;", Space);
14888   verifyFormat("constexpr char hello []{\"hello\"};", Space);
14889   verifyFormat("double &operator[](int i) { return 0; }\n"
14890                "int i;",
14891                Space);
14892   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
14893   verifyFormat("int i = a [a][a]->f();", Space);
14894   verifyFormat("int i = (*b) [a]->f();", Space);
14895 
14896   verifyFormat("int a [1];", Space);
14897   verifyFormat("int 1 [a];", Space);
14898   verifyFormat("int a [1][2];", Space);
14899   verifyFormat("a [7] = 5;", Space);
14900   verifyFormat("int a = (f()) [23];", Space);
14901   verifyFormat("f([] {})", Space);
14902 }
14903 
14904 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
14905   verifyFormat("int a = 5;");
14906   verifyFormat("a += 42;");
14907   verifyFormat("a or_eq 8;");
14908 
14909   FormatStyle Spaces = getLLVMStyle();
14910   Spaces.SpaceBeforeAssignmentOperators = false;
14911   verifyFormat("int a= 5;", Spaces);
14912   verifyFormat("a+= 42;", Spaces);
14913   verifyFormat("a or_eq 8;", Spaces);
14914 }
14915 
14916 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
14917   verifyFormat("class Foo : public Bar {};");
14918   verifyFormat("Foo::Foo() : foo(1) {}");
14919   verifyFormat("for (auto a : b) {\n}");
14920   verifyFormat("int x = a ? b : c;");
14921   verifyFormat("{\n"
14922                "label0:\n"
14923                "  int x = 0;\n"
14924                "}");
14925   verifyFormat("switch (x) {\n"
14926                "case 1:\n"
14927                "default:\n"
14928                "}");
14929   verifyFormat("switch (allBraces) {\n"
14930                "case 1: {\n"
14931                "  break;\n"
14932                "}\n"
14933                "case 2: {\n"
14934                "  [[fallthrough]];\n"
14935                "}\n"
14936                "default: {\n"
14937                "  break;\n"
14938                "}\n"
14939                "}");
14940 
14941   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
14942   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
14943   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
14944   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
14945   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
14946   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
14947   verifyFormat("{\n"
14948                "label1:\n"
14949                "  int x = 0;\n"
14950                "}",
14951                CtorInitializerStyle);
14952   verifyFormat("switch (x) {\n"
14953                "case 1:\n"
14954                "default:\n"
14955                "}",
14956                CtorInitializerStyle);
14957   verifyFormat("switch (allBraces) {\n"
14958                "case 1: {\n"
14959                "  break;\n"
14960                "}\n"
14961                "case 2: {\n"
14962                "  [[fallthrough]];\n"
14963                "}\n"
14964                "default: {\n"
14965                "  break;\n"
14966                "}\n"
14967                "}",
14968                CtorInitializerStyle);
14969   CtorInitializerStyle.BreakConstructorInitializers =
14970       FormatStyle::BCIS_AfterColon;
14971   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
14972                "    aaaaaaaaaaaaaaaa(1),\n"
14973                "    bbbbbbbbbbbbbbbb(2) {}",
14974                CtorInitializerStyle);
14975   CtorInitializerStyle.BreakConstructorInitializers =
14976       FormatStyle::BCIS_BeforeComma;
14977   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14978                "    : aaaaaaaaaaaaaaaa(1)\n"
14979                "    , bbbbbbbbbbbbbbbb(2) {}",
14980                CtorInitializerStyle);
14981   CtorInitializerStyle.BreakConstructorInitializers =
14982       FormatStyle::BCIS_BeforeColon;
14983   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14984                "    : aaaaaaaaaaaaaaaa(1),\n"
14985                "      bbbbbbbbbbbbbbbb(2) {}",
14986                CtorInitializerStyle);
14987   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
14988   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14989                ": aaaaaaaaaaaaaaaa(1),\n"
14990                "  bbbbbbbbbbbbbbbb(2) {}",
14991                CtorInitializerStyle);
14992 
14993   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
14994   InheritanceStyle.SpaceBeforeInheritanceColon = false;
14995   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
14996   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
14997   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
14998   verifyFormat("int x = a ? b : c;", InheritanceStyle);
14999   verifyFormat("{\n"
15000                "label2:\n"
15001                "  int x = 0;\n"
15002                "}",
15003                InheritanceStyle);
15004   verifyFormat("switch (x) {\n"
15005                "case 1:\n"
15006                "default:\n"
15007                "}",
15008                InheritanceStyle);
15009   verifyFormat("switch (allBraces) {\n"
15010                "case 1: {\n"
15011                "  break;\n"
15012                "}\n"
15013                "case 2: {\n"
15014                "  [[fallthrough]];\n"
15015                "}\n"
15016                "default: {\n"
15017                "  break;\n"
15018                "}\n"
15019                "}",
15020                InheritanceStyle);
15021   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15022   verifyFormat("class Foooooooooooooooooooooo\n"
15023                "    : public aaaaaaaaaaaaaaaaaa,\n"
15024                "      public bbbbbbbbbbbbbbbbbb {\n"
15025                "}",
15026                InheritanceStyle);
15027   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15028   verifyFormat("class Foooooooooooooooooooooo:\n"
15029                "    public aaaaaaaaaaaaaaaaaa,\n"
15030                "    public bbbbbbbbbbbbbbbbbb {\n"
15031                "}",
15032                InheritanceStyle);
15033   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15034   verifyFormat("class Foooooooooooooooooooooo\n"
15035                "    : public aaaaaaaaaaaaaaaaaa\n"
15036                "    , public bbbbbbbbbbbbbbbbbb {\n"
15037                "}",
15038                InheritanceStyle);
15039   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15040   verifyFormat("class Foooooooooooooooooooooo\n"
15041                "    : public aaaaaaaaaaaaaaaaaa,\n"
15042                "      public bbbbbbbbbbbbbbbbbb {\n"
15043                "}",
15044                InheritanceStyle);
15045   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15046   verifyFormat("class Foooooooooooooooooooooo\n"
15047                ": public aaaaaaaaaaaaaaaaaa,\n"
15048                "  public bbbbbbbbbbbbbbbbbb {}",
15049                InheritanceStyle);
15050 
15051   FormatStyle ForLoopStyle = getLLVMStyle();
15052   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15053   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15054   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15055   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15056   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15057   verifyFormat("{\n"
15058                "label2:\n"
15059                "  int x = 0;\n"
15060                "}",
15061                ForLoopStyle);
15062   verifyFormat("switch (x) {\n"
15063                "case 1:\n"
15064                "default:\n"
15065                "}",
15066                ForLoopStyle);
15067   verifyFormat("switch (allBraces) {\n"
15068                "case 1: {\n"
15069                "  break;\n"
15070                "}\n"
15071                "case 2: {\n"
15072                "  [[fallthrough]];\n"
15073                "}\n"
15074                "default: {\n"
15075                "  break;\n"
15076                "}\n"
15077                "}",
15078                ForLoopStyle);
15079 
15080   FormatStyle CaseStyle = getLLVMStyle();
15081   CaseStyle.SpaceBeforeCaseColon = true;
15082   verifyFormat("class Foo : public Bar {};", CaseStyle);
15083   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15084   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15085   verifyFormat("int x = a ? b : c;", CaseStyle);
15086   verifyFormat("switch (x) {\n"
15087                "case 1 :\n"
15088                "default :\n"
15089                "}",
15090                CaseStyle);
15091   verifyFormat("switch (allBraces) {\n"
15092                "case 1 : {\n"
15093                "  break;\n"
15094                "}\n"
15095                "case 2 : {\n"
15096                "  [[fallthrough]];\n"
15097                "}\n"
15098                "default : {\n"
15099                "  break;\n"
15100                "}\n"
15101                "}",
15102                CaseStyle);
15103 
15104   FormatStyle NoSpaceStyle = getLLVMStyle();
15105   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15106   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15107   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15108   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15109   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15110   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15111   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15112   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15113   verifyFormat("{\n"
15114                "label3:\n"
15115                "  int x = 0;\n"
15116                "}",
15117                NoSpaceStyle);
15118   verifyFormat("switch (x) {\n"
15119                "case 1:\n"
15120                "default:\n"
15121                "}",
15122                NoSpaceStyle);
15123   verifyFormat("switch (allBraces) {\n"
15124                "case 1: {\n"
15125                "  break;\n"
15126                "}\n"
15127                "case 2: {\n"
15128                "  [[fallthrough]];\n"
15129                "}\n"
15130                "default: {\n"
15131                "  break;\n"
15132                "}\n"
15133                "}",
15134                NoSpaceStyle);
15135 
15136   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15137   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15138   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15139   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15140   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15141   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15142   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15143   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15144   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15145   verifyFormat("{\n"
15146                "label3:\n"
15147                "  int x = 0;\n"
15148                "}",
15149                InvertedSpaceStyle);
15150   verifyFormat("switch (x) {\n"
15151                "case 1 :\n"
15152                "case 2 : {\n"
15153                "  break;\n"
15154                "}\n"
15155                "default :\n"
15156                "  break;\n"
15157                "}",
15158                InvertedSpaceStyle);
15159   verifyFormat("switch (allBraces) {\n"
15160                "case 1 : {\n"
15161                "  break;\n"
15162                "}\n"
15163                "case 2 : {\n"
15164                "  [[fallthrough]];\n"
15165                "}\n"
15166                "default : {\n"
15167                "  break;\n"
15168                "}\n"
15169                "}",
15170                InvertedSpaceStyle);
15171 }
15172 
15173 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15174   FormatStyle Style = getLLVMStyle();
15175 
15176   Style.PointerAlignment = FormatStyle::PAS_Left;
15177   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15178   verifyFormat("void* const* x = NULL;", Style);
15179 
15180 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15181   do {                                                                         \
15182     Style.PointerAlignment = FormatStyle::Pointers;                            \
15183     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15184     verifyFormat(Code, Style);                                                 \
15185   } while (false)
15186 
15187   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15188   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15189   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15190 
15191   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15192   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15193   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15194 
15195   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15196   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15197   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15198 
15199   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15200   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15201   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15202 
15203   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15204   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15205                         SAPQ_Default);
15206   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15207                         SAPQ_Default);
15208 
15209   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15210   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15211                         SAPQ_Before);
15212   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15213                         SAPQ_Before);
15214 
15215   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15216   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15217   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15218                         SAPQ_After);
15219 
15220   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15221   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15222   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15223 
15224 #undef verifyQualifierSpaces
15225 
15226   FormatStyle Spaces = getLLVMStyle();
15227   Spaces.AttributeMacros.push_back("qualified");
15228   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15229   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15230   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15231   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15232   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15233   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15234   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15235   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15236   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15237   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15238   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15239   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15240   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15241 
15242   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15243   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15244   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15245   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15246   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15247   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15248   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15249   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15250   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15251   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15252   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15253   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15254   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15255   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15256   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15257 
15258   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15259   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15260   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15261   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15262   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15263   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15264   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15265   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15266 }
15267 
15268 TEST_F(FormatTest, AlignConsecutiveMacros) {
15269   FormatStyle Style = getLLVMStyle();
15270   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15271   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15272   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15273 
15274   verifyFormat("#define a 3\n"
15275                "#define bbbb 4\n"
15276                "#define ccc (5)",
15277                Style);
15278 
15279   verifyFormat("#define f(x) (x * x)\n"
15280                "#define fff(x, y, z) (x * y + z)\n"
15281                "#define ffff(x, y) (x - y)",
15282                Style);
15283 
15284   verifyFormat("#define foo(x, y) (x + y)\n"
15285                "#define bar (5, 6)(2 + 2)",
15286                Style);
15287 
15288   verifyFormat("#define a 3\n"
15289                "#define bbbb 4\n"
15290                "#define ccc (5)\n"
15291                "#define f(x) (x * x)\n"
15292                "#define fff(x, y, z) (x * y + z)\n"
15293                "#define ffff(x, y) (x - y)",
15294                Style);
15295 
15296   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15297   verifyFormat("#define a    3\n"
15298                "#define bbbb 4\n"
15299                "#define ccc  (5)",
15300                Style);
15301 
15302   verifyFormat("#define f(x)         (x * x)\n"
15303                "#define fff(x, y, z) (x * y + z)\n"
15304                "#define ffff(x, y)   (x - y)",
15305                Style);
15306 
15307   verifyFormat("#define foo(x, y) (x + y)\n"
15308                "#define bar       (5, 6)(2 + 2)",
15309                Style);
15310 
15311   verifyFormat("#define a            3\n"
15312                "#define bbbb         4\n"
15313                "#define ccc          (5)\n"
15314                "#define f(x)         (x * x)\n"
15315                "#define fff(x, y, z) (x * y + z)\n"
15316                "#define ffff(x, y)   (x - y)",
15317                Style);
15318 
15319   verifyFormat("#define a         5\n"
15320                "#define foo(x, y) (x + y)\n"
15321                "#define CCC       (6)\n"
15322                "auto lambda = []() {\n"
15323                "  auto  ii = 0;\n"
15324                "  float j  = 0;\n"
15325                "  return 0;\n"
15326                "};\n"
15327                "int   i  = 0;\n"
15328                "float i2 = 0;\n"
15329                "auto  v  = type{\n"
15330                "    i = 1,   //\n"
15331                "    (i = 2), //\n"
15332                "    i = 3    //\n"
15333                "};",
15334                Style);
15335 
15336   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15337   Style.ColumnLimit = 20;
15338 
15339   verifyFormat("#define a          \\\n"
15340                "  \"aabbbbbbbbbbbb\"\n"
15341                "#define D          \\\n"
15342                "  \"aabbbbbbbbbbbb\" \\\n"
15343                "  \"ccddeeeeeeeee\"\n"
15344                "#define B          \\\n"
15345                "  \"QQQQQQQQQQQQQ\"  \\\n"
15346                "  \"FFFFFFFFFFFFF\"  \\\n"
15347                "  \"LLLLLLLL\"\n",
15348                Style);
15349 
15350   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15351   verifyFormat("#define a          \\\n"
15352                "  \"aabbbbbbbbbbbb\"\n"
15353                "#define D          \\\n"
15354                "  \"aabbbbbbbbbbbb\" \\\n"
15355                "  \"ccddeeeeeeeee\"\n"
15356                "#define B          \\\n"
15357                "  \"QQQQQQQQQQQQQ\"  \\\n"
15358                "  \"FFFFFFFFFFFFF\"  \\\n"
15359                "  \"LLLLLLLL\"\n",
15360                Style);
15361 
15362   // Test across comments
15363   Style.MaxEmptyLinesToKeep = 10;
15364   Style.ReflowComments = false;
15365   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
15366   EXPECT_EQ("#define a    3\n"
15367             "// line comment\n"
15368             "#define bbbb 4\n"
15369             "#define ccc  (5)",
15370             format("#define a 3\n"
15371                    "// line comment\n"
15372                    "#define bbbb 4\n"
15373                    "#define ccc (5)",
15374                    Style));
15375 
15376   EXPECT_EQ("#define a    3\n"
15377             "/* block comment */\n"
15378             "#define bbbb 4\n"
15379             "#define ccc  (5)",
15380             format("#define a  3\n"
15381                    "/* block comment */\n"
15382                    "#define bbbb 4\n"
15383                    "#define ccc (5)",
15384                    Style));
15385 
15386   EXPECT_EQ("#define a    3\n"
15387             "/* multi-line *\n"
15388             " * block comment */\n"
15389             "#define bbbb 4\n"
15390             "#define ccc  (5)",
15391             format("#define a 3\n"
15392                    "/* multi-line *\n"
15393                    " * block comment */\n"
15394                    "#define bbbb 4\n"
15395                    "#define ccc (5)",
15396                    Style));
15397 
15398   EXPECT_EQ("#define a    3\n"
15399             "// multi-line line comment\n"
15400             "//\n"
15401             "#define bbbb 4\n"
15402             "#define ccc  (5)",
15403             format("#define a  3\n"
15404                    "// multi-line line comment\n"
15405                    "//\n"
15406                    "#define bbbb 4\n"
15407                    "#define ccc (5)",
15408                    Style));
15409 
15410   EXPECT_EQ("#define a 3\n"
15411             "// empty lines still break.\n"
15412             "\n"
15413             "#define bbbb 4\n"
15414             "#define ccc  (5)",
15415             format("#define a     3\n"
15416                    "// empty lines still break.\n"
15417                    "\n"
15418                    "#define bbbb     4\n"
15419                    "#define ccc  (5)",
15420                    Style));
15421 
15422   // Test across empty lines
15423   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
15424   EXPECT_EQ("#define a    3\n"
15425             "\n"
15426             "#define bbbb 4\n"
15427             "#define ccc  (5)",
15428             format("#define a 3\n"
15429                    "\n"
15430                    "#define bbbb 4\n"
15431                    "#define ccc (5)",
15432                    Style));
15433 
15434   EXPECT_EQ("#define a    3\n"
15435             "\n"
15436             "\n"
15437             "\n"
15438             "#define bbbb 4\n"
15439             "#define ccc  (5)",
15440             format("#define a        3\n"
15441                    "\n"
15442                    "\n"
15443                    "\n"
15444                    "#define bbbb 4\n"
15445                    "#define ccc (5)",
15446                    Style));
15447 
15448   EXPECT_EQ("#define a 3\n"
15449             "// comments should break alignment\n"
15450             "//\n"
15451             "#define bbbb 4\n"
15452             "#define ccc  (5)",
15453             format("#define a        3\n"
15454                    "// comments should break alignment\n"
15455                    "//\n"
15456                    "#define bbbb 4\n"
15457                    "#define ccc (5)",
15458                    Style));
15459 
15460   // Test across empty lines and comments
15461   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
15462   verifyFormat("#define a    3\n"
15463                "\n"
15464                "// line comment\n"
15465                "#define bbbb 4\n"
15466                "#define ccc  (5)",
15467                Style);
15468 
15469   EXPECT_EQ("#define a    3\n"
15470             "\n"
15471             "\n"
15472             "/* multi-line *\n"
15473             " * block comment */\n"
15474             "\n"
15475             "\n"
15476             "#define bbbb 4\n"
15477             "#define ccc  (5)",
15478             format("#define a 3\n"
15479                    "\n"
15480                    "\n"
15481                    "/* multi-line *\n"
15482                    " * block comment */\n"
15483                    "\n"
15484                    "\n"
15485                    "#define bbbb 4\n"
15486                    "#define ccc (5)",
15487                    Style));
15488 
15489   EXPECT_EQ("#define a    3\n"
15490             "\n"
15491             "\n"
15492             "/* multi-line *\n"
15493             " * block comment */\n"
15494             "\n"
15495             "\n"
15496             "#define bbbb 4\n"
15497             "#define ccc  (5)",
15498             format("#define a 3\n"
15499                    "\n"
15500                    "\n"
15501                    "/* multi-line *\n"
15502                    " * block comment */\n"
15503                    "\n"
15504                    "\n"
15505                    "#define bbbb 4\n"
15506                    "#define ccc       (5)",
15507                    Style));
15508 }
15509 
15510 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
15511   FormatStyle Alignment = getLLVMStyle();
15512   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15513   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
15514 
15515   Alignment.MaxEmptyLinesToKeep = 10;
15516   /* Test alignment across empty lines */
15517   EXPECT_EQ("int a           = 5;\n"
15518             "\n"
15519             "int oneTwoThree = 123;",
15520             format("int a       = 5;\n"
15521                    "\n"
15522                    "int oneTwoThree= 123;",
15523                    Alignment));
15524   EXPECT_EQ("int a           = 5;\n"
15525             "int one         = 1;\n"
15526             "\n"
15527             "int oneTwoThree = 123;",
15528             format("int a = 5;\n"
15529                    "int one = 1;\n"
15530                    "\n"
15531                    "int oneTwoThree = 123;",
15532                    Alignment));
15533   EXPECT_EQ("int a           = 5;\n"
15534             "int one         = 1;\n"
15535             "\n"
15536             "int oneTwoThree = 123;\n"
15537             "int oneTwo      = 12;",
15538             format("int a = 5;\n"
15539                    "int one = 1;\n"
15540                    "\n"
15541                    "int oneTwoThree = 123;\n"
15542                    "int oneTwo = 12;",
15543                    Alignment));
15544 
15545   /* Test across comments */
15546   EXPECT_EQ("int a = 5;\n"
15547             "/* block comment */\n"
15548             "int oneTwoThree = 123;",
15549             format("int a = 5;\n"
15550                    "/* block comment */\n"
15551                    "int oneTwoThree=123;",
15552                    Alignment));
15553 
15554   EXPECT_EQ("int a = 5;\n"
15555             "// line comment\n"
15556             "int oneTwoThree = 123;",
15557             format("int a = 5;\n"
15558                    "// line comment\n"
15559                    "int oneTwoThree=123;",
15560                    Alignment));
15561 
15562   /* Test across comments and newlines */
15563   EXPECT_EQ("int a = 5;\n"
15564             "\n"
15565             "/* block comment */\n"
15566             "int oneTwoThree = 123;",
15567             format("int a = 5;\n"
15568                    "\n"
15569                    "/* block comment */\n"
15570                    "int oneTwoThree=123;",
15571                    Alignment));
15572 
15573   EXPECT_EQ("int a = 5;\n"
15574             "\n"
15575             "// line comment\n"
15576             "int oneTwoThree = 123;",
15577             format("int a = 5;\n"
15578                    "\n"
15579                    "// line comment\n"
15580                    "int oneTwoThree=123;",
15581                    Alignment));
15582 }
15583 
15584 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
15585   FormatStyle Alignment = getLLVMStyle();
15586   Alignment.AlignConsecutiveDeclarations =
15587       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15588   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15589 
15590   Alignment.MaxEmptyLinesToKeep = 10;
15591   /* Test alignment across empty lines */
15592   EXPECT_EQ("int         a = 5;\n"
15593             "\n"
15594             "float const oneTwoThree = 123;",
15595             format("int a = 5;\n"
15596                    "\n"
15597                    "float const oneTwoThree = 123;",
15598                    Alignment));
15599   EXPECT_EQ("int         a = 5;\n"
15600             "float const one = 1;\n"
15601             "\n"
15602             "int         oneTwoThree = 123;",
15603             format("int a = 5;\n"
15604                    "float const one = 1;\n"
15605                    "\n"
15606                    "int oneTwoThree = 123;",
15607                    Alignment));
15608 
15609   /* Test across comments */
15610   EXPECT_EQ("float const a = 5;\n"
15611             "/* block comment */\n"
15612             "int         oneTwoThree = 123;",
15613             format("float const a = 5;\n"
15614                    "/* block comment */\n"
15615                    "int oneTwoThree=123;",
15616                    Alignment));
15617 
15618   EXPECT_EQ("float const a = 5;\n"
15619             "// line comment\n"
15620             "int         oneTwoThree = 123;",
15621             format("float const a = 5;\n"
15622                    "// line comment\n"
15623                    "int oneTwoThree=123;",
15624                    Alignment));
15625 
15626   /* Test across comments and newlines */
15627   EXPECT_EQ("float const a = 5;\n"
15628             "\n"
15629             "/* block comment */\n"
15630             "int         oneTwoThree = 123;",
15631             format("float const a = 5;\n"
15632                    "\n"
15633                    "/* block comment */\n"
15634                    "int         oneTwoThree=123;",
15635                    Alignment));
15636 
15637   EXPECT_EQ("float const a = 5;\n"
15638             "\n"
15639             "// line comment\n"
15640             "int         oneTwoThree = 123;",
15641             format("float const a = 5;\n"
15642                    "\n"
15643                    "// line comment\n"
15644                    "int oneTwoThree=123;",
15645                    Alignment));
15646 }
15647 
15648 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
15649   FormatStyle Alignment = getLLVMStyle();
15650   Alignment.AlignConsecutiveBitFields =
15651       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15652 
15653   Alignment.MaxEmptyLinesToKeep = 10;
15654   /* Test alignment across empty lines */
15655   EXPECT_EQ("int a            : 5;\n"
15656             "\n"
15657             "int longbitfield : 6;",
15658             format("int a : 5;\n"
15659                    "\n"
15660                    "int longbitfield : 6;",
15661                    Alignment));
15662   EXPECT_EQ("int a            : 5;\n"
15663             "int one          : 1;\n"
15664             "\n"
15665             "int longbitfield : 6;",
15666             format("int a : 5;\n"
15667                    "int one : 1;\n"
15668                    "\n"
15669                    "int longbitfield : 6;",
15670                    Alignment));
15671 
15672   /* Test across comments */
15673   EXPECT_EQ("int a            : 5;\n"
15674             "/* block comment */\n"
15675             "int longbitfield : 6;",
15676             format("int a : 5;\n"
15677                    "/* block comment */\n"
15678                    "int longbitfield : 6;",
15679                    Alignment));
15680   EXPECT_EQ("int a            : 5;\n"
15681             "int one          : 1;\n"
15682             "// line comment\n"
15683             "int longbitfield : 6;",
15684             format("int a : 5;\n"
15685                    "int one : 1;\n"
15686                    "// line comment\n"
15687                    "int longbitfield : 6;",
15688                    Alignment));
15689 
15690   /* Test across comments and newlines */
15691   EXPECT_EQ("int a            : 5;\n"
15692             "/* block comment */\n"
15693             "\n"
15694             "int longbitfield : 6;",
15695             format("int a : 5;\n"
15696                    "/* block comment */\n"
15697                    "\n"
15698                    "int longbitfield : 6;",
15699                    Alignment));
15700   EXPECT_EQ("int a            : 5;\n"
15701             "int one          : 1;\n"
15702             "\n"
15703             "// line comment\n"
15704             "\n"
15705             "int longbitfield : 6;",
15706             format("int a : 5;\n"
15707                    "int one : 1;\n"
15708                    "\n"
15709                    "// line comment \n"
15710                    "\n"
15711                    "int longbitfield : 6;",
15712                    Alignment));
15713 }
15714 
15715 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
15716   FormatStyle Alignment = getLLVMStyle();
15717   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15718   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
15719 
15720   Alignment.MaxEmptyLinesToKeep = 10;
15721   /* Test alignment across empty lines */
15722   EXPECT_EQ("int a = 5;\n"
15723             "\n"
15724             "int oneTwoThree = 123;",
15725             format("int a       = 5;\n"
15726                    "\n"
15727                    "int oneTwoThree= 123;",
15728                    Alignment));
15729   EXPECT_EQ("int a   = 5;\n"
15730             "int one = 1;\n"
15731             "\n"
15732             "int oneTwoThree = 123;",
15733             format("int a = 5;\n"
15734                    "int one = 1;\n"
15735                    "\n"
15736                    "int oneTwoThree = 123;",
15737                    Alignment));
15738 
15739   /* Test across comments */
15740   EXPECT_EQ("int a           = 5;\n"
15741             "/* block comment */\n"
15742             "int oneTwoThree = 123;",
15743             format("int a = 5;\n"
15744                    "/* block comment */\n"
15745                    "int oneTwoThree=123;",
15746                    Alignment));
15747 
15748   EXPECT_EQ("int a           = 5;\n"
15749             "// line comment\n"
15750             "int oneTwoThree = 123;",
15751             format("int a = 5;\n"
15752                    "// line comment\n"
15753                    "int oneTwoThree=123;",
15754                    Alignment));
15755 
15756   EXPECT_EQ("int a           = 5;\n"
15757             "/*\n"
15758             " * multi-line block comment\n"
15759             " */\n"
15760             "int oneTwoThree = 123;",
15761             format("int a = 5;\n"
15762                    "/*\n"
15763                    " * multi-line block comment\n"
15764                    " */\n"
15765                    "int oneTwoThree=123;",
15766                    Alignment));
15767 
15768   EXPECT_EQ("int a           = 5;\n"
15769             "//\n"
15770             "// multi-line line comment\n"
15771             "//\n"
15772             "int oneTwoThree = 123;",
15773             format("int a = 5;\n"
15774                    "//\n"
15775                    "// multi-line line comment\n"
15776                    "//\n"
15777                    "int oneTwoThree=123;",
15778                    Alignment));
15779 
15780   /* Test across comments and newlines */
15781   EXPECT_EQ("int a = 5;\n"
15782             "\n"
15783             "/* block comment */\n"
15784             "int oneTwoThree = 123;",
15785             format("int a = 5;\n"
15786                    "\n"
15787                    "/* block comment */\n"
15788                    "int oneTwoThree=123;",
15789                    Alignment));
15790 
15791   EXPECT_EQ("int a = 5;\n"
15792             "\n"
15793             "// line comment\n"
15794             "int oneTwoThree = 123;",
15795             format("int a = 5;\n"
15796                    "\n"
15797                    "// line comment\n"
15798                    "int oneTwoThree=123;",
15799                    Alignment));
15800 }
15801 
15802 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
15803   FormatStyle Alignment = getLLVMStyle();
15804   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15805   Alignment.AlignConsecutiveAssignments =
15806       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15807   verifyFormat("int a           = 5;\n"
15808                "int oneTwoThree = 123;",
15809                Alignment);
15810   verifyFormat("int a           = method();\n"
15811                "int oneTwoThree = 133;",
15812                Alignment);
15813   verifyFormat("a &= 5;\n"
15814                "bcd *= 5;\n"
15815                "ghtyf += 5;\n"
15816                "dvfvdb -= 5;\n"
15817                "a /= 5;\n"
15818                "vdsvsv %= 5;\n"
15819                "sfdbddfbdfbb ^= 5;\n"
15820                "dvsdsv |= 5;\n"
15821                "int dsvvdvsdvvv = 123;",
15822                Alignment);
15823   verifyFormat("int i = 1, j = 10;\n"
15824                "something = 2000;",
15825                Alignment);
15826   verifyFormat("something = 2000;\n"
15827                "int i = 1, j = 10;\n",
15828                Alignment);
15829   verifyFormat("something = 2000;\n"
15830                "another   = 911;\n"
15831                "int i = 1, j = 10;\n"
15832                "oneMore = 1;\n"
15833                "i       = 2;",
15834                Alignment);
15835   verifyFormat("int a   = 5;\n"
15836                "int one = 1;\n"
15837                "method();\n"
15838                "int oneTwoThree = 123;\n"
15839                "int oneTwo      = 12;",
15840                Alignment);
15841   verifyFormat("int oneTwoThree = 123;\n"
15842                "int oneTwo      = 12;\n"
15843                "method();\n",
15844                Alignment);
15845   verifyFormat("int oneTwoThree = 123; // comment\n"
15846                "int oneTwo      = 12;  // comment",
15847                Alignment);
15848 
15849   // Bug 25167
15850   /* Uncomment when fixed
15851     verifyFormat("#if A\n"
15852                  "#else\n"
15853                  "int aaaaaaaa = 12;\n"
15854                  "#endif\n"
15855                  "#if B\n"
15856                  "#else\n"
15857                  "int a = 12;\n"
15858                  "#endif\n",
15859                  Alignment);
15860     verifyFormat("enum foo {\n"
15861                  "#if A\n"
15862                  "#else\n"
15863                  "  aaaaaaaa = 12;\n"
15864                  "#endif\n"
15865                  "#if B\n"
15866                  "#else\n"
15867                  "  a = 12;\n"
15868                  "#endif\n"
15869                  "};\n",
15870                  Alignment);
15871   */
15872 
15873   Alignment.MaxEmptyLinesToKeep = 10;
15874   /* Test alignment across empty lines */
15875   EXPECT_EQ("int a           = 5;\n"
15876             "\n"
15877             "int oneTwoThree = 123;",
15878             format("int a       = 5;\n"
15879                    "\n"
15880                    "int oneTwoThree= 123;",
15881                    Alignment));
15882   EXPECT_EQ("int a           = 5;\n"
15883             "int one         = 1;\n"
15884             "\n"
15885             "int oneTwoThree = 123;",
15886             format("int a = 5;\n"
15887                    "int one = 1;\n"
15888                    "\n"
15889                    "int oneTwoThree = 123;",
15890                    Alignment));
15891   EXPECT_EQ("int a           = 5;\n"
15892             "int one         = 1;\n"
15893             "\n"
15894             "int oneTwoThree = 123;\n"
15895             "int oneTwo      = 12;",
15896             format("int a = 5;\n"
15897                    "int one = 1;\n"
15898                    "\n"
15899                    "int oneTwoThree = 123;\n"
15900                    "int oneTwo = 12;",
15901                    Alignment));
15902 
15903   /* Test across comments */
15904   EXPECT_EQ("int a           = 5;\n"
15905             "/* block comment */\n"
15906             "int oneTwoThree = 123;",
15907             format("int a = 5;\n"
15908                    "/* block comment */\n"
15909                    "int oneTwoThree=123;",
15910                    Alignment));
15911 
15912   EXPECT_EQ("int a           = 5;\n"
15913             "// line comment\n"
15914             "int oneTwoThree = 123;",
15915             format("int a = 5;\n"
15916                    "// line comment\n"
15917                    "int oneTwoThree=123;",
15918                    Alignment));
15919 
15920   /* Test across comments and newlines */
15921   EXPECT_EQ("int a           = 5;\n"
15922             "\n"
15923             "/* block comment */\n"
15924             "int oneTwoThree = 123;",
15925             format("int a = 5;\n"
15926                    "\n"
15927                    "/* block comment */\n"
15928                    "int oneTwoThree=123;",
15929                    Alignment));
15930 
15931   EXPECT_EQ("int a           = 5;\n"
15932             "\n"
15933             "// line comment\n"
15934             "int oneTwoThree = 123;",
15935             format("int a = 5;\n"
15936                    "\n"
15937                    "// line comment\n"
15938                    "int oneTwoThree=123;",
15939                    Alignment));
15940 
15941   EXPECT_EQ("int a           = 5;\n"
15942             "//\n"
15943             "// multi-line line comment\n"
15944             "//\n"
15945             "int oneTwoThree = 123;",
15946             format("int a = 5;\n"
15947                    "//\n"
15948                    "// multi-line line comment\n"
15949                    "//\n"
15950                    "int oneTwoThree=123;",
15951                    Alignment));
15952 
15953   EXPECT_EQ("int a           = 5;\n"
15954             "/*\n"
15955             " *  multi-line block comment\n"
15956             " */\n"
15957             "int oneTwoThree = 123;",
15958             format("int a = 5;\n"
15959                    "/*\n"
15960                    " *  multi-line block comment\n"
15961                    " */\n"
15962                    "int oneTwoThree=123;",
15963                    Alignment));
15964 
15965   EXPECT_EQ("int a           = 5;\n"
15966             "\n"
15967             "/* block comment */\n"
15968             "\n"
15969             "\n"
15970             "\n"
15971             "int oneTwoThree = 123;",
15972             format("int a = 5;\n"
15973                    "\n"
15974                    "/* block comment */\n"
15975                    "\n"
15976                    "\n"
15977                    "\n"
15978                    "int oneTwoThree=123;",
15979                    Alignment));
15980 
15981   EXPECT_EQ("int a           = 5;\n"
15982             "\n"
15983             "// line comment\n"
15984             "\n"
15985             "\n"
15986             "\n"
15987             "int oneTwoThree = 123;",
15988             format("int a = 5;\n"
15989                    "\n"
15990                    "// line comment\n"
15991                    "\n"
15992                    "\n"
15993                    "\n"
15994                    "int oneTwoThree=123;",
15995                    Alignment));
15996 
15997   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
15998   verifyFormat("#define A \\\n"
15999                "  int aaaa       = 12; \\\n"
16000                "  int b          = 23; \\\n"
16001                "  int ccc        = 234; \\\n"
16002                "  int dddddddddd = 2345;",
16003                Alignment);
16004   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16005   verifyFormat("#define A               \\\n"
16006                "  int aaaa       = 12;  \\\n"
16007                "  int b          = 23;  \\\n"
16008                "  int ccc        = 234; \\\n"
16009                "  int dddddddddd = 2345;",
16010                Alignment);
16011   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16012   verifyFormat("#define A                                                      "
16013                "                \\\n"
16014                "  int aaaa       = 12;                                         "
16015                "                \\\n"
16016                "  int b          = 23;                                         "
16017                "                \\\n"
16018                "  int ccc        = 234;                                        "
16019                "                \\\n"
16020                "  int dddddddddd = 2345;",
16021                Alignment);
16022   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16023                "k = 4, int l = 5,\n"
16024                "                  int m = 6) {\n"
16025                "  int j      = 10;\n"
16026                "  otherThing = 1;\n"
16027                "}",
16028                Alignment);
16029   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16030                "  int i   = 1;\n"
16031                "  int j   = 2;\n"
16032                "  int big = 10000;\n"
16033                "}",
16034                Alignment);
16035   verifyFormat("class C {\n"
16036                "public:\n"
16037                "  int i            = 1;\n"
16038                "  virtual void f() = 0;\n"
16039                "};",
16040                Alignment);
16041   verifyFormat("int i = 1;\n"
16042                "if (SomeType t = getSomething()) {\n"
16043                "}\n"
16044                "int j   = 2;\n"
16045                "int big = 10000;",
16046                Alignment);
16047   verifyFormat("int j = 7;\n"
16048                "for (int k = 0; k < N; ++k) {\n"
16049                "}\n"
16050                "int j   = 2;\n"
16051                "int big = 10000;\n"
16052                "}",
16053                Alignment);
16054   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16055   verifyFormat("int i = 1;\n"
16056                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16057                "    = someLooooooooooooooooongFunction();\n"
16058                "int j = 2;",
16059                Alignment);
16060   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16061   verifyFormat("int i = 1;\n"
16062                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16063                "    someLooooooooooooooooongFunction();\n"
16064                "int j = 2;",
16065                Alignment);
16066 
16067   verifyFormat("auto lambda = []() {\n"
16068                "  auto i = 0;\n"
16069                "  return 0;\n"
16070                "};\n"
16071                "int i  = 0;\n"
16072                "auto v = type{\n"
16073                "    i = 1,   //\n"
16074                "    (i = 2), //\n"
16075                "    i = 3    //\n"
16076                "};",
16077                Alignment);
16078 
16079   verifyFormat(
16080       "int i      = 1;\n"
16081       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16082       "                          loooooooooooooooooooooongParameterB);\n"
16083       "int j      = 2;",
16084       Alignment);
16085 
16086   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16087                "          typename B   = very_long_type_name_1,\n"
16088                "          typename T_2 = very_long_type_name_2>\n"
16089                "auto foo() {}\n",
16090                Alignment);
16091   verifyFormat("int a, b = 1;\n"
16092                "int c  = 2;\n"
16093                "int dd = 3;\n",
16094                Alignment);
16095   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16096                "float b[1][] = {{3.f}};\n",
16097                Alignment);
16098   verifyFormat("for (int i = 0; i < 1; i++)\n"
16099                "  int x = 1;\n",
16100                Alignment);
16101   verifyFormat("for (i = 0; i < 1; i++)\n"
16102                "  x = 1;\n"
16103                "y = 1;\n",
16104                Alignment);
16105 
16106   Alignment.ReflowComments = true;
16107   Alignment.ColumnLimit = 50;
16108   EXPECT_EQ("int x   = 0;\n"
16109             "int yy  = 1; /// specificlennospace\n"
16110             "int zzz = 2;\n",
16111             format("int x   = 0;\n"
16112                    "int yy  = 1; ///specificlennospace\n"
16113                    "int zzz = 2;\n",
16114                    Alignment));
16115 }
16116 
16117 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16118   FormatStyle Alignment = getLLVMStyle();
16119   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16120   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16121   verifyFormat("int a = 5;\n"
16122                "int oneTwoThree = 123;",
16123                Alignment);
16124   verifyFormat("int a = 5;\n"
16125                "int oneTwoThree = 123;",
16126                Alignment);
16127 
16128   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16129   verifyFormat("int a           = 5;\n"
16130                "int oneTwoThree = 123;",
16131                Alignment);
16132   verifyFormat("int a           = method();\n"
16133                "int oneTwoThree = 133;",
16134                Alignment);
16135   verifyFormat("a &= 5;\n"
16136                "bcd *= 5;\n"
16137                "ghtyf += 5;\n"
16138                "dvfvdb -= 5;\n"
16139                "a /= 5;\n"
16140                "vdsvsv %= 5;\n"
16141                "sfdbddfbdfbb ^= 5;\n"
16142                "dvsdsv |= 5;\n"
16143                "int dsvvdvsdvvv = 123;",
16144                Alignment);
16145   verifyFormat("int i = 1, j = 10;\n"
16146                "something = 2000;",
16147                Alignment);
16148   verifyFormat("something = 2000;\n"
16149                "int i = 1, j = 10;\n",
16150                Alignment);
16151   verifyFormat("something = 2000;\n"
16152                "another   = 911;\n"
16153                "int i = 1, j = 10;\n"
16154                "oneMore = 1;\n"
16155                "i       = 2;",
16156                Alignment);
16157   verifyFormat("int a   = 5;\n"
16158                "int one = 1;\n"
16159                "method();\n"
16160                "int oneTwoThree = 123;\n"
16161                "int oneTwo      = 12;",
16162                Alignment);
16163   verifyFormat("int oneTwoThree = 123;\n"
16164                "int oneTwo      = 12;\n"
16165                "method();\n",
16166                Alignment);
16167   verifyFormat("int oneTwoThree = 123; // comment\n"
16168                "int oneTwo      = 12;  // comment",
16169                Alignment);
16170 
16171   // Bug 25167
16172   /* Uncomment when fixed
16173     verifyFormat("#if A\n"
16174                  "#else\n"
16175                  "int aaaaaaaa = 12;\n"
16176                  "#endif\n"
16177                  "#if B\n"
16178                  "#else\n"
16179                  "int a = 12;\n"
16180                  "#endif\n",
16181                  Alignment);
16182     verifyFormat("enum foo {\n"
16183                  "#if A\n"
16184                  "#else\n"
16185                  "  aaaaaaaa = 12;\n"
16186                  "#endif\n"
16187                  "#if B\n"
16188                  "#else\n"
16189                  "  a = 12;\n"
16190                  "#endif\n"
16191                  "};\n",
16192                  Alignment);
16193   */
16194 
16195   EXPECT_EQ("int a = 5;\n"
16196             "\n"
16197             "int oneTwoThree = 123;",
16198             format("int a       = 5;\n"
16199                    "\n"
16200                    "int oneTwoThree= 123;",
16201                    Alignment));
16202   EXPECT_EQ("int a   = 5;\n"
16203             "int one = 1;\n"
16204             "\n"
16205             "int oneTwoThree = 123;",
16206             format("int a = 5;\n"
16207                    "int one = 1;\n"
16208                    "\n"
16209                    "int oneTwoThree = 123;",
16210                    Alignment));
16211   EXPECT_EQ("int a   = 5;\n"
16212             "int one = 1;\n"
16213             "\n"
16214             "int oneTwoThree = 123;\n"
16215             "int oneTwo      = 12;",
16216             format("int a = 5;\n"
16217                    "int one = 1;\n"
16218                    "\n"
16219                    "int oneTwoThree = 123;\n"
16220                    "int oneTwo = 12;",
16221                    Alignment));
16222   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16223   verifyFormat("#define A \\\n"
16224                "  int aaaa       = 12; \\\n"
16225                "  int b          = 23; \\\n"
16226                "  int ccc        = 234; \\\n"
16227                "  int dddddddddd = 2345;",
16228                Alignment);
16229   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16230   verifyFormat("#define A               \\\n"
16231                "  int aaaa       = 12;  \\\n"
16232                "  int b          = 23;  \\\n"
16233                "  int ccc        = 234; \\\n"
16234                "  int dddddddddd = 2345;",
16235                Alignment);
16236   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16237   verifyFormat("#define A                                                      "
16238                "                \\\n"
16239                "  int aaaa       = 12;                                         "
16240                "                \\\n"
16241                "  int b          = 23;                                         "
16242                "                \\\n"
16243                "  int ccc        = 234;                                        "
16244                "                \\\n"
16245                "  int dddddddddd = 2345;",
16246                Alignment);
16247   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16248                "k = 4, int l = 5,\n"
16249                "                  int m = 6) {\n"
16250                "  int j      = 10;\n"
16251                "  otherThing = 1;\n"
16252                "}",
16253                Alignment);
16254   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16255                "  int i   = 1;\n"
16256                "  int j   = 2;\n"
16257                "  int big = 10000;\n"
16258                "}",
16259                Alignment);
16260   verifyFormat("class C {\n"
16261                "public:\n"
16262                "  int i            = 1;\n"
16263                "  virtual void f() = 0;\n"
16264                "};",
16265                Alignment);
16266   verifyFormat("int i = 1;\n"
16267                "if (SomeType t = getSomething()) {\n"
16268                "}\n"
16269                "int j   = 2;\n"
16270                "int big = 10000;",
16271                Alignment);
16272   verifyFormat("int j = 7;\n"
16273                "for (int k = 0; k < N; ++k) {\n"
16274                "}\n"
16275                "int j   = 2;\n"
16276                "int big = 10000;\n"
16277                "}",
16278                Alignment);
16279   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16280   verifyFormat("int i = 1;\n"
16281                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16282                "    = someLooooooooooooooooongFunction();\n"
16283                "int j = 2;",
16284                Alignment);
16285   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16286   verifyFormat("int i = 1;\n"
16287                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16288                "    someLooooooooooooooooongFunction();\n"
16289                "int j = 2;",
16290                Alignment);
16291 
16292   verifyFormat("auto lambda = []() {\n"
16293                "  auto i = 0;\n"
16294                "  return 0;\n"
16295                "};\n"
16296                "int i  = 0;\n"
16297                "auto v = type{\n"
16298                "    i = 1,   //\n"
16299                "    (i = 2), //\n"
16300                "    i = 3    //\n"
16301                "};",
16302                Alignment);
16303 
16304   verifyFormat(
16305       "int i      = 1;\n"
16306       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16307       "                          loooooooooooooooooooooongParameterB);\n"
16308       "int j      = 2;",
16309       Alignment);
16310 
16311   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16312                "          typename B   = very_long_type_name_1,\n"
16313                "          typename T_2 = very_long_type_name_2>\n"
16314                "auto foo() {}\n",
16315                Alignment);
16316   verifyFormat("int a, b = 1;\n"
16317                "int c  = 2;\n"
16318                "int dd = 3;\n",
16319                Alignment);
16320   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16321                "float b[1][] = {{3.f}};\n",
16322                Alignment);
16323   verifyFormat("for (int i = 0; i < 1; i++)\n"
16324                "  int x = 1;\n",
16325                Alignment);
16326   verifyFormat("for (i = 0; i < 1; i++)\n"
16327                "  x = 1;\n"
16328                "y = 1;\n",
16329                Alignment);
16330 
16331   Alignment.ReflowComments = true;
16332   Alignment.ColumnLimit = 50;
16333   EXPECT_EQ("int x   = 0;\n"
16334             "int yy  = 1; /// specificlennospace\n"
16335             "int zzz = 2;\n",
16336             format("int x   = 0;\n"
16337                    "int yy  = 1; ///specificlennospace\n"
16338                    "int zzz = 2;\n",
16339                    Alignment));
16340 }
16341 
16342 TEST_F(FormatTest, AlignConsecutiveBitFields) {
16343   FormatStyle Alignment = getLLVMStyle();
16344   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
16345   verifyFormat("int const a     : 5;\n"
16346                "int oneTwoThree : 23;",
16347                Alignment);
16348 
16349   // Initializers are allowed starting with c++2a
16350   verifyFormat("int const a     : 5 = 1;\n"
16351                "int oneTwoThree : 23 = 0;",
16352                Alignment);
16353 
16354   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16355   verifyFormat("int const a           : 5;\n"
16356                "int       oneTwoThree : 23;",
16357                Alignment);
16358 
16359   verifyFormat("int const a           : 5;  // comment\n"
16360                "int       oneTwoThree : 23; // comment",
16361                Alignment);
16362 
16363   verifyFormat("int const a           : 5 = 1;\n"
16364                "int       oneTwoThree : 23 = 0;",
16365                Alignment);
16366 
16367   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16368   verifyFormat("int const a           : 5  = 1;\n"
16369                "int       oneTwoThree : 23 = 0;",
16370                Alignment);
16371   verifyFormat("int const a           : 5  = {1};\n"
16372                "int       oneTwoThree : 23 = 0;",
16373                Alignment);
16374 
16375   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
16376   verifyFormat("int const a          :5;\n"
16377                "int       oneTwoThree:23;",
16378                Alignment);
16379 
16380   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
16381   verifyFormat("int const a           :5;\n"
16382                "int       oneTwoThree :23;",
16383                Alignment);
16384 
16385   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
16386   verifyFormat("int const a          : 5;\n"
16387                "int       oneTwoThree: 23;",
16388                Alignment);
16389 
16390   // Known limitations: ':' is only recognized as a bitfield colon when
16391   // followed by a number.
16392   /*
16393   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
16394                "int a           : 5;",
16395                Alignment);
16396   */
16397 }
16398 
16399 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
16400   FormatStyle Alignment = getLLVMStyle();
16401   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16402   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16403   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16404   verifyFormat("float const a = 5;\n"
16405                "int oneTwoThree = 123;",
16406                Alignment);
16407   verifyFormat("int a = 5;\n"
16408                "float const oneTwoThree = 123;",
16409                Alignment);
16410 
16411   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16412   verifyFormat("float const a = 5;\n"
16413                "int         oneTwoThree = 123;",
16414                Alignment);
16415   verifyFormat("int         a = method();\n"
16416                "float const oneTwoThree = 133;",
16417                Alignment);
16418   verifyFormat("int i = 1, j = 10;\n"
16419                "something = 2000;",
16420                Alignment);
16421   verifyFormat("something = 2000;\n"
16422                "int i = 1, j = 10;\n",
16423                Alignment);
16424   verifyFormat("float      something = 2000;\n"
16425                "double     another = 911;\n"
16426                "int        i = 1, j = 10;\n"
16427                "const int *oneMore = 1;\n"
16428                "unsigned   i = 2;",
16429                Alignment);
16430   verifyFormat("float a = 5;\n"
16431                "int   one = 1;\n"
16432                "method();\n"
16433                "const double       oneTwoThree = 123;\n"
16434                "const unsigned int oneTwo = 12;",
16435                Alignment);
16436   verifyFormat("int      oneTwoThree{0}; // comment\n"
16437                "unsigned oneTwo;         // comment",
16438                Alignment);
16439   verifyFormat("unsigned int       *a;\n"
16440                "int                *b;\n"
16441                "unsigned int Const *c;\n"
16442                "unsigned int const *d;\n"
16443                "unsigned int Const &e;\n"
16444                "unsigned int const &f;",
16445                Alignment);
16446   verifyFormat("Const unsigned int *c;\n"
16447                "const unsigned int *d;\n"
16448                "Const unsigned int &e;\n"
16449                "const unsigned int &f;\n"
16450                "const unsigned      g;\n"
16451                "Const unsigned      h;",
16452                Alignment);
16453   EXPECT_EQ("float const a = 5;\n"
16454             "\n"
16455             "int oneTwoThree = 123;",
16456             format("float const   a = 5;\n"
16457                    "\n"
16458                    "int           oneTwoThree= 123;",
16459                    Alignment));
16460   EXPECT_EQ("float a = 5;\n"
16461             "int   one = 1;\n"
16462             "\n"
16463             "unsigned oneTwoThree = 123;",
16464             format("float    a = 5;\n"
16465                    "int      one = 1;\n"
16466                    "\n"
16467                    "unsigned oneTwoThree = 123;",
16468                    Alignment));
16469   EXPECT_EQ("float a = 5;\n"
16470             "int   one = 1;\n"
16471             "\n"
16472             "unsigned oneTwoThree = 123;\n"
16473             "int      oneTwo = 12;",
16474             format("float    a = 5;\n"
16475                    "int one = 1;\n"
16476                    "\n"
16477                    "unsigned oneTwoThree = 123;\n"
16478                    "int oneTwo = 12;",
16479                    Alignment));
16480   // Function prototype alignment
16481   verifyFormat("int    a();\n"
16482                "double b();",
16483                Alignment);
16484   verifyFormat("int    a(int x);\n"
16485                "double b();",
16486                Alignment);
16487   unsigned OldColumnLimit = Alignment.ColumnLimit;
16488   // We need to set ColumnLimit to zero, in order to stress nested alignments,
16489   // otherwise the function parameters will be re-flowed onto a single line.
16490   Alignment.ColumnLimit = 0;
16491   EXPECT_EQ("int    a(int   x,\n"
16492             "         float y);\n"
16493             "double b(int    x,\n"
16494             "         double y);",
16495             format("int a(int x,\n"
16496                    " float y);\n"
16497                    "double b(int x,\n"
16498                    " double y);",
16499                    Alignment));
16500   // This ensures that function parameters of function declarations are
16501   // correctly indented when their owning functions are indented.
16502   // The failure case here is for 'double y' to not be indented enough.
16503   EXPECT_EQ("double a(int x);\n"
16504             "int    b(int    y,\n"
16505             "         double z);",
16506             format("double a(int x);\n"
16507                    "int b(int y,\n"
16508                    " double z);",
16509                    Alignment));
16510   // Set ColumnLimit low so that we induce wrapping immediately after
16511   // the function name and opening paren.
16512   Alignment.ColumnLimit = 13;
16513   verifyFormat("int function(\n"
16514                "    int  x,\n"
16515                "    bool y);",
16516                Alignment);
16517   Alignment.ColumnLimit = OldColumnLimit;
16518   // Ensure function pointers don't screw up recursive alignment
16519   verifyFormat("int    a(int x, void (*fp)(int y));\n"
16520                "double b();",
16521                Alignment);
16522   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16523   // Ensure recursive alignment is broken by function braces, so that the
16524   // "a = 1" does not align with subsequent assignments inside the function
16525   // body.
16526   verifyFormat("int func(int a = 1) {\n"
16527                "  int b  = 2;\n"
16528                "  int cc = 3;\n"
16529                "}",
16530                Alignment);
16531   verifyFormat("float      something = 2000;\n"
16532                "double     another   = 911;\n"
16533                "int        i = 1, j = 10;\n"
16534                "const int *oneMore = 1;\n"
16535                "unsigned   i       = 2;",
16536                Alignment);
16537   verifyFormat("int      oneTwoThree = {0}; // comment\n"
16538                "unsigned oneTwo      = 0;   // comment",
16539                Alignment);
16540   // Make sure that scope is correctly tracked, in the absence of braces
16541   verifyFormat("for (int i = 0; i < n; i++)\n"
16542                "  j = i;\n"
16543                "double x = 1;\n",
16544                Alignment);
16545   verifyFormat("if (int i = 0)\n"
16546                "  j = i;\n"
16547                "double x = 1;\n",
16548                Alignment);
16549   // Ensure operator[] and operator() are comprehended
16550   verifyFormat("struct test {\n"
16551                "  long long int foo();\n"
16552                "  int           operator[](int a);\n"
16553                "  double        bar();\n"
16554                "};\n",
16555                Alignment);
16556   verifyFormat("struct test {\n"
16557                "  long long int foo();\n"
16558                "  int           operator()(int a);\n"
16559                "  double        bar();\n"
16560                "};\n",
16561                Alignment);
16562   // http://llvm.org/PR52914
16563   verifyFormat("char *a[]     = {\"a\", // comment\n"
16564                "                 \"bb\"};\n"
16565                "int   bbbbbbb = 0;",
16566                Alignment);
16567 
16568   // PAS_Right
16569   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16570             "  int const i   = 1;\n"
16571             "  int      *j   = 2;\n"
16572             "  int       big = 10000;\n"
16573             "\n"
16574             "  unsigned oneTwoThree = 123;\n"
16575             "  int      oneTwo      = 12;\n"
16576             "  method();\n"
16577             "  float k  = 2;\n"
16578             "  int   ll = 10000;\n"
16579             "}",
16580             format("void SomeFunction(int parameter= 0) {\n"
16581                    " int const  i= 1;\n"
16582                    "  int *j=2;\n"
16583                    " int big  =  10000;\n"
16584                    "\n"
16585                    "unsigned oneTwoThree  =123;\n"
16586                    "int oneTwo = 12;\n"
16587                    "  method();\n"
16588                    "float k= 2;\n"
16589                    "int ll=10000;\n"
16590                    "}",
16591                    Alignment));
16592   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16593             "  int const i   = 1;\n"
16594             "  int     **j   = 2, ***k;\n"
16595             "  int      &k   = i;\n"
16596             "  int     &&l   = i + j;\n"
16597             "  int       big = 10000;\n"
16598             "\n"
16599             "  unsigned oneTwoThree = 123;\n"
16600             "  int      oneTwo      = 12;\n"
16601             "  method();\n"
16602             "  float k  = 2;\n"
16603             "  int   ll = 10000;\n"
16604             "}",
16605             format("void SomeFunction(int parameter= 0) {\n"
16606                    " int const  i= 1;\n"
16607                    "  int **j=2,***k;\n"
16608                    "int &k=i;\n"
16609                    "int &&l=i+j;\n"
16610                    " int big  =  10000;\n"
16611                    "\n"
16612                    "unsigned oneTwoThree  =123;\n"
16613                    "int oneTwo = 12;\n"
16614                    "  method();\n"
16615                    "float k= 2;\n"
16616                    "int ll=10000;\n"
16617                    "}",
16618                    Alignment));
16619   // variables are aligned at their name, pointers are at the right most
16620   // position
16621   verifyFormat("int   *a;\n"
16622                "int  **b;\n"
16623                "int ***c;\n"
16624                "int    foobar;\n",
16625                Alignment);
16626 
16627   // PAS_Left
16628   FormatStyle AlignmentLeft = Alignment;
16629   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
16630   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16631             "  int const i   = 1;\n"
16632             "  int*      j   = 2;\n"
16633             "  int       big = 10000;\n"
16634             "\n"
16635             "  unsigned oneTwoThree = 123;\n"
16636             "  int      oneTwo      = 12;\n"
16637             "  method();\n"
16638             "  float k  = 2;\n"
16639             "  int   ll = 10000;\n"
16640             "}",
16641             format("void SomeFunction(int parameter= 0) {\n"
16642                    " int const  i= 1;\n"
16643                    "  int *j=2;\n"
16644                    " int big  =  10000;\n"
16645                    "\n"
16646                    "unsigned oneTwoThree  =123;\n"
16647                    "int oneTwo = 12;\n"
16648                    "  method();\n"
16649                    "float k= 2;\n"
16650                    "int ll=10000;\n"
16651                    "}",
16652                    AlignmentLeft));
16653   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16654             "  int const i   = 1;\n"
16655             "  int**     j   = 2;\n"
16656             "  int&      k   = i;\n"
16657             "  int&&     l   = i + j;\n"
16658             "  int       big = 10000;\n"
16659             "\n"
16660             "  unsigned oneTwoThree = 123;\n"
16661             "  int      oneTwo      = 12;\n"
16662             "  method();\n"
16663             "  float k  = 2;\n"
16664             "  int   ll = 10000;\n"
16665             "}",
16666             format("void SomeFunction(int parameter= 0) {\n"
16667                    " int const  i= 1;\n"
16668                    "  int **j=2;\n"
16669                    "int &k=i;\n"
16670                    "int &&l=i+j;\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                    AlignmentLeft));
16680   // variables are aligned at their name, pointers are at the left most position
16681   verifyFormat("int*   a;\n"
16682                "int**  b;\n"
16683                "int*** c;\n"
16684                "int    foobar;\n",
16685                AlignmentLeft);
16686 
16687   // PAS_Middle
16688   FormatStyle AlignmentMiddle = Alignment;
16689   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
16690   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16691             "  int const i   = 1;\n"
16692             "  int *     j   = 2;\n"
16693             "  int       big = 10000;\n"
16694             "\n"
16695             "  unsigned oneTwoThree = 123;\n"
16696             "  int      oneTwo      = 12;\n"
16697             "  method();\n"
16698             "  float k  = 2;\n"
16699             "  int   ll = 10000;\n"
16700             "}",
16701             format("void SomeFunction(int parameter= 0) {\n"
16702                    " int const  i= 1;\n"
16703                    "  int *j=2;\n"
16704                    " int big  =  10000;\n"
16705                    "\n"
16706                    "unsigned oneTwoThree  =123;\n"
16707                    "int oneTwo = 12;\n"
16708                    "  method();\n"
16709                    "float k= 2;\n"
16710                    "int ll=10000;\n"
16711                    "}",
16712                    AlignmentMiddle));
16713   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16714             "  int const i   = 1;\n"
16715             "  int **    j   = 2, ***k;\n"
16716             "  int &     k   = i;\n"
16717             "  int &&    l   = i + j;\n"
16718             "  int       big = 10000;\n"
16719             "\n"
16720             "  unsigned oneTwoThree = 123;\n"
16721             "  int      oneTwo      = 12;\n"
16722             "  method();\n"
16723             "  float k  = 2;\n"
16724             "  int   ll = 10000;\n"
16725             "}",
16726             format("void SomeFunction(int parameter= 0) {\n"
16727                    " int const  i= 1;\n"
16728                    "  int **j=2,***k;\n"
16729                    "int &k=i;\n"
16730                    "int &&l=i+j;\n"
16731                    " int big  =  10000;\n"
16732                    "\n"
16733                    "unsigned oneTwoThree  =123;\n"
16734                    "int oneTwo = 12;\n"
16735                    "  method();\n"
16736                    "float k= 2;\n"
16737                    "int ll=10000;\n"
16738                    "}",
16739                    AlignmentMiddle));
16740   // variables are aligned at their name, pointers are in the middle
16741   verifyFormat("int *   a;\n"
16742                "int *   b;\n"
16743                "int *** c;\n"
16744                "int     foobar;\n",
16745                AlignmentMiddle);
16746 
16747   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16748   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16749   verifyFormat("#define A \\\n"
16750                "  int       aaaa = 12; \\\n"
16751                "  float     b = 23; \\\n"
16752                "  const int ccc = 234; \\\n"
16753                "  unsigned  dddddddddd = 2345;",
16754                Alignment);
16755   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16756   verifyFormat("#define A              \\\n"
16757                "  int       aaaa = 12; \\\n"
16758                "  float     b = 23;    \\\n"
16759                "  const int ccc = 234; \\\n"
16760                "  unsigned  dddddddddd = 2345;",
16761                Alignment);
16762   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16763   Alignment.ColumnLimit = 30;
16764   verifyFormat("#define A                    \\\n"
16765                "  int       aaaa = 12;       \\\n"
16766                "  float     b = 23;          \\\n"
16767                "  const int ccc = 234;       \\\n"
16768                "  int       dddddddddd = 2345;",
16769                Alignment);
16770   Alignment.ColumnLimit = 80;
16771   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16772                "k = 4, int l = 5,\n"
16773                "                  int m = 6) {\n"
16774                "  const int j = 10;\n"
16775                "  otherThing = 1;\n"
16776                "}",
16777                Alignment);
16778   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16779                "  int const i = 1;\n"
16780                "  int      *j = 2;\n"
16781                "  int       big = 10000;\n"
16782                "}",
16783                Alignment);
16784   verifyFormat("class C {\n"
16785                "public:\n"
16786                "  int          i = 1;\n"
16787                "  virtual void f() = 0;\n"
16788                "};",
16789                Alignment);
16790   verifyFormat("float i = 1;\n"
16791                "if (SomeType t = getSomething()) {\n"
16792                "}\n"
16793                "const unsigned j = 2;\n"
16794                "int            big = 10000;",
16795                Alignment);
16796   verifyFormat("float j = 7;\n"
16797                "for (int k = 0; k < N; ++k) {\n"
16798                "}\n"
16799                "unsigned j = 2;\n"
16800                "int      big = 10000;\n"
16801                "}",
16802                Alignment);
16803   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16804   verifyFormat("float              i = 1;\n"
16805                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16806                "    = someLooooooooooooooooongFunction();\n"
16807                "int j = 2;",
16808                Alignment);
16809   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16810   verifyFormat("int                i = 1;\n"
16811                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16812                "    someLooooooooooooooooongFunction();\n"
16813                "int j = 2;",
16814                Alignment);
16815 
16816   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16817   verifyFormat("auto lambda = []() {\n"
16818                "  auto  ii = 0;\n"
16819                "  float j  = 0;\n"
16820                "  return 0;\n"
16821                "};\n"
16822                "int   i  = 0;\n"
16823                "float i2 = 0;\n"
16824                "auto  v  = type{\n"
16825                "    i = 1,   //\n"
16826                "    (i = 2), //\n"
16827                "    i = 3    //\n"
16828                "};",
16829                Alignment);
16830   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16831 
16832   verifyFormat(
16833       "int      i = 1;\n"
16834       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16835       "                          loooooooooooooooooooooongParameterB);\n"
16836       "int      j = 2;",
16837       Alignment);
16838 
16839   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
16840   // We expect declarations and assignments to align, as long as it doesn't
16841   // exceed the column limit, starting a new alignment sequence whenever it
16842   // happens.
16843   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16844   Alignment.ColumnLimit = 30;
16845   verifyFormat("float    ii              = 1;\n"
16846                "unsigned j               = 2;\n"
16847                "int someVerylongVariable = 1;\n"
16848                "AnotherLongType  ll = 123456;\n"
16849                "VeryVeryLongType k  = 2;\n"
16850                "int              myvar = 1;",
16851                Alignment);
16852   Alignment.ColumnLimit = 80;
16853   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16854 
16855   verifyFormat(
16856       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
16857       "          typename LongType, typename B>\n"
16858       "auto foo() {}\n",
16859       Alignment);
16860   verifyFormat("float a, b = 1;\n"
16861                "int   c = 2;\n"
16862                "int   dd = 3;\n",
16863                Alignment);
16864   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
16865                "float b[1][] = {{3.f}};\n",
16866                Alignment);
16867   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16868   verifyFormat("float a, b = 1;\n"
16869                "int   c  = 2;\n"
16870                "int   dd = 3;\n",
16871                Alignment);
16872   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
16873                "float b[1][] = {{3.f}};\n",
16874                Alignment);
16875   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16876 
16877   Alignment.ColumnLimit = 30;
16878   Alignment.BinPackParameters = false;
16879   verifyFormat("void foo(float     a,\n"
16880                "         float     b,\n"
16881                "         int       c,\n"
16882                "         uint32_t *d) {\n"
16883                "  int   *e = 0;\n"
16884                "  float  f = 0;\n"
16885                "  double g = 0;\n"
16886                "}\n"
16887                "void bar(ino_t     a,\n"
16888                "         int       b,\n"
16889                "         uint32_t *c,\n"
16890                "         bool      d) {}\n",
16891                Alignment);
16892   Alignment.BinPackParameters = true;
16893   Alignment.ColumnLimit = 80;
16894 
16895   // Bug 33507
16896   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16897   verifyFormat(
16898       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
16899       "  static const Version verVs2017;\n"
16900       "  return true;\n"
16901       "});\n",
16902       Alignment);
16903   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16904 
16905   // See llvm.org/PR35641
16906   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16907   verifyFormat("int func() { //\n"
16908                "  int      b;\n"
16909                "  unsigned c;\n"
16910                "}",
16911                Alignment);
16912 
16913   // See PR37175
16914   FormatStyle Style = getMozillaStyle();
16915   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16916   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
16917             "foo(int a);",
16918             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
16919 
16920   Alignment.PointerAlignment = FormatStyle::PAS_Left;
16921   verifyFormat("unsigned int*       a;\n"
16922                "int*                b;\n"
16923                "unsigned int Const* c;\n"
16924                "unsigned int const* d;\n"
16925                "unsigned int Const& e;\n"
16926                "unsigned int const& f;",
16927                Alignment);
16928   verifyFormat("Const unsigned int* c;\n"
16929                "const unsigned int* d;\n"
16930                "Const unsigned int& e;\n"
16931                "const unsigned int& f;\n"
16932                "const unsigned      g;\n"
16933                "Const unsigned      h;",
16934                Alignment);
16935 
16936   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16937   verifyFormat("unsigned int *       a;\n"
16938                "int *                b;\n"
16939                "unsigned int Const * c;\n"
16940                "unsigned int const * d;\n"
16941                "unsigned int Const & e;\n"
16942                "unsigned int const & f;",
16943                Alignment);
16944   verifyFormat("Const unsigned int * c;\n"
16945                "const unsigned int * d;\n"
16946                "Const unsigned int & e;\n"
16947                "const unsigned int & f;\n"
16948                "const unsigned       g;\n"
16949                "Const unsigned       h;",
16950                Alignment);
16951 }
16952 
16953 TEST_F(FormatTest, AlignWithLineBreaks) {
16954   auto Style = getLLVMStyleWithColumns(120);
16955 
16956   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
16957   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16958   verifyFormat("void foo() {\n"
16959                "  int myVar = 5;\n"
16960                "  double x = 3.14;\n"
16961                "  auto str = \"Hello \"\n"
16962                "             \"World\";\n"
16963                "  auto s = \"Hello \"\n"
16964                "           \"Again\";\n"
16965                "}",
16966                Style);
16967 
16968   // clang-format off
16969   verifyFormat("void foo() {\n"
16970                "  const int capacityBefore = Entries.capacity();\n"
16971                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16972                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16973                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16974                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16975                "}",
16976                Style);
16977   // clang-format on
16978 
16979   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16980   verifyFormat("void foo() {\n"
16981                "  int myVar = 5;\n"
16982                "  double x  = 3.14;\n"
16983                "  auto str  = \"Hello \"\n"
16984                "              \"World\";\n"
16985                "  auto s    = \"Hello \"\n"
16986                "              \"Again\";\n"
16987                "}",
16988                Style);
16989 
16990   // clang-format off
16991   verifyFormat("void foo() {\n"
16992                "  const int capacityBefore = Entries.capacity();\n"
16993                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16994                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16995                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16996                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16997                "}",
16998                Style);
16999   // clang-format on
17000 
17001   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17002   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17003   verifyFormat("void foo() {\n"
17004                "  int    myVar = 5;\n"
17005                "  double x = 3.14;\n"
17006                "  auto   str = \"Hello \"\n"
17007                "               \"World\";\n"
17008                "  auto   s = \"Hello \"\n"
17009                "             \"Again\";\n"
17010                "}",
17011                Style);
17012 
17013   // clang-format off
17014   verifyFormat("void foo() {\n"
17015                "  const int  capacityBefore = Entries.capacity();\n"
17016                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17017                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17018                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17019                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17020                "}",
17021                Style);
17022   // clang-format on
17023 
17024   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17025   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17026 
17027   verifyFormat("void foo() {\n"
17028                "  int    myVar = 5;\n"
17029                "  double x     = 3.14;\n"
17030                "  auto   str   = \"Hello \"\n"
17031                "                 \"World\";\n"
17032                "  auto   s     = \"Hello \"\n"
17033                "                 \"Again\";\n"
17034                "}",
17035                Style);
17036 
17037   // clang-format off
17038   verifyFormat("void foo() {\n"
17039                "  const int  capacityBefore = Entries.capacity();\n"
17040                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17041                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17042                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17043                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17044                "}",
17045                Style);
17046   // clang-format on
17047 
17048   Style = getLLVMStyleWithColumns(120);
17049   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17050   Style.ContinuationIndentWidth = 4;
17051   Style.IndentWidth = 4;
17052 
17053   // clang-format off
17054   verifyFormat("void SomeFunc() {\n"
17055                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17056                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17057                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17058                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17059                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17060                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17061                "}",
17062                Style);
17063   // clang-format on
17064 
17065   Style.BinPackArguments = false;
17066 
17067   // clang-format off
17068   verifyFormat("void SomeFunc() {\n"
17069                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
17070                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17071                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
17072                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17073                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
17074                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17075                "}",
17076                Style);
17077   // clang-format on
17078 }
17079 
17080 TEST_F(FormatTest, AlignWithInitializerPeriods) {
17081   auto Style = getLLVMStyleWithColumns(60);
17082 
17083   verifyFormat("void foo1(void) {\n"
17084                "  BYTE p[1] = 1;\n"
17085                "  A B = {.one_foooooooooooooooo = 2,\n"
17086                "         .two_fooooooooooooo = 3,\n"
17087                "         .three_fooooooooooooo = 4};\n"
17088                "  BYTE payload = 2;\n"
17089                "}",
17090                Style);
17091 
17092   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17093   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
17094   verifyFormat("void foo2(void) {\n"
17095                "  BYTE p[1]    = 1;\n"
17096                "  A B          = {.one_foooooooooooooooo = 2,\n"
17097                "                  .two_fooooooooooooo    = 3,\n"
17098                "                  .three_fooooooooooooo  = 4};\n"
17099                "  BYTE payload = 2;\n"
17100                "}",
17101                Style);
17102 
17103   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17104   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17105   verifyFormat("void foo3(void) {\n"
17106                "  BYTE p[1] = 1;\n"
17107                "  A    B = {.one_foooooooooooooooo = 2,\n"
17108                "            .two_fooooooooooooo = 3,\n"
17109                "            .three_fooooooooooooo = 4};\n"
17110                "  BYTE payload = 2;\n"
17111                "}",
17112                Style);
17113 
17114   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17115   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17116   verifyFormat("void foo4(void) {\n"
17117                "  BYTE p[1]    = 1;\n"
17118                "  A    B       = {.one_foooooooooooooooo = 2,\n"
17119                "                  .two_fooooooooooooo    = 3,\n"
17120                "                  .three_fooooooooooooo  = 4};\n"
17121                "  BYTE payload = 2;\n"
17122                "}",
17123                Style);
17124 }
17125 
17126 TEST_F(FormatTest, LinuxBraceBreaking) {
17127   FormatStyle LinuxBraceStyle = getLLVMStyle();
17128   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
17129   verifyFormat("namespace a\n"
17130                "{\n"
17131                "class A\n"
17132                "{\n"
17133                "  void f()\n"
17134                "  {\n"
17135                "    if (true) {\n"
17136                "      a();\n"
17137                "      b();\n"
17138                "    } else {\n"
17139                "      a();\n"
17140                "    }\n"
17141                "  }\n"
17142                "  void g() { return; }\n"
17143                "};\n"
17144                "struct B {\n"
17145                "  int x;\n"
17146                "};\n"
17147                "} // namespace a\n",
17148                LinuxBraceStyle);
17149   verifyFormat("enum X {\n"
17150                "  Y = 0,\n"
17151                "}\n",
17152                LinuxBraceStyle);
17153   verifyFormat("struct S {\n"
17154                "  int Type;\n"
17155                "  union {\n"
17156                "    int x;\n"
17157                "    double y;\n"
17158                "  } Value;\n"
17159                "  class C\n"
17160                "  {\n"
17161                "    MyFavoriteType Value;\n"
17162                "  } Class;\n"
17163                "}\n",
17164                LinuxBraceStyle);
17165 }
17166 
17167 TEST_F(FormatTest, MozillaBraceBreaking) {
17168   FormatStyle MozillaBraceStyle = getLLVMStyle();
17169   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
17170   MozillaBraceStyle.FixNamespaceComments = false;
17171   verifyFormat("namespace a {\n"
17172                "class A\n"
17173                "{\n"
17174                "  void f()\n"
17175                "  {\n"
17176                "    if (true) {\n"
17177                "      a();\n"
17178                "      b();\n"
17179                "    }\n"
17180                "  }\n"
17181                "  void g() { return; }\n"
17182                "};\n"
17183                "enum E\n"
17184                "{\n"
17185                "  A,\n"
17186                "  // foo\n"
17187                "  B,\n"
17188                "  C\n"
17189                "};\n"
17190                "struct B\n"
17191                "{\n"
17192                "  int x;\n"
17193                "};\n"
17194                "}\n",
17195                MozillaBraceStyle);
17196   verifyFormat("struct S\n"
17197                "{\n"
17198                "  int Type;\n"
17199                "  union\n"
17200                "  {\n"
17201                "    int x;\n"
17202                "    double y;\n"
17203                "  } Value;\n"
17204                "  class C\n"
17205                "  {\n"
17206                "    MyFavoriteType Value;\n"
17207                "  } Class;\n"
17208                "}\n",
17209                MozillaBraceStyle);
17210 }
17211 
17212 TEST_F(FormatTest, StroustrupBraceBreaking) {
17213   FormatStyle StroustrupBraceStyle = getLLVMStyle();
17214   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
17215   verifyFormat("namespace a {\n"
17216                "class A {\n"
17217                "  void f()\n"
17218                "  {\n"
17219                "    if (true) {\n"
17220                "      a();\n"
17221                "      b();\n"
17222                "    }\n"
17223                "  }\n"
17224                "  void g() { return; }\n"
17225                "};\n"
17226                "struct B {\n"
17227                "  int x;\n"
17228                "};\n"
17229                "} // namespace a\n",
17230                StroustrupBraceStyle);
17231 
17232   verifyFormat("void foo()\n"
17233                "{\n"
17234                "  if (a) {\n"
17235                "    a();\n"
17236                "  }\n"
17237                "  else {\n"
17238                "    b();\n"
17239                "  }\n"
17240                "}\n",
17241                StroustrupBraceStyle);
17242 
17243   verifyFormat("#ifdef _DEBUG\n"
17244                "int foo(int i = 0)\n"
17245                "#else\n"
17246                "int foo(int i = 5)\n"
17247                "#endif\n"
17248                "{\n"
17249                "  return i;\n"
17250                "}",
17251                StroustrupBraceStyle);
17252 
17253   verifyFormat("void foo() {}\n"
17254                "void bar()\n"
17255                "#ifdef _DEBUG\n"
17256                "{\n"
17257                "  foo();\n"
17258                "}\n"
17259                "#else\n"
17260                "{\n"
17261                "}\n"
17262                "#endif",
17263                StroustrupBraceStyle);
17264 
17265   verifyFormat("void foobar() { int i = 5; }\n"
17266                "#ifdef _DEBUG\n"
17267                "void bar() {}\n"
17268                "#else\n"
17269                "void bar() { foobar(); }\n"
17270                "#endif",
17271                StroustrupBraceStyle);
17272 }
17273 
17274 TEST_F(FormatTest, AllmanBraceBreaking) {
17275   FormatStyle AllmanBraceStyle = getLLVMStyle();
17276   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
17277 
17278   EXPECT_EQ("namespace a\n"
17279             "{\n"
17280             "void f();\n"
17281             "void g();\n"
17282             "} // namespace a\n",
17283             format("namespace a\n"
17284                    "{\n"
17285                    "void f();\n"
17286                    "void g();\n"
17287                    "}\n",
17288                    AllmanBraceStyle));
17289 
17290   verifyFormat("namespace a\n"
17291                "{\n"
17292                "class A\n"
17293                "{\n"
17294                "  void f()\n"
17295                "  {\n"
17296                "    if (true)\n"
17297                "    {\n"
17298                "      a();\n"
17299                "      b();\n"
17300                "    }\n"
17301                "  }\n"
17302                "  void g() { return; }\n"
17303                "};\n"
17304                "struct B\n"
17305                "{\n"
17306                "  int x;\n"
17307                "};\n"
17308                "union C\n"
17309                "{\n"
17310                "};\n"
17311                "} // namespace a",
17312                AllmanBraceStyle);
17313 
17314   verifyFormat("void f()\n"
17315                "{\n"
17316                "  if (true)\n"
17317                "  {\n"
17318                "    a();\n"
17319                "  }\n"
17320                "  else if (false)\n"
17321                "  {\n"
17322                "    b();\n"
17323                "  }\n"
17324                "  else\n"
17325                "  {\n"
17326                "    c();\n"
17327                "  }\n"
17328                "}\n",
17329                AllmanBraceStyle);
17330 
17331   verifyFormat("void f()\n"
17332                "{\n"
17333                "  for (int i = 0; i < 10; ++i)\n"
17334                "  {\n"
17335                "    a();\n"
17336                "  }\n"
17337                "  while (false)\n"
17338                "  {\n"
17339                "    b();\n"
17340                "  }\n"
17341                "  do\n"
17342                "  {\n"
17343                "    c();\n"
17344                "  } while (false)\n"
17345                "}\n",
17346                AllmanBraceStyle);
17347 
17348   verifyFormat("void f(int a)\n"
17349                "{\n"
17350                "  switch (a)\n"
17351                "  {\n"
17352                "  case 0:\n"
17353                "    break;\n"
17354                "  case 1:\n"
17355                "  {\n"
17356                "    break;\n"
17357                "  }\n"
17358                "  case 2:\n"
17359                "  {\n"
17360                "  }\n"
17361                "  break;\n"
17362                "  default:\n"
17363                "    break;\n"
17364                "  }\n"
17365                "}\n",
17366                AllmanBraceStyle);
17367 
17368   verifyFormat("enum X\n"
17369                "{\n"
17370                "  Y = 0,\n"
17371                "}\n",
17372                AllmanBraceStyle);
17373   verifyFormat("enum X\n"
17374                "{\n"
17375                "  Y = 0\n"
17376                "}\n",
17377                AllmanBraceStyle);
17378 
17379   verifyFormat("@interface BSApplicationController ()\n"
17380                "{\n"
17381                "@private\n"
17382                "  id _extraIvar;\n"
17383                "}\n"
17384                "@end\n",
17385                AllmanBraceStyle);
17386 
17387   verifyFormat("#ifdef _DEBUG\n"
17388                "int foo(int i = 0)\n"
17389                "#else\n"
17390                "int foo(int i = 5)\n"
17391                "#endif\n"
17392                "{\n"
17393                "  return i;\n"
17394                "}",
17395                AllmanBraceStyle);
17396 
17397   verifyFormat("void foo() {}\n"
17398                "void bar()\n"
17399                "#ifdef _DEBUG\n"
17400                "{\n"
17401                "  foo();\n"
17402                "}\n"
17403                "#else\n"
17404                "{\n"
17405                "}\n"
17406                "#endif",
17407                AllmanBraceStyle);
17408 
17409   verifyFormat("void foobar() { int i = 5; }\n"
17410                "#ifdef _DEBUG\n"
17411                "void bar() {}\n"
17412                "#else\n"
17413                "void bar() { foobar(); }\n"
17414                "#endif",
17415                AllmanBraceStyle);
17416 
17417   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
17418             FormatStyle::SLS_All);
17419 
17420   verifyFormat("[](int i) { return i + 2; };\n"
17421                "[](int i, int j)\n"
17422                "{\n"
17423                "  auto x = i + j;\n"
17424                "  auto y = i * j;\n"
17425                "  return x ^ y;\n"
17426                "};\n"
17427                "void foo()\n"
17428                "{\n"
17429                "  auto shortLambda = [](int i) { return i + 2; };\n"
17430                "  auto longLambda = [](int i, int j)\n"
17431                "  {\n"
17432                "    auto x = i + j;\n"
17433                "    auto y = i * j;\n"
17434                "    return x ^ y;\n"
17435                "  };\n"
17436                "}",
17437                AllmanBraceStyle);
17438 
17439   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17440 
17441   verifyFormat("[](int i)\n"
17442                "{\n"
17443                "  return i + 2;\n"
17444                "};\n"
17445                "[](int i, int j)\n"
17446                "{\n"
17447                "  auto x = i + j;\n"
17448                "  auto y = i * j;\n"
17449                "  return x ^ y;\n"
17450                "};\n"
17451                "void foo()\n"
17452                "{\n"
17453                "  auto shortLambda = [](int i)\n"
17454                "  {\n"
17455                "    return i + 2;\n"
17456                "  };\n"
17457                "  auto longLambda = [](int i, int j)\n"
17458                "  {\n"
17459                "    auto x = i + j;\n"
17460                "    auto y = i * j;\n"
17461                "    return x ^ y;\n"
17462                "  };\n"
17463                "}",
17464                AllmanBraceStyle);
17465 
17466   // Reset
17467   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
17468 
17469   // This shouldn't affect ObjC blocks..
17470   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
17471                "  // ...\n"
17472                "  int i;\n"
17473                "}];",
17474                AllmanBraceStyle);
17475   verifyFormat("void (^block)(void) = ^{\n"
17476                "  // ...\n"
17477                "  int i;\n"
17478                "};",
17479                AllmanBraceStyle);
17480   // .. or dict literals.
17481   verifyFormat("void f()\n"
17482                "{\n"
17483                "  // ...\n"
17484                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
17485                "}",
17486                AllmanBraceStyle);
17487   verifyFormat("void f()\n"
17488                "{\n"
17489                "  // ...\n"
17490                "  [object someMethod:@{a : @\"b\"}];\n"
17491                "}",
17492                AllmanBraceStyle);
17493   verifyFormat("int f()\n"
17494                "{ // comment\n"
17495                "  return 42;\n"
17496                "}",
17497                AllmanBraceStyle);
17498 
17499   AllmanBraceStyle.ColumnLimit = 19;
17500   verifyFormat("void f() { int i; }", AllmanBraceStyle);
17501   AllmanBraceStyle.ColumnLimit = 18;
17502   verifyFormat("void f()\n"
17503                "{\n"
17504                "  int i;\n"
17505                "}",
17506                AllmanBraceStyle);
17507   AllmanBraceStyle.ColumnLimit = 80;
17508 
17509   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
17510   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
17511       FormatStyle::SIS_WithoutElse;
17512   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
17513   verifyFormat("void f(bool b)\n"
17514                "{\n"
17515                "  if (b)\n"
17516                "  {\n"
17517                "    return;\n"
17518                "  }\n"
17519                "}\n",
17520                BreakBeforeBraceShortIfs);
17521   verifyFormat("void f(bool b)\n"
17522                "{\n"
17523                "  if constexpr (b)\n"
17524                "  {\n"
17525                "    return;\n"
17526                "  }\n"
17527                "}\n",
17528                BreakBeforeBraceShortIfs);
17529   verifyFormat("void f(bool b)\n"
17530                "{\n"
17531                "  if CONSTEXPR (b)\n"
17532                "  {\n"
17533                "    return;\n"
17534                "  }\n"
17535                "}\n",
17536                BreakBeforeBraceShortIfs);
17537   verifyFormat("void f(bool b)\n"
17538                "{\n"
17539                "  if (b) return;\n"
17540                "}\n",
17541                BreakBeforeBraceShortIfs);
17542   verifyFormat("void f(bool b)\n"
17543                "{\n"
17544                "  if constexpr (b) return;\n"
17545                "}\n",
17546                BreakBeforeBraceShortIfs);
17547   verifyFormat("void f(bool b)\n"
17548                "{\n"
17549                "  if CONSTEXPR (b) return;\n"
17550                "}\n",
17551                BreakBeforeBraceShortIfs);
17552   verifyFormat("void f(bool b)\n"
17553                "{\n"
17554                "  while (b)\n"
17555                "  {\n"
17556                "    return;\n"
17557                "  }\n"
17558                "}\n",
17559                BreakBeforeBraceShortIfs);
17560 }
17561 
17562 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
17563   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
17564   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
17565 
17566   // Make a few changes to the style for testing purposes
17567   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
17568       FormatStyle::SFS_Empty;
17569   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17570 
17571   // FIXME: this test case can't decide whether there should be a blank line
17572   // after the ~D() line or not. It adds one if one doesn't exist in the test
17573   // and it removes the line if one exists.
17574   /*
17575   verifyFormat("class A;\n"
17576                "namespace B\n"
17577                "  {\n"
17578                "class C;\n"
17579                "// Comment\n"
17580                "class D\n"
17581                "  {\n"
17582                "public:\n"
17583                "  D();\n"
17584                "  ~D() {}\n"
17585                "private:\n"
17586                "  enum E\n"
17587                "    {\n"
17588                "    F\n"
17589                "    }\n"
17590                "  };\n"
17591                "  } // namespace B\n",
17592                WhitesmithsBraceStyle);
17593   */
17594 
17595   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
17596   verifyFormat("namespace a\n"
17597                "  {\n"
17598                "class A\n"
17599                "  {\n"
17600                "  void f()\n"
17601                "    {\n"
17602                "    if (true)\n"
17603                "      {\n"
17604                "      a();\n"
17605                "      b();\n"
17606                "      }\n"
17607                "    }\n"
17608                "  void g()\n"
17609                "    {\n"
17610                "    return;\n"
17611                "    }\n"
17612                "  };\n"
17613                "struct B\n"
17614                "  {\n"
17615                "  int x;\n"
17616                "  };\n"
17617                "  } // namespace a",
17618                WhitesmithsBraceStyle);
17619 
17620   verifyFormat("namespace a\n"
17621                "  {\n"
17622                "namespace b\n"
17623                "  {\n"
17624                "class A\n"
17625                "  {\n"
17626                "  void f()\n"
17627                "    {\n"
17628                "    if (true)\n"
17629                "      {\n"
17630                "      a();\n"
17631                "      b();\n"
17632                "      }\n"
17633                "    }\n"
17634                "  void g()\n"
17635                "    {\n"
17636                "    return;\n"
17637                "    }\n"
17638                "  };\n"
17639                "struct B\n"
17640                "  {\n"
17641                "  int x;\n"
17642                "  };\n"
17643                "  } // namespace b\n"
17644                "  } // namespace a",
17645                WhitesmithsBraceStyle);
17646 
17647   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
17648   verifyFormat("namespace a\n"
17649                "  {\n"
17650                "namespace b\n"
17651                "  {\n"
17652                "  class A\n"
17653                "    {\n"
17654                "    void f()\n"
17655                "      {\n"
17656                "      if (true)\n"
17657                "        {\n"
17658                "        a();\n"
17659                "        b();\n"
17660                "        }\n"
17661                "      }\n"
17662                "    void g()\n"
17663                "      {\n"
17664                "      return;\n"
17665                "      }\n"
17666                "    };\n"
17667                "  struct B\n"
17668                "    {\n"
17669                "    int x;\n"
17670                "    };\n"
17671                "  } // namespace b\n"
17672                "  } // namespace a",
17673                WhitesmithsBraceStyle);
17674 
17675   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
17676   verifyFormat("namespace a\n"
17677                "  {\n"
17678                "  namespace b\n"
17679                "    {\n"
17680                "    class A\n"
17681                "      {\n"
17682                "      void f()\n"
17683                "        {\n"
17684                "        if (true)\n"
17685                "          {\n"
17686                "          a();\n"
17687                "          b();\n"
17688                "          }\n"
17689                "        }\n"
17690                "      void g()\n"
17691                "        {\n"
17692                "        return;\n"
17693                "        }\n"
17694                "      };\n"
17695                "    struct B\n"
17696                "      {\n"
17697                "      int x;\n"
17698                "      };\n"
17699                "    } // namespace b\n"
17700                "  }   // namespace a",
17701                WhitesmithsBraceStyle);
17702 
17703   verifyFormat("void f()\n"
17704                "  {\n"
17705                "  if (true)\n"
17706                "    {\n"
17707                "    a();\n"
17708                "    }\n"
17709                "  else if (false)\n"
17710                "    {\n"
17711                "    b();\n"
17712                "    }\n"
17713                "  else\n"
17714                "    {\n"
17715                "    c();\n"
17716                "    }\n"
17717                "  }\n",
17718                WhitesmithsBraceStyle);
17719 
17720   verifyFormat("void f()\n"
17721                "  {\n"
17722                "  for (int i = 0; i < 10; ++i)\n"
17723                "    {\n"
17724                "    a();\n"
17725                "    }\n"
17726                "  while (false)\n"
17727                "    {\n"
17728                "    b();\n"
17729                "    }\n"
17730                "  do\n"
17731                "    {\n"
17732                "    c();\n"
17733                "    } while (false)\n"
17734                "  }\n",
17735                WhitesmithsBraceStyle);
17736 
17737   WhitesmithsBraceStyle.IndentCaseLabels = true;
17738   verifyFormat("void switchTest1(int a)\n"
17739                "  {\n"
17740                "  switch (a)\n"
17741                "    {\n"
17742                "    case 2:\n"
17743                "      {\n"
17744                "      }\n"
17745                "      break;\n"
17746                "    }\n"
17747                "  }\n",
17748                WhitesmithsBraceStyle);
17749 
17750   verifyFormat("void switchTest2(int a)\n"
17751                "  {\n"
17752                "  switch (a)\n"
17753                "    {\n"
17754                "    case 0:\n"
17755                "      break;\n"
17756                "    case 1:\n"
17757                "      {\n"
17758                "      break;\n"
17759                "      }\n"
17760                "    case 2:\n"
17761                "      {\n"
17762                "      }\n"
17763                "      break;\n"
17764                "    default:\n"
17765                "      break;\n"
17766                "    }\n"
17767                "  }\n",
17768                WhitesmithsBraceStyle);
17769 
17770   verifyFormat("void switchTest3(int a)\n"
17771                "  {\n"
17772                "  switch (a)\n"
17773                "    {\n"
17774                "    case 0:\n"
17775                "      {\n"
17776                "      foo(x);\n"
17777                "      }\n"
17778                "      break;\n"
17779                "    default:\n"
17780                "      {\n"
17781                "      foo(1);\n"
17782                "      }\n"
17783                "      break;\n"
17784                "    }\n"
17785                "  }\n",
17786                WhitesmithsBraceStyle);
17787 
17788   WhitesmithsBraceStyle.IndentCaseLabels = false;
17789 
17790   verifyFormat("void switchTest4(int a)\n"
17791                "  {\n"
17792                "  switch (a)\n"
17793                "    {\n"
17794                "  case 2:\n"
17795                "    {\n"
17796                "    }\n"
17797                "    break;\n"
17798                "    }\n"
17799                "  }\n",
17800                WhitesmithsBraceStyle);
17801 
17802   verifyFormat("void switchTest5(int a)\n"
17803                "  {\n"
17804                "  switch (a)\n"
17805                "    {\n"
17806                "  case 0:\n"
17807                "    break;\n"
17808                "  case 1:\n"
17809                "    {\n"
17810                "    foo();\n"
17811                "    break;\n"
17812                "    }\n"
17813                "  case 2:\n"
17814                "    {\n"
17815                "    }\n"
17816                "    break;\n"
17817                "  default:\n"
17818                "    break;\n"
17819                "    }\n"
17820                "  }\n",
17821                WhitesmithsBraceStyle);
17822 
17823   verifyFormat("void switchTest6(int a)\n"
17824                "  {\n"
17825                "  switch (a)\n"
17826                "    {\n"
17827                "  case 0:\n"
17828                "    {\n"
17829                "    foo(x);\n"
17830                "    }\n"
17831                "    break;\n"
17832                "  default:\n"
17833                "    {\n"
17834                "    foo(1);\n"
17835                "    }\n"
17836                "    break;\n"
17837                "    }\n"
17838                "  }\n",
17839                WhitesmithsBraceStyle);
17840 
17841   verifyFormat("enum X\n"
17842                "  {\n"
17843                "  Y = 0, // testing\n"
17844                "  }\n",
17845                WhitesmithsBraceStyle);
17846 
17847   verifyFormat("enum X\n"
17848                "  {\n"
17849                "  Y = 0\n"
17850                "  }\n",
17851                WhitesmithsBraceStyle);
17852   verifyFormat("enum X\n"
17853                "  {\n"
17854                "  Y = 0,\n"
17855                "  Z = 1\n"
17856                "  };\n",
17857                WhitesmithsBraceStyle);
17858 
17859   verifyFormat("@interface BSApplicationController ()\n"
17860                "  {\n"
17861                "@private\n"
17862                "  id _extraIvar;\n"
17863                "  }\n"
17864                "@end\n",
17865                WhitesmithsBraceStyle);
17866 
17867   verifyFormat("#ifdef _DEBUG\n"
17868                "int foo(int i = 0)\n"
17869                "#else\n"
17870                "int foo(int i = 5)\n"
17871                "#endif\n"
17872                "  {\n"
17873                "  return i;\n"
17874                "  }",
17875                WhitesmithsBraceStyle);
17876 
17877   verifyFormat("void foo() {}\n"
17878                "void bar()\n"
17879                "#ifdef _DEBUG\n"
17880                "  {\n"
17881                "  foo();\n"
17882                "  }\n"
17883                "#else\n"
17884                "  {\n"
17885                "  }\n"
17886                "#endif",
17887                WhitesmithsBraceStyle);
17888 
17889   verifyFormat("void foobar()\n"
17890                "  {\n"
17891                "  int i = 5;\n"
17892                "  }\n"
17893                "#ifdef _DEBUG\n"
17894                "void bar()\n"
17895                "  {\n"
17896                "  }\n"
17897                "#else\n"
17898                "void bar()\n"
17899                "  {\n"
17900                "  foobar();\n"
17901                "  }\n"
17902                "#endif",
17903                WhitesmithsBraceStyle);
17904 
17905   // This shouldn't affect ObjC blocks..
17906   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
17907                "  // ...\n"
17908                "  int i;\n"
17909                "}];",
17910                WhitesmithsBraceStyle);
17911   verifyFormat("void (^block)(void) = ^{\n"
17912                "  // ...\n"
17913                "  int i;\n"
17914                "};",
17915                WhitesmithsBraceStyle);
17916   // .. or dict literals.
17917   verifyFormat("void f()\n"
17918                "  {\n"
17919                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
17920                "  }",
17921                WhitesmithsBraceStyle);
17922 
17923   verifyFormat("int f()\n"
17924                "  { // comment\n"
17925                "  return 42;\n"
17926                "  }",
17927                WhitesmithsBraceStyle);
17928 
17929   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
17930   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
17931       FormatStyle::SIS_OnlyFirstIf;
17932   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
17933   verifyFormat("void f(bool b)\n"
17934                "  {\n"
17935                "  if (b)\n"
17936                "    {\n"
17937                "    return;\n"
17938                "    }\n"
17939                "  }\n",
17940                BreakBeforeBraceShortIfs);
17941   verifyFormat("void f(bool b)\n"
17942                "  {\n"
17943                "  if (b) return;\n"
17944                "  }\n",
17945                BreakBeforeBraceShortIfs);
17946   verifyFormat("void f(bool b)\n"
17947                "  {\n"
17948                "  while (b)\n"
17949                "    {\n"
17950                "    return;\n"
17951                "    }\n"
17952                "  }\n",
17953                BreakBeforeBraceShortIfs);
17954 }
17955 
17956 TEST_F(FormatTest, GNUBraceBreaking) {
17957   FormatStyle GNUBraceStyle = getLLVMStyle();
17958   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
17959   verifyFormat("namespace a\n"
17960                "{\n"
17961                "class A\n"
17962                "{\n"
17963                "  void f()\n"
17964                "  {\n"
17965                "    int a;\n"
17966                "    {\n"
17967                "      int b;\n"
17968                "    }\n"
17969                "    if (true)\n"
17970                "      {\n"
17971                "        a();\n"
17972                "        b();\n"
17973                "      }\n"
17974                "  }\n"
17975                "  void g() { return; }\n"
17976                "}\n"
17977                "} // namespace a",
17978                GNUBraceStyle);
17979 
17980   verifyFormat("void f()\n"
17981                "{\n"
17982                "  if (true)\n"
17983                "    {\n"
17984                "      a();\n"
17985                "    }\n"
17986                "  else if (false)\n"
17987                "    {\n"
17988                "      b();\n"
17989                "    }\n"
17990                "  else\n"
17991                "    {\n"
17992                "      c();\n"
17993                "    }\n"
17994                "}\n",
17995                GNUBraceStyle);
17996 
17997   verifyFormat("void f()\n"
17998                "{\n"
17999                "  for (int i = 0; i < 10; ++i)\n"
18000                "    {\n"
18001                "      a();\n"
18002                "    }\n"
18003                "  while (false)\n"
18004                "    {\n"
18005                "      b();\n"
18006                "    }\n"
18007                "  do\n"
18008                "    {\n"
18009                "      c();\n"
18010                "    }\n"
18011                "  while (false);\n"
18012                "}\n",
18013                GNUBraceStyle);
18014 
18015   verifyFormat("void f(int a)\n"
18016                "{\n"
18017                "  switch (a)\n"
18018                "    {\n"
18019                "    case 0:\n"
18020                "      break;\n"
18021                "    case 1:\n"
18022                "      {\n"
18023                "        break;\n"
18024                "      }\n"
18025                "    case 2:\n"
18026                "      {\n"
18027                "      }\n"
18028                "      break;\n"
18029                "    default:\n"
18030                "      break;\n"
18031                "    }\n"
18032                "}\n",
18033                GNUBraceStyle);
18034 
18035   verifyFormat("enum X\n"
18036                "{\n"
18037                "  Y = 0,\n"
18038                "}\n",
18039                GNUBraceStyle);
18040 
18041   verifyFormat("@interface BSApplicationController ()\n"
18042                "{\n"
18043                "@private\n"
18044                "  id _extraIvar;\n"
18045                "}\n"
18046                "@end\n",
18047                GNUBraceStyle);
18048 
18049   verifyFormat("#ifdef _DEBUG\n"
18050                "int foo(int i = 0)\n"
18051                "#else\n"
18052                "int foo(int i = 5)\n"
18053                "#endif\n"
18054                "{\n"
18055                "  return i;\n"
18056                "}",
18057                GNUBraceStyle);
18058 
18059   verifyFormat("void foo() {}\n"
18060                "void bar()\n"
18061                "#ifdef _DEBUG\n"
18062                "{\n"
18063                "  foo();\n"
18064                "}\n"
18065                "#else\n"
18066                "{\n"
18067                "}\n"
18068                "#endif",
18069                GNUBraceStyle);
18070 
18071   verifyFormat("void foobar() { int i = 5; }\n"
18072                "#ifdef _DEBUG\n"
18073                "void bar() {}\n"
18074                "#else\n"
18075                "void bar() { foobar(); }\n"
18076                "#endif",
18077                GNUBraceStyle);
18078 }
18079 
18080 TEST_F(FormatTest, WebKitBraceBreaking) {
18081   FormatStyle WebKitBraceStyle = getLLVMStyle();
18082   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
18083   WebKitBraceStyle.FixNamespaceComments = false;
18084   verifyFormat("namespace a {\n"
18085                "class A {\n"
18086                "  void f()\n"
18087                "  {\n"
18088                "    if (true) {\n"
18089                "      a();\n"
18090                "      b();\n"
18091                "    }\n"
18092                "  }\n"
18093                "  void g() { return; }\n"
18094                "};\n"
18095                "enum E {\n"
18096                "  A,\n"
18097                "  // foo\n"
18098                "  B,\n"
18099                "  C\n"
18100                "};\n"
18101                "struct B {\n"
18102                "  int x;\n"
18103                "};\n"
18104                "}\n",
18105                WebKitBraceStyle);
18106   verifyFormat("struct S {\n"
18107                "  int Type;\n"
18108                "  union {\n"
18109                "    int x;\n"
18110                "    double y;\n"
18111                "  } Value;\n"
18112                "  class C {\n"
18113                "    MyFavoriteType Value;\n"
18114                "  } Class;\n"
18115                "};\n",
18116                WebKitBraceStyle);
18117 }
18118 
18119 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
18120   verifyFormat("void f() {\n"
18121                "  try {\n"
18122                "  } catch (const Exception &e) {\n"
18123                "  }\n"
18124                "}\n",
18125                getLLVMStyle());
18126 }
18127 
18128 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
18129   auto Style = getLLVMStyle();
18130   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18131   Style.AlignConsecutiveAssignments =
18132       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18133   Style.AlignConsecutiveDeclarations =
18134       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18135   verifyFormat("struct test demo[] = {\n"
18136                "    {56,    23, \"hello\"},\n"
18137                "    {-1, 93463, \"world\"},\n"
18138                "    { 7,     5,    \"!!\"}\n"
18139                "};\n",
18140                Style);
18141 
18142   verifyFormat("struct test demo[] = {\n"
18143                "    {56,    23, \"hello\"}, // first line\n"
18144                "    {-1, 93463, \"world\"}, // second line\n"
18145                "    { 7,     5,    \"!!\"}  // third line\n"
18146                "};\n",
18147                Style);
18148 
18149   verifyFormat("struct test demo[4] = {\n"
18150                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18151                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18152                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18153                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18154                "};\n",
18155                Style);
18156 
18157   verifyFormat("struct test demo[3] = {\n"
18158                "    {56,    23, \"hello\"},\n"
18159                "    {-1, 93463, \"world\"},\n"
18160                "    { 7,     5,    \"!!\"}\n"
18161                "};\n",
18162                Style);
18163 
18164   verifyFormat("struct test demo[3] = {\n"
18165                "    {int{56},    23, \"hello\"},\n"
18166                "    {int{-1}, 93463, \"world\"},\n"
18167                "    { int{7},     5,    \"!!\"}\n"
18168                "};\n",
18169                Style);
18170 
18171   verifyFormat("struct test demo[] = {\n"
18172                "    {56,    23, \"hello\"},\n"
18173                "    {-1, 93463, \"world\"},\n"
18174                "    { 7,     5,    \"!!\"},\n"
18175                "};\n",
18176                Style);
18177 
18178   verifyFormat("test demo[] = {\n"
18179                "    {56,    23, \"hello\"},\n"
18180                "    {-1, 93463, \"world\"},\n"
18181                "    { 7,     5,    \"!!\"},\n"
18182                "};\n",
18183                Style);
18184 
18185   verifyFormat("demo = std::array<struct test, 3>{\n"
18186                "    test{56,    23, \"hello\"},\n"
18187                "    test{-1, 93463, \"world\"},\n"
18188                "    test{ 7,     5,    \"!!\"},\n"
18189                "};\n",
18190                Style);
18191 
18192   verifyFormat("test demo[] = {\n"
18193                "    {56,    23, \"hello\"},\n"
18194                "#if X\n"
18195                "    {-1, 93463, \"world\"},\n"
18196                "#endif\n"
18197                "    { 7,     5,    \"!!\"}\n"
18198                "};\n",
18199                Style);
18200 
18201   verifyFormat(
18202       "test demo[] = {\n"
18203       "    { 7,    23,\n"
18204       "     \"hello world i am a very long line that really, in any\"\n"
18205       "     \"just world, ought to be split over multiple lines\"},\n"
18206       "    {-1, 93463,                                  \"world\"},\n"
18207       "    {56,     5,                                     \"!!\"}\n"
18208       "};\n",
18209       Style);
18210 
18211   verifyFormat("return GradForUnaryCwise(g, {\n"
18212                "                                {{\"sign\"}, \"Sign\",  "
18213                "  {\"x\", \"dy\"}},\n"
18214                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
18215                ", \"sign\"}},\n"
18216                "});\n",
18217                Style);
18218 
18219   Style.ColumnLimit = 0;
18220   EXPECT_EQ(
18221       "test demo[] = {\n"
18222       "    {56,    23, \"hello world i am a very long line that really, "
18223       "in any just world, ought to be split over multiple lines\"},\n"
18224       "    {-1, 93463,                                                  "
18225       "                                                 \"world\"},\n"
18226       "    { 7,     5,                                                  "
18227       "                                                    \"!!\"},\n"
18228       "};",
18229       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18230              "that really, in any just world, ought to be split over multiple "
18231              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18232              Style));
18233 
18234   Style.ColumnLimit = 80;
18235   verifyFormat("test demo[] = {\n"
18236                "    {56,    23, /* a comment */ \"hello\"},\n"
18237                "    {-1, 93463,                 \"world\"},\n"
18238                "    { 7,     5,                    \"!!\"}\n"
18239                "};\n",
18240                Style);
18241 
18242   verifyFormat("test demo[] = {\n"
18243                "    {56,    23,                    \"hello\"},\n"
18244                "    {-1, 93463, \"world\" /* comment here */},\n"
18245                "    { 7,     5,                       \"!!\"}\n"
18246                "};\n",
18247                Style);
18248 
18249   verifyFormat("test demo[] = {\n"
18250                "    {56, /* a comment */ 23, \"hello\"},\n"
18251                "    {-1,              93463, \"world\"},\n"
18252                "    { 7,                  5,    \"!!\"}\n"
18253                "};\n",
18254                Style);
18255 
18256   Style.ColumnLimit = 20;
18257   EXPECT_EQ(
18258       "demo = std::array<\n"
18259       "    struct test, 3>{\n"
18260       "    test{\n"
18261       "         56,    23,\n"
18262       "         \"hello \"\n"
18263       "         \"world i \"\n"
18264       "         \"am a very \"\n"
18265       "         \"long line \"\n"
18266       "         \"that \"\n"
18267       "         \"really, \"\n"
18268       "         \"in any \"\n"
18269       "         \"just \"\n"
18270       "         \"world, \"\n"
18271       "         \"ought to \"\n"
18272       "         \"be split \"\n"
18273       "         \"over \"\n"
18274       "         \"multiple \"\n"
18275       "         \"lines\"},\n"
18276       "    test{-1, 93463,\n"
18277       "         \"world\"},\n"
18278       "    test{ 7,     5,\n"
18279       "         \"!!\"   },\n"
18280       "};",
18281       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18282              "i am a very long line that really, in any just world, ought "
18283              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18284              "test{7, 5, \"!!\"},};",
18285              Style));
18286   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18287   Style = getLLVMStyleWithColumns(50);
18288   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18289   verifyFormat("static A x = {\n"
18290                "    {{init1, init2, init3, init4},\n"
18291                "     {init1, init2, init3, init4}}\n"
18292                "};",
18293                Style);
18294   Style.ColumnLimit = 100;
18295   EXPECT_EQ(
18296       "test demo[] = {\n"
18297       "    {56,    23,\n"
18298       "     \"hello world i am a very long line that really, in any just world"
18299       ", ought to be split over \"\n"
18300       "     \"multiple lines\"  },\n"
18301       "    {-1, 93463, \"world\"},\n"
18302       "    { 7,     5,    \"!!\"},\n"
18303       "};",
18304       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18305              "that really, in any just world, ought to be split over multiple "
18306              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18307              Style));
18308 
18309   Style = getLLVMStyleWithColumns(50);
18310   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18311   Style.AlignConsecutiveAssignments =
18312       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18313   Style.AlignConsecutiveDeclarations =
18314       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18315   verifyFormat("struct test demo[] = {\n"
18316                "    {56,    23, \"hello\"},\n"
18317                "    {-1, 93463, \"world\"},\n"
18318                "    { 7,     5,    \"!!\"}\n"
18319                "};\n"
18320                "static A x = {\n"
18321                "    {{init1, init2, init3, init4},\n"
18322                "     {init1, init2, init3, init4}}\n"
18323                "};",
18324                Style);
18325   Style.ColumnLimit = 100;
18326   Style.AlignConsecutiveAssignments =
18327       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18328   Style.AlignConsecutiveDeclarations =
18329       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18330   verifyFormat("struct test demo[] = {\n"
18331                "    {56,    23, \"hello\"},\n"
18332                "    {-1, 93463, \"world\"},\n"
18333                "    { 7,     5,    \"!!\"}\n"
18334                "};\n"
18335                "struct test demo[4] = {\n"
18336                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18337                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18338                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18339                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18340                "};\n",
18341                Style);
18342   EXPECT_EQ(
18343       "test demo[] = {\n"
18344       "    {56,\n"
18345       "     \"hello world i am a very long line that really, in any just world"
18346       ", ought to be split over \"\n"
18347       "     \"multiple lines\",    23},\n"
18348       "    {-1,      \"world\", 93463},\n"
18349       "    { 7,         \"!!\",     5},\n"
18350       "};",
18351       format("test demo[] = {{56, \"hello world i am a very long line "
18352              "that really, in any just world, ought to be split over multiple "
18353              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
18354              Style));
18355 }
18356 
18357 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
18358   auto Style = getLLVMStyle();
18359   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18360   /* FIXME: This case gets misformatted.
18361   verifyFormat("auto foo = Items{\n"
18362                "    Section{0, bar(), },\n"
18363                "    Section{1, boo()  }\n"
18364                "};\n",
18365                Style);
18366   */
18367   verifyFormat("auto foo = Items{\n"
18368                "    Section{\n"
18369                "            0, bar(),\n"
18370                "            }\n"
18371                "};\n",
18372                Style);
18373   verifyFormat("struct test demo[] = {\n"
18374                "    {56, 23,    \"hello\"},\n"
18375                "    {-1, 93463, \"world\"},\n"
18376                "    {7,  5,     \"!!\"   }\n"
18377                "};\n",
18378                Style);
18379   verifyFormat("struct test demo[] = {\n"
18380                "    {56, 23,    \"hello\"}, // first line\n"
18381                "    {-1, 93463, \"world\"}, // second line\n"
18382                "    {7,  5,     \"!!\"   }  // third line\n"
18383                "};\n",
18384                Style);
18385   verifyFormat("struct test demo[4] = {\n"
18386                "    {56,  23,    21, \"oh\"      }, // first line\n"
18387                "    {-1,  93463, 22, \"my\"      }, // second line\n"
18388                "    {7,   5,     1,  \"goodness\"}  // third line\n"
18389                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
18390                "};\n",
18391                Style);
18392   verifyFormat("struct test demo[3] = {\n"
18393                "    {56, 23,    \"hello\"},\n"
18394                "    {-1, 93463, \"world\"},\n"
18395                "    {7,  5,     \"!!\"   }\n"
18396                "};\n",
18397                Style);
18398 
18399   verifyFormat("struct test demo[3] = {\n"
18400                "    {int{56}, 23,    \"hello\"},\n"
18401                "    {int{-1}, 93463, \"world\"},\n"
18402                "    {int{7},  5,     \"!!\"   }\n"
18403                "};\n",
18404                Style);
18405   verifyFormat("struct test demo[] = {\n"
18406                "    {56, 23,    \"hello\"},\n"
18407                "    {-1, 93463, \"world\"},\n"
18408                "    {7,  5,     \"!!\"   },\n"
18409                "};\n",
18410                Style);
18411   verifyFormat("test demo[] = {\n"
18412                "    {56, 23,    \"hello\"},\n"
18413                "    {-1, 93463, \"world\"},\n"
18414                "    {7,  5,     \"!!\"   },\n"
18415                "};\n",
18416                Style);
18417   verifyFormat("demo = std::array<struct test, 3>{\n"
18418                "    test{56, 23,    \"hello\"},\n"
18419                "    test{-1, 93463, \"world\"},\n"
18420                "    test{7,  5,     \"!!\"   },\n"
18421                "};\n",
18422                Style);
18423   verifyFormat("test demo[] = {\n"
18424                "    {56, 23,    \"hello\"},\n"
18425                "#if X\n"
18426                "    {-1, 93463, \"world\"},\n"
18427                "#endif\n"
18428                "    {7,  5,     \"!!\"   }\n"
18429                "};\n",
18430                Style);
18431   verifyFormat(
18432       "test demo[] = {\n"
18433       "    {7,  23,\n"
18434       "     \"hello world i am a very long line that really, in any\"\n"
18435       "     \"just world, ought to be split over multiple lines\"},\n"
18436       "    {-1, 93463, \"world\"                                 },\n"
18437       "    {56, 5,     \"!!\"                                    }\n"
18438       "};\n",
18439       Style);
18440 
18441   verifyFormat("return GradForUnaryCwise(g, {\n"
18442                "                                {{\"sign\"}, \"Sign\", {\"x\", "
18443                "\"dy\"}   },\n"
18444                "                                {{\"dx\"},   \"Mul\",  "
18445                "{\"dy\", \"sign\"}},\n"
18446                "});\n",
18447                Style);
18448 
18449   Style.ColumnLimit = 0;
18450   EXPECT_EQ(
18451       "test demo[] = {\n"
18452       "    {56, 23,    \"hello world i am a very long line that really, in any "
18453       "just world, ought to be split over multiple lines\"},\n"
18454       "    {-1, 93463, \"world\"                                               "
18455       "                                                   },\n"
18456       "    {7,  5,     \"!!\"                                                  "
18457       "                                                   },\n"
18458       "};",
18459       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18460              "that really, in any just world, ought to be split over multiple "
18461              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18462              Style));
18463 
18464   Style.ColumnLimit = 80;
18465   verifyFormat("test demo[] = {\n"
18466                "    {56, 23,    /* a comment */ \"hello\"},\n"
18467                "    {-1, 93463, \"world\"                },\n"
18468                "    {7,  5,     \"!!\"                   }\n"
18469                "};\n",
18470                Style);
18471 
18472   verifyFormat("test demo[] = {\n"
18473                "    {56, 23,    \"hello\"                   },\n"
18474                "    {-1, 93463, \"world\" /* comment here */},\n"
18475                "    {7,  5,     \"!!\"                      }\n"
18476                "};\n",
18477                Style);
18478 
18479   verifyFormat("test demo[] = {\n"
18480                "    {56, /* a comment */ 23, \"hello\"},\n"
18481                "    {-1, 93463,              \"world\"},\n"
18482                "    {7,  5,                  \"!!\"   }\n"
18483                "};\n",
18484                Style);
18485 
18486   Style.ColumnLimit = 20;
18487   EXPECT_EQ(
18488       "demo = std::array<\n"
18489       "    struct test, 3>{\n"
18490       "    test{\n"
18491       "         56, 23,\n"
18492       "         \"hello \"\n"
18493       "         \"world i \"\n"
18494       "         \"am a very \"\n"
18495       "         \"long line \"\n"
18496       "         \"that \"\n"
18497       "         \"really, \"\n"
18498       "         \"in any \"\n"
18499       "         \"just \"\n"
18500       "         \"world, \"\n"
18501       "         \"ought to \"\n"
18502       "         \"be split \"\n"
18503       "         \"over \"\n"
18504       "         \"multiple \"\n"
18505       "         \"lines\"},\n"
18506       "    test{-1, 93463,\n"
18507       "         \"world\"},\n"
18508       "    test{7,  5,\n"
18509       "         \"!!\"   },\n"
18510       "};",
18511       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18512              "i am a very long line that really, in any just world, ought "
18513              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18514              "test{7, 5, \"!!\"},};",
18515              Style));
18516 
18517   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18518   Style = getLLVMStyleWithColumns(50);
18519   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18520   verifyFormat("static A x = {\n"
18521                "    {{init1, init2, init3, init4},\n"
18522                "     {init1, init2, init3, init4}}\n"
18523                "};",
18524                Style);
18525   Style.ColumnLimit = 100;
18526   EXPECT_EQ(
18527       "test demo[] = {\n"
18528       "    {56, 23,\n"
18529       "     \"hello world i am a very long line that really, in any just world"
18530       ", ought to be split over \"\n"
18531       "     \"multiple lines\"  },\n"
18532       "    {-1, 93463, \"world\"},\n"
18533       "    {7,  5,     \"!!\"   },\n"
18534       "};",
18535       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18536              "that really, in any just world, ought to be split over multiple "
18537              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18538              Style));
18539 }
18540 
18541 TEST_F(FormatTest, UnderstandsPragmas) {
18542   verifyFormat("#pragma omp reduction(| : var)");
18543   verifyFormat("#pragma omp reduction(+ : var)");
18544 
18545   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
18546             "(including parentheses).",
18547             format("#pragma    mark   Any non-hyphenated or hyphenated string "
18548                    "(including parentheses)."));
18549 }
18550 
18551 TEST_F(FormatTest, UnderstandPragmaOption) {
18552   verifyFormat("#pragma option -C -A");
18553 
18554   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
18555 }
18556 
18557 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
18558   FormatStyle Style = getLLVMStyleWithColumns(20);
18559 
18560   // See PR41213
18561   EXPECT_EQ("/*\n"
18562             " *\t9012345\n"
18563             " * /8901\n"
18564             " */",
18565             format("/*\n"
18566                    " *\t9012345 /8901\n"
18567                    " */",
18568                    Style));
18569   EXPECT_EQ("/*\n"
18570             " *345678\n"
18571             " *\t/8901\n"
18572             " */",
18573             format("/*\n"
18574                    " *345678\t/8901\n"
18575                    " */",
18576                    Style));
18577 
18578   verifyFormat("int a; // the\n"
18579                "       // comment",
18580                Style);
18581   EXPECT_EQ("int a; /* first line\n"
18582             "        * second\n"
18583             "        * line third\n"
18584             "        * line\n"
18585             "        */",
18586             format("int a; /* first line\n"
18587                    "        * second\n"
18588                    "        * line third\n"
18589                    "        * line\n"
18590                    "        */",
18591                    Style));
18592   EXPECT_EQ("int a; // first line\n"
18593             "       // second\n"
18594             "       // line third\n"
18595             "       // line",
18596             format("int a; // first line\n"
18597                    "       // second line\n"
18598                    "       // third line",
18599                    Style));
18600 
18601   Style.PenaltyExcessCharacter = 90;
18602   verifyFormat("int a; // the comment", Style);
18603   EXPECT_EQ("int a; // the comment\n"
18604             "       // aaa",
18605             format("int a; // the comment aaa", Style));
18606   EXPECT_EQ("int a; /* first line\n"
18607             "        * second line\n"
18608             "        * third line\n"
18609             "        */",
18610             format("int a; /* first line\n"
18611                    "        * second line\n"
18612                    "        * third line\n"
18613                    "        */",
18614                    Style));
18615   EXPECT_EQ("int a; // first line\n"
18616             "       // second line\n"
18617             "       // third line",
18618             format("int a; // first line\n"
18619                    "       // second line\n"
18620                    "       // third line",
18621                    Style));
18622   // FIXME: Investigate why this is not getting the same layout as the test
18623   // above.
18624   EXPECT_EQ("int a; /* first line\n"
18625             "        * second line\n"
18626             "        * third line\n"
18627             "        */",
18628             format("int a; /* first line second line third line"
18629                    "\n*/",
18630                    Style));
18631 
18632   EXPECT_EQ("// foo bar baz bazfoo\n"
18633             "// foo bar foo bar\n",
18634             format("// foo bar baz bazfoo\n"
18635                    "// foo bar foo           bar\n",
18636                    Style));
18637   EXPECT_EQ("// foo bar baz bazfoo\n"
18638             "// foo bar foo bar\n",
18639             format("// foo bar baz      bazfoo\n"
18640                    "// foo            bar foo bar\n",
18641                    Style));
18642 
18643   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
18644   // next one.
18645   EXPECT_EQ("// foo bar baz bazfoo\n"
18646             "// bar foo bar\n",
18647             format("// foo bar baz      bazfoo bar\n"
18648                    "// foo            bar\n",
18649                    Style));
18650 
18651   EXPECT_EQ("// foo bar baz bazfoo\n"
18652             "// foo bar baz bazfoo\n"
18653             "// bar foo bar\n",
18654             format("// foo bar baz      bazfoo\n"
18655                    "// foo bar baz      bazfoo bar\n"
18656                    "// foo bar\n",
18657                    Style));
18658 
18659   EXPECT_EQ("// foo bar baz bazfoo\n"
18660             "// foo bar baz bazfoo\n"
18661             "// bar foo bar\n",
18662             format("// foo bar baz      bazfoo\n"
18663                    "// foo bar baz      bazfoo bar\n"
18664                    "// foo           bar\n",
18665                    Style));
18666 
18667   // Make sure we do not keep protruding characters if strict mode reflow is
18668   // cheaper than keeping protruding characters.
18669   Style.ColumnLimit = 21;
18670   EXPECT_EQ(
18671       "// foo foo foo foo\n"
18672       "// foo foo foo foo\n"
18673       "// foo foo foo foo\n",
18674       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
18675 
18676   EXPECT_EQ("int a = /* long block\n"
18677             "           comment */\n"
18678             "    42;",
18679             format("int a = /* long block comment */ 42;", Style));
18680 }
18681 
18682 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
18683   FormatStyle Style = getLLVMStyle();
18684   Style.ColumnLimit = 8;
18685   Style.PenaltyExcessCharacter = 15;
18686   verifyFormat("int foo(\n"
18687                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
18688                Style);
18689   Style.PenaltyBreakOpenParenthesis = 200;
18690   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
18691             format("int foo(\n"
18692                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
18693                    Style));
18694 }
18695 
18696 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
18697   FormatStyle Style = getLLVMStyle();
18698   Style.ColumnLimit = 5;
18699   Style.PenaltyExcessCharacter = 150;
18700   verifyFormat("foo((\n"
18701                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
18702 
18703                Style);
18704   Style.PenaltyBreakOpenParenthesis = 100000;
18705   EXPECT_EQ("foo((int)\n"
18706             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
18707             format("foo((\n"
18708                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
18709                    Style));
18710 }
18711 
18712 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
18713   FormatStyle Style = getLLVMStyle();
18714   Style.ColumnLimit = 4;
18715   Style.PenaltyExcessCharacter = 100;
18716   verifyFormat("for (\n"
18717                "    int iiiiiiiiiiiiiiiii =\n"
18718                "        0;\n"
18719                "    iiiiiiiiiiiiiiiii <\n"
18720                "    2;\n"
18721                "    iiiiiiiiiiiiiiiii++) {\n"
18722                "}",
18723 
18724                Style);
18725   Style.PenaltyBreakOpenParenthesis = 1250;
18726   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
18727             "         0;\n"
18728             "     iiiiiiiiiiiiiiiii <\n"
18729             "     2;\n"
18730             "     iiiiiiiiiiiiiiiii++) {\n"
18731             "}",
18732             format("for (\n"
18733                    "    int iiiiiiiiiiiiiiiii =\n"
18734                    "        0;\n"
18735                    "    iiiiiiiiiiiiiiiii <\n"
18736                    "    2;\n"
18737                    "    iiiiiiiiiiiiiiiii++) {\n"
18738                    "}",
18739                    Style));
18740 }
18741 
18742 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
18743   for (size_t i = 1; i < Styles.size(); ++i)                                   \
18744   EXPECT_EQ(Styles[0], Styles[i])                                              \
18745       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
18746 
18747 TEST_F(FormatTest, GetsPredefinedStyleByName) {
18748   SmallVector<FormatStyle, 3> Styles;
18749   Styles.resize(3);
18750 
18751   Styles[0] = getLLVMStyle();
18752   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
18753   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
18754   EXPECT_ALL_STYLES_EQUAL(Styles);
18755 
18756   Styles[0] = getGoogleStyle();
18757   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
18758   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
18759   EXPECT_ALL_STYLES_EQUAL(Styles);
18760 
18761   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18762   EXPECT_TRUE(
18763       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
18764   EXPECT_TRUE(
18765       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
18766   EXPECT_ALL_STYLES_EQUAL(Styles);
18767 
18768   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
18769   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
18770   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
18771   EXPECT_ALL_STYLES_EQUAL(Styles);
18772 
18773   Styles[0] = getMozillaStyle();
18774   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
18775   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
18776   EXPECT_ALL_STYLES_EQUAL(Styles);
18777 
18778   Styles[0] = getWebKitStyle();
18779   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
18780   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
18781   EXPECT_ALL_STYLES_EQUAL(Styles);
18782 
18783   Styles[0] = getGNUStyle();
18784   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
18785   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
18786   EXPECT_ALL_STYLES_EQUAL(Styles);
18787 
18788   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
18789 }
18790 
18791 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
18792   SmallVector<FormatStyle, 8> Styles;
18793   Styles.resize(2);
18794 
18795   Styles[0] = getGoogleStyle();
18796   Styles[1] = getLLVMStyle();
18797   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18798   EXPECT_ALL_STYLES_EQUAL(Styles);
18799 
18800   Styles.resize(5);
18801   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18802   Styles[1] = getLLVMStyle();
18803   Styles[1].Language = FormatStyle::LK_JavaScript;
18804   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18805 
18806   Styles[2] = getLLVMStyle();
18807   Styles[2].Language = FormatStyle::LK_JavaScript;
18808   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
18809                                   "BasedOnStyle: Google",
18810                                   &Styles[2])
18811                    .value());
18812 
18813   Styles[3] = getLLVMStyle();
18814   Styles[3].Language = FormatStyle::LK_JavaScript;
18815   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
18816                                   "Language: JavaScript",
18817                                   &Styles[3])
18818                    .value());
18819 
18820   Styles[4] = getLLVMStyle();
18821   Styles[4].Language = FormatStyle::LK_JavaScript;
18822   EXPECT_EQ(0, parseConfiguration("---\n"
18823                                   "BasedOnStyle: LLVM\n"
18824                                   "IndentWidth: 123\n"
18825                                   "---\n"
18826                                   "BasedOnStyle: Google\n"
18827                                   "Language: JavaScript",
18828                                   &Styles[4])
18829                    .value());
18830   EXPECT_ALL_STYLES_EQUAL(Styles);
18831 }
18832 
18833 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
18834   Style.FIELD = false;                                                         \
18835   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
18836   EXPECT_TRUE(Style.FIELD);                                                    \
18837   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
18838   EXPECT_FALSE(Style.FIELD);
18839 
18840 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
18841 
18842 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
18843   Style.STRUCT.FIELD = false;                                                  \
18844   EXPECT_EQ(0,                                                                 \
18845             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
18846                 .value());                                                     \
18847   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
18848   EXPECT_EQ(0,                                                                 \
18849             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
18850                 .value());                                                     \
18851   EXPECT_FALSE(Style.STRUCT.FIELD);
18852 
18853 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
18854   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
18855 
18856 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
18857   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
18858   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
18859   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
18860 
18861 TEST_F(FormatTest, ParsesConfigurationBools) {
18862   FormatStyle Style = {};
18863   Style.Language = FormatStyle::LK_Cpp;
18864   CHECK_PARSE_BOOL(AlignTrailingComments);
18865   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
18866   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
18867   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
18868   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
18869   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
18870   CHECK_PARSE_BOOL(BinPackArguments);
18871   CHECK_PARSE_BOOL(BinPackParameters);
18872   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
18873   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
18874   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
18875   CHECK_PARSE_BOOL(BreakStringLiterals);
18876   CHECK_PARSE_BOOL(CompactNamespaces);
18877   CHECK_PARSE_BOOL(DeriveLineEnding);
18878   CHECK_PARSE_BOOL(DerivePointerAlignment);
18879   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
18880   CHECK_PARSE_BOOL(DisableFormat);
18881   CHECK_PARSE_BOOL(IndentAccessModifiers);
18882   CHECK_PARSE_BOOL(IndentCaseLabels);
18883   CHECK_PARSE_BOOL(IndentCaseBlocks);
18884   CHECK_PARSE_BOOL(IndentGotoLabels);
18885   CHECK_PARSE_BOOL(IndentRequires);
18886   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
18887   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
18888   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
18889   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
18890   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
18891   CHECK_PARSE_BOOL(ReflowComments);
18892   CHECK_PARSE_BOOL(RemoveBracesLLVM);
18893   CHECK_PARSE_BOOL(SortUsingDeclarations);
18894   CHECK_PARSE_BOOL(SpacesInParentheses);
18895   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
18896   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
18897   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
18898   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
18899   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
18900   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
18901   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
18902   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
18903   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
18904   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
18905   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
18906   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
18907   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
18908   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
18909   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
18910   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
18911   CHECK_PARSE_BOOL(UseCRLF);
18912 
18913   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
18914   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
18915   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
18916   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
18917   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
18918   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
18919   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
18920   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
18921   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
18922   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
18923   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
18924   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
18925   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
18926   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
18927   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
18928   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
18929   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
18930   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
18931   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
18932   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
18933                           AfterFunctionDeclarationName);
18934   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
18935                           AfterFunctionDefinitionName);
18936   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
18937   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
18938   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
18939 }
18940 
18941 #undef CHECK_PARSE_BOOL
18942 
18943 TEST_F(FormatTest, ParsesConfiguration) {
18944   FormatStyle Style = {};
18945   Style.Language = FormatStyle::LK_Cpp;
18946   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
18947   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
18948               ConstructorInitializerIndentWidth, 1234u);
18949   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
18950   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
18951   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
18952   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
18953   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
18954               PenaltyBreakBeforeFirstCallParameter, 1234u);
18955   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
18956               PenaltyBreakTemplateDeclaration, 1234u);
18957   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
18958               1234u);
18959   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
18960   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
18961               PenaltyReturnTypeOnItsOwnLine, 1234u);
18962   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
18963               SpacesBeforeTrailingComments, 1234u);
18964   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
18965   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
18966   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
18967 
18968   Style.QualifierAlignment = FormatStyle::QAS_Right;
18969   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
18970               FormatStyle::QAS_Leave);
18971   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
18972               FormatStyle::QAS_Right);
18973   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
18974               FormatStyle::QAS_Left);
18975   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
18976               FormatStyle::QAS_Custom);
18977 
18978   Style.QualifierOrder.clear();
18979   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
18980               std::vector<std::string>({"const", "volatile", "type"}));
18981   Style.QualifierOrder.clear();
18982   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
18983               std::vector<std::string>({"const", "type"}));
18984   Style.QualifierOrder.clear();
18985   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
18986               std::vector<std::string>({"volatile", "type"}));
18987 
18988   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
18989   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
18990               FormatStyle::ACS_None);
18991   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
18992               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
18993   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
18994               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
18995   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
18996               AlignConsecutiveAssignments,
18997               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18998   // For backwards compability, false / true should still parse
18999   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
19000               FormatStyle::ACS_None);
19001   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
19002               FormatStyle::ACS_Consecutive);
19003 
19004   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
19005   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
19006               FormatStyle::ACS_None);
19007   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
19008               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
19009   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
19010               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
19011   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
19012               AlignConsecutiveBitFields,
19013               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19014   // For backwards compability, false / true should still parse
19015   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
19016               FormatStyle::ACS_None);
19017   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
19018               FormatStyle::ACS_Consecutive);
19019 
19020   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
19021   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
19022               FormatStyle::ACS_None);
19023   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
19024               FormatStyle::ACS_Consecutive);
19025   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
19026               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
19027   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
19028               AlignConsecutiveMacros,
19029               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19030   // For backwards compability, false / true should still parse
19031   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
19032               FormatStyle::ACS_None);
19033   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
19034               FormatStyle::ACS_Consecutive);
19035 
19036   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
19037   CHECK_PARSE("AlignConsecutiveDeclarations: None",
19038               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
19039   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
19040               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
19041   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
19042               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
19043   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
19044               AlignConsecutiveDeclarations,
19045               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19046   // For backwards compability, false / true should still parse
19047   CHECK_PARSE("AlignConsecutiveDeclarations: false",
19048               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
19049   CHECK_PARSE("AlignConsecutiveDeclarations: true",
19050               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
19051 
19052   Style.PointerAlignment = FormatStyle::PAS_Middle;
19053   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
19054               FormatStyle::PAS_Left);
19055   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
19056               FormatStyle::PAS_Right);
19057   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
19058               FormatStyle::PAS_Middle);
19059   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
19060   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
19061               FormatStyle::RAS_Pointer);
19062   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
19063               FormatStyle::RAS_Left);
19064   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
19065               FormatStyle::RAS_Right);
19066   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
19067               FormatStyle::RAS_Middle);
19068   // For backward compatibility:
19069   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
19070               FormatStyle::PAS_Left);
19071   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
19072               FormatStyle::PAS_Right);
19073   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
19074               FormatStyle::PAS_Middle);
19075 
19076   Style.Standard = FormatStyle::LS_Auto;
19077   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
19078   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
19079   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
19080   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
19081   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
19082   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
19083   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
19084   // Legacy aliases:
19085   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
19086   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
19087   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
19088   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
19089 
19090   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
19091   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
19092               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
19093   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
19094               FormatStyle::BOS_None);
19095   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
19096               FormatStyle::BOS_All);
19097   // For backward compatibility:
19098   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
19099               FormatStyle::BOS_None);
19100   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
19101               FormatStyle::BOS_All);
19102 
19103   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
19104   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
19105               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
19106   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
19107               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
19108   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
19109               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
19110   // For backward compatibility:
19111   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
19112               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
19113 
19114   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
19115   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
19116               FormatStyle::BILS_AfterComma);
19117   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
19118               FormatStyle::BILS_BeforeComma);
19119   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
19120               FormatStyle::BILS_AfterColon);
19121   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
19122               FormatStyle::BILS_BeforeColon);
19123   // For backward compatibility:
19124   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
19125               FormatStyle::BILS_BeforeComma);
19126 
19127   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19128   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
19129               FormatStyle::PCIS_Never);
19130   CHECK_PARSE("PackConstructorInitializers: BinPack",
19131               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19132   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
19133               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19134   CHECK_PARSE("PackConstructorInitializers: NextLine",
19135               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19136   // For backward compatibility:
19137   CHECK_PARSE("BasedOnStyle: Google\n"
19138               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19139               "AllowAllConstructorInitializersOnNextLine: false",
19140               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19141   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
19142   CHECK_PARSE("BasedOnStyle: Google\n"
19143               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
19144               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19145   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19146               "AllowAllConstructorInitializersOnNextLine: true",
19147               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19148   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19149   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19150               "AllowAllConstructorInitializersOnNextLine: false",
19151               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19152 
19153   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
19154   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
19155               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
19156   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
19157               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
19158   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
19159               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
19160   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
19161               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
19162 
19163   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19164   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
19165               FormatStyle::BAS_Align);
19166   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
19167               FormatStyle::BAS_DontAlign);
19168   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
19169               FormatStyle::BAS_AlwaysBreak);
19170   // For backward compatibility:
19171   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
19172               FormatStyle::BAS_DontAlign);
19173   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
19174               FormatStyle::BAS_Align);
19175 
19176   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
19177   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
19178               FormatStyle::ENAS_DontAlign);
19179   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
19180               FormatStyle::ENAS_Left);
19181   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
19182               FormatStyle::ENAS_Right);
19183   // For backward compatibility:
19184   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
19185               FormatStyle::ENAS_Left);
19186   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
19187               FormatStyle::ENAS_Right);
19188 
19189   Style.AlignOperands = FormatStyle::OAS_Align;
19190   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
19191               FormatStyle::OAS_DontAlign);
19192   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
19193   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
19194               FormatStyle::OAS_AlignAfterOperator);
19195   // For backward compatibility:
19196   CHECK_PARSE("AlignOperands: false", AlignOperands,
19197               FormatStyle::OAS_DontAlign);
19198   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
19199 
19200   Style.UseTab = FormatStyle::UT_ForIndentation;
19201   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
19202   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
19203   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
19204   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
19205               FormatStyle::UT_ForContinuationAndIndentation);
19206   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
19207               FormatStyle::UT_AlignWithSpaces);
19208   // For backward compatibility:
19209   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
19210   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
19211 
19212   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
19213   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
19214               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19215   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
19216               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
19217   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
19218               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19219   // For backward compatibility:
19220   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
19221               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19222   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
19223               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19224 
19225   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
19226   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
19227               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19228   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
19229               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
19230   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
19231               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
19232   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
19233               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19234   // For backward compatibility:
19235   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
19236               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19237   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
19238               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19239 
19240   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
19241   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
19242               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
19243   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
19244               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
19245   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
19246               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
19247   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
19248               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
19249 
19250   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
19251   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
19252               FormatStyle::SBPO_Never);
19253   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
19254               FormatStyle::SBPO_Always);
19255   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
19256               FormatStyle::SBPO_ControlStatements);
19257   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
19258               SpaceBeforeParens,
19259               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19260   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
19261               FormatStyle::SBPO_NonEmptyParentheses);
19262   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
19263               FormatStyle::SBPO_Custom);
19264   // For backward compatibility:
19265   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
19266               FormatStyle::SBPO_Never);
19267   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
19268               FormatStyle::SBPO_ControlStatements);
19269   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
19270               SpaceBeforeParens,
19271               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19272 
19273   Style.ColumnLimit = 123;
19274   FormatStyle BaseStyle = getLLVMStyle();
19275   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
19276   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
19277 
19278   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
19279   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
19280               FormatStyle::BS_Attach);
19281   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
19282               FormatStyle::BS_Linux);
19283   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
19284               FormatStyle::BS_Mozilla);
19285   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
19286               FormatStyle::BS_Stroustrup);
19287   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
19288               FormatStyle::BS_Allman);
19289   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
19290               FormatStyle::BS_Whitesmiths);
19291   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
19292   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
19293               FormatStyle::BS_WebKit);
19294   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
19295               FormatStyle::BS_Custom);
19296 
19297   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
19298   CHECK_PARSE("BraceWrapping:\n"
19299               "  AfterControlStatement: MultiLine",
19300               BraceWrapping.AfterControlStatement,
19301               FormatStyle::BWACS_MultiLine);
19302   CHECK_PARSE("BraceWrapping:\n"
19303               "  AfterControlStatement: Always",
19304               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19305   CHECK_PARSE("BraceWrapping:\n"
19306               "  AfterControlStatement: Never",
19307               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19308   // For backward compatibility:
19309   CHECK_PARSE("BraceWrapping:\n"
19310               "  AfterControlStatement: true",
19311               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19312   CHECK_PARSE("BraceWrapping:\n"
19313               "  AfterControlStatement: false",
19314               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19315 
19316   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
19317   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
19318               FormatStyle::RTBS_None);
19319   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
19320               FormatStyle::RTBS_All);
19321   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
19322               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
19323   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
19324               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
19325   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
19326               AlwaysBreakAfterReturnType,
19327               FormatStyle::RTBS_TopLevelDefinitions);
19328 
19329   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
19330   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
19331               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
19332   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
19333               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19334   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
19335               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19336   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
19337               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19338   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
19339               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19340 
19341   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
19342   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
19343               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
19344   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
19345               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
19346   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
19347               AlwaysBreakAfterDefinitionReturnType,
19348               FormatStyle::DRTBS_TopLevel);
19349 
19350   Style.NamespaceIndentation = FormatStyle::NI_All;
19351   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
19352               FormatStyle::NI_None);
19353   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
19354               FormatStyle::NI_Inner);
19355   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
19356               FormatStyle::NI_All);
19357 
19358   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
19359   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
19360               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19361   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
19362               AllowShortIfStatementsOnASingleLine,
19363               FormatStyle::SIS_WithoutElse);
19364   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
19365               AllowShortIfStatementsOnASingleLine,
19366               FormatStyle::SIS_OnlyFirstIf);
19367   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
19368               AllowShortIfStatementsOnASingleLine,
19369               FormatStyle::SIS_AllIfsAndElse);
19370   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
19371               AllowShortIfStatementsOnASingleLine,
19372               FormatStyle::SIS_OnlyFirstIf);
19373   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
19374               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19375   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
19376               AllowShortIfStatementsOnASingleLine,
19377               FormatStyle::SIS_WithoutElse);
19378 
19379   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
19380   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
19381               FormatStyle::IEBS_AfterExternBlock);
19382   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
19383               FormatStyle::IEBS_Indent);
19384   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
19385               FormatStyle::IEBS_NoIndent);
19386   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
19387               FormatStyle::IEBS_Indent);
19388   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
19389               FormatStyle::IEBS_NoIndent);
19390 
19391   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
19392   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
19393               FormatStyle::BFCS_Both);
19394   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
19395               FormatStyle::BFCS_None);
19396   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
19397               FormatStyle::BFCS_Before);
19398   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
19399               FormatStyle::BFCS_After);
19400 
19401   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
19402   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
19403               FormatStyle::SJSIO_After);
19404   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
19405               FormatStyle::SJSIO_Before);
19406 
19407   // FIXME: This is required because parsing a configuration simply overwrites
19408   // the first N elements of the list instead of resetting it.
19409   Style.ForEachMacros.clear();
19410   std::vector<std::string> BoostForeach;
19411   BoostForeach.push_back("BOOST_FOREACH");
19412   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
19413   std::vector<std::string> BoostAndQForeach;
19414   BoostAndQForeach.push_back("BOOST_FOREACH");
19415   BoostAndQForeach.push_back("Q_FOREACH");
19416   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
19417               BoostAndQForeach);
19418 
19419   Style.IfMacros.clear();
19420   std::vector<std::string> CustomIfs;
19421   CustomIfs.push_back("MYIF");
19422   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
19423 
19424   Style.AttributeMacros.clear();
19425   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
19426               std::vector<std::string>{"__capability"});
19427   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
19428               std::vector<std::string>({"attr1", "attr2"}));
19429 
19430   Style.StatementAttributeLikeMacros.clear();
19431   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
19432               StatementAttributeLikeMacros,
19433               std::vector<std::string>({"emit", "Q_EMIT"}));
19434 
19435   Style.StatementMacros.clear();
19436   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
19437               std::vector<std::string>{"QUNUSED"});
19438   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
19439               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
19440 
19441   Style.NamespaceMacros.clear();
19442   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
19443               std::vector<std::string>{"TESTSUITE"});
19444   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
19445               std::vector<std::string>({"TESTSUITE", "SUITE"}));
19446 
19447   Style.WhitespaceSensitiveMacros.clear();
19448   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
19449               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
19450   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
19451               WhitespaceSensitiveMacros,
19452               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
19453   Style.WhitespaceSensitiveMacros.clear();
19454   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
19455               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
19456   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
19457               WhitespaceSensitiveMacros,
19458               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
19459 
19460   Style.IncludeStyle.IncludeCategories.clear();
19461   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
19462       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
19463   CHECK_PARSE("IncludeCategories:\n"
19464               "  - Regex: abc/.*\n"
19465               "    Priority: 2\n"
19466               "  - Regex: .*\n"
19467               "    Priority: 1\n"
19468               "    CaseSensitive: true\n",
19469               IncludeStyle.IncludeCategories, ExpectedCategories);
19470   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
19471               "abc$");
19472   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
19473               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
19474 
19475   Style.SortIncludes = FormatStyle::SI_Never;
19476   CHECK_PARSE("SortIncludes: true", SortIncludes,
19477               FormatStyle::SI_CaseSensitive);
19478   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
19479   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
19480               FormatStyle::SI_CaseInsensitive);
19481   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
19482               FormatStyle::SI_CaseSensitive);
19483   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
19484 
19485   Style.RawStringFormats.clear();
19486   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
19487       {
19488           FormatStyle::LK_TextProto,
19489           {"pb", "proto"},
19490           {"PARSE_TEXT_PROTO"},
19491           /*CanonicalDelimiter=*/"",
19492           "llvm",
19493       },
19494       {
19495           FormatStyle::LK_Cpp,
19496           {"cc", "cpp"},
19497           {"C_CODEBLOCK", "CPPEVAL"},
19498           /*CanonicalDelimiter=*/"cc",
19499           /*BasedOnStyle=*/"",
19500       },
19501   };
19502 
19503   CHECK_PARSE("RawStringFormats:\n"
19504               "  - Language: TextProto\n"
19505               "    Delimiters:\n"
19506               "      - 'pb'\n"
19507               "      - 'proto'\n"
19508               "    EnclosingFunctions:\n"
19509               "      - 'PARSE_TEXT_PROTO'\n"
19510               "    BasedOnStyle: llvm\n"
19511               "  - Language: Cpp\n"
19512               "    Delimiters:\n"
19513               "      - 'cc'\n"
19514               "      - 'cpp'\n"
19515               "    EnclosingFunctions:\n"
19516               "      - 'C_CODEBLOCK'\n"
19517               "      - 'CPPEVAL'\n"
19518               "    CanonicalDelimiter: 'cc'",
19519               RawStringFormats, ExpectedRawStringFormats);
19520 
19521   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19522               "  Minimum: 0\n"
19523               "  Maximum: 0",
19524               SpacesInLineCommentPrefix.Minimum, 0u);
19525   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
19526   Style.SpacesInLineCommentPrefix.Minimum = 1;
19527   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19528               "  Minimum: 2",
19529               SpacesInLineCommentPrefix.Minimum, 0u);
19530   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19531               "  Maximum: -1",
19532               SpacesInLineCommentPrefix.Maximum, -1u);
19533   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19534               "  Minimum: 2",
19535               SpacesInLineCommentPrefix.Minimum, 2u);
19536   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19537               "  Maximum: 1",
19538               SpacesInLineCommentPrefix.Maximum, 1u);
19539   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
19540 
19541   Style.SpacesInAngles = FormatStyle::SIAS_Always;
19542   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
19543   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
19544               FormatStyle::SIAS_Always);
19545   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
19546   // For backward compatibility:
19547   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
19548   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
19549 }
19550 
19551 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
19552   FormatStyle Style = {};
19553   Style.Language = FormatStyle::LK_Cpp;
19554   CHECK_PARSE("Language: Cpp\n"
19555               "IndentWidth: 12",
19556               IndentWidth, 12u);
19557   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
19558                                "IndentWidth: 34",
19559                                &Style),
19560             ParseError::Unsuitable);
19561   FormatStyle BinPackedTCS = {};
19562   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
19563   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
19564                                "InsertTrailingCommas: Wrapped",
19565                                &BinPackedTCS),
19566             ParseError::BinPackTrailingCommaConflict);
19567   EXPECT_EQ(12u, Style.IndentWidth);
19568   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
19569   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19570 
19571   Style.Language = FormatStyle::LK_JavaScript;
19572   CHECK_PARSE("Language: JavaScript\n"
19573               "IndentWidth: 12",
19574               IndentWidth, 12u);
19575   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
19576   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
19577                                "IndentWidth: 34",
19578                                &Style),
19579             ParseError::Unsuitable);
19580   EXPECT_EQ(23u, Style.IndentWidth);
19581   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
19582   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19583 
19584   CHECK_PARSE("BasedOnStyle: LLVM\n"
19585               "IndentWidth: 67",
19586               IndentWidth, 67u);
19587 
19588   CHECK_PARSE("---\n"
19589               "Language: JavaScript\n"
19590               "IndentWidth: 12\n"
19591               "---\n"
19592               "Language: Cpp\n"
19593               "IndentWidth: 34\n"
19594               "...\n",
19595               IndentWidth, 12u);
19596 
19597   Style.Language = FormatStyle::LK_Cpp;
19598   CHECK_PARSE("---\n"
19599               "Language: JavaScript\n"
19600               "IndentWidth: 12\n"
19601               "---\n"
19602               "Language: Cpp\n"
19603               "IndentWidth: 34\n"
19604               "...\n",
19605               IndentWidth, 34u);
19606   CHECK_PARSE("---\n"
19607               "IndentWidth: 78\n"
19608               "---\n"
19609               "Language: JavaScript\n"
19610               "IndentWidth: 56\n"
19611               "...\n",
19612               IndentWidth, 78u);
19613 
19614   Style.ColumnLimit = 123;
19615   Style.IndentWidth = 234;
19616   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
19617   Style.TabWidth = 345;
19618   EXPECT_FALSE(parseConfiguration("---\n"
19619                                   "IndentWidth: 456\n"
19620                                   "BreakBeforeBraces: Allman\n"
19621                                   "---\n"
19622                                   "Language: JavaScript\n"
19623                                   "IndentWidth: 111\n"
19624                                   "TabWidth: 111\n"
19625                                   "---\n"
19626                                   "Language: Cpp\n"
19627                                   "BreakBeforeBraces: Stroustrup\n"
19628                                   "TabWidth: 789\n"
19629                                   "...\n",
19630                                   &Style));
19631   EXPECT_EQ(123u, Style.ColumnLimit);
19632   EXPECT_EQ(456u, Style.IndentWidth);
19633   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
19634   EXPECT_EQ(789u, Style.TabWidth);
19635 
19636   EXPECT_EQ(parseConfiguration("---\n"
19637                                "Language: JavaScript\n"
19638                                "IndentWidth: 56\n"
19639                                "---\n"
19640                                "IndentWidth: 78\n"
19641                                "...\n",
19642                                &Style),
19643             ParseError::Error);
19644   EXPECT_EQ(parseConfiguration("---\n"
19645                                "Language: JavaScript\n"
19646                                "IndentWidth: 56\n"
19647                                "---\n"
19648                                "Language: JavaScript\n"
19649                                "IndentWidth: 78\n"
19650                                "...\n",
19651                                &Style),
19652             ParseError::Error);
19653 
19654   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19655 }
19656 
19657 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
19658   FormatStyle Style = {};
19659   Style.Language = FormatStyle::LK_JavaScript;
19660   Style.BreakBeforeTernaryOperators = true;
19661   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
19662   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19663 
19664   Style.BreakBeforeTernaryOperators = true;
19665   EXPECT_EQ(0, parseConfiguration("---\n"
19666                                   "BasedOnStyle: Google\n"
19667                                   "---\n"
19668                                   "Language: JavaScript\n"
19669                                   "IndentWidth: 76\n"
19670                                   "...\n",
19671                                   &Style)
19672                    .value());
19673   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19674   EXPECT_EQ(76u, Style.IndentWidth);
19675   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19676 }
19677 
19678 TEST_F(FormatTest, ConfigurationRoundTripTest) {
19679   FormatStyle Style = getLLVMStyle();
19680   std::string YAML = configurationAsText(Style);
19681   FormatStyle ParsedStyle = {};
19682   ParsedStyle.Language = FormatStyle::LK_Cpp;
19683   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
19684   EXPECT_EQ(Style, ParsedStyle);
19685 }
19686 
19687 TEST_F(FormatTest, WorksFor8bitEncodings) {
19688   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
19689             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
19690             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
19691             "\"\xef\xee\xf0\xf3...\"",
19692             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
19693                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
19694                    "\xef\xee\xf0\xf3...\"",
19695                    getLLVMStyleWithColumns(12)));
19696 }
19697 
19698 TEST_F(FormatTest, HandlesUTF8BOM) {
19699   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
19700   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
19701             format("\xef\xbb\xbf#include <iostream>"));
19702   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
19703             format("\xef\xbb\xbf\n#include <iostream>"));
19704 }
19705 
19706 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
19707 #if !defined(_MSC_VER)
19708 
19709 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
19710   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
19711                getLLVMStyleWithColumns(35));
19712   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
19713                getLLVMStyleWithColumns(31));
19714   verifyFormat("// Однажды в студёную зимнюю пору...",
19715                getLLVMStyleWithColumns(36));
19716   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
19717   verifyFormat("/* Однажды в студёную зимнюю пору... */",
19718                getLLVMStyleWithColumns(39));
19719   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
19720                getLLVMStyleWithColumns(35));
19721 }
19722 
19723 TEST_F(FormatTest, SplitsUTF8Strings) {
19724   // Non-printable characters' width is currently considered to be the length in
19725   // bytes in UTF8. The characters can be displayed in very different manner
19726   // (zero-width, single width with a substitution glyph, expanded to their code
19727   // (e.g. "<8d>"), so there's no single correct way to handle them.
19728   EXPECT_EQ("\"aaaaÄ\"\n"
19729             "\"\xc2\x8d\";",
19730             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19731   EXPECT_EQ("\"aaaaaaaÄ\"\n"
19732             "\"\xc2\x8d\";",
19733             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19734   EXPECT_EQ("\"Однажды, в \"\n"
19735             "\"студёную \"\n"
19736             "\"зимнюю \"\n"
19737             "\"пору,\"",
19738             format("\"Однажды, в студёную зимнюю пору,\"",
19739                    getLLVMStyleWithColumns(13)));
19740   EXPECT_EQ(
19741       "\"一 二 三 \"\n"
19742       "\"四 五六 \"\n"
19743       "\"七 八 九 \"\n"
19744       "\"十\"",
19745       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
19746   EXPECT_EQ("\"一\t\"\n"
19747             "\"二 \t\"\n"
19748             "\"三 四 \"\n"
19749             "\"五\t\"\n"
19750             "\"六 \t\"\n"
19751             "\"七 \"\n"
19752             "\"八九十\tqq\"",
19753             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
19754                    getLLVMStyleWithColumns(11)));
19755 
19756   // UTF8 character in an escape sequence.
19757   EXPECT_EQ("\"aaaaaa\"\n"
19758             "\"\\\xC2\x8D\"",
19759             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
19760 }
19761 
19762 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
19763   EXPECT_EQ("const char *sssss =\n"
19764             "    \"一二三四五六七八\\\n"
19765             " 九 十\";",
19766             format("const char *sssss = \"一二三四五六七八\\\n"
19767                    " 九 十\";",
19768                    getLLVMStyleWithColumns(30)));
19769 }
19770 
19771 TEST_F(FormatTest, SplitsUTF8LineComments) {
19772   EXPECT_EQ("// aaaaÄ\xc2\x8d",
19773             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
19774   EXPECT_EQ("// Я из лесу\n"
19775             "// вышел; был\n"
19776             "// сильный\n"
19777             "// мороз.",
19778             format("// Я из лесу вышел; был сильный мороз.",
19779                    getLLVMStyleWithColumns(13)));
19780   EXPECT_EQ("// 一二三\n"
19781             "// 四五六七\n"
19782             "// 八  九\n"
19783             "// 十",
19784             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
19785 }
19786 
19787 TEST_F(FormatTest, SplitsUTF8BlockComments) {
19788   EXPECT_EQ("/* Гляжу,\n"
19789             " * поднимается\n"
19790             " * медленно в\n"
19791             " * гору\n"
19792             " * Лошадка,\n"
19793             " * везущая\n"
19794             " * хворосту\n"
19795             " * воз. */",
19796             format("/* Гляжу, поднимается медленно в гору\n"
19797                    " * Лошадка, везущая хворосту воз. */",
19798                    getLLVMStyleWithColumns(13)));
19799   EXPECT_EQ(
19800       "/* 一二三\n"
19801       " * 四五六七\n"
19802       " * 八  九\n"
19803       " * 十  */",
19804       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
19805   EXPECT_EQ("/* �������� ��������\n"
19806             " * ��������\n"
19807             " * ������-�� */",
19808             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
19809 }
19810 
19811 #endif // _MSC_VER
19812 
19813 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
19814   FormatStyle Style = getLLVMStyle();
19815 
19816   Style.ConstructorInitializerIndentWidth = 4;
19817   verifyFormat(
19818       "SomeClass::Constructor()\n"
19819       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19820       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19821       Style);
19822 
19823   Style.ConstructorInitializerIndentWidth = 2;
19824   verifyFormat(
19825       "SomeClass::Constructor()\n"
19826       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19827       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19828       Style);
19829 
19830   Style.ConstructorInitializerIndentWidth = 0;
19831   verifyFormat(
19832       "SomeClass::Constructor()\n"
19833       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19834       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19835       Style);
19836   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19837   verifyFormat(
19838       "SomeLongTemplateVariableName<\n"
19839       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
19840       Style);
19841   verifyFormat("bool smaller = 1 < "
19842                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
19843                "                       "
19844                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
19845                Style);
19846 
19847   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
19848   verifyFormat("SomeClass::Constructor() :\n"
19849                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
19850                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
19851                Style);
19852 }
19853 
19854 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
19855   FormatStyle Style = getLLVMStyle();
19856   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
19857   Style.ConstructorInitializerIndentWidth = 4;
19858   verifyFormat("SomeClass::Constructor()\n"
19859                "    : a(a)\n"
19860                "    , b(b)\n"
19861                "    , c(c) {}",
19862                Style);
19863   verifyFormat("SomeClass::Constructor()\n"
19864                "    : a(a) {}",
19865                Style);
19866 
19867   Style.ColumnLimit = 0;
19868   verifyFormat("SomeClass::Constructor()\n"
19869                "    : a(a) {}",
19870                Style);
19871   verifyFormat("SomeClass::Constructor() noexcept\n"
19872                "    : a(a) {}",
19873                Style);
19874   verifyFormat("SomeClass::Constructor()\n"
19875                "    : a(a)\n"
19876                "    , b(b)\n"
19877                "    , c(c) {}",
19878                Style);
19879   verifyFormat("SomeClass::Constructor()\n"
19880                "    : a(a) {\n"
19881                "  foo();\n"
19882                "  bar();\n"
19883                "}",
19884                Style);
19885 
19886   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
19887   verifyFormat("SomeClass::Constructor()\n"
19888                "    : a(a)\n"
19889                "    , b(b)\n"
19890                "    , c(c) {\n}",
19891                Style);
19892   verifyFormat("SomeClass::Constructor()\n"
19893                "    : a(a) {\n}",
19894                Style);
19895 
19896   Style.ColumnLimit = 80;
19897   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
19898   Style.ConstructorInitializerIndentWidth = 2;
19899   verifyFormat("SomeClass::Constructor()\n"
19900                "  : a(a)\n"
19901                "  , b(b)\n"
19902                "  , c(c) {}",
19903                Style);
19904 
19905   Style.ConstructorInitializerIndentWidth = 0;
19906   verifyFormat("SomeClass::Constructor()\n"
19907                ": a(a)\n"
19908                ", b(b)\n"
19909                ", c(c) {}",
19910                Style);
19911 
19912   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
19913   Style.ConstructorInitializerIndentWidth = 4;
19914   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
19915   verifyFormat(
19916       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
19917       Style);
19918   verifyFormat(
19919       "SomeClass::Constructor()\n"
19920       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
19921       Style);
19922   Style.ConstructorInitializerIndentWidth = 4;
19923   Style.ColumnLimit = 60;
19924   verifyFormat("SomeClass::Constructor()\n"
19925                "    : aaaaaaaa(aaaaaaaa)\n"
19926                "    , aaaaaaaa(aaaaaaaa)\n"
19927                "    , aaaaaaaa(aaaaaaaa) {}",
19928                Style);
19929 }
19930 
19931 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
19932   FormatStyle Style = getLLVMStyle();
19933   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
19934   Style.ConstructorInitializerIndentWidth = 4;
19935   verifyFormat("SomeClass::Constructor()\n"
19936                "    : a{a}\n"
19937                "    , b{b} {}",
19938                Style);
19939   verifyFormat("SomeClass::Constructor()\n"
19940                "    : a{a}\n"
19941                "#if CONDITION\n"
19942                "    , b{b}\n"
19943                "#endif\n"
19944                "{\n}",
19945                Style);
19946   Style.ConstructorInitializerIndentWidth = 2;
19947   verifyFormat("SomeClass::Constructor()\n"
19948                "#if CONDITION\n"
19949                "  : a{a}\n"
19950                "#endif\n"
19951                "  , b{b}\n"
19952                "  , c{c} {\n}",
19953                Style);
19954   Style.ConstructorInitializerIndentWidth = 0;
19955   verifyFormat("SomeClass::Constructor()\n"
19956                ": a{a}\n"
19957                "#ifdef CONDITION\n"
19958                ", b{b}\n"
19959                "#else\n"
19960                ", c{c}\n"
19961                "#endif\n"
19962                ", d{d} {\n}",
19963                Style);
19964   Style.ConstructorInitializerIndentWidth = 4;
19965   verifyFormat("SomeClass::Constructor()\n"
19966                "    : a{a}\n"
19967                "#if WINDOWS\n"
19968                "#if DEBUG\n"
19969                "    , b{0}\n"
19970                "#else\n"
19971                "    , b{1}\n"
19972                "#endif\n"
19973                "#else\n"
19974                "#if DEBUG\n"
19975                "    , b{2}\n"
19976                "#else\n"
19977                "    , b{3}\n"
19978                "#endif\n"
19979                "#endif\n"
19980                "{\n}",
19981                Style);
19982   verifyFormat("SomeClass::Constructor()\n"
19983                "    : a{a}\n"
19984                "#if WINDOWS\n"
19985                "    , b{0}\n"
19986                "#if DEBUG\n"
19987                "    , c{0}\n"
19988                "#else\n"
19989                "    , c{1}\n"
19990                "#endif\n"
19991                "#else\n"
19992                "#if DEBUG\n"
19993                "    , c{2}\n"
19994                "#else\n"
19995                "    , c{3}\n"
19996                "#endif\n"
19997                "    , b{1}\n"
19998                "#endif\n"
19999                "{\n}",
20000                Style);
20001 }
20002 
20003 TEST_F(FormatTest, Destructors) {
20004   verifyFormat("void F(int &i) { i.~int(); }");
20005   verifyFormat("void F(int &i) { i->~int(); }");
20006 }
20007 
20008 TEST_F(FormatTest, FormatsWithWebKitStyle) {
20009   FormatStyle Style = getWebKitStyle();
20010 
20011   // Don't indent in outer namespaces.
20012   verifyFormat("namespace outer {\n"
20013                "int i;\n"
20014                "namespace inner {\n"
20015                "    int i;\n"
20016                "} // namespace inner\n"
20017                "} // namespace outer\n"
20018                "namespace other_outer {\n"
20019                "int i;\n"
20020                "}",
20021                Style);
20022 
20023   // Don't indent case labels.
20024   verifyFormat("switch (variable) {\n"
20025                "case 1:\n"
20026                "case 2:\n"
20027                "    doSomething();\n"
20028                "    break;\n"
20029                "default:\n"
20030                "    ++variable;\n"
20031                "}",
20032                Style);
20033 
20034   // Wrap before binary operators.
20035   EXPECT_EQ("void f()\n"
20036             "{\n"
20037             "    if (aaaaaaaaaaaaaaaa\n"
20038             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
20039             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20040             "        return;\n"
20041             "}",
20042             format("void f() {\n"
20043                    "if (aaaaaaaaaaaaaaaa\n"
20044                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
20045                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20046                    "return;\n"
20047                    "}",
20048                    Style));
20049 
20050   // Allow functions on a single line.
20051   verifyFormat("void f() { return; }", Style);
20052 
20053   // Allow empty blocks on a single line and insert a space in empty blocks.
20054   EXPECT_EQ("void f() { }", format("void f() {}", Style));
20055   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
20056   // However, don't merge non-empty short loops.
20057   EXPECT_EQ("while (true) {\n"
20058             "    continue;\n"
20059             "}",
20060             format("while (true) { continue; }", Style));
20061 
20062   // Constructor initializers are formatted one per line with the "," on the
20063   // new line.
20064   verifyFormat("Constructor()\n"
20065                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
20066                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
20067                "          aaaaaaaaaaaaaa)\n"
20068                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
20069                "{\n"
20070                "}",
20071                Style);
20072   verifyFormat("SomeClass::Constructor()\n"
20073                "    : a(a)\n"
20074                "{\n"
20075                "}",
20076                Style);
20077   EXPECT_EQ("SomeClass::Constructor()\n"
20078             "    : a(a)\n"
20079             "{\n"
20080             "}",
20081             format("SomeClass::Constructor():a(a){}", Style));
20082   verifyFormat("SomeClass::Constructor()\n"
20083                "    : a(a)\n"
20084                "    , b(b)\n"
20085                "    , c(c)\n"
20086                "{\n"
20087                "}",
20088                Style);
20089   verifyFormat("SomeClass::Constructor()\n"
20090                "    : a(a)\n"
20091                "{\n"
20092                "    foo();\n"
20093                "    bar();\n"
20094                "}",
20095                Style);
20096 
20097   // Access specifiers should be aligned left.
20098   verifyFormat("class C {\n"
20099                "public:\n"
20100                "    int i;\n"
20101                "};",
20102                Style);
20103 
20104   // Do not align comments.
20105   verifyFormat("int a; // Do not\n"
20106                "double b; // align comments.",
20107                Style);
20108 
20109   // Do not align operands.
20110   EXPECT_EQ("ASSERT(aaaa\n"
20111             "    || bbbb);",
20112             format("ASSERT ( aaaa\n||bbbb);", Style));
20113 
20114   // Accept input's line breaks.
20115   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
20116             "    || bbbbbbbbbbbbbbb) {\n"
20117             "    i++;\n"
20118             "}",
20119             format("if (aaaaaaaaaaaaaaa\n"
20120                    "|| bbbbbbbbbbbbbbb) { i++; }",
20121                    Style));
20122   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
20123             "    i++;\n"
20124             "}",
20125             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
20126 
20127   // Don't automatically break all macro definitions (llvm.org/PR17842).
20128   verifyFormat("#define aNumber 10", Style);
20129   // However, generally keep the line breaks that the user authored.
20130   EXPECT_EQ("#define aNumber \\\n"
20131             "    10",
20132             format("#define aNumber \\\n"
20133                    " 10",
20134                    Style));
20135 
20136   // Keep empty and one-element array literals on a single line.
20137   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
20138             "                                  copyItems:YES];",
20139             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
20140                    "copyItems:YES];",
20141                    Style));
20142   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
20143             "                                  copyItems:YES];",
20144             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
20145                    "             copyItems:YES];",
20146                    Style));
20147   // FIXME: This does not seem right, there should be more indentation before
20148   // the array literal's entries. Nested blocks have the same problem.
20149   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20150             "    @\"a\",\n"
20151             "    @\"a\"\n"
20152             "]\n"
20153             "                                  copyItems:YES];",
20154             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20155                    "     @\"a\",\n"
20156                    "     @\"a\"\n"
20157                    "     ]\n"
20158                    "       copyItems:YES];",
20159                    Style));
20160   EXPECT_EQ(
20161       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20162       "                                  copyItems:YES];",
20163       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20164              "   copyItems:YES];",
20165              Style));
20166 
20167   verifyFormat("[self.a b:c c:d];", Style);
20168   EXPECT_EQ("[self.a b:c\n"
20169             "        c:d];",
20170             format("[self.a b:c\n"
20171                    "c:d];",
20172                    Style));
20173 }
20174 
20175 TEST_F(FormatTest, FormatsLambdas) {
20176   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
20177   verifyFormat(
20178       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
20179   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
20180   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
20181   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
20182   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
20183   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
20184   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
20185   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
20186   verifyFormat("int x = f(*+[] {});");
20187   verifyFormat("void f() {\n"
20188                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
20189                "}\n");
20190   verifyFormat("void f() {\n"
20191                "  other(x.begin(), //\n"
20192                "        x.end(),   //\n"
20193                "        [&](int, int) { return 1; });\n"
20194                "}\n");
20195   verifyFormat("void f() {\n"
20196                "  other.other.other.other.other(\n"
20197                "      x.begin(), x.end(),\n"
20198                "      [something, rather](int, int, int, int, int, int, int) { "
20199                "return 1; });\n"
20200                "}\n");
20201   verifyFormat(
20202       "void f() {\n"
20203       "  other.other.other.other.other(\n"
20204       "      x.begin(), x.end(),\n"
20205       "      [something, rather](int, int, int, int, int, int, int) {\n"
20206       "        //\n"
20207       "      });\n"
20208       "}\n");
20209   verifyFormat("SomeFunction([]() { // A cool function...\n"
20210                "  return 43;\n"
20211                "});");
20212   EXPECT_EQ("SomeFunction([]() {\n"
20213             "#define A a\n"
20214             "  return 43;\n"
20215             "});",
20216             format("SomeFunction([](){\n"
20217                    "#define A a\n"
20218                    "return 43;\n"
20219                    "});"));
20220   verifyFormat("void f() {\n"
20221                "  SomeFunction([](decltype(x), A *a) {});\n"
20222                "  SomeFunction([](typeof(x), A *a) {});\n"
20223                "  SomeFunction([](_Atomic(x), A *a) {});\n"
20224                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
20225                "}");
20226   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20227                "    [](const aaaaaaaaaa &a) { return a; });");
20228   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
20229                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
20230                "});");
20231   verifyFormat("Constructor()\n"
20232                "    : Field([] { // comment\n"
20233                "        int i;\n"
20234                "      }) {}");
20235   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
20236                "  return some_parameter.size();\n"
20237                "};");
20238   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
20239                "    [](const string &s) { return s; };");
20240   verifyFormat("int i = aaaaaa ? 1 //\n"
20241                "               : [] {\n"
20242                "                   return 2; //\n"
20243                "                 }();");
20244   verifyFormat("llvm::errs() << \"number of twos is \"\n"
20245                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
20246                "                  return x == 2; // force break\n"
20247                "                });");
20248   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20249                "    [=](int iiiiiiiiiiii) {\n"
20250                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
20251                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
20252                "    });",
20253                getLLVMStyleWithColumns(60));
20254 
20255   verifyFormat("SomeFunction({[&] {\n"
20256                "                // comment\n"
20257                "              },\n"
20258                "              [&] {\n"
20259                "                // comment\n"
20260                "              }});");
20261   verifyFormat("SomeFunction({[&] {\n"
20262                "  // comment\n"
20263                "}});");
20264   verifyFormat(
20265       "virtual aaaaaaaaaaaaaaaa(\n"
20266       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
20267       "    aaaaa aaaaaaaaa);");
20268 
20269   // Lambdas with return types.
20270   verifyFormat("int c = []() -> int { return 2; }();\n");
20271   verifyFormat("int c = []() -> int * { return 2; }();\n");
20272   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
20273   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
20274   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
20275   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
20276   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
20277   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
20278   verifyFormat("[a, a]() -> a<1> {};");
20279   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
20280   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
20281   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
20282   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
20283   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
20284   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
20285   verifyFormat("[]() -> foo<!5> { return {}; };");
20286   verifyFormat("[]() -> foo<~5> { return {}; };");
20287   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
20288   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
20289   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
20290   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
20291   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
20292   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
20293   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
20294   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
20295   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
20296   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
20297   verifyFormat("namespace bar {\n"
20298                "// broken:\n"
20299                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
20300                "} // namespace bar");
20301   verifyFormat("namespace bar {\n"
20302                "// broken:\n"
20303                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
20304                "} // namespace bar");
20305   verifyFormat("namespace bar {\n"
20306                "// broken:\n"
20307                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
20308                "} // namespace bar");
20309   verifyFormat("namespace bar {\n"
20310                "// broken:\n"
20311                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
20312                "} // namespace bar");
20313   verifyFormat("namespace bar {\n"
20314                "// broken:\n"
20315                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
20316                "} // namespace bar");
20317   verifyFormat("namespace bar {\n"
20318                "// broken:\n"
20319                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
20320                "} // namespace bar");
20321   verifyFormat("namespace bar {\n"
20322                "// broken:\n"
20323                "auto foo{[]() -> foo<!5> { return {}; }};\n"
20324                "} // namespace bar");
20325   verifyFormat("namespace bar {\n"
20326                "// broken:\n"
20327                "auto foo{[]() -> foo<~5> { return {}; }};\n"
20328                "} // namespace bar");
20329   verifyFormat("namespace bar {\n"
20330                "// broken:\n"
20331                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
20332                "} // namespace bar");
20333   verifyFormat("namespace bar {\n"
20334                "// broken:\n"
20335                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
20336                "} // namespace bar");
20337   verifyFormat("namespace bar {\n"
20338                "// broken:\n"
20339                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
20340                "} // namespace bar");
20341   verifyFormat("namespace bar {\n"
20342                "// broken:\n"
20343                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
20344                "} // namespace bar");
20345   verifyFormat("namespace bar {\n"
20346                "// broken:\n"
20347                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
20348                "} // namespace bar");
20349   verifyFormat("namespace bar {\n"
20350                "// broken:\n"
20351                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
20352                "} // namespace bar");
20353   verifyFormat("namespace bar {\n"
20354                "// broken:\n"
20355                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
20356                "} // namespace bar");
20357   verifyFormat("namespace bar {\n"
20358                "// broken:\n"
20359                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
20360                "} // namespace bar");
20361   verifyFormat("namespace bar {\n"
20362                "// broken:\n"
20363                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
20364                "} // namespace bar");
20365   verifyFormat("namespace bar {\n"
20366                "// broken:\n"
20367                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
20368                "} // namespace bar");
20369   verifyFormat("[]() -> a<1> {};");
20370   verifyFormat("[]() -> a<1> { ; };");
20371   verifyFormat("[]() -> a<1> { ; }();");
20372   verifyFormat("[a, a]() -> a<true> {};");
20373   verifyFormat("[]() -> a<true> {};");
20374   verifyFormat("[]() -> a<true> { ; };");
20375   verifyFormat("[]() -> a<true> { ; }();");
20376   verifyFormat("[a, a]() -> a<false> {};");
20377   verifyFormat("[]() -> a<false> {};");
20378   verifyFormat("[]() -> a<false> { ; };");
20379   verifyFormat("[]() -> a<false> { ; }();");
20380   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
20381   verifyFormat("namespace bar {\n"
20382                "auto foo{[]() -> foo<false> { ; }};\n"
20383                "} // namespace bar");
20384   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
20385                "                   int j) -> int {\n"
20386                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
20387                "};");
20388   verifyFormat(
20389       "aaaaaaaaaaaaaaaaaaaaaa(\n"
20390       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
20391       "      return aaaaaaaaaaaaaaaaa;\n"
20392       "    });",
20393       getLLVMStyleWithColumns(70));
20394   verifyFormat("[]() //\n"
20395                "    -> int {\n"
20396                "  return 1; //\n"
20397                "};");
20398   verifyFormat("[]() -> Void<T...> {};");
20399   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
20400   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
20401   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
20402   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
20403   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
20404   verifyFormat("return int{[x = x]() { return x; }()};");
20405 
20406   // Lambdas with explicit template argument lists.
20407   verifyFormat(
20408       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
20409 
20410   // Multiple lambdas in the same parentheses change indentation rules. These
20411   // lambdas are forced to start on new lines.
20412   verifyFormat("SomeFunction(\n"
20413                "    []() {\n"
20414                "      //\n"
20415                "    },\n"
20416                "    []() {\n"
20417                "      //\n"
20418                "    });");
20419 
20420   // A lambda passed as arg0 is always pushed to the next line.
20421   verifyFormat("SomeFunction(\n"
20422                "    [this] {\n"
20423                "      //\n"
20424                "    },\n"
20425                "    1);\n");
20426 
20427   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
20428   // the arg0 case above.
20429   auto Style = getGoogleStyle();
20430   Style.BinPackArguments = false;
20431   verifyFormat("SomeFunction(\n"
20432                "    a,\n"
20433                "    [this] {\n"
20434                "      //\n"
20435                "    },\n"
20436                "    b);\n",
20437                Style);
20438   verifyFormat("SomeFunction(\n"
20439                "    a,\n"
20440                "    [this] {\n"
20441                "      //\n"
20442                "    },\n"
20443                "    b);\n");
20444 
20445   // A lambda with a very long line forces arg0 to be pushed out irrespective of
20446   // the BinPackArguments value (as long as the code is wide enough).
20447   verifyFormat(
20448       "something->SomeFunction(\n"
20449       "    a,\n"
20450       "    [this] {\n"
20451       "      "
20452       "D0000000000000000000000000000000000000000000000000000000000001();\n"
20453       "    },\n"
20454       "    b);\n");
20455 
20456   // A multi-line lambda is pulled up as long as the introducer fits on the
20457   // previous line and there are no further args.
20458   verifyFormat("function(1, [this, that] {\n"
20459                "  //\n"
20460                "});\n");
20461   verifyFormat("function([this, that] {\n"
20462                "  //\n"
20463                "});\n");
20464   // FIXME: this format is not ideal and we should consider forcing the first
20465   // arg onto its own line.
20466   verifyFormat("function(a, b, c, //\n"
20467                "         d, [this, that] {\n"
20468                "           //\n"
20469                "         });\n");
20470 
20471   // Multiple lambdas are treated correctly even when there is a short arg0.
20472   verifyFormat("SomeFunction(\n"
20473                "    1,\n"
20474                "    [this] {\n"
20475                "      //\n"
20476                "    },\n"
20477                "    [this] {\n"
20478                "      //\n"
20479                "    },\n"
20480                "    1);\n");
20481 
20482   // More complex introducers.
20483   verifyFormat("return [i, args...] {};");
20484 
20485   // Not lambdas.
20486   verifyFormat("constexpr char hello[]{\"hello\"};");
20487   verifyFormat("double &operator[](int i) { return 0; }\n"
20488                "int i;");
20489   verifyFormat("std::unique_ptr<int[]> foo() {}");
20490   verifyFormat("int i = a[a][a]->f();");
20491   verifyFormat("int i = (*b)[a]->f();");
20492 
20493   // Other corner cases.
20494   verifyFormat("void f() {\n"
20495                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
20496                "  );\n"
20497                "}");
20498 
20499   // Lambdas created through weird macros.
20500   verifyFormat("void f() {\n"
20501                "  MACRO((const AA &a) { return 1; });\n"
20502                "  MACRO((AA &a) { return 1; });\n"
20503                "}");
20504 
20505   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
20506                "      doo_dah();\n"
20507                "      doo_dah();\n"
20508                "    })) {\n"
20509                "}");
20510   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
20511                "                doo_dah();\n"
20512                "                doo_dah();\n"
20513                "              })) {\n"
20514                "}");
20515   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
20516                "                doo_dah();\n"
20517                "                doo_dah();\n"
20518                "              })) {\n"
20519                "}");
20520   verifyFormat("auto lambda = []() {\n"
20521                "  int a = 2\n"
20522                "#if A\n"
20523                "          + 2\n"
20524                "#endif\n"
20525                "      ;\n"
20526                "};");
20527 
20528   // Lambdas with complex multiline introducers.
20529   verifyFormat(
20530       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20531       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
20532       "        -> ::std::unordered_set<\n"
20533       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
20534       "      //\n"
20535       "    });");
20536 
20537   FormatStyle DoNotMerge = getLLVMStyle();
20538   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
20539   verifyFormat("auto c = []() {\n"
20540                "  return b;\n"
20541                "};",
20542                "auto c = []() { return b; };", DoNotMerge);
20543   verifyFormat("auto c = []() {\n"
20544                "};",
20545                " auto c = []() {};", DoNotMerge);
20546 
20547   FormatStyle MergeEmptyOnly = getLLVMStyle();
20548   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
20549   verifyFormat("auto c = []() {\n"
20550                "  return b;\n"
20551                "};",
20552                "auto c = []() {\n"
20553                "  return b;\n"
20554                " };",
20555                MergeEmptyOnly);
20556   verifyFormat("auto c = []() {};",
20557                "auto c = []() {\n"
20558                "};",
20559                MergeEmptyOnly);
20560 
20561   FormatStyle MergeInline = getLLVMStyle();
20562   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
20563   verifyFormat("auto c = []() {\n"
20564                "  return b;\n"
20565                "};",
20566                "auto c = []() { return b; };", MergeInline);
20567   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
20568                MergeInline);
20569   verifyFormat("function([]() { return b; }, a)",
20570                "function([]() { return b; }, a)", MergeInline);
20571   verifyFormat("function(a, []() { return b; })",
20572                "function(a, []() { return b; })", MergeInline);
20573 
20574   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
20575   // AllowShortLambdasOnASingleLine
20576   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
20577   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
20578   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
20579   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20580       FormatStyle::ShortLambdaStyle::SLS_None;
20581   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
20582                "    []()\n"
20583                "    {\n"
20584                "      return 17;\n"
20585                "    });",
20586                LLVMWithBeforeLambdaBody);
20587   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
20588                "    []()\n"
20589                "    {\n"
20590                "    });",
20591                LLVMWithBeforeLambdaBody);
20592   verifyFormat("auto fct_SLS_None = []()\n"
20593                "{\n"
20594                "  return 17;\n"
20595                "};",
20596                LLVMWithBeforeLambdaBody);
20597   verifyFormat("TwoNestedLambdas_SLS_None(\n"
20598                "    []()\n"
20599                "    {\n"
20600                "      return Call(\n"
20601                "          []()\n"
20602                "          {\n"
20603                "            return 17;\n"
20604                "          });\n"
20605                "    });",
20606                LLVMWithBeforeLambdaBody);
20607   verifyFormat("void Fct() {\n"
20608                "  return {[]()\n"
20609                "          {\n"
20610                "            return 17;\n"
20611                "          }};\n"
20612                "}",
20613                LLVMWithBeforeLambdaBody);
20614 
20615   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20616       FormatStyle::ShortLambdaStyle::SLS_Empty;
20617   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
20618                "    []()\n"
20619                "    {\n"
20620                "      return 17;\n"
20621                "    });",
20622                LLVMWithBeforeLambdaBody);
20623   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
20624                LLVMWithBeforeLambdaBody);
20625   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
20626                "ongFunctionName_SLS_Empty(\n"
20627                "    []() {});",
20628                LLVMWithBeforeLambdaBody);
20629   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
20630                "                                []()\n"
20631                "                                {\n"
20632                "                                  return 17;\n"
20633                "                                });",
20634                LLVMWithBeforeLambdaBody);
20635   verifyFormat("auto fct_SLS_Empty = []()\n"
20636                "{\n"
20637                "  return 17;\n"
20638                "};",
20639                LLVMWithBeforeLambdaBody);
20640   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
20641                "    []()\n"
20642                "    {\n"
20643                "      return Call([]() {});\n"
20644                "    });",
20645                LLVMWithBeforeLambdaBody);
20646   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
20647                "                           []()\n"
20648                "                           {\n"
20649                "                             return Call([]() {});\n"
20650                "                           });",
20651                LLVMWithBeforeLambdaBody);
20652   verifyFormat(
20653       "FctWithLongLineInLambda_SLS_Empty(\n"
20654       "    []()\n"
20655       "    {\n"
20656       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20657       "                               AndShouldNotBeConsiderAsInline,\n"
20658       "                               LambdaBodyMustBeBreak);\n"
20659       "    });",
20660       LLVMWithBeforeLambdaBody);
20661 
20662   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20663       FormatStyle::ShortLambdaStyle::SLS_Inline;
20664   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
20665                LLVMWithBeforeLambdaBody);
20666   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
20667                LLVMWithBeforeLambdaBody);
20668   verifyFormat("auto fct_SLS_Inline = []()\n"
20669                "{\n"
20670                "  return 17;\n"
20671                "};",
20672                LLVMWithBeforeLambdaBody);
20673   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
20674                "17; }); });",
20675                LLVMWithBeforeLambdaBody);
20676   verifyFormat(
20677       "FctWithLongLineInLambda_SLS_Inline(\n"
20678       "    []()\n"
20679       "    {\n"
20680       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20681       "                               AndShouldNotBeConsiderAsInline,\n"
20682       "                               LambdaBodyMustBeBreak);\n"
20683       "    });",
20684       LLVMWithBeforeLambdaBody);
20685   verifyFormat("FctWithMultipleParams_SLS_Inline("
20686                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20687                "                                 []() { return 17; });",
20688                LLVMWithBeforeLambdaBody);
20689   verifyFormat(
20690       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
20691       LLVMWithBeforeLambdaBody);
20692 
20693   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20694       FormatStyle::ShortLambdaStyle::SLS_All;
20695   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
20696                LLVMWithBeforeLambdaBody);
20697   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
20698                LLVMWithBeforeLambdaBody);
20699   verifyFormat("auto fct_SLS_All = []() { return 17; };",
20700                LLVMWithBeforeLambdaBody);
20701   verifyFormat("FctWithOneParam_SLS_All(\n"
20702                "    []()\n"
20703                "    {\n"
20704                "      // A cool function...\n"
20705                "      return 43;\n"
20706                "    });",
20707                LLVMWithBeforeLambdaBody);
20708   verifyFormat("FctWithMultipleParams_SLS_All("
20709                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20710                "                              []() { return 17; });",
20711                LLVMWithBeforeLambdaBody);
20712   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
20713                LLVMWithBeforeLambdaBody);
20714   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
20715                LLVMWithBeforeLambdaBody);
20716   verifyFormat(
20717       "FctWithLongLineInLambda_SLS_All(\n"
20718       "    []()\n"
20719       "    {\n"
20720       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20721       "                               AndShouldNotBeConsiderAsInline,\n"
20722       "                               LambdaBodyMustBeBreak);\n"
20723       "    });",
20724       LLVMWithBeforeLambdaBody);
20725   verifyFormat(
20726       "auto fct_SLS_All = []()\n"
20727       "{\n"
20728       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20729       "                           AndShouldNotBeConsiderAsInline,\n"
20730       "                           LambdaBodyMustBeBreak);\n"
20731       "};",
20732       LLVMWithBeforeLambdaBody);
20733   LLVMWithBeforeLambdaBody.BinPackParameters = false;
20734   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
20735                LLVMWithBeforeLambdaBody);
20736   verifyFormat(
20737       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
20738       "                                FirstParam,\n"
20739       "                                SecondParam,\n"
20740       "                                ThirdParam,\n"
20741       "                                FourthParam);",
20742       LLVMWithBeforeLambdaBody);
20743   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20744                "    []() { return "
20745                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
20746                "    FirstParam,\n"
20747                "    SecondParam,\n"
20748                "    ThirdParam,\n"
20749                "    FourthParam);",
20750                LLVMWithBeforeLambdaBody);
20751   verifyFormat(
20752       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
20753       "                                SecondParam,\n"
20754       "                                ThirdParam,\n"
20755       "                                FourthParam,\n"
20756       "                                []() { return SomeValueNotSoLong; });",
20757       LLVMWithBeforeLambdaBody);
20758   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20759                "    []()\n"
20760                "    {\n"
20761                "      return "
20762                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
20763                "eConsiderAsInline;\n"
20764                "    });",
20765                LLVMWithBeforeLambdaBody);
20766   verifyFormat(
20767       "FctWithLongLineInLambda_SLS_All(\n"
20768       "    []()\n"
20769       "    {\n"
20770       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20771       "                               AndShouldNotBeConsiderAsInline,\n"
20772       "                               LambdaBodyMustBeBreak);\n"
20773       "    });",
20774       LLVMWithBeforeLambdaBody);
20775   verifyFormat("FctWithTwoParams_SLS_All(\n"
20776                "    []()\n"
20777                "    {\n"
20778                "      // A cool function...\n"
20779                "      return 43;\n"
20780                "    },\n"
20781                "    87);",
20782                LLVMWithBeforeLambdaBody);
20783   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
20784                LLVMWithBeforeLambdaBody);
20785   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
20786                LLVMWithBeforeLambdaBody);
20787   verifyFormat(
20788       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
20789       LLVMWithBeforeLambdaBody);
20790   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
20791                "}); }, x);",
20792                LLVMWithBeforeLambdaBody);
20793   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20794                "    []()\n"
20795                "    {\n"
20796                "      // A cool function...\n"
20797                "      return Call([]() { return 17; });\n"
20798                "    });",
20799                LLVMWithBeforeLambdaBody);
20800   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20801                "    []()\n"
20802                "    {\n"
20803                "      return Call(\n"
20804                "          []()\n"
20805                "          {\n"
20806                "            // A cool function...\n"
20807                "            return 17;\n"
20808                "          });\n"
20809                "    });",
20810                LLVMWithBeforeLambdaBody);
20811 
20812   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20813       FormatStyle::ShortLambdaStyle::SLS_None;
20814 
20815   verifyFormat("auto select = [this]() -> const Library::Object *\n"
20816                "{\n"
20817                "  return MyAssignment::SelectFromList(this);\n"
20818                "};\n",
20819                LLVMWithBeforeLambdaBody);
20820 
20821   verifyFormat("auto select = [this]() -> const Library::Object &\n"
20822                "{\n"
20823                "  return MyAssignment::SelectFromList(this);\n"
20824                "};\n",
20825                LLVMWithBeforeLambdaBody);
20826 
20827   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
20828                "{\n"
20829                "  return MyAssignment::SelectFromList(this);\n"
20830                "};\n",
20831                LLVMWithBeforeLambdaBody);
20832 
20833   verifyFormat("namespace test {\n"
20834                "class Test {\n"
20835                "public:\n"
20836                "  Test() = default;\n"
20837                "};\n"
20838                "} // namespace test",
20839                LLVMWithBeforeLambdaBody);
20840 
20841   // Lambdas with different indentation styles.
20842   Style = getLLVMStyleWithColumns(100);
20843   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20844             "  return promise.then(\n"
20845             "      [this, &someVariable, someObject = "
20846             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20847             "        return someObject.startAsyncAction().then(\n"
20848             "            [this, &someVariable](AsyncActionResult result) "
20849             "mutable { result.processMore(); });\n"
20850             "      });\n"
20851             "}\n",
20852             format("SomeResult doSomething(SomeObject promise) {\n"
20853                    "  return promise.then([this, &someVariable, someObject = "
20854                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20855                    "    return someObject.startAsyncAction().then([this, "
20856                    "&someVariable](AsyncActionResult result) mutable {\n"
20857                    "      result.processMore();\n"
20858                    "    });\n"
20859                    "  });\n"
20860                    "}\n",
20861                    Style));
20862   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20863   verifyFormat("test() {\n"
20864                "  ([]() -> {\n"
20865                "    int b = 32;\n"
20866                "    return 3;\n"
20867                "  }).foo();\n"
20868                "}",
20869                Style);
20870   verifyFormat("test() {\n"
20871                "  []() -> {\n"
20872                "    int b = 32;\n"
20873                "    return 3;\n"
20874                "  }\n"
20875                "}",
20876                Style);
20877   verifyFormat("std::sort(v.begin(), v.end(),\n"
20878                "          [](const auto &someLongArgumentName, const auto "
20879                "&someOtherLongArgumentName) {\n"
20880                "  return someLongArgumentName.someMemberVariable < "
20881                "someOtherLongArgumentName.someMemberVariable;\n"
20882                "});",
20883                Style);
20884   verifyFormat("test() {\n"
20885                "  (\n"
20886                "      []() -> {\n"
20887                "        int b = 32;\n"
20888                "        return 3;\n"
20889                "      },\n"
20890                "      foo, bar)\n"
20891                "      .foo();\n"
20892                "}",
20893                Style);
20894   verifyFormat("test() {\n"
20895                "  ([]() -> {\n"
20896                "    int b = 32;\n"
20897                "    return 3;\n"
20898                "  })\n"
20899                "      .foo()\n"
20900                "      .bar();\n"
20901                "}",
20902                Style);
20903   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20904             "  return promise.then(\n"
20905             "      [this, &someVariable, someObject = "
20906             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20907             "    return someObject.startAsyncAction().then(\n"
20908             "        [this, &someVariable](AsyncActionResult result) mutable { "
20909             "result.processMore(); });\n"
20910             "  });\n"
20911             "}\n",
20912             format("SomeResult doSomething(SomeObject promise) {\n"
20913                    "  return promise.then([this, &someVariable, someObject = "
20914                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20915                    "    return someObject.startAsyncAction().then([this, "
20916                    "&someVariable](AsyncActionResult result) mutable {\n"
20917                    "      result.processMore();\n"
20918                    "    });\n"
20919                    "  });\n"
20920                    "}\n",
20921                    Style));
20922   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20923             "  return promise.then([this, &someVariable] {\n"
20924             "    return someObject.startAsyncAction().then(\n"
20925             "        [this, &someVariable](AsyncActionResult result) mutable { "
20926             "result.processMore(); });\n"
20927             "  });\n"
20928             "}\n",
20929             format("SomeResult doSomething(SomeObject promise) {\n"
20930                    "  return promise.then([this, &someVariable] {\n"
20931                    "    return someObject.startAsyncAction().then([this, "
20932                    "&someVariable](AsyncActionResult result) mutable {\n"
20933                    "      result.processMore();\n"
20934                    "    });\n"
20935                    "  });\n"
20936                    "}\n",
20937                    Style));
20938   Style = getGoogleStyle();
20939   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20940   EXPECT_EQ("#define A                                       \\\n"
20941             "  [] {                                          \\\n"
20942             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
20943             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
20944             "      }",
20945             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
20946                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
20947                    Style));
20948   // TODO: The current formatting has a minor issue that's not worth fixing
20949   // right now whereby the closing brace is indented relative to the signature
20950   // instead of being aligned. This only happens with macros.
20951 }
20952 
20953 TEST_F(FormatTest, LambdaWithLineComments) {
20954   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
20955   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
20956   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
20957   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20958       FormatStyle::ShortLambdaStyle::SLS_All;
20959 
20960   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
20961   verifyFormat("auto k = []() // comment\n"
20962                "{ return; }",
20963                LLVMWithBeforeLambdaBody);
20964   verifyFormat("auto k = []() /* comment */ { return; }",
20965                LLVMWithBeforeLambdaBody);
20966   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
20967                LLVMWithBeforeLambdaBody);
20968   verifyFormat("auto k = []() // X\n"
20969                "{ return; }",
20970                LLVMWithBeforeLambdaBody);
20971   verifyFormat(
20972       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
20973       "{ return; }",
20974       LLVMWithBeforeLambdaBody);
20975 }
20976 
20977 TEST_F(FormatTest, EmptyLinesInLambdas) {
20978   verifyFormat("auto lambda = []() {\n"
20979                "  x(); //\n"
20980                "};",
20981                "auto lambda = []() {\n"
20982                "\n"
20983                "  x(); //\n"
20984                "\n"
20985                "};");
20986 }
20987 
20988 TEST_F(FormatTest, FormatsBlocks) {
20989   FormatStyle ShortBlocks = getLLVMStyle();
20990   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
20991   verifyFormat("int (^Block)(int, int);", ShortBlocks);
20992   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
20993   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
20994   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
20995   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
20996   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
20997 
20998   verifyFormat("foo(^{ bar(); });", ShortBlocks);
20999   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
21000   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
21001 
21002   verifyFormat("[operation setCompletionBlock:^{\n"
21003                "  [self onOperationDone];\n"
21004                "}];");
21005   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
21006                "  [self onOperationDone];\n"
21007                "}]};");
21008   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
21009                "  f();\n"
21010                "}];");
21011   verifyFormat("int a = [operation block:^int(int *i) {\n"
21012                "  return 1;\n"
21013                "}];");
21014   verifyFormat("[myObject doSomethingWith:arg1\n"
21015                "                      aaa:^int(int *a) {\n"
21016                "                        return 1;\n"
21017                "                      }\n"
21018                "                      bbb:f(a * bbbbbbbb)];");
21019 
21020   verifyFormat("[operation setCompletionBlock:^{\n"
21021                "  [self.delegate newDataAvailable];\n"
21022                "}];",
21023                getLLVMStyleWithColumns(60));
21024   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
21025                "  NSString *path = [self sessionFilePath];\n"
21026                "  if (path) {\n"
21027                "    // ...\n"
21028                "  }\n"
21029                "});");
21030   verifyFormat("[[SessionService sharedService]\n"
21031                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21032                "      if (window) {\n"
21033                "        [self windowDidLoad:window];\n"
21034                "      } else {\n"
21035                "        [self errorLoadingWindow];\n"
21036                "      }\n"
21037                "    }];");
21038   verifyFormat("void (^largeBlock)(void) = ^{\n"
21039                "  // ...\n"
21040                "};\n",
21041                getLLVMStyleWithColumns(40));
21042   verifyFormat("[[SessionService sharedService]\n"
21043                "    loadWindowWithCompletionBlock: //\n"
21044                "        ^(SessionWindow *window) {\n"
21045                "          if (window) {\n"
21046                "            [self windowDidLoad:window];\n"
21047                "          } else {\n"
21048                "            [self errorLoadingWindow];\n"
21049                "          }\n"
21050                "        }];",
21051                getLLVMStyleWithColumns(60));
21052   verifyFormat("[myObject doSomethingWith:arg1\n"
21053                "    firstBlock:^(Foo *a) {\n"
21054                "      // ...\n"
21055                "      int i;\n"
21056                "    }\n"
21057                "    secondBlock:^(Bar *b) {\n"
21058                "      // ...\n"
21059                "      int i;\n"
21060                "    }\n"
21061                "    thirdBlock:^Foo(Bar *b) {\n"
21062                "      // ...\n"
21063                "      int i;\n"
21064                "    }];");
21065   verifyFormat("[myObject doSomethingWith:arg1\n"
21066                "               firstBlock:-1\n"
21067                "              secondBlock:^(Bar *b) {\n"
21068                "                // ...\n"
21069                "                int i;\n"
21070                "              }];");
21071 
21072   verifyFormat("f(^{\n"
21073                "  @autoreleasepool {\n"
21074                "    if (a) {\n"
21075                "      g();\n"
21076                "    }\n"
21077                "  }\n"
21078                "});");
21079   verifyFormat("Block b = ^int *(A *a, B *b) {}");
21080   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
21081                "};");
21082 
21083   FormatStyle FourIndent = getLLVMStyle();
21084   FourIndent.ObjCBlockIndentWidth = 4;
21085   verifyFormat("[operation setCompletionBlock:^{\n"
21086                "    [self onOperationDone];\n"
21087                "}];",
21088                FourIndent);
21089 }
21090 
21091 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
21092   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
21093 
21094   verifyFormat("[[SessionService sharedService] "
21095                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21096                "  if (window) {\n"
21097                "    [self windowDidLoad:window];\n"
21098                "  } else {\n"
21099                "    [self errorLoadingWindow];\n"
21100                "  }\n"
21101                "}];",
21102                ZeroColumn);
21103   EXPECT_EQ("[[SessionService sharedService]\n"
21104             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21105             "      if (window) {\n"
21106             "        [self windowDidLoad:window];\n"
21107             "      } else {\n"
21108             "        [self errorLoadingWindow];\n"
21109             "      }\n"
21110             "    }];",
21111             format("[[SessionService sharedService]\n"
21112                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21113                    "                if (window) {\n"
21114                    "    [self windowDidLoad:window];\n"
21115                    "  } else {\n"
21116                    "    [self errorLoadingWindow];\n"
21117                    "  }\n"
21118                    "}];",
21119                    ZeroColumn));
21120   verifyFormat("[myObject doSomethingWith:arg1\n"
21121                "    firstBlock:^(Foo *a) {\n"
21122                "      // ...\n"
21123                "      int i;\n"
21124                "    }\n"
21125                "    secondBlock:^(Bar *b) {\n"
21126                "      // ...\n"
21127                "      int i;\n"
21128                "    }\n"
21129                "    thirdBlock:^Foo(Bar *b) {\n"
21130                "      // ...\n"
21131                "      int i;\n"
21132                "    }];",
21133                ZeroColumn);
21134   verifyFormat("f(^{\n"
21135                "  @autoreleasepool {\n"
21136                "    if (a) {\n"
21137                "      g();\n"
21138                "    }\n"
21139                "  }\n"
21140                "});",
21141                ZeroColumn);
21142   verifyFormat("void (^largeBlock)(void) = ^{\n"
21143                "  // ...\n"
21144                "};",
21145                ZeroColumn);
21146 
21147   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21148   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
21149             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21150   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
21151   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
21152             "  int i;\n"
21153             "};",
21154             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21155 }
21156 
21157 TEST_F(FormatTest, SupportsCRLF) {
21158   EXPECT_EQ("int a;\r\n"
21159             "int b;\r\n"
21160             "int c;\r\n",
21161             format("int a;\r\n"
21162                    "  int b;\r\n"
21163                    "    int c;\r\n",
21164                    getLLVMStyle()));
21165   EXPECT_EQ("int a;\r\n"
21166             "int b;\r\n"
21167             "int c;\r\n",
21168             format("int a;\r\n"
21169                    "  int b;\n"
21170                    "    int c;\r\n",
21171                    getLLVMStyle()));
21172   EXPECT_EQ("int a;\n"
21173             "int b;\n"
21174             "int c;\n",
21175             format("int a;\r\n"
21176                    "  int b;\n"
21177                    "    int c;\n",
21178                    getLLVMStyle()));
21179   EXPECT_EQ("\"aaaaaaa \"\r\n"
21180             "\"bbbbbbb\";\r\n",
21181             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
21182   EXPECT_EQ("#define A \\\r\n"
21183             "  b;      \\\r\n"
21184             "  c;      \\\r\n"
21185             "  d;\r\n",
21186             format("#define A \\\r\n"
21187                    "  b; \\\r\n"
21188                    "  c; d; \r\n",
21189                    getGoogleStyle()));
21190 
21191   EXPECT_EQ("/*\r\n"
21192             "multi line block comments\r\n"
21193             "should not introduce\r\n"
21194             "an extra carriage return\r\n"
21195             "*/\r\n",
21196             format("/*\r\n"
21197                    "multi line block comments\r\n"
21198                    "should not introduce\r\n"
21199                    "an extra carriage return\r\n"
21200                    "*/\r\n"));
21201   EXPECT_EQ("/*\r\n"
21202             "\r\n"
21203             "*/",
21204             format("/*\r\n"
21205                    "    \r\r\r\n"
21206                    "*/"));
21207 
21208   FormatStyle style = getLLVMStyle();
21209 
21210   style.DeriveLineEnding = true;
21211   style.UseCRLF = false;
21212   EXPECT_EQ("union FooBarBazQux {\n"
21213             "  int foo;\n"
21214             "  int bar;\n"
21215             "  int baz;\n"
21216             "};",
21217             format("union FooBarBazQux {\r\n"
21218                    "  int foo;\n"
21219                    "  int bar;\r\n"
21220                    "  int baz;\n"
21221                    "};",
21222                    style));
21223   style.UseCRLF = true;
21224   EXPECT_EQ("union FooBarBazQux {\r\n"
21225             "  int foo;\r\n"
21226             "  int bar;\r\n"
21227             "  int baz;\r\n"
21228             "};",
21229             format("union FooBarBazQux {\r\n"
21230                    "  int foo;\n"
21231                    "  int bar;\r\n"
21232                    "  int baz;\n"
21233                    "};",
21234                    style));
21235 
21236   style.DeriveLineEnding = false;
21237   style.UseCRLF = false;
21238   EXPECT_EQ("union FooBarBazQux {\n"
21239             "  int foo;\n"
21240             "  int bar;\n"
21241             "  int baz;\n"
21242             "  int qux;\n"
21243             "};",
21244             format("union FooBarBazQux {\r\n"
21245                    "  int foo;\n"
21246                    "  int bar;\r\n"
21247                    "  int baz;\n"
21248                    "  int qux;\r\n"
21249                    "};",
21250                    style));
21251   style.UseCRLF = true;
21252   EXPECT_EQ("union FooBarBazQux {\r\n"
21253             "  int foo;\r\n"
21254             "  int bar;\r\n"
21255             "  int baz;\r\n"
21256             "  int qux;\r\n"
21257             "};",
21258             format("union FooBarBazQux {\r\n"
21259                    "  int foo;\n"
21260                    "  int bar;\r\n"
21261                    "  int baz;\n"
21262                    "  int qux;\n"
21263                    "};",
21264                    style));
21265 
21266   style.DeriveLineEnding = true;
21267   style.UseCRLF = false;
21268   EXPECT_EQ("union FooBarBazQux {\r\n"
21269             "  int foo;\r\n"
21270             "  int bar;\r\n"
21271             "  int baz;\r\n"
21272             "  int qux;\r\n"
21273             "};",
21274             format("union FooBarBazQux {\r\n"
21275                    "  int foo;\n"
21276                    "  int bar;\r\n"
21277                    "  int baz;\n"
21278                    "  int qux;\r\n"
21279                    "};",
21280                    style));
21281   style.UseCRLF = true;
21282   EXPECT_EQ("union FooBarBazQux {\n"
21283             "  int foo;\n"
21284             "  int bar;\n"
21285             "  int baz;\n"
21286             "  int qux;\n"
21287             "};",
21288             format("union FooBarBazQux {\r\n"
21289                    "  int foo;\n"
21290                    "  int bar;\r\n"
21291                    "  int baz;\n"
21292                    "  int qux;\n"
21293                    "};",
21294                    style));
21295 }
21296 
21297 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
21298   verifyFormat("MY_CLASS(C) {\n"
21299                "  int i;\n"
21300                "  int j;\n"
21301                "};");
21302 }
21303 
21304 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
21305   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
21306   TwoIndent.ContinuationIndentWidth = 2;
21307 
21308   EXPECT_EQ("int i =\n"
21309             "  longFunction(\n"
21310             "    arg);",
21311             format("int i = longFunction(arg);", TwoIndent));
21312 
21313   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
21314   SixIndent.ContinuationIndentWidth = 6;
21315 
21316   EXPECT_EQ("int i =\n"
21317             "      longFunction(\n"
21318             "            arg);",
21319             format("int i = longFunction(arg);", SixIndent));
21320 }
21321 
21322 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
21323   FormatStyle Style = getLLVMStyle();
21324   verifyFormat("int Foo::getter(\n"
21325                "    //\n"
21326                ") const {\n"
21327                "  return foo;\n"
21328                "}",
21329                Style);
21330   verifyFormat("void Foo::setter(\n"
21331                "    //\n"
21332                ") {\n"
21333                "  foo = 1;\n"
21334                "}",
21335                Style);
21336 }
21337 
21338 TEST_F(FormatTest, SpacesInAngles) {
21339   FormatStyle Spaces = getLLVMStyle();
21340   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21341 
21342   verifyFormat("vector< ::std::string > x1;", Spaces);
21343   verifyFormat("Foo< int, Bar > x2;", Spaces);
21344   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
21345 
21346   verifyFormat("static_cast< int >(arg);", Spaces);
21347   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
21348   verifyFormat("f< int, float >();", Spaces);
21349   verifyFormat("template <> g() {}", Spaces);
21350   verifyFormat("template < std::vector< int > > f() {}", Spaces);
21351   verifyFormat("std::function< void(int, int) > fct;", Spaces);
21352   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
21353                Spaces);
21354 
21355   Spaces.Standard = FormatStyle::LS_Cpp03;
21356   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21357   verifyFormat("A< A< int > >();", Spaces);
21358 
21359   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
21360   verifyFormat("A<A<int> >();", Spaces);
21361 
21362   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
21363   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
21364                Spaces);
21365   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
21366                Spaces);
21367 
21368   verifyFormat("A<A<int> >();", Spaces);
21369   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
21370   verifyFormat("A< A< int > >();", Spaces);
21371 
21372   Spaces.Standard = FormatStyle::LS_Cpp11;
21373   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21374   verifyFormat("A< A< int > >();", Spaces);
21375 
21376   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
21377   verifyFormat("vector<::std::string> x4;", Spaces);
21378   verifyFormat("vector<int> x5;", Spaces);
21379   verifyFormat("Foo<int, Bar> x6;", Spaces);
21380   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
21381 
21382   verifyFormat("A<A<int>>();", Spaces);
21383 
21384   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
21385   verifyFormat("vector<::std::string> x4;", Spaces);
21386   verifyFormat("vector< ::std::string > x4;", Spaces);
21387   verifyFormat("vector<int> x5;", Spaces);
21388   verifyFormat("vector< int > x5;", Spaces);
21389   verifyFormat("Foo<int, Bar> x6;", Spaces);
21390   verifyFormat("Foo< int, Bar > x6;", Spaces);
21391   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
21392   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
21393 
21394   verifyFormat("A<A<int>>();", Spaces);
21395   verifyFormat("A< A< int > >();", Spaces);
21396   verifyFormat("A<A<int > >();", Spaces);
21397   verifyFormat("A< A< int>>();", Spaces);
21398 
21399   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21400   verifyFormat("// clang-format off\n"
21401                "foo<<<1, 1>>>();\n"
21402                "// clang-format on\n",
21403                Spaces);
21404   verifyFormat("// clang-format off\n"
21405                "foo< < <1, 1> > >();\n"
21406                "// clang-format on\n",
21407                Spaces);
21408 }
21409 
21410 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
21411   FormatStyle Style = getLLVMStyle();
21412   Style.SpaceAfterTemplateKeyword = false;
21413   verifyFormat("template<int> void foo();", Style);
21414 }
21415 
21416 TEST_F(FormatTest, TripleAngleBrackets) {
21417   verifyFormat("f<<<1, 1>>>();");
21418   verifyFormat("f<<<1, 1, 1, s>>>();");
21419   verifyFormat("f<<<a, b, c, d>>>();");
21420   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
21421   verifyFormat("f<param><<<1, 1>>>();");
21422   verifyFormat("f<1><<<1, 1>>>();");
21423   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
21424   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21425                "aaaaaaaaaaa<<<\n    1, 1>>>();");
21426   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
21427                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
21428 }
21429 
21430 TEST_F(FormatTest, MergeLessLessAtEnd) {
21431   verifyFormat("<<");
21432   EXPECT_EQ("< < <", format("\\\n<<<"));
21433   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21434                "aaallvm::outs() <<");
21435   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21436                "aaaallvm::outs()\n    <<");
21437 }
21438 
21439 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
21440   std::string code = "#if A\n"
21441                      "#if B\n"
21442                      "a.\n"
21443                      "#endif\n"
21444                      "    a = 1;\n"
21445                      "#else\n"
21446                      "#endif\n"
21447                      "#if C\n"
21448                      "#else\n"
21449                      "#endif\n";
21450   EXPECT_EQ(code, format(code));
21451 }
21452 
21453 TEST_F(FormatTest, HandleConflictMarkers) {
21454   // Git/SVN conflict markers.
21455   EXPECT_EQ("int a;\n"
21456             "void f() {\n"
21457             "  callme(some(parameter1,\n"
21458             "<<<<<<< text by the vcs\n"
21459             "              parameter2),\n"
21460             "||||||| text by the vcs\n"
21461             "              parameter2),\n"
21462             "         parameter3,\n"
21463             "======= text by the vcs\n"
21464             "              parameter2, parameter3),\n"
21465             ">>>>>>> text by the vcs\n"
21466             "         otherparameter);\n",
21467             format("int a;\n"
21468                    "void f() {\n"
21469                    "  callme(some(parameter1,\n"
21470                    "<<<<<<< text by the vcs\n"
21471                    "  parameter2),\n"
21472                    "||||||| text by the vcs\n"
21473                    "  parameter2),\n"
21474                    "  parameter3,\n"
21475                    "======= text by the vcs\n"
21476                    "  parameter2,\n"
21477                    "  parameter3),\n"
21478                    ">>>>>>> text by the vcs\n"
21479                    "  otherparameter);\n"));
21480 
21481   // Perforce markers.
21482   EXPECT_EQ("void f() {\n"
21483             "  function(\n"
21484             ">>>> text by the vcs\n"
21485             "      parameter,\n"
21486             "==== text by the vcs\n"
21487             "      parameter,\n"
21488             "==== text by the vcs\n"
21489             "      parameter,\n"
21490             "<<<< text by the vcs\n"
21491             "      parameter);\n",
21492             format("void f() {\n"
21493                    "  function(\n"
21494                    ">>>> text by the vcs\n"
21495                    "  parameter,\n"
21496                    "==== text by the vcs\n"
21497                    "  parameter,\n"
21498                    "==== text by the vcs\n"
21499                    "  parameter,\n"
21500                    "<<<< text by the vcs\n"
21501                    "  parameter);\n"));
21502 
21503   EXPECT_EQ("<<<<<<<\n"
21504             "|||||||\n"
21505             "=======\n"
21506             ">>>>>>>",
21507             format("<<<<<<<\n"
21508                    "|||||||\n"
21509                    "=======\n"
21510                    ">>>>>>>"));
21511 
21512   EXPECT_EQ("<<<<<<<\n"
21513             "|||||||\n"
21514             "int i;\n"
21515             "=======\n"
21516             ">>>>>>>",
21517             format("<<<<<<<\n"
21518                    "|||||||\n"
21519                    "int i;\n"
21520                    "=======\n"
21521                    ">>>>>>>"));
21522 
21523   // FIXME: Handle parsing of macros around conflict markers correctly:
21524   EXPECT_EQ("#define Macro \\\n"
21525             "<<<<<<<\n"
21526             "Something \\\n"
21527             "|||||||\n"
21528             "Else \\\n"
21529             "=======\n"
21530             "Other \\\n"
21531             ">>>>>>>\n"
21532             "    End int i;\n",
21533             format("#define Macro \\\n"
21534                    "<<<<<<<\n"
21535                    "  Something \\\n"
21536                    "|||||||\n"
21537                    "  Else \\\n"
21538                    "=======\n"
21539                    "  Other \\\n"
21540                    ">>>>>>>\n"
21541                    "  End\n"
21542                    "int i;\n"));
21543 
21544   verifyFormat(R"(====
21545 #ifdef A
21546 a
21547 #else
21548 b
21549 #endif
21550 )");
21551 }
21552 
21553 TEST_F(FormatTest, DisableRegions) {
21554   EXPECT_EQ("int i;\n"
21555             "// clang-format off\n"
21556             "  int j;\n"
21557             "// clang-format on\n"
21558             "int k;",
21559             format(" int  i;\n"
21560                    "   // clang-format off\n"
21561                    "  int j;\n"
21562                    " // clang-format on\n"
21563                    "   int   k;"));
21564   EXPECT_EQ("int i;\n"
21565             "/* clang-format off */\n"
21566             "  int j;\n"
21567             "/* clang-format on */\n"
21568             "int k;",
21569             format(" int  i;\n"
21570                    "   /* clang-format off */\n"
21571                    "  int j;\n"
21572                    " /* clang-format on */\n"
21573                    "   int   k;"));
21574 
21575   // Don't reflow comments within disabled regions.
21576   EXPECT_EQ("// clang-format off\n"
21577             "// long long long long long long line\n"
21578             "/* clang-format on */\n"
21579             "/* long long long\n"
21580             " * long long long\n"
21581             " * line */\n"
21582             "int i;\n"
21583             "/* clang-format off */\n"
21584             "/* long long long long long long line */\n",
21585             format("// clang-format off\n"
21586                    "// long long long long long long line\n"
21587                    "/* clang-format on */\n"
21588                    "/* long long long long long long line */\n"
21589                    "int i;\n"
21590                    "/* clang-format off */\n"
21591                    "/* long long long long long long line */\n",
21592                    getLLVMStyleWithColumns(20)));
21593 }
21594 
21595 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
21596   format("? ) =");
21597   verifyNoCrash("#define a\\\n /**/}");
21598 }
21599 
21600 TEST_F(FormatTest, FormatsTableGenCode) {
21601   FormatStyle Style = getLLVMStyle();
21602   Style.Language = FormatStyle::LK_TableGen;
21603   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
21604 }
21605 
21606 TEST_F(FormatTest, ArrayOfTemplates) {
21607   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
21608             format("auto a = new unique_ptr<int > [ 10];"));
21609 
21610   FormatStyle Spaces = getLLVMStyle();
21611   Spaces.SpacesInSquareBrackets = true;
21612   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
21613             format("auto a = new unique_ptr<int > [10];", Spaces));
21614 }
21615 
21616 TEST_F(FormatTest, ArrayAsTemplateType) {
21617   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
21618             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
21619 
21620   FormatStyle Spaces = getLLVMStyle();
21621   Spaces.SpacesInSquareBrackets = true;
21622   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
21623             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
21624 }
21625 
21626 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
21627 
21628 TEST(FormatStyle, GetStyleWithEmptyFileName) {
21629   llvm::vfs::InMemoryFileSystem FS;
21630   auto Style1 = getStyle("file", "", "Google", "", &FS);
21631   ASSERT_TRUE((bool)Style1);
21632   ASSERT_EQ(*Style1, getGoogleStyle());
21633 }
21634 
21635 TEST(FormatStyle, GetStyleOfFile) {
21636   llvm::vfs::InMemoryFileSystem FS;
21637   // Test 1: format file in the same directory.
21638   ASSERT_TRUE(
21639       FS.addFile("/a/.clang-format", 0,
21640                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
21641   ASSERT_TRUE(
21642       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21643   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
21644   ASSERT_TRUE((bool)Style1);
21645   ASSERT_EQ(*Style1, getLLVMStyle());
21646 
21647   // Test 2.1: fallback to default.
21648   ASSERT_TRUE(
21649       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21650   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
21651   ASSERT_TRUE((bool)Style2);
21652   ASSERT_EQ(*Style2, getMozillaStyle());
21653 
21654   // Test 2.2: no format on 'none' fallback style.
21655   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21656   ASSERT_TRUE((bool)Style2);
21657   ASSERT_EQ(*Style2, getNoStyle());
21658 
21659   // Test 2.3: format if config is found with no based style while fallback is
21660   // 'none'.
21661   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
21662                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
21663   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21664   ASSERT_TRUE((bool)Style2);
21665   ASSERT_EQ(*Style2, getLLVMStyle());
21666 
21667   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
21668   Style2 = getStyle("{}", "a.h", "none", "", &FS);
21669   ASSERT_TRUE((bool)Style2);
21670   ASSERT_EQ(*Style2, getLLVMStyle());
21671 
21672   // Test 3: format file in parent directory.
21673   ASSERT_TRUE(
21674       FS.addFile("/c/.clang-format", 0,
21675                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21676   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
21677                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21678   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21679   ASSERT_TRUE((bool)Style3);
21680   ASSERT_EQ(*Style3, getGoogleStyle());
21681 
21682   // Test 4: error on invalid fallback style
21683   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
21684   ASSERT_FALSE((bool)Style4);
21685   llvm::consumeError(Style4.takeError());
21686 
21687   // Test 5: error on invalid yaml on command line
21688   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
21689   ASSERT_FALSE((bool)Style5);
21690   llvm::consumeError(Style5.takeError());
21691 
21692   // Test 6: error on invalid style
21693   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
21694   ASSERT_FALSE((bool)Style6);
21695   llvm::consumeError(Style6.takeError());
21696 
21697   // Test 7: found config file, error on parsing it
21698   ASSERT_TRUE(
21699       FS.addFile("/d/.clang-format", 0,
21700                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
21701                                                   "InvalidKey: InvalidValue")));
21702   ASSERT_TRUE(
21703       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21704   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
21705   ASSERT_FALSE((bool)Style7a);
21706   llvm::consumeError(Style7a.takeError());
21707 
21708   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
21709   ASSERT_TRUE((bool)Style7b);
21710 
21711   // Test 8: inferred per-language defaults apply.
21712   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
21713   ASSERT_TRUE((bool)StyleTd);
21714   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
21715 
21716   // Test 9.1.1: overwriting a file style, when no parent file exists with no
21717   // fallback style.
21718   ASSERT_TRUE(FS.addFile(
21719       "/e/sub/.clang-format", 0,
21720       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
21721                                        "ColumnLimit: 20")));
21722   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
21723                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21724   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21725   ASSERT_TRUE(static_cast<bool>(Style9));
21726   ASSERT_EQ(*Style9, [] {
21727     auto Style = getNoStyle();
21728     Style.ColumnLimit = 20;
21729     return Style;
21730   }());
21731 
21732   // Test 9.1.2: propagate more than one level with no parent file.
21733   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
21734                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21735   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
21736                          llvm::MemoryBuffer::getMemBuffer(
21737                              "BasedOnStyle: InheritParentConfig\n"
21738                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
21739   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
21740 
21741   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
21742   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
21743   ASSERT_TRUE(static_cast<bool>(Style9));
21744   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
21745     auto Style = getNoStyle();
21746     Style.ColumnLimit = 20;
21747     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
21748     return Style;
21749   }());
21750 
21751   // Test 9.2: with LLVM fallback style
21752   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
21753   ASSERT_TRUE(static_cast<bool>(Style9));
21754   ASSERT_EQ(*Style9, [] {
21755     auto Style = getLLVMStyle();
21756     Style.ColumnLimit = 20;
21757     return Style;
21758   }());
21759 
21760   // Test 9.3: with a parent file
21761   ASSERT_TRUE(
21762       FS.addFile("/e/.clang-format", 0,
21763                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
21764                                                   "UseTab: Always")));
21765   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21766   ASSERT_TRUE(static_cast<bool>(Style9));
21767   ASSERT_EQ(*Style9, [] {
21768     auto Style = getGoogleStyle();
21769     Style.ColumnLimit = 20;
21770     Style.UseTab = FormatStyle::UT_Always;
21771     return Style;
21772   }());
21773 
21774   // Test 9.4: propagate more than one level with a parent file.
21775   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
21776     auto Style = getGoogleStyle();
21777     Style.ColumnLimit = 20;
21778     Style.UseTab = FormatStyle::UT_Always;
21779     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
21780     return Style;
21781   }();
21782 
21783   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
21784   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
21785   ASSERT_TRUE(static_cast<bool>(Style9));
21786   ASSERT_EQ(*Style9, SubSubStyle);
21787 
21788   // Test 9.5: use InheritParentConfig as style name
21789   Style9 =
21790       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
21791   ASSERT_TRUE(static_cast<bool>(Style9));
21792   ASSERT_EQ(*Style9, SubSubStyle);
21793 
21794   // Test 9.6: use command line style with inheritance
21795   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
21796                     "none", "", &FS);
21797   ASSERT_TRUE(static_cast<bool>(Style9));
21798   ASSERT_EQ(*Style9, SubSubStyle);
21799 
21800   // Test 9.7: use command line style with inheritance and own config
21801   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
21802                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
21803                     "/e/sub/code.cpp", "none", "", &FS);
21804   ASSERT_TRUE(static_cast<bool>(Style9));
21805   ASSERT_EQ(*Style9, SubSubStyle);
21806 
21807   // Test 9.8: use inheritance from a file without BasedOnStyle
21808   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
21809                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
21810   ASSERT_TRUE(
21811       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
21812                  llvm::MemoryBuffer::getMemBuffer(
21813                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
21814   // Make sure we do not use the fallback style
21815   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
21816   ASSERT_TRUE(static_cast<bool>(Style9));
21817   ASSERT_EQ(*Style9, [] {
21818     auto Style = getLLVMStyle();
21819     Style.ColumnLimit = 123;
21820     return Style;
21821   }());
21822 
21823   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
21824   ASSERT_TRUE(static_cast<bool>(Style9));
21825   ASSERT_EQ(*Style9, [] {
21826     auto Style = getLLVMStyle();
21827     Style.ColumnLimit = 123;
21828     Style.IndentWidth = 7;
21829     return Style;
21830   }());
21831 
21832   // Test 9.9: use inheritance from a specific config file.
21833   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
21834                     "none", "", &FS);
21835   ASSERT_TRUE(static_cast<bool>(Style9));
21836   ASSERT_EQ(*Style9, SubSubStyle);
21837 }
21838 
21839 TEST(FormatStyle, GetStyleOfSpecificFile) {
21840   llvm::vfs::InMemoryFileSystem FS;
21841   // Specify absolute path to a format file in a parent directory.
21842   ASSERT_TRUE(
21843       FS.addFile("/e/.clang-format", 0,
21844                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
21845   ASSERT_TRUE(
21846       FS.addFile("/e/explicit.clang-format", 0,
21847                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21848   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
21849                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21850   auto Style = getStyle("file:/e/explicit.clang-format",
21851                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21852   ASSERT_TRUE(static_cast<bool>(Style));
21853   ASSERT_EQ(*Style, getGoogleStyle());
21854 
21855   // Specify relative path to a format file.
21856   ASSERT_TRUE(
21857       FS.addFile("../../e/explicit.clang-format", 0,
21858                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21859   Style = getStyle("file:../../e/explicit.clang-format",
21860                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21861   ASSERT_TRUE(static_cast<bool>(Style));
21862   ASSERT_EQ(*Style, getGoogleStyle());
21863 
21864   // Specify path to a format file that does not exist.
21865   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
21866                    "LLVM", "", &FS);
21867   ASSERT_FALSE(static_cast<bool>(Style));
21868   llvm::consumeError(Style.takeError());
21869 
21870   // Specify path to a file on the filesystem.
21871   SmallString<128> FormatFilePath;
21872   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
21873       "FormatFileTest", "tpl", FormatFilePath);
21874   EXPECT_FALSE((bool)ECF);
21875   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
21876   EXPECT_FALSE((bool)ECF);
21877   FormatFileTest << "BasedOnStyle: Google\n";
21878   FormatFileTest.close();
21879 
21880   SmallString<128> TestFilePath;
21881   std::error_code ECT =
21882       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
21883   EXPECT_FALSE((bool)ECT);
21884   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
21885   CodeFileTest << "int i;\n";
21886   CodeFileTest.close();
21887 
21888   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
21889   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
21890 
21891   llvm::sys::fs::remove(FormatFilePath.c_str());
21892   llvm::sys::fs::remove(TestFilePath.c_str());
21893   ASSERT_TRUE(static_cast<bool>(Style));
21894   ASSERT_EQ(*Style, getGoogleStyle());
21895 }
21896 
21897 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
21898   // Column limit is 20.
21899   std::string Code = "Type *a =\n"
21900                      "    new Type();\n"
21901                      "g(iiiii, 0, jjjjj,\n"
21902                      "  0, kkkkk, 0, mm);\n"
21903                      "int  bad     = format   ;";
21904   std::string Expected = "auto a = new Type();\n"
21905                          "g(iiiii, nullptr,\n"
21906                          "  jjjjj, nullptr,\n"
21907                          "  kkkkk, nullptr,\n"
21908                          "  mm);\n"
21909                          "int  bad     = format   ;";
21910   FileID ID = Context.createInMemoryFile("format.cpp", Code);
21911   tooling::Replacements Replaces = toReplacements(
21912       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
21913                             "auto "),
21914        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
21915                             "nullptr"),
21916        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
21917                             "nullptr"),
21918        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
21919                             "nullptr")});
21920 
21921   FormatStyle Style = getLLVMStyle();
21922   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
21923   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21924   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21925       << llvm::toString(FormattedReplaces.takeError()) << "\n";
21926   auto Result = applyAllReplacements(Code, *FormattedReplaces);
21927   EXPECT_TRUE(static_cast<bool>(Result));
21928   EXPECT_EQ(Expected, *Result);
21929 }
21930 
21931 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
21932   std::string Code = "#include \"a.h\"\n"
21933                      "#include \"c.h\"\n"
21934                      "\n"
21935                      "int main() {\n"
21936                      "  return 0;\n"
21937                      "}";
21938   std::string Expected = "#include \"a.h\"\n"
21939                          "#include \"b.h\"\n"
21940                          "#include \"c.h\"\n"
21941                          "\n"
21942                          "int main() {\n"
21943                          "  return 0;\n"
21944                          "}";
21945   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
21946   tooling::Replacements Replaces = toReplacements(
21947       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
21948                             "#include \"b.h\"\n")});
21949 
21950   FormatStyle Style = getLLVMStyle();
21951   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
21952   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21953   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21954       << llvm::toString(FormattedReplaces.takeError()) << "\n";
21955   auto Result = applyAllReplacements(Code, *FormattedReplaces);
21956   EXPECT_TRUE(static_cast<bool>(Result));
21957   EXPECT_EQ(Expected, *Result);
21958 }
21959 
21960 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
21961   EXPECT_EQ("using std::cin;\n"
21962             "using std::cout;",
21963             format("using std::cout;\n"
21964                    "using std::cin;",
21965                    getGoogleStyle()));
21966 }
21967 
21968 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
21969   FormatStyle Style = getLLVMStyle();
21970   Style.Standard = FormatStyle::LS_Cpp03;
21971   // cpp03 recognize this string as identifier u8 and literal character 'a'
21972   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
21973 }
21974 
21975 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
21976   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
21977   // all modes, including C++11, C++14 and C++17
21978   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
21979 }
21980 
21981 TEST_F(FormatTest, DoNotFormatLikelyXml) {
21982   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
21983   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
21984 }
21985 
21986 TEST_F(FormatTest, StructuredBindings) {
21987   // Structured bindings is a C++17 feature.
21988   // all modes, including C++11, C++14 and C++17
21989   verifyFormat("auto [a, b] = f();");
21990   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
21991   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
21992   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
21993   EXPECT_EQ("auto const volatile [a, b] = f();",
21994             format("auto  const   volatile[a, b] = f();"));
21995   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
21996   EXPECT_EQ("auto &[a, b, c] = f();",
21997             format("auto   &[  a  ,  b,c   ] = f();"));
21998   EXPECT_EQ("auto &&[a, b, c] = f();",
21999             format("auto   &&[  a  ,  b,c   ] = f();"));
22000   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
22001   EXPECT_EQ("auto const volatile &&[a, b] = f();",
22002             format("auto  const  volatile  &&[a, b] = f();"));
22003   EXPECT_EQ("auto const &&[a, b] = f();",
22004             format("auto  const   &&  [a, b] = f();"));
22005   EXPECT_EQ("const auto &[a, b] = f();",
22006             format("const  auto  &  [a, b] = f();"));
22007   EXPECT_EQ("const auto volatile &&[a, b] = f();",
22008             format("const  auto   volatile  &&[a, b] = f();"));
22009   EXPECT_EQ("volatile const auto &&[a, b] = f();",
22010             format("volatile  const  auto   &&[a, b] = f();"));
22011   EXPECT_EQ("const auto &&[a, b] = f();",
22012             format("const  auto  &&  [a, b] = f();"));
22013 
22014   // Make sure we don't mistake structured bindings for lambdas.
22015   FormatStyle PointerMiddle = getLLVMStyle();
22016   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
22017   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
22018   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
22019   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
22020   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
22021   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
22022   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
22023   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
22024   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
22025   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
22026   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
22027   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
22028   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
22029 
22030   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
22031             format("for (const auto   &&   [a, b] : some_range) {\n}"));
22032   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
22033             format("for (const auto   &   [a, b] : some_range) {\n}"));
22034   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
22035             format("for (const auto[a, b] : some_range) {\n}"));
22036   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
22037   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
22038   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
22039   EXPECT_EQ("auto const &[x, y](expr);",
22040             format("auto  const  &  [x,y]  (expr);"));
22041   EXPECT_EQ("auto const &&[x, y](expr);",
22042             format("auto  const  &&  [x,y]  (expr);"));
22043   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
22044   EXPECT_EQ("auto const &[x, y]{expr};",
22045             format("auto  const  &  [x,y]  {expr};"));
22046   EXPECT_EQ("auto const &&[x, y]{expr};",
22047             format("auto  const  &&  [x,y]  {expr};"));
22048 
22049   FormatStyle Spaces = getLLVMStyle();
22050   Spaces.SpacesInSquareBrackets = true;
22051   verifyFormat("auto [ a, b ] = f();", Spaces);
22052   verifyFormat("auto &&[ a, b ] = f();", Spaces);
22053   verifyFormat("auto &[ a, b ] = f();", Spaces);
22054   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
22055   verifyFormat("auto const &[ a, b ] = f();", Spaces);
22056 }
22057 
22058 TEST_F(FormatTest, FileAndCode) {
22059   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
22060   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
22061   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
22062   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
22063   EXPECT_EQ(FormatStyle::LK_ObjC,
22064             guessLanguage("foo.h", "@interface Foo\n@end\n"));
22065   EXPECT_EQ(
22066       FormatStyle::LK_ObjC,
22067       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
22068   EXPECT_EQ(FormatStyle::LK_ObjC,
22069             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
22070   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
22071   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
22072   EXPECT_EQ(FormatStyle::LK_ObjC,
22073             guessLanguage("foo", "@interface Foo\n@end\n"));
22074   EXPECT_EQ(FormatStyle::LK_ObjC,
22075             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
22076   EXPECT_EQ(
22077       FormatStyle::LK_ObjC,
22078       guessLanguage("foo.h",
22079                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
22080   EXPECT_EQ(
22081       FormatStyle::LK_Cpp,
22082       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
22083 }
22084 
22085 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
22086   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
22087   EXPECT_EQ(FormatStyle::LK_ObjC,
22088             guessLanguage("foo.h", "array[[calculator getIndex]];"));
22089   EXPECT_EQ(FormatStyle::LK_Cpp,
22090             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
22091   EXPECT_EQ(
22092       FormatStyle::LK_Cpp,
22093       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
22094   EXPECT_EQ(FormatStyle::LK_ObjC,
22095             guessLanguage("foo.h", "[[noreturn foo] bar];"));
22096   EXPECT_EQ(FormatStyle::LK_Cpp,
22097             guessLanguage("foo.h", "[[clang::fallthrough]];"));
22098   EXPECT_EQ(FormatStyle::LK_ObjC,
22099             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
22100   EXPECT_EQ(FormatStyle::LK_Cpp,
22101             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
22102   EXPECT_EQ(FormatStyle::LK_Cpp,
22103             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
22104   EXPECT_EQ(FormatStyle::LK_ObjC,
22105             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
22106   EXPECT_EQ(FormatStyle::LK_Cpp,
22107             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
22108   EXPECT_EQ(
22109       FormatStyle::LK_Cpp,
22110       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
22111   EXPECT_EQ(
22112       FormatStyle::LK_Cpp,
22113       guessLanguage("foo.h",
22114                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
22115   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
22116 }
22117 
22118 TEST_F(FormatTest, GuessLanguageWithCaret) {
22119   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
22120   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
22121   EXPECT_EQ(FormatStyle::LK_ObjC,
22122             guessLanguage("foo.h", "int(^)(char, float);"));
22123   EXPECT_EQ(FormatStyle::LK_ObjC,
22124             guessLanguage("foo.h", "int(^foo)(char, float);"));
22125   EXPECT_EQ(FormatStyle::LK_ObjC,
22126             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
22127   EXPECT_EQ(FormatStyle::LK_ObjC,
22128             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
22129   EXPECT_EQ(
22130       FormatStyle::LK_ObjC,
22131       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
22132 }
22133 
22134 TEST_F(FormatTest, GuessLanguageWithPragmas) {
22135   EXPECT_EQ(FormatStyle::LK_Cpp,
22136             guessLanguage("foo.h", "__pragma(warning(disable:))"));
22137   EXPECT_EQ(FormatStyle::LK_Cpp,
22138             guessLanguage("foo.h", "#pragma(warning(disable:))"));
22139   EXPECT_EQ(FormatStyle::LK_Cpp,
22140             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
22141 }
22142 
22143 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
22144   // ASM symbolic names are identifiers that must be surrounded by [] without
22145   // space in between:
22146   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
22147 
22148   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
22149   verifyFormat(R"(//
22150 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
22151 )");
22152 
22153   // A list of several ASM symbolic names.
22154   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
22155 
22156   // ASM symbolic names in inline ASM with inputs and outputs.
22157   verifyFormat(R"(//
22158 asm("cmoveq %1, %2, %[result]"
22159     : [result] "=r"(result)
22160     : "r"(test), "r"(new), "[result]"(old));
22161 )");
22162 
22163   // ASM symbolic names in inline ASM with no outputs.
22164   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
22165 }
22166 
22167 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
22168   EXPECT_EQ(FormatStyle::LK_Cpp,
22169             guessLanguage("foo.h", "void f() {\n"
22170                                    "  asm (\"mov %[e], %[d]\"\n"
22171                                    "     : [d] \"=rm\" (d)\n"
22172                                    "       [e] \"rm\" (*e));\n"
22173                                    "}"));
22174   EXPECT_EQ(FormatStyle::LK_Cpp,
22175             guessLanguage("foo.h", "void f() {\n"
22176                                    "  _asm (\"mov %[e], %[d]\"\n"
22177                                    "     : [d] \"=rm\" (d)\n"
22178                                    "       [e] \"rm\" (*e));\n"
22179                                    "}"));
22180   EXPECT_EQ(FormatStyle::LK_Cpp,
22181             guessLanguage("foo.h", "void f() {\n"
22182                                    "  __asm (\"mov %[e], %[d]\"\n"
22183                                    "     : [d] \"=rm\" (d)\n"
22184                                    "       [e] \"rm\" (*e));\n"
22185                                    "}"));
22186   EXPECT_EQ(FormatStyle::LK_Cpp,
22187             guessLanguage("foo.h", "void f() {\n"
22188                                    "  __asm__ (\"mov %[e], %[d]\"\n"
22189                                    "     : [d] \"=rm\" (d)\n"
22190                                    "       [e] \"rm\" (*e));\n"
22191                                    "}"));
22192   EXPECT_EQ(FormatStyle::LK_Cpp,
22193             guessLanguage("foo.h", "void f() {\n"
22194                                    "  asm (\"mov %[e], %[d]\"\n"
22195                                    "     : [d] \"=rm\" (d),\n"
22196                                    "       [e] \"rm\" (*e));\n"
22197                                    "}"));
22198   EXPECT_EQ(FormatStyle::LK_Cpp,
22199             guessLanguage("foo.h", "void f() {\n"
22200                                    "  asm volatile (\"mov %[e], %[d]\"\n"
22201                                    "     : [d] \"=rm\" (d)\n"
22202                                    "       [e] \"rm\" (*e));\n"
22203                                    "}"));
22204 }
22205 
22206 TEST_F(FormatTest, GuessLanguageWithChildLines) {
22207   EXPECT_EQ(FormatStyle::LK_Cpp,
22208             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
22209   EXPECT_EQ(FormatStyle::LK_ObjC,
22210             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
22211   EXPECT_EQ(
22212       FormatStyle::LK_Cpp,
22213       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
22214   EXPECT_EQ(
22215       FormatStyle::LK_ObjC,
22216       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
22217 }
22218 
22219 TEST_F(FormatTest, TypenameMacros) {
22220   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
22221 
22222   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
22223   FormatStyle Google = getGoogleStyleWithColumns(0);
22224   Google.TypenameMacros = TypenameMacros;
22225   verifyFormat("struct foo {\n"
22226                "  int bar;\n"
22227                "  TAILQ_ENTRY(a) bleh;\n"
22228                "};",
22229                Google);
22230 
22231   FormatStyle Macros = getLLVMStyle();
22232   Macros.TypenameMacros = TypenameMacros;
22233 
22234   verifyFormat("STACK_OF(int) a;", Macros);
22235   verifyFormat("STACK_OF(int) *a;", Macros);
22236   verifyFormat("STACK_OF(int const *) *a;", Macros);
22237   verifyFormat("STACK_OF(int *const) *a;", Macros);
22238   verifyFormat("STACK_OF(int, string) a;", Macros);
22239   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
22240   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
22241   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
22242   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
22243   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
22244   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
22245 
22246   Macros.PointerAlignment = FormatStyle::PAS_Left;
22247   verifyFormat("STACK_OF(int)* a;", Macros);
22248   verifyFormat("STACK_OF(int*)* a;", Macros);
22249   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
22250   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
22251   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
22252 }
22253 
22254 TEST_F(FormatTest, AtomicQualifier) {
22255   // Check that we treate _Atomic as a type and not a function call
22256   FormatStyle Google = getGoogleStyleWithColumns(0);
22257   verifyFormat("struct foo {\n"
22258                "  int a1;\n"
22259                "  _Atomic(a) a2;\n"
22260                "  _Atomic(_Atomic(int) *const) a3;\n"
22261                "};",
22262                Google);
22263   verifyFormat("_Atomic(uint64_t) a;");
22264   verifyFormat("_Atomic(uint64_t) *a;");
22265   verifyFormat("_Atomic(uint64_t const *) *a;");
22266   verifyFormat("_Atomic(uint64_t *const) *a;");
22267   verifyFormat("_Atomic(const uint64_t *) *a;");
22268   verifyFormat("_Atomic(uint64_t) a;");
22269   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
22270   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
22271   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
22272   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
22273 
22274   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
22275   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
22276   FormatStyle Style = getLLVMStyle();
22277   Style.PointerAlignment = FormatStyle::PAS_Left;
22278   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
22279   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
22280   verifyFormat("_Atomic(int)* a;", Style);
22281   verifyFormat("_Atomic(int*)* a;", Style);
22282   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
22283 
22284   Style.SpacesInCStyleCastParentheses = true;
22285   Style.SpacesInParentheses = false;
22286   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
22287   Style.SpacesInCStyleCastParentheses = false;
22288   Style.SpacesInParentheses = true;
22289   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
22290   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
22291 }
22292 
22293 TEST_F(FormatTest, AmbersandInLamda) {
22294   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
22295   FormatStyle AlignStyle = getLLVMStyle();
22296   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
22297   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22298   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
22299   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22300 }
22301 
22302 TEST_F(FormatTest, SpacesInConditionalStatement) {
22303   FormatStyle Spaces = getLLVMStyle();
22304   Spaces.IfMacros.clear();
22305   Spaces.IfMacros.push_back("MYIF");
22306   Spaces.SpacesInConditionalStatement = true;
22307   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
22308   verifyFormat("if ( !a )\n  return;", Spaces);
22309   verifyFormat("if ( a )\n  return;", Spaces);
22310   verifyFormat("if constexpr ( a )\n  return;", Spaces);
22311   verifyFormat("MYIF ( a )\n  return;", Spaces);
22312   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
22313   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
22314   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
22315   verifyFormat("while ( a )\n  return;", Spaces);
22316   verifyFormat("while ( (a && b) )\n  return;", Spaces);
22317   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
22318   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
22319   // Check that space on the left of "::" is inserted as expected at beginning
22320   // of condition.
22321   verifyFormat("while ( ::func() )\n  return;", Spaces);
22322 
22323   // Check impact of ControlStatementsExceptControlMacros is honored.
22324   Spaces.SpaceBeforeParens =
22325       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
22326   verifyFormat("MYIF( a )\n  return;", Spaces);
22327   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
22328   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
22329 }
22330 
22331 TEST_F(FormatTest, AlternativeOperators) {
22332   // Test case for ensuring alternate operators are not
22333   // combined with their right most neighbour.
22334   verifyFormat("int a and b;");
22335   verifyFormat("int a and_eq b;");
22336   verifyFormat("int a bitand b;");
22337   verifyFormat("int a bitor b;");
22338   verifyFormat("int a compl b;");
22339   verifyFormat("int a not b;");
22340   verifyFormat("int a not_eq b;");
22341   verifyFormat("int a or b;");
22342   verifyFormat("int a xor b;");
22343   verifyFormat("int a xor_eq b;");
22344   verifyFormat("return this not_eq bitand other;");
22345   verifyFormat("bool operator not_eq(const X bitand other)");
22346 
22347   verifyFormat("int a and 5;");
22348   verifyFormat("int a and_eq 5;");
22349   verifyFormat("int a bitand 5;");
22350   verifyFormat("int a bitor 5;");
22351   verifyFormat("int a compl 5;");
22352   verifyFormat("int a not 5;");
22353   verifyFormat("int a not_eq 5;");
22354   verifyFormat("int a or 5;");
22355   verifyFormat("int a xor 5;");
22356   verifyFormat("int a xor_eq 5;");
22357 
22358   verifyFormat("int a compl(5);");
22359   verifyFormat("int a not(5);");
22360 
22361   /* FIXME handle alternate tokens
22362    * https://en.cppreference.com/w/cpp/language/operator_alternative
22363   // alternative tokens
22364   verifyFormat("compl foo();");     //  ~foo();
22365   verifyFormat("foo() <%%>;");      // foo();
22366   verifyFormat("void foo() <%%>;"); // void foo(){}
22367   verifyFormat("int a <:1:>;");     // int a[1];[
22368   verifyFormat("%:define ABC abc"); // #define ABC abc
22369   verifyFormat("%:%:");             // ##
22370   */
22371 }
22372 
22373 TEST_F(FormatTest, STLWhileNotDefineChed) {
22374   verifyFormat("#if defined(while)\n"
22375                "#define while EMIT WARNING C4005\n"
22376                "#endif // while");
22377 }
22378 
22379 TEST_F(FormatTest, OperatorSpacing) {
22380   FormatStyle Style = getLLVMStyle();
22381   Style.PointerAlignment = FormatStyle::PAS_Right;
22382   verifyFormat("Foo::operator*();", Style);
22383   verifyFormat("Foo::operator void *();", Style);
22384   verifyFormat("Foo::operator void **();", Style);
22385   verifyFormat("Foo::operator void *&();", Style);
22386   verifyFormat("Foo::operator void *&&();", Style);
22387   verifyFormat("Foo::operator void const *();", Style);
22388   verifyFormat("Foo::operator void const **();", Style);
22389   verifyFormat("Foo::operator void const *&();", Style);
22390   verifyFormat("Foo::operator void const *&&();", Style);
22391   verifyFormat("Foo::operator()(void *);", Style);
22392   verifyFormat("Foo::operator*(void *);", Style);
22393   verifyFormat("Foo::operator*();", Style);
22394   verifyFormat("Foo::operator**();", Style);
22395   verifyFormat("Foo::operator&();", Style);
22396   verifyFormat("Foo::operator<int> *();", Style);
22397   verifyFormat("Foo::operator<Foo> *();", Style);
22398   verifyFormat("Foo::operator<int> **();", Style);
22399   verifyFormat("Foo::operator<Foo> **();", Style);
22400   verifyFormat("Foo::operator<int> &();", Style);
22401   verifyFormat("Foo::operator<Foo> &();", Style);
22402   verifyFormat("Foo::operator<int> &&();", Style);
22403   verifyFormat("Foo::operator<Foo> &&();", Style);
22404   verifyFormat("Foo::operator<int> *&();", Style);
22405   verifyFormat("Foo::operator<Foo> *&();", Style);
22406   verifyFormat("Foo::operator<int> *&&();", Style);
22407   verifyFormat("Foo::operator<Foo> *&&();", Style);
22408   verifyFormat("operator*(int (*)(), class Foo);", Style);
22409 
22410   verifyFormat("Foo::operator&();", Style);
22411   verifyFormat("Foo::operator void &();", Style);
22412   verifyFormat("Foo::operator void const &();", Style);
22413   verifyFormat("Foo::operator()(void &);", Style);
22414   verifyFormat("Foo::operator&(void &);", Style);
22415   verifyFormat("Foo::operator&();", Style);
22416   verifyFormat("operator&(int (&)(), class Foo);", Style);
22417   verifyFormat("operator&&(int (&)(), class Foo);", Style);
22418 
22419   verifyFormat("Foo::operator&&();", Style);
22420   verifyFormat("Foo::operator**();", Style);
22421   verifyFormat("Foo::operator void &&();", Style);
22422   verifyFormat("Foo::operator void const &&();", Style);
22423   verifyFormat("Foo::operator()(void &&);", Style);
22424   verifyFormat("Foo::operator&&(void &&);", Style);
22425   verifyFormat("Foo::operator&&();", Style);
22426   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22427   verifyFormat("operator const nsTArrayRight<E> &()", Style);
22428   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
22429                Style);
22430   verifyFormat("operator void **()", Style);
22431   verifyFormat("operator const FooRight<Object> &()", Style);
22432   verifyFormat("operator const FooRight<Object> *()", Style);
22433   verifyFormat("operator const FooRight<Object> **()", Style);
22434   verifyFormat("operator const FooRight<Object> *&()", Style);
22435   verifyFormat("operator const FooRight<Object> *&&()", Style);
22436 
22437   Style.PointerAlignment = FormatStyle::PAS_Left;
22438   verifyFormat("Foo::operator*();", Style);
22439   verifyFormat("Foo::operator**();", Style);
22440   verifyFormat("Foo::operator void*();", Style);
22441   verifyFormat("Foo::operator void**();", Style);
22442   verifyFormat("Foo::operator void*&();", Style);
22443   verifyFormat("Foo::operator void*&&();", Style);
22444   verifyFormat("Foo::operator void const*();", Style);
22445   verifyFormat("Foo::operator void const**();", Style);
22446   verifyFormat("Foo::operator void const*&();", Style);
22447   verifyFormat("Foo::operator void const*&&();", Style);
22448   verifyFormat("Foo::operator/*comment*/ void*();", Style);
22449   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
22450   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
22451   verifyFormat("Foo::operator()(void*);", Style);
22452   verifyFormat("Foo::operator*(void*);", Style);
22453   verifyFormat("Foo::operator*();", Style);
22454   verifyFormat("Foo::operator<int>*();", Style);
22455   verifyFormat("Foo::operator<Foo>*();", Style);
22456   verifyFormat("Foo::operator<int>**();", Style);
22457   verifyFormat("Foo::operator<Foo>**();", Style);
22458   verifyFormat("Foo::operator<Foo>*&();", Style);
22459   verifyFormat("Foo::operator<int>&();", Style);
22460   verifyFormat("Foo::operator<Foo>&();", Style);
22461   verifyFormat("Foo::operator<int>&&();", Style);
22462   verifyFormat("Foo::operator<Foo>&&();", Style);
22463   verifyFormat("Foo::operator<int>*&();", Style);
22464   verifyFormat("Foo::operator<Foo>*&();", Style);
22465   verifyFormat("operator*(int (*)(), class Foo);", Style);
22466 
22467   verifyFormat("Foo::operator&();", Style);
22468   verifyFormat("Foo::operator void&();", Style);
22469   verifyFormat("Foo::operator void const&();", Style);
22470   verifyFormat("Foo::operator/*comment*/ void&();", Style);
22471   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
22472   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
22473   verifyFormat("Foo::operator()(void&);", Style);
22474   verifyFormat("Foo::operator&(void&);", Style);
22475   verifyFormat("Foo::operator&();", Style);
22476   verifyFormat("operator&(int (&)(), class Foo);", Style);
22477   verifyFormat("operator&(int (&&)(), class Foo);", Style);
22478   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22479 
22480   verifyFormat("Foo::operator&&();", Style);
22481   verifyFormat("Foo::operator void&&();", Style);
22482   verifyFormat("Foo::operator void const&&();", Style);
22483   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
22484   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
22485   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
22486   verifyFormat("Foo::operator()(void&&);", Style);
22487   verifyFormat("Foo::operator&&(void&&);", Style);
22488   verifyFormat("Foo::operator&&();", Style);
22489   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22490   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
22491   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
22492                Style);
22493   verifyFormat("operator void**()", Style);
22494   verifyFormat("operator const FooLeft<Object>&()", Style);
22495   verifyFormat("operator const FooLeft<Object>*()", Style);
22496   verifyFormat("operator const FooLeft<Object>**()", Style);
22497   verifyFormat("operator const FooLeft<Object>*&()", Style);
22498   verifyFormat("operator const FooLeft<Object>*&&()", Style);
22499 
22500   // PR45107
22501   verifyFormat("operator Vector<String>&();", Style);
22502   verifyFormat("operator const Vector<String>&();", Style);
22503   verifyFormat("operator foo::Bar*();", Style);
22504   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
22505   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
22506                Style);
22507 
22508   Style.PointerAlignment = FormatStyle::PAS_Middle;
22509   verifyFormat("Foo::operator*();", Style);
22510   verifyFormat("Foo::operator void *();", Style);
22511   verifyFormat("Foo::operator()(void *);", Style);
22512   verifyFormat("Foo::operator*(void *);", Style);
22513   verifyFormat("Foo::operator*();", Style);
22514   verifyFormat("operator*(int (*)(), class Foo);", Style);
22515 
22516   verifyFormat("Foo::operator&();", Style);
22517   verifyFormat("Foo::operator void &();", Style);
22518   verifyFormat("Foo::operator void const &();", Style);
22519   verifyFormat("Foo::operator()(void &);", Style);
22520   verifyFormat("Foo::operator&(void &);", Style);
22521   verifyFormat("Foo::operator&();", Style);
22522   verifyFormat("operator&(int (&)(), class Foo);", Style);
22523 
22524   verifyFormat("Foo::operator&&();", Style);
22525   verifyFormat("Foo::operator void &&();", Style);
22526   verifyFormat("Foo::operator void const &&();", Style);
22527   verifyFormat("Foo::operator()(void &&);", Style);
22528   verifyFormat("Foo::operator&&(void &&);", Style);
22529   verifyFormat("Foo::operator&&();", Style);
22530   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22531 }
22532 
22533 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
22534   FormatStyle Style = getLLVMStyle();
22535   // PR46157
22536   verifyFormat("foo(operator+, -42);", Style);
22537   verifyFormat("foo(operator++, -42);", Style);
22538   verifyFormat("foo(operator--, -42);", Style);
22539   verifyFormat("foo(-42, operator--);", Style);
22540   verifyFormat("foo(-42, operator, );", Style);
22541   verifyFormat("foo(operator, , -42);", Style);
22542 }
22543 
22544 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
22545   FormatStyle Style = getLLVMStyle();
22546   Style.WhitespaceSensitiveMacros.push_back("FOO");
22547 
22548   // Don't use the helpers here, since 'mess up' will change the whitespace
22549   // and these are all whitespace sensitive by definition
22550   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
22551             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
22552   EXPECT_EQ(
22553       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
22554       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
22555   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
22556             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
22557   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
22558             "       Still=Intentional);",
22559             format("FOO(String-ized&Messy+But,: :\n"
22560                    "       Still=Intentional);",
22561                    Style));
22562   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
22563   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
22564             "       Still=Intentional);",
22565             format("FOO(String-ized=&Messy+But,: :\n"
22566                    "       Still=Intentional);",
22567                    Style));
22568 
22569   Style.ColumnLimit = 21;
22570   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
22571             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
22572 }
22573 
22574 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
22575   // These tests are not in NamespaceFixer because that doesn't
22576   // test its interaction with line wrapping
22577   FormatStyle Style = getLLVMStyleWithColumns(80);
22578   verifyFormat("namespace {\n"
22579                "int i;\n"
22580                "int j;\n"
22581                "} // namespace",
22582                Style);
22583 
22584   verifyFormat("namespace AAA {\n"
22585                "int i;\n"
22586                "int j;\n"
22587                "} // namespace AAA",
22588                Style);
22589 
22590   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
22591             "int i;\n"
22592             "int j;\n"
22593             "} // namespace Averyveryveryverylongnamespace",
22594             format("namespace Averyveryveryverylongnamespace {\n"
22595                    "int i;\n"
22596                    "int j;\n"
22597                    "}",
22598                    Style));
22599 
22600   EXPECT_EQ(
22601       "namespace "
22602       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
22603       "    went::mad::now {\n"
22604       "int i;\n"
22605       "int j;\n"
22606       "} // namespace\n"
22607       "  // "
22608       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
22609       "went::mad::now",
22610       format("namespace "
22611              "would::it::save::you::a::lot::of::time::if_::i::"
22612              "just::gave::up::and_::went::mad::now {\n"
22613              "int i;\n"
22614              "int j;\n"
22615              "}",
22616              Style));
22617 
22618   // This used to duplicate the comment again and again on subsequent runs
22619   EXPECT_EQ(
22620       "namespace "
22621       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
22622       "    went::mad::now {\n"
22623       "int i;\n"
22624       "int j;\n"
22625       "} // namespace\n"
22626       "  // "
22627       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
22628       "went::mad::now",
22629       format("namespace "
22630              "would::it::save::you::a::lot::of::time::if_::i::"
22631              "just::gave::up::and_::went::mad::now {\n"
22632              "int i;\n"
22633              "int j;\n"
22634              "} // namespace\n"
22635              "  // "
22636              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
22637              "and_::went::mad::now",
22638              Style));
22639 }
22640 
22641 TEST_F(FormatTest, LikelyUnlikely) {
22642   FormatStyle Style = getLLVMStyle();
22643 
22644   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22645                "  return 29;\n"
22646                "}",
22647                Style);
22648 
22649   verifyFormat("if (argc > 5) [[likely]] {\n"
22650                "  return 29;\n"
22651                "}",
22652                Style);
22653 
22654   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22655                "  return 29;\n"
22656                "} else [[likely]] {\n"
22657                "  return 42;\n"
22658                "}\n",
22659                Style);
22660 
22661   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22662                "  return 29;\n"
22663                "} else if (argc > 10) [[likely]] {\n"
22664                "  return 99;\n"
22665                "} else {\n"
22666                "  return 42;\n"
22667                "}\n",
22668                Style);
22669 
22670   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
22671                "  return 29;\n"
22672                "}",
22673                Style);
22674 
22675   verifyFormat("if (argc > 5) [[unlikely]]\n"
22676                "  return 29;\n",
22677                Style);
22678   verifyFormat("if (argc > 5) [[likely]]\n"
22679                "  return 29;\n",
22680                Style);
22681 
22682   Style.AttributeMacros.push_back("UNLIKELY");
22683   Style.AttributeMacros.push_back("LIKELY");
22684   verifyFormat("if (argc > 5) UNLIKELY\n"
22685                "  return 29;\n",
22686                Style);
22687 
22688   verifyFormat("if (argc > 5) UNLIKELY {\n"
22689                "  return 29;\n"
22690                "}",
22691                Style);
22692   verifyFormat("if (argc > 5) UNLIKELY {\n"
22693                "  return 29;\n"
22694                "} else [[likely]] {\n"
22695                "  return 42;\n"
22696                "}\n",
22697                Style);
22698   verifyFormat("if (argc > 5) UNLIKELY {\n"
22699                "  return 29;\n"
22700                "} else LIKELY {\n"
22701                "  return 42;\n"
22702                "}\n",
22703                Style);
22704   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22705                "  return 29;\n"
22706                "} else LIKELY {\n"
22707                "  return 42;\n"
22708                "}\n",
22709                Style);
22710 }
22711 
22712 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
22713   verifyFormat("Constructor()\n"
22714                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
22715                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
22716                "aaaaaaaaaaaaaaaaaat))");
22717   verifyFormat("Constructor()\n"
22718                "    : aaaaaaaaaaaaa(aaaaaa), "
22719                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
22720 
22721   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
22722   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
22723   verifyFormat("Constructor()\n"
22724                "    : aaaaaa(aaaaaa),\n"
22725                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
22726                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
22727                StyleWithWhitespacePenalty);
22728   verifyFormat("Constructor()\n"
22729                "    : aaaaaaaaaaaaa(aaaaaa), "
22730                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
22731                StyleWithWhitespacePenalty);
22732 }
22733 
22734 TEST_F(FormatTest, LLVMDefaultStyle) {
22735   FormatStyle Style = getLLVMStyle();
22736   verifyFormat("extern \"C\" {\n"
22737                "int foo();\n"
22738                "}",
22739                Style);
22740 }
22741 TEST_F(FormatTest, GNUDefaultStyle) {
22742   FormatStyle Style = getGNUStyle();
22743   verifyFormat("extern \"C\"\n"
22744                "{\n"
22745                "  int foo ();\n"
22746                "}",
22747                Style);
22748 }
22749 TEST_F(FormatTest, MozillaDefaultStyle) {
22750   FormatStyle Style = getMozillaStyle();
22751   verifyFormat("extern \"C\"\n"
22752                "{\n"
22753                "  int foo();\n"
22754                "}",
22755                Style);
22756 }
22757 TEST_F(FormatTest, GoogleDefaultStyle) {
22758   FormatStyle Style = getGoogleStyle();
22759   verifyFormat("extern \"C\" {\n"
22760                "int foo();\n"
22761                "}",
22762                Style);
22763 }
22764 TEST_F(FormatTest, ChromiumDefaultStyle) {
22765   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
22766   verifyFormat("extern \"C\" {\n"
22767                "int foo();\n"
22768                "}",
22769                Style);
22770 }
22771 TEST_F(FormatTest, MicrosoftDefaultStyle) {
22772   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
22773   verifyFormat("extern \"C\"\n"
22774                "{\n"
22775                "    int foo();\n"
22776                "}",
22777                Style);
22778 }
22779 TEST_F(FormatTest, WebKitDefaultStyle) {
22780   FormatStyle Style = getWebKitStyle();
22781   verifyFormat("extern \"C\" {\n"
22782                "int foo();\n"
22783                "}",
22784                Style);
22785 }
22786 
22787 TEST_F(FormatTest, ConceptsAndRequires) {
22788   FormatStyle Style = getLLVMStyle();
22789   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
22790 
22791   verifyFormat("template <typename T>\n"
22792                "concept Hashable = requires(T a) {\n"
22793                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22794                "};",
22795                Style);
22796   verifyFormat("template <typename T>\n"
22797                "concept EqualityComparable = requires(T a, T b) {\n"
22798                "  { a == b } -> bool;\n"
22799                "};",
22800                Style);
22801   verifyFormat("template <typename T>\n"
22802                "concept EqualityComparable = requires(T a, T b) {\n"
22803                "  { a == b } -> bool;\n"
22804                "  { a != b } -> bool;\n"
22805                "};",
22806                Style);
22807   verifyFormat("template <typename T>\n"
22808                "concept EqualityComparable = requires(T a, T b) {\n"
22809                "  { a == b } -> bool;\n"
22810                "  { a != b } -> bool;\n"
22811                "};",
22812                Style);
22813 
22814   verifyFormat("template <typename It>\n"
22815                "requires Iterator<It>\n"
22816                "void sort(It begin, It end) {\n"
22817                "  //....\n"
22818                "}",
22819                Style);
22820 
22821   verifyFormat("template <typename T>\n"
22822                "concept Large = sizeof(T) > 10;",
22823                Style);
22824 
22825   verifyFormat("template <typename T, typename U>\n"
22826                "concept FooableWith = requires(T t, U u) {\n"
22827                "  typename T::foo_type;\n"
22828                "  { t.foo(u) } -> typename T::foo_type;\n"
22829                "  t++;\n"
22830                "};\n"
22831                "void doFoo(FooableWith<int> auto t) {\n"
22832                "  t.foo(3);\n"
22833                "}",
22834                Style);
22835   verifyFormat("template <typename T>\n"
22836                "concept Context = sizeof(T) == 1;",
22837                Style);
22838   verifyFormat("template <typename T>\n"
22839                "concept Context = is_specialization_of_v<context, T>;",
22840                Style);
22841   verifyFormat("template <typename T>\n"
22842                "concept Node = std::is_object_v<T>;",
22843                Style);
22844   verifyFormat("template <typename T>\n"
22845                "concept Tree = true;",
22846                Style);
22847 
22848   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
22849                "  //...\n"
22850                "}",
22851                Style);
22852 
22853   verifyFormat(
22854       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
22855       "  //...\n"
22856       "}",
22857       Style);
22858 
22859   verifyFormat(
22860       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
22861       "  //...\n"
22862       "}",
22863       Style);
22864 
22865   verifyFormat("template <typename T>\n"
22866                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
22867                "Concept2<I> {\n"
22868                "  //...\n"
22869                "}",
22870                Style);
22871 
22872   verifyFormat("template <typename T>\n"
22873                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
22874                "Concept2<I> {\n"
22875                "  //...\n"
22876                "}",
22877                Style);
22878 
22879   verifyFormat(
22880       "template <typename T>\n"
22881       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
22882       "  //...\n"
22883       "}",
22884       Style);
22885 
22886   verifyFormat(
22887       "template <typename T>\n"
22888       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
22889       "  //...\n"
22890       "}",
22891       Style);
22892 
22893   verifyFormat("template <typename It>\n"
22894                "requires Foo<It>() && Bar<It> {\n"
22895                "  //....\n"
22896                "}",
22897                Style);
22898 
22899   verifyFormat("template <typename It>\n"
22900                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
22901                "  //....\n"
22902                "}",
22903                Style);
22904 
22905   verifyFormat("template <typename It>\n"
22906                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
22907                "  //....\n"
22908                "}",
22909                Style);
22910 
22911   verifyFormat(
22912       "template <typename It>\n"
22913       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
22914       "  //....\n"
22915       "}",
22916       Style);
22917 
22918   Style.IndentRequires = true;
22919   verifyFormat("template <typename It>\n"
22920                "  requires Iterator<It>\n"
22921                "void sort(It begin, It end) {\n"
22922                "  //....\n"
22923                "}",
22924                Style);
22925   verifyFormat("template <std::size index_>\n"
22926                "  requires(index_ < sizeof...(Children_))\n"
22927                "Tree auto &child() {\n"
22928                "  // ...\n"
22929                "}",
22930                Style);
22931 
22932   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
22933   verifyFormat("template <typename T>\n"
22934                "concept Hashable = requires (T a) {\n"
22935                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22936                "};",
22937                Style);
22938 
22939   verifyFormat("template <class T = void>\n"
22940                "  requires EqualityComparable<T> || Same<T, void>\n"
22941                "struct equal_to;",
22942                Style);
22943 
22944   verifyFormat("template <class T>\n"
22945                "  requires requires {\n"
22946                "    T{};\n"
22947                "    T (int);\n"
22948                "  }\n",
22949                Style);
22950 
22951   Style.ColumnLimit = 78;
22952   verifyFormat("template <typename T>\n"
22953                "concept Context = Traits<typename T::traits_type> and\n"
22954                "    Interface<typename T::interface_type> and\n"
22955                "    Request<typename T::request_type> and\n"
22956                "    Response<typename T::response_type> and\n"
22957                "    ContextExtension<typename T::extension_type> and\n"
22958                "    ::std::is_copy_constructable<T> and "
22959                "::std::is_move_constructable<T> and\n"
22960                "    requires (T c) {\n"
22961                "  { c.response; } -> Response;\n"
22962                "} and requires (T c) {\n"
22963                "  { c.request; } -> Request;\n"
22964                "}\n",
22965                Style);
22966 
22967   verifyFormat("template <typename T>\n"
22968                "concept Context = Traits<typename T::traits_type> or\n"
22969                "    Interface<typename T::interface_type> or\n"
22970                "    Request<typename T::request_type> or\n"
22971                "    Response<typename T::response_type> or\n"
22972                "    ContextExtension<typename T::extension_type> or\n"
22973                "    ::std::is_copy_constructable<T> or "
22974                "::std::is_move_constructable<T> or\n"
22975                "    requires (T c) {\n"
22976                "  { c.response; } -> Response;\n"
22977                "} or requires (T c) {\n"
22978                "  { c.request; } -> Request;\n"
22979                "}\n",
22980                Style);
22981 
22982   verifyFormat("template <typename T>\n"
22983                "concept Context = Traits<typename T::traits_type> &&\n"
22984                "    Interface<typename T::interface_type> &&\n"
22985                "    Request<typename T::request_type> &&\n"
22986                "    Response<typename T::response_type> &&\n"
22987                "    ContextExtension<typename T::extension_type> &&\n"
22988                "    ::std::is_copy_constructable<T> && "
22989                "::std::is_move_constructable<T> &&\n"
22990                "    requires (T c) {\n"
22991                "  { c.response; } -> Response;\n"
22992                "} && requires (T c) {\n"
22993                "  { c.request; } -> Request;\n"
22994                "}\n",
22995                Style);
22996 
22997   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
22998                "Constraint2<T>;");
22999 
23000   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
23001   Style.BraceWrapping.AfterFunction = true;
23002   Style.BraceWrapping.AfterClass = true;
23003   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
23004   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
23005   verifyFormat("void Foo () requires (std::copyable<T>)\n"
23006                "{\n"
23007                "  return\n"
23008                "}\n",
23009                Style);
23010 
23011   verifyFormat("void Foo () requires std::copyable<T>\n"
23012                "{\n"
23013                "  return\n"
23014                "}\n",
23015                Style);
23016 
23017   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
23018                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
23019                "struct constant;",
23020                Style);
23021 
23022   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
23023                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
23024                "struct constant;",
23025                Style);
23026 
23027   verifyFormat("template <class T>\n"
23028                "class plane_with_very_very_very_long_name\n"
23029                "{\n"
23030                "  constexpr plane_with_very_very_very_long_name () requires "
23031                "std::copyable<T>\n"
23032                "      : plane_with_very_very_very_long_name (1)\n"
23033                "  {\n"
23034                "  }\n"
23035                "}\n",
23036                Style);
23037 
23038   verifyFormat("template <class T>\n"
23039                "class plane_with_long_name\n"
23040                "{\n"
23041                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
23042                "      : plane_with_long_name (1)\n"
23043                "  {\n"
23044                "  }\n"
23045                "}\n",
23046                Style);
23047 
23048   Style.BreakBeforeConceptDeclarations = false;
23049   verifyFormat("template <typename T> concept Tree = true;", Style);
23050 
23051   Style.IndentRequires = false;
23052   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
23053                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
23054                "struct constant;",
23055                Style);
23056 }
23057 
23058 TEST_F(FormatTest, StatementAttributeLikeMacros) {
23059   FormatStyle Style = getLLVMStyle();
23060   StringRef Source = "void Foo::slot() {\n"
23061                      "  unsigned char MyChar = 'x';\n"
23062                      "  emit signal(MyChar);\n"
23063                      "  Q_EMIT signal(MyChar);\n"
23064                      "}";
23065 
23066   EXPECT_EQ(Source, format(Source, Style));
23067 
23068   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
23069   EXPECT_EQ("void Foo::slot() {\n"
23070             "  unsigned char MyChar = 'x';\n"
23071             "  emit          signal(MyChar);\n"
23072             "  Q_EMIT signal(MyChar);\n"
23073             "}",
23074             format(Source, Style));
23075 
23076   Style.StatementAttributeLikeMacros.push_back("emit");
23077   EXPECT_EQ(Source, format(Source, Style));
23078 
23079   Style.StatementAttributeLikeMacros = {};
23080   EXPECT_EQ("void Foo::slot() {\n"
23081             "  unsigned char MyChar = 'x';\n"
23082             "  emit          signal(MyChar);\n"
23083             "  Q_EMIT        signal(MyChar);\n"
23084             "}",
23085             format(Source, Style));
23086 }
23087 
23088 TEST_F(FormatTest, IndentAccessModifiers) {
23089   FormatStyle Style = getLLVMStyle();
23090   Style.IndentAccessModifiers = true;
23091   // Members are *two* levels below the record;
23092   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
23093   verifyFormat("class C {\n"
23094                "    int i;\n"
23095                "};\n",
23096                Style);
23097   verifyFormat("union C {\n"
23098                "    int i;\n"
23099                "    unsigned u;\n"
23100                "};\n",
23101                Style);
23102   // Access modifiers should be indented one level below the record.
23103   verifyFormat("class C {\n"
23104                "  public:\n"
23105                "    int i;\n"
23106                "};\n",
23107                Style);
23108   verifyFormat("struct S {\n"
23109                "  private:\n"
23110                "    class C {\n"
23111                "        int j;\n"
23112                "\n"
23113                "      public:\n"
23114                "        C();\n"
23115                "    };\n"
23116                "\n"
23117                "  public:\n"
23118                "    int i;\n"
23119                "};\n",
23120                Style);
23121   // Enumerations are not records and should be unaffected.
23122   Style.AllowShortEnumsOnASingleLine = false;
23123   verifyFormat("enum class E {\n"
23124                "  A,\n"
23125                "  B\n"
23126                "};\n",
23127                Style);
23128   // Test with a different indentation width;
23129   // also proves that the result is Style.AccessModifierOffset agnostic.
23130   Style.IndentWidth = 3;
23131   verifyFormat("class C {\n"
23132                "   public:\n"
23133                "      int i;\n"
23134                "};\n",
23135                Style);
23136 }
23137 
23138 TEST_F(FormatTest, LimitlessStringsAndComments) {
23139   auto Style = getLLVMStyleWithColumns(0);
23140   constexpr StringRef Code =
23141       "/**\n"
23142       " * This is a multiline comment with quite some long lines, at least for "
23143       "the LLVM Style.\n"
23144       " * We will redo this with strings and line comments. Just to  check if "
23145       "everything is working.\n"
23146       " */\n"
23147       "bool foo() {\n"
23148       "  /* Single line multi line comment. */\n"
23149       "  const std::string String = \"This is a multiline string with quite "
23150       "some long lines, at least for the LLVM Style.\"\n"
23151       "                             \"We already did it with multi line "
23152       "comments, and we will do it with line comments. Just to check if "
23153       "everything is working.\";\n"
23154       "  // This is a line comment (block) with quite some long lines, at "
23155       "least for the LLVM Style.\n"
23156       "  // We already did this with multi line comments and strings. Just to "
23157       "check if everything is working.\n"
23158       "  const std::string SmallString = \"Hello World\";\n"
23159       "  // Small line comment\n"
23160       "  return String.size() > SmallString.size();\n"
23161       "}";
23162   EXPECT_EQ(Code, format(Code, Style));
23163 }
23164 
23165 TEST_F(FormatTest, FormatDecayCopy) {
23166   // error cases from unit tests
23167   verifyFormat("foo(auto())");
23168   verifyFormat("foo(auto{})");
23169   verifyFormat("foo(auto({}))");
23170   verifyFormat("foo(auto{{}})");
23171 
23172   verifyFormat("foo(auto(1))");
23173   verifyFormat("foo(auto{1})");
23174   verifyFormat("foo(new auto(1))");
23175   verifyFormat("foo(new auto{1})");
23176   verifyFormat("decltype(auto(1)) x;");
23177   verifyFormat("decltype(auto{1}) x;");
23178   verifyFormat("auto(x);");
23179   verifyFormat("auto{x};");
23180   verifyFormat("new auto{x};");
23181   verifyFormat("auto{x} = y;");
23182   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
23183                                 // the user's own fault
23184   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
23185                                          // clearly the user's own fault
23186   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
23187 }
23188 
23189 TEST_F(FormatTest, Cpp20ModulesSupport) {
23190   FormatStyle Style = getLLVMStyle();
23191   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
23192   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
23193 
23194   verifyFormat("export import foo;", Style);
23195   verifyFormat("export import foo:bar;", Style);
23196   verifyFormat("export import foo.bar;", Style);
23197   verifyFormat("export import foo.bar:baz;", Style);
23198   verifyFormat("export import :bar;", Style);
23199   verifyFormat("export module foo:bar;", Style);
23200   verifyFormat("export module foo;", Style);
23201   verifyFormat("export module foo.bar;", Style);
23202   verifyFormat("export module foo.bar:baz;", Style);
23203   verifyFormat("export import <string_view>;", Style);
23204 
23205   verifyFormat("export type_name var;", Style);
23206   verifyFormat("template <class T> export using A = B<T>;", Style);
23207   verifyFormat("export using A = B;", Style);
23208   verifyFormat("export int func() {\n"
23209                "  foo();\n"
23210                "}",
23211                Style);
23212   verifyFormat("export struct {\n"
23213                "  int foo;\n"
23214                "};",
23215                Style);
23216   verifyFormat("export {\n"
23217                "  int foo;\n"
23218                "};",
23219                Style);
23220   verifyFormat("export export char const *hello() { return \"hello\"; }");
23221 
23222   verifyFormat("import bar;", Style);
23223   verifyFormat("import foo.bar;", Style);
23224   verifyFormat("import foo:bar;", Style);
23225   verifyFormat("import :bar;", Style);
23226   verifyFormat("import <ctime>;", Style);
23227   verifyFormat("import \"header\";", Style);
23228 
23229   verifyFormat("module foo;", Style);
23230   verifyFormat("module foo:bar;", Style);
23231   verifyFormat("module foo.bar;", Style);
23232   verifyFormat("module;", Style);
23233 
23234   verifyFormat("export namespace hi {\n"
23235                "const char *sayhi();\n"
23236                "}",
23237                Style);
23238 
23239   verifyFormat("module :private;", Style);
23240   verifyFormat("import <foo/bar.h>;", Style);
23241   verifyFormat("import foo...bar;", Style);
23242   verifyFormat("import ..........;", Style);
23243   verifyFormat("module foo:private;", Style);
23244   verifyFormat("import a", Style);
23245   verifyFormat("module a", Style);
23246   verifyFormat("export import a", Style);
23247   verifyFormat("export module a", Style);
23248 
23249   verifyFormat("import", Style);
23250   verifyFormat("module", Style);
23251   verifyFormat("export", Style);
23252 }
23253 
23254 TEST_F(FormatTest, CoroutineForCoawait) {
23255   FormatStyle Style = getLLVMStyle();
23256   verifyFormat("for co_await (auto x : range())\n  ;");
23257   verifyFormat("for (auto i : arr) {\n"
23258                "}",
23259                Style);
23260   verifyFormat("for co_await (auto i : arr) {\n"
23261                "}",
23262                Style);
23263   verifyFormat("for co_await (auto i : foo(T{})) {\n"
23264                "}",
23265                Style);
23266 }
23267 
23268 TEST_F(FormatTest, CoroutineCoAwait) {
23269   verifyFormat("int x = co_await foo();");
23270   verifyFormat("int x = (co_await foo());");
23271   verifyFormat("co_await (42);");
23272   verifyFormat("void operator co_await(int);");
23273   verifyFormat("void operator co_await(a);");
23274   verifyFormat("co_await a;");
23275   verifyFormat("co_await missing_await_resume{};");
23276   verifyFormat("co_await a; // comment");
23277   verifyFormat("void test0() { co_await a; }");
23278   verifyFormat("co_await co_await co_await foo();");
23279   verifyFormat("co_await foo().bar();");
23280   verifyFormat("co_await [this]() -> Task { co_return x; }");
23281   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
23282                "foo(); }(x, y);");
23283 
23284   FormatStyle Style = getLLVMStyleWithColumns(40);
23285   verifyFormat("co_await [this](int a, int b) -> Task {\n"
23286                "  co_return co_await foo();\n"
23287                "}(x, y);",
23288                Style);
23289   verifyFormat("co_await;");
23290 }
23291 
23292 TEST_F(FormatTest, CoroutineCoYield) {
23293   verifyFormat("int x = co_yield foo();");
23294   verifyFormat("int x = (co_yield foo());");
23295   verifyFormat("co_yield (42);");
23296   verifyFormat("co_yield {42};");
23297   verifyFormat("co_yield 42;");
23298   verifyFormat("co_yield n++;");
23299   verifyFormat("co_yield ++n;");
23300   verifyFormat("co_yield;");
23301 }
23302 
23303 TEST_F(FormatTest, CoroutineCoReturn) {
23304   verifyFormat("co_return (42);");
23305   verifyFormat("co_return;");
23306   verifyFormat("co_return {};");
23307   verifyFormat("co_return x;");
23308   verifyFormat("co_return co_await foo();");
23309   verifyFormat("co_return co_yield foo();");
23310 }
23311 
23312 TEST_F(FormatTest, EmptyShortBlock) {
23313   auto Style = getLLVMStyle();
23314   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
23315 
23316   verifyFormat("try {\n"
23317                "  doA();\n"
23318                "} catch (Exception &e) {\n"
23319                "  e.printStackTrace();\n"
23320                "}\n",
23321                Style);
23322 
23323   verifyFormat("try {\n"
23324                "  doA();\n"
23325                "} catch (Exception &e) {}\n",
23326                Style);
23327 }
23328 
23329 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
23330   auto Style = getLLVMStyle();
23331 
23332   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
23333   verifyFormat("struct Y<[] { return 0; }> {};", Style);
23334 
23335   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
23336 }
23337 
23338 TEST_F(FormatTest, RemoveBraces) {
23339   FormatStyle Style = getLLVMStyle();
23340   Style.RemoveBracesLLVM = true;
23341 
23342   // The following eight test cases are fully-braced versions of the examples at
23343   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
23344   // statement-bodies-of-if-else-loop-statements".
23345 
23346   // 1. Omit the braces, since the body is simple and clearly associated with
23347   // the if.
23348   verifyFormat("if (isa<FunctionDecl>(D))\n"
23349                "  handleFunctionDecl(D);\n"
23350                "else if (isa<VarDecl>(D))\n"
23351                "  handleVarDecl(D);",
23352                "if (isa<FunctionDecl>(D)) {\n"
23353                "  handleFunctionDecl(D);\n"
23354                "} else if (isa<VarDecl>(D)) {\n"
23355                "  handleVarDecl(D);\n"
23356                "}",
23357                Style);
23358 
23359   // 2. Here we document the condition itself and not the body.
23360   verifyFormat("if (isa<VarDecl>(D)) {\n"
23361                "  // It is necessary that we explain the situation with this\n"
23362                "  // surprisingly long comment, so it would be unclear\n"
23363                "  // without the braces whether the following statement is in\n"
23364                "  // the scope of the `if`.\n"
23365                "  // Because the condition is documented, we can't really\n"
23366                "  // hoist this comment that applies to the body above the\n"
23367                "  // if.\n"
23368                "  handleOtherDecl(D);\n"
23369                "}",
23370                Style);
23371 
23372   // 3. Use braces on the outer `if` to avoid a potential dangling else
23373   // situation.
23374   verifyFormat("if (isa<VarDecl>(D)) {\n"
23375                "  for (auto *A : D.attrs())\n"
23376                "    if (shouldProcessAttr(A))\n"
23377                "      handleAttr(A);\n"
23378                "}",
23379                "if (isa<VarDecl>(D)) {\n"
23380                "  for (auto *A : D.attrs()) {\n"
23381                "    if (shouldProcessAttr(A)) {\n"
23382                "      handleAttr(A);\n"
23383                "    }\n"
23384                "  }\n"
23385                "}",
23386                Style);
23387 
23388   // 4. Use braces for the `if` block to keep it uniform with the else block.
23389   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
23390                "  handleFunctionDecl(D);\n"
23391                "} else {\n"
23392                "  // In this else case, it is necessary that we explain the\n"
23393                "  // situation with this surprisingly long comment, so it\n"
23394                "  // would be unclear without the braces whether the\n"
23395                "  // following statement is in the scope of the `if`.\n"
23396                "  handleOtherDecl(D);\n"
23397                "}",
23398                Style);
23399 
23400   // 5. This should also omit braces.  The `for` loop contains only a single
23401   // statement, so it shouldn't have braces.  The `if` also only contains a
23402   // single simple statement (the for loop), so it also should omit braces.
23403   verifyFormat("if (isa<FunctionDecl>(D))\n"
23404                "  for (auto *A : D.attrs())\n"
23405                "    handleAttr(A);",
23406                "if (isa<FunctionDecl>(D)) {\n"
23407                "  for (auto *A : D.attrs()) {\n"
23408                "    handleAttr(A);\n"
23409                "  }\n"
23410                "}",
23411                Style);
23412 
23413   // 6. Use braces for the outer `if` since the nested `for` is braced.
23414   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
23415                "  for (auto *A : D.attrs()) {\n"
23416                "    // In this for loop body, it is necessary that we explain\n"
23417                "    // the situation with this surprisingly long comment,\n"
23418                "    // forcing braces on the `for` block.\n"
23419                "    handleAttr(A);\n"
23420                "  }\n"
23421                "}",
23422                Style);
23423 
23424   // 7. Use braces on the outer block because there are more than two levels of
23425   // nesting.
23426   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
23427                "  for (auto *A : D.attrs())\n"
23428                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
23429                "      handleAttrOnDecl(D, A, i);\n"
23430                "}",
23431                "if (isa<FunctionDecl>(D)) {\n"
23432                "  for (auto *A : D.attrs()) {\n"
23433                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
23434                "      handleAttrOnDecl(D, A, i);\n"
23435                "    }\n"
23436                "  }\n"
23437                "}",
23438                Style);
23439 
23440   // 8. Use braces on the outer block because of a nested `if`, otherwise the
23441   // compiler would warn: `add explicit braces to avoid dangling else`
23442   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
23443                "  if (shouldProcess(D))\n"
23444                "    handleVarDecl(D);\n"
23445                "  else\n"
23446                "    markAsIgnored(D);\n"
23447                "}",
23448                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
23449                "  if (shouldProcess(D)) {\n"
23450                "    handleVarDecl(D);\n"
23451                "  } else {\n"
23452                "    markAsIgnored(D);\n"
23453                "  }\n"
23454                "}",
23455                Style);
23456 
23457   verifyFormat("if (a)\n"
23458                "  b; // comment\n"
23459                "else if (c)\n"
23460                "  d; /* comment */\n"
23461                "else\n"
23462                "  e;",
23463                "if (a) {\n"
23464                "  b; // comment\n"
23465                "} else if (c) {\n"
23466                "  d; /* comment */\n"
23467                "} else {\n"
23468                "  e;\n"
23469                "}",
23470                Style);
23471 
23472   verifyFormat("if (a) {\n"
23473                "  b;\n"
23474                "  c;\n"
23475                "} else if (d) {\n"
23476                "  e;\n"
23477                "}",
23478                Style);
23479 
23480   verifyFormat("if (a) {\n"
23481                "#undef NDEBUG\n"
23482                "  b;\n"
23483                "} else {\n"
23484                "  c;\n"
23485                "}",
23486                Style);
23487 
23488   verifyFormat("if (a) {\n"
23489                "  // comment\n"
23490                "} else if (b) {\n"
23491                "  c;\n"
23492                "}",
23493                Style);
23494 
23495   verifyFormat("if (a) {\n"
23496                "  b;\n"
23497                "} else {\n"
23498                "  { c; }\n"
23499                "}",
23500                Style);
23501 
23502   verifyFormat("if (a) {\n"
23503                "  if (b) // comment\n"
23504                "    c;\n"
23505                "} else if (d) {\n"
23506                "  e;\n"
23507                "}",
23508                "if (a) {\n"
23509                "  if (b) { // comment\n"
23510                "    c;\n"
23511                "  }\n"
23512                "} else if (d) {\n"
23513                "  e;\n"
23514                "}",
23515                Style);
23516 
23517   verifyFormat("if (a) {\n"
23518                "  if (b) {\n"
23519                "    c;\n"
23520                "    // comment\n"
23521                "  } else if (d) {\n"
23522                "    e;\n"
23523                "  }\n"
23524                "}",
23525                Style);
23526 
23527   verifyFormat("if (a) {\n"
23528                "  if (b)\n"
23529                "    c;\n"
23530                "}",
23531                "if (a) {\n"
23532                "  if (b) {\n"
23533                "    c;\n"
23534                "  }\n"
23535                "}",
23536                Style);
23537 
23538   verifyFormat("if (a)\n"
23539                "  if (b)\n"
23540                "    c;\n"
23541                "  else\n"
23542                "    d;\n"
23543                "else\n"
23544                "  e;",
23545                "if (a) {\n"
23546                "  if (b) {\n"
23547                "    c;\n"
23548                "  } else {\n"
23549                "    d;\n"
23550                "  }\n"
23551                "} else {\n"
23552                "  e;\n"
23553                "}",
23554                Style);
23555 
23556   verifyFormat("if (a) {\n"
23557                "  // comment\n"
23558                "  if (b)\n"
23559                "    c;\n"
23560                "  else if (d)\n"
23561                "    e;\n"
23562                "} else {\n"
23563                "  g;\n"
23564                "}",
23565                "if (a) {\n"
23566                "  // comment\n"
23567                "  if (b) {\n"
23568                "    c;\n"
23569                "  } else if (d) {\n"
23570                "    e;\n"
23571                "  }\n"
23572                "} else {\n"
23573                "  g;\n"
23574                "}",
23575                Style);
23576 
23577   verifyFormat("if (a)\n"
23578                "  b;\n"
23579                "else if (c)\n"
23580                "  d;\n"
23581                "else\n"
23582                "  e;",
23583                "if (a) {\n"
23584                "  b;\n"
23585                "} else {\n"
23586                "  if (c) {\n"
23587                "    d;\n"
23588                "  } else {\n"
23589                "    e;\n"
23590                "  }\n"
23591                "}",
23592                Style);
23593 
23594   verifyFormat("if (a) {\n"
23595                "  if (b)\n"
23596                "    c;\n"
23597                "  else if (d)\n"
23598                "    e;\n"
23599                "} else {\n"
23600                "  g;\n"
23601                "}",
23602                "if (a) {\n"
23603                "  if (b)\n"
23604                "    c;\n"
23605                "  else {\n"
23606                "    if (d)\n"
23607                "      e;\n"
23608                "  }\n"
23609                "} else {\n"
23610                "  g;\n"
23611                "}",
23612                Style);
23613 
23614   verifyFormat("if (a)\n"
23615                "  b;\n"
23616                "else if (c)\n"
23617                "  while (d)\n"
23618                "    e;\n"
23619                "// comment",
23620                "if (a)\n"
23621                "{\n"
23622                "  b;\n"
23623                "} else if (c) {\n"
23624                "  while (d) {\n"
23625                "    e;\n"
23626                "  }\n"
23627                "}\n"
23628                "// comment",
23629                Style);
23630 
23631   verifyFormat("if (a) {\n"
23632                "  b;\n"
23633                "} else if (c) {\n"
23634                "  d;\n"
23635                "} else {\n"
23636                "  e;\n"
23637                "  g;\n"
23638                "}",
23639                Style);
23640 
23641   verifyFormat("if (a) {\n"
23642                "  b;\n"
23643                "} else if (c) {\n"
23644                "  d;\n"
23645                "} else {\n"
23646                "  e;\n"
23647                "} // comment",
23648                Style);
23649 
23650   verifyFormat("int abs = [](int i) {\n"
23651                "  if (i >= 0)\n"
23652                "    return i;\n"
23653                "  return -i;\n"
23654                "};",
23655                "int abs = [](int i) {\n"
23656                "  if (i >= 0) {\n"
23657                "    return i;\n"
23658                "  }\n"
23659                "  return -i;\n"
23660                "};",
23661                Style);
23662 
23663   Style.ColumnLimit = 20;
23664 
23665   verifyFormat("if (a) {\n"
23666                "  b = c + // 1 -\n"
23667                "      d;\n"
23668                "}",
23669                Style);
23670 
23671   verifyFormat("if (a) {\n"
23672                "  b = c >= 0 ? d\n"
23673                "             : e;\n"
23674                "}",
23675                "if (a) {\n"
23676                "  b = c >= 0 ? d : e;\n"
23677                "}",
23678                Style);
23679 
23680   verifyFormat("if (a)\n"
23681                "  b = c > 0 ? d : e;",
23682                "if (a) {\n"
23683                "  b = c > 0 ? d : e;\n"
23684                "}",
23685                Style);
23686 
23687   Style.ColumnLimit = 0;
23688 
23689   verifyFormat("if (a)\n"
23690                "  b234567890223456789032345678904234567890 = "
23691                "c234567890223456789032345678904234567890;",
23692                "if (a) {\n"
23693                "  b234567890223456789032345678904234567890 = "
23694                "c234567890223456789032345678904234567890;\n"
23695                "}",
23696                Style);
23697 }
23698 
23699 } // namespace
23700 } // namespace format
23701 } // namespace clang
23702