xref: /llvm-project/clang/unittests/Format/FormatTest.cpp (revision 93948c5299d7ee446aa707221751a0af2b87c12b)
1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Format/Format.h"
10 
11 #include "../Tooling/ReplacementTest.h"
12 #include "FormatTestUtils.h"
13 
14 #include "llvm/Support/Debug.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "gtest/gtest.h"
17 
18 #define DEBUG_TYPE "format-test"
19 
20 using clang::tooling::ReplacementTest;
21 using clang::tooling::toReplacements;
22 using testing::ScopedTrace;
23 
24 namespace clang {
25 namespace format {
26 namespace {
27 
28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
29 
30 class FormatTest : public ::testing::Test {
31 protected:
32   enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck };
33 
34   std::string format(llvm::StringRef Code,
35                      const FormatStyle &Style = getLLVMStyle(),
36                      StatusCheck CheckComplete = SC_ExpectComplete) {
37     LLVM_DEBUG(llvm::errs() << "---\n");
38     LLVM_DEBUG(llvm::errs() << Code << "\n\n");
39     std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
40     FormattingAttemptStatus Status;
41     tooling::Replacements Replaces =
42         reformat(Style, Code, Ranges, "<stdin>", &Status);
43     if (CheckComplete != SC_DoNotCheck) {
44       bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete;
45       EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete)
46           << Code << "\n\n";
47     }
48     ReplacementCount = Replaces.size();
49     auto Result = applyAllReplacements(Code, Replaces);
50     EXPECT_TRUE(static_cast<bool>(Result));
51     LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
52     return *Result;
53   }
54 
55   FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) {
56     Style.ColumnLimit = ColumnLimit;
57     return Style;
58   }
59 
60   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
61     return getStyleWithColumns(getLLVMStyle(), ColumnLimit);
62   }
63 
64   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
65     return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
66   }
67 
68   void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
69                      llvm::StringRef Code,
70                      const FormatStyle &Style = getLLVMStyle()) {
71     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
72     EXPECT_EQ(Expected.str(), format(Expected, Style))
73         << "Expected code is not stable";
74     EXPECT_EQ(Expected.str(), format(Code, Style));
75     if (Style.Language == FormatStyle::LK_Cpp) {
76       // Objective-C++ is a superset of C++, so everything checked for C++
77       // needs to be checked for Objective-C++ as well.
78       FormatStyle ObjCStyle = Style;
79       ObjCStyle.Language = FormatStyle::LK_ObjC;
80       EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle));
81     }
82   }
83 
84   void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
85                      const FormatStyle &Style = getLLVMStyle()) {
86     _verifyFormat(File, Line, Code, test::messUp(Code), Style);
87   }
88 
89   void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code,
90                                const FormatStyle &Style = getLLVMStyle()) {
91     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
92     EXPECT_EQ(Code.str(),
93               format(test::messUp(Code), Style, SC_ExpectIncomplete));
94   }
95 
96   void _verifyIndependentOfContext(const char *File, int Line,
97                                    llvm::StringRef Text,
98                                    const FormatStyle &Style = getLLVMStyle()) {
99     _verifyFormat(File, Line, Text, Style);
100     _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(),
101                   Style);
102   }
103 
104   /// \brief Verify that clang-format does not crash on the given input.
105   void verifyNoCrash(llvm::StringRef Code,
106                      const FormatStyle &Style = getLLVMStyle()) {
107     format(Code, Style, SC_DoNotCheck);
108   }
109 
110   int ReplacementCount;
111 };
112 
113 #define verifyIndependentOfContext(...)                                        \
114   _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__)
115 #define verifyIncompleteFormat(...)                                            \
116   _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle())
119 
120 TEST_F(FormatTest, MessUp) {
121   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
122   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
123   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
124   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
125   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
126 }
127 
128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
129   EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
130 }
131 
132 TEST_F(FormatTest, LLVMStyleOverride) {
133   EXPECT_EQ(FormatStyle::LK_Proto,
134             getLLVMStyle(FormatStyle::LK_Proto).Language);
135 }
136 
137 //===----------------------------------------------------------------------===//
138 // Basic function tests.
139 //===----------------------------------------------------------------------===//
140 
141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
142   EXPECT_EQ(";", format(";"));
143 }
144 
145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
146   EXPECT_EQ("int i;", format("  int i;"));
147   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
148   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
149   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
150 }
151 
152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
153   EXPECT_EQ("int i;", format("int\ni;"));
154 }
155 
156 TEST_F(FormatTest, FormatsNestedBlockStatements) {
157   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
158 }
159 
160 TEST_F(FormatTest, FormatsNestedCall) {
161   verifyFormat("Method(f1, f2(f3));");
162   verifyFormat("Method(f1(f2, f3()));");
163   verifyFormat("Method(f1(f2, (f3())));");
164 }
165 
166 TEST_F(FormatTest, NestedNameSpecifiers) {
167   verifyFormat("vector<::Type> v;");
168   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
169   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
170   verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
171   verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
172   verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
173   verifyFormat("bool a = 2 < ::SomeFunction();");
174   verifyFormat("ALWAYS_INLINE ::std::string getName();");
175   verifyFormat("some::string getName();");
176 }
177 
178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
179   EXPECT_EQ("if (a) {\n"
180             "  f();\n"
181             "}",
182             format("if(a){f();}"));
183   EXPECT_EQ(4, ReplacementCount);
184   EXPECT_EQ("if (a) {\n"
185             "  f();\n"
186             "}",
187             format("if (a) {\n"
188                    "  f();\n"
189                    "}"));
190   EXPECT_EQ(0, ReplacementCount);
191   EXPECT_EQ("/*\r\n"
192             "\r\n"
193             "*/\r\n",
194             format("/*\r\n"
195                    "\r\n"
196                    "*/\r\n"));
197   EXPECT_EQ(0, ReplacementCount);
198 }
199 
200 TEST_F(FormatTest, RemovesEmptyLines) {
201   EXPECT_EQ("class C {\n"
202             "  int i;\n"
203             "};",
204             format("class C {\n"
205                    " int i;\n"
206                    "\n"
207                    "};"));
208 
209   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
210   EXPECT_EQ("namespace N {\n"
211             "\n"
212             "int i;\n"
213             "}",
214             format("namespace N {\n"
215                    "\n"
216                    "int    i;\n"
217                    "}",
218                    getGoogleStyle()));
219   EXPECT_EQ("/* something */ namespace N {\n"
220             "\n"
221             "int i;\n"
222             "}",
223             format("/* something */ namespace N {\n"
224                    "\n"
225                    "int    i;\n"
226                    "}",
227                    getGoogleStyle()));
228   EXPECT_EQ("inline namespace N {\n"
229             "\n"
230             "int i;\n"
231             "}",
232             format("inline namespace N {\n"
233                    "\n"
234                    "int    i;\n"
235                    "}",
236                    getGoogleStyle()));
237   EXPECT_EQ("/* something */ inline namespace N {\n"
238             "\n"
239             "int i;\n"
240             "}",
241             format("/* something */ inline namespace N {\n"
242                    "\n"
243                    "int    i;\n"
244                    "}",
245                    getGoogleStyle()));
246   EXPECT_EQ("export namespace N {\n"
247             "\n"
248             "int i;\n"
249             "}",
250             format("export namespace N {\n"
251                    "\n"
252                    "int    i;\n"
253                    "}",
254                    getGoogleStyle()));
255   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
256             "\n"
257             "int i;\n"
258             "}",
259             format("extern /**/ \"C\" /**/ {\n"
260                    "\n"
261                    "int    i;\n"
262                    "}",
263                    getGoogleStyle()));
264 
265   auto CustomStyle = getLLVMStyle();
266   CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom;
267   CustomStyle.BraceWrapping.AfterNamespace = true;
268   CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
269   EXPECT_EQ("namespace N\n"
270             "{\n"
271             "\n"
272             "int i;\n"
273             "}",
274             format("namespace N\n"
275                    "{\n"
276                    "\n"
277                    "\n"
278                    "int    i;\n"
279                    "}",
280                    CustomStyle));
281   EXPECT_EQ("/* something */ namespace N\n"
282             "{\n"
283             "\n"
284             "int i;\n"
285             "}",
286             format("/* something */ namespace N {\n"
287                    "\n"
288                    "\n"
289                    "int    i;\n"
290                    "}",
291                    CustomStyle));
292   EXPECT_EQ("inline namespace N\n"
293             "{\n"
294             "\n"
295             "int i;\n"
296             "}",
297             format("inline namespace N\n"
298                    "{\n"
299                    "\n"
300                    "\n"
301                    "int    i;\n"
302                    "}",
303                    CustomStyle));
304   EXPECT_EQ("/* something */ inline namespace N\n"
305             "{\n"
306             "\n"
307             "int i;\n"
308             "}",
309             format("/* something */ inline namespace N\n"
310                    "{\n"
311                    "\n"
312                    "int    i;\n"
313                    "}",
314                    CustomStyle));
315   EXPECT_EQ("export namespace N\n"
316             "{\n"
317             "\n"
318             "int i;\n"
319             "}",
320             format("export namespace N\n"
321                    "{\n"
322                    "\n"
323                    "int    i;\n"
324                    "}",
325                    CustomStyle));
326   EXPECT_EQ("namespace a\n"
327             "{\n"
328             "namespace b\n"
329             "{\n"
330             "\n"
331             "class AA {};\n"
332             "\n"
333             "} // namespace b\n"
334             "} // namespace a\n",
335             format("namespace a\n"
336                    "{\n"
337                    "namespace b\n"
338                    "{\n"
339                    "\n"
340                    "\n"
341                    "class AA {};\n"
342                    "\n"
343                    "\n"
344                    "}\n"
345                    "}\n",
346                    CustomStyle));
347   EXPECT_EQ("namespace A /* comment */\n"
348             "{\n"
349             "class B {}\n"
350             "} // namespace A",
351             format("namespace A /* comment */ { class B {} }", CustomStyle));
352   EXPECT_EQ("namespace A\n"
353             "{ /* comment */\n"
354             "class B {}\n"
355             "} // namespace A",
356             format("namespace A {/* comment */ class B {} }", CustomStyle));
357   EXPECT_EQ("namespace A\n"
358             "{ /* comment */\n"
359             "\n"
360             "class B {}\n"
361             "\n"
362             ""
363             "} // namespace A",
364             format("namespace A { /* comment */\n"
365                    "\n"
366                    "\n"
367                    "class B {}\n"
368                    "\n"
369                    "\n"
370                    "}",
371                    CustomStyle));
372   EXPECT_EQ("namespace A /* comment */\n"
373             "{\n"
374             "\n"
375             "class B {}\n"
376             "\n"
377             "} // namespace A",
378             format("namespace A/* comment */ {\n"
379                    "\n"
380                    "\n"
381                    "class B {}\n"
382                    "\n"
383                    "\n"
384                    "}",
385                    CustomStyle));
386 
387   // ...but do keep inlining and removing empty lines for non-block extern "C"
388   // functions.
389   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
390   EXPECT_EQ("extern \"C\" int f() {\n"
391             "  int i = 42;\n"
392             "  return i;\n"
393             "}",
394             format("extern \"C\" int f() {\n"
395                    "\n"
396                    "  int i = 42;\n"
397                    "  return i;\n"
398                    "}",
399                    getGoogleStyle()));
400 
401   // Remove empty lines at the beginning and end of blocks.
402   EXPECT_EQ("void f() {\n"
403             "\n"
404             "  if (a) {\n"
405             "\n"
406             "    f();\n"
407             "  }\n"
408             "}",
409             format("void f() {\n"
410                    "\n"
411                    "  if (a) {\n"
412                    "\n"
413                    "    f();\n"
414                    "\n"
415                    "  }\n"
416                    "\n"
417                    "}",
418                    getLLVMStyle()));
419   EXPECT_EQ("void f() {\n"
420             "  if (a) {\n"
421             "    f();\n"
422             "  }\n"
423             "}",
424             format("void f() {\n"
425                    "\n"
426                    "  if (a) {\n"
427                    "\n"
428                    "    f();\n"
429                    "\n"
430                    "  }\n"
431                    "\n"
432                    "}",
433                    getGoogleStyle()));
434 
435   // Don't remove empty lines in more complex control statements.
436   EXPECT_EQ("void f() {\n"
437             "  if (a) {\n"
438             "    f();\n"
439             "\n"
440             "  } else if (b) {\n"
441             "    f();\n"
442             "  }\n"
443             "}",
444             format("void f() {\n"
445                    "  if (a) {\n"
446                    "    f();\n"
447                    "\n"
448                    "  } else if (b) {\n"
449                    "    f();\n"
450                    "\n"
451                    "  }\n"
452                    "\n"
453                    "}"));
454 
455   // Don't remove empty lines before namespace endings.
456   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
457   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
458   EXPECT_EQ("namespace {\n"
459             "int i;\n"
460             "\n"
461             "}",
462             format("namespace {\n"
463                    "int i;\n"
464                    "\n"
465                    "}",
466                    LLVMWithNoNamespaceFix));
467   EXPECT_EQ("namespace {\n"
468             "int i;\n"
469             "}",
470             format("namespace {\n"
471                    "int i;\n"
472                    "}",
473                    LLVMWithNoNamespaceFix));
474   EXPECT_EQ("namespace {\n"
475             "int i;\n"
476             "\n"
477             "};",
478             format("namespace {\n"
479                    "int i;\n"
480                    "\n"
481                    "};",
482                    LLVMWithNoNamespaceFix));
483   EXPECT_EQ("namespace {\n"
484             "int i;\n"
485             "};",
486             format("namespace {\n"
487                    "int i;\n"
488                    "};",
489                    LLVMWithNoNamespaceFix));
490   EXPECT_EQ("namespace {\n"
491             "int i;\n"
492             "\n"
493             "}",
494             format("namespace {\n"
495                    "int i;\n"
496                    "\n"
497                    "}"));
498   EXPECT_EQ("namespace {\n"
499             "int i;\n"
500             "\n"
501             "} // namespace",
502             format("namespace {\n"
503                    "int i;\n"
504                    "\n"
505                    "}  // namespace"));
506 
507   FormatStyle Style = getLLVMStyle();
508   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
509   Style.MaxEmptyLinesToKeep = 2;
510   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
511   Style.BraceWrapping.AfterClass = true;
512   Style.BraceWrapping.AfterFunction = true;
513   Style.KeepEmptyLinesAtTheStartOfBlocks = false;
514 
515   EXPECT_EQ("class Foo\n"
516             "{\n"
517             "  Foo() {}\n"
518             "\n"
519             "  void funk() {}\n"
520             "};",
521             format("class Foo\n"
522                    "{\n"
523                    "  Foo()\n"
524                    "  {\n"
525                    "  }\n"
526                    "\n"
527                    "  void funk() {}\n"
528                    "};",
529                    Style));
530 }
531 
532 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
533   verifyFormat("x = (a) and (b);");
534   verifyFormat("x = (a) or (b);");
535   verifyFormat("x = (a) bitand (b);");
536   verifyFormat("x = (a) bitor (b);");
537   verifyFormat("x = (a) not_eq (b);");
538   verifyFormat("x = (a) and_eq (b);");
539   verifyFormat("x = (a) or_eq (b);");
540   verifyFormat("x = (a) xor (b);");
541 }
542 
543 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
544   verifyFormat("x = compl(a);");
545   verifyFormat("x = not(a);");
546   verifyFormat("x = bitand(a);");
547   // Unary operator must not be merged with the next identifier
548   verifyFormat("x = compl a;");
549   verifyFormat("x = not a;");
550   verifyFormat("x = bitand a;");
551 }
552 
553 //===----------------------------------------------------------------------===//
554 // Tests for control statements.
555 //===----------------------------------------------------------------------===//
556 
557 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
558   verifyFormat("if (true)\n  f();\ng();");
559   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
560   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
561   verifyFormat("if constexpr (true)\n"
562                "  f();\ng();");
563   verifyFormat("if CONSTEXPR (true)\n"
564                "  f();\ng();");
565   verifyFormat("if constexpr (a)\n"
566                "  if constexpr (b)\n"
567                "    if constexpr (c)\n"
568                "      g();\n"
569                "h();");
570   verifyFormat("if CONSTEXPR (a)\n"
571                "  if CONSTEXPR (b)\n"
572                "    if CONSTEXPR (c)\n"
573                "      g();\n"
574                "h();");
575   verifyFormat("if constexpr (a)\n"
576                "  if constexpr (b) {\n"
577                "    f();\n"
578                "  }\n"
579                "g();");
580   verifyFormat("if CONSTEXPR (a)\n"
581                "  if CONSTEXPR (b) {\n"
582                "    f();\n"
583                "  }\n"
584                "g();");
585 
586   verifyFormat("if (a)\n"
587                "  g();");
588   verifyFormat("if (a) {\n"
589                "  g()\n"
590                "};");
591   verifyFormat("if (a)\n"
592                "  g();\n"
593                "else\n"
594                "  g();");
595   verifyFormat("if (a) {\n"
596                "  g();\n"
597                "} else\n"
598                "  g();");
599   verifyFormat("if (a)\n"
600                "  g();\n"
601                "else {\n"
602                "  g();\n"
603                "}");
604   verifyFormat("if (a) {\n"
605                "  g();\n"
606                "} else {\n"
607                "  g();\n"
608                "}");
609   verifyFormat("if (a)\n"
610                "  g();\n"
611                "else if (b)\n"
612                "  g();\n"
613                "else\n"
614                "  g();");
615   verifyFormat("if (a) {\n"
616                "  g();\n"
617                "} else if (b)\n"
618                "  g();\n"
619                "else\n"
620                "  g();");
621   verifyFormat("if (a)\n"
622                "  g();\n"
623                "else if (b) {\n"
624                "  g();\n"
625                "} else\n"
626                "  g();");
627   verifyFormat("if (a)\n"
628                "  g();\n"
629                "else if (b)\n"
630                "  g();\n"
631                "else {\n"
632                "  g();\n"
633                "}");
634   verifyFormat("if (a)\n"
635                "  g();\n"
636                "else if (b) {\n"
637                "  g();\n"
638                "} else {\n"
639                "  g();\n"
640                "}");
641   verifyFormat("if (a) {\n"
642                "  g();\n"
643                "} else if (b) {\n"
644                "  g();\n"
645                "} else {\n"
646                "  g();\n"
647                "}");
648 
649   FormatStyle AllowsMergedIf = getLLVMStyle();
650   AllowsMergedIf.IfMacros.push_back("MYIF");
651   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
652   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
653       FormatStyle::SIS_WithoutElse;
654   verifyFormat("if (a)\n"
655                "  // comment\n"
656                "  f();",
657                AllowsMergedIf);
658   verifyFormat("{\n"
659                "  if (a)\n"
660                "  label:\n"
661                "    f();\n"
662                "}",
663                AllowsMergedIf);
664   verifyFormat("#define A \\\n"
665                "  if (a)  \\\n"
666                "  label:  \\\n"
667                "    f()",
668                AllowsMergedIf);
669   verifyFormat("if (a)\n"
670                "  ;",
671                AllowsMergedIf);
672   verifyFormat("if (a)\n"
673                "  if (b) return;",
674                AllowsMergedIf);
675 
676   verifyFormat("if (a) // Can't merge this\n"
677                "  f();\n",
678                AllowsMergedIf);
679   verifyFormat("if (a) /* still don't merge */\n"
680                "  f();",
681                AllowsMergedIf);
682   verifyFormat("if (a) { // Never merge this\n"
683                "  f();\n"
684                "}",
685                AllowsMergedIf);
686   verifyFormat("if (a) { /* Never merge this */\n"
687                "  f();\n"
688                "}",
689                AllowsMergedIf);
690   verifyFormat("MYIF (a)\n"
691                "  // comment\n"
692                "  f();",
693                AllowsMergedIf);
694   verifyFormat("{\n"
695                "  MYIF (a)\n"
696                "  label:\n"
697                "    f();\n"
698                "}",
699                AllowsMergedIf);
700   verifyFormat("#define A  \\\n"
701                "  MYIF (a) \\\n"
702                "  label:   \\\n"
703                "    f()",
704                AllowsMergedIf);
705   verifyFormat("MYIF (a)\n"
706                "  ;",
707                AllowsMergedIf);
708   verifyFormat("MYIF (a)\n"
709                "  MYIF (b) return;",
710                AllowsMergedIf);
711 
712   verifyFormat("MYIF (a) // Can't merge this\n"
713                "  f();\n",
714                AllowsMergedIf);
715   verifyFormat("MYIF (a) /* still don't merge */\n"
716                "  f();",
717                AllowsMergedIf);
718   verifyFormat("MYIF (a) { // Never merge this\n"
719                "  f();\n"
720                "}",
721                AllowsMergedIf);
722   verifyFormat("MYIF (a) { /* Never merge this */\n"
723                "  f();\n"
724                "}",
725                AllowsMergedIf);
726 
727   AllowsMergedIf.ColumnLimit = 14;
728   // Where line-lengths matter, a 2-letter synonym that maintains line length.
729   // Not IF to avoid any confusion that IF is somehow special.
730   AllowsMergedIf.IfMacros.push_back("FI");
731   verifyFormat("if (a) return;", AllowsMergedIf);
732   verifyFormat("if (aaaaaaaaa)\n"
733                "  return;",
734                AllowsMergedIf);
735   verifyFormat("FI (a) return;", AllowsMergedIf);
736   verifyFormat("FI (aaaaaaaaa)\n"
737                "  return;",
738                AllowsMergedIf);
739 
740   AllowsMergedIf.ColumnLimit = 13;
741   verifyFormat("if (a)\n  return;", AllowsMergedIf);
742   verifyFormat("FI (a)\n  return;", AllowsMergedIf);
743 
744   FormatStyle AllowsMergedIfElse = getLLVMStyle();
745   AllowsMergedIfElse.IfMacros.push_back("MYIF");
746   AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine =
747       FormatStyle::SIS_AllIfsAndElse;
748   verifyFormat("if (a)\n"
749                "  // comment\n"
750                "  f();\n"
751                "else\n"
752                "  // comment\n"
753                "  f();",
754                AllowsMergedIfElse);
755   verifyFormat("{\n"
756                "  if (a)\n"
757                "  label:\n"
758                "    f();\n"
759                "  else\n"
760                "  label:\n"
761                "    f();\n"
762                "}",
763                AllowsMergedIfElse);
764   verifyFormat("if (a)\n"
765                "  ;\n"
766                "else\n"
767                "  ;",
768                AllowsMergedIfElse);
769   verifyFormat("if (a) {\n"
770                "} else {\n"
771                "}",
772                AllowsMergedIfElse);
773   verifyFormat("if (a) return;\n"
774                "else if (b) return;\n"
775                "else return;",
776                AllowsMergedIfElse);
777   verifyFormat("if (a) {\n"
778                "} else return;",
779                AllowsMergedIfElse);
780   verifyFormat("if (a) {\n"
781                "} else if (b) return;\n"
782                "else return;",
783                AllowsMergedIfElse);
784   verifyFormat("if (a) return;\n"
785                "else if (b) {\n"
786                "} else return;",
787                AllowsMergedIfElse);
788   verifyFormat("if (a)\n"
789                "  if (b) return;\n"
790                "  else return;",
791                AllowsMergedIfElse);
792   verifyFormat("if constexpr (a)\n"
793                "  if constexpr (b) return;\n"
794                "  else if constexpr (c) return;\n"
795                "  else return;",
796                AllowsMergedIfElse);
797   verifyFormat("MYIF (a)\n"
798                "  // comment\n"
799                "  f();\n"
800                "else\n"
801                "  // comment\n"
802                "  f();",
803                AllowsMergedIfElse);
804   verifyFormat("{\n"
805                "  MYIF (a)\n"
806                "  label:\n"
807                "    f();\n"
808                "  else\n"
809                "  label:\n"
810                "    f();\n"
811                "}",
812                AllowsMergedIfElse);
813   verifyFormat("MYIF (a)\n"
814                "  ;\n"
815                "else\n"
816                "  ;",
817                AllowsMergedIfElse);
818   verifyFormat("MYIF (a) {\n"
819                "} else {\n"
820                "}",
821                AllowsMergedIfElse);
822   verifyFormat("MYIF (a) return;\n"
823                "else MYIF (b) return;\n"
824                "else return;",
825                AllowsMergedIfElse);
826   verifyFormat("MYIF (a) {\n"
827                "} else return;",
828                AllowsMergedIfElse);
829   verifyFormat("MYIF (a) {\n"
830                "} else MYIF (b) return;\n"
831                "else return;",
832                AllowsMergedIfElse);
833   verifyFormat("MYIF (a) return;\n"
834                "else MYIF (b) {\n"
835                "} else return;",
836                AllowsMergedIfElse);
837   verifyFormat("MYIF (a)\n"
838                "  MYIF (b) return;\n"
839                "  else return;",
840                AllowsMergedIfElse);
841   verifyFormat("MYIF constexpr (a)\n"
842                "  MYIF constexpr (b) return;\n"
843                "  else MYIF constexpr (c) return;\n"
844                "  else return;",
845                AllowsMergedIfElse);
846 }
847 
848 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
849   FormatStyle AllowsMergedIf = getLLVMStyle();
850   AllowsMergedIf.IfMacros.push_back("MYIF");
851   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
852   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
853       FormatStyle::SIS_WithoutElse;
854   verifyFormat("if (a)\n"
855                "  f();\n"
856                "else {\n"
857                "  g();\n"
858                "}",
859                AllowsMergedIf);
860   verifyFormat("if (a)\n"
861                "  f();\n"
862                "else\n"
863                "  g();\n",
864                AllowsMergedIf);
865 
866   verifyFormat("if (a) g();", AllowsMergedIf);
867   verifyFormat("if (a) {\n"
868                "  g()\n"
869                "};",
870                AllowsMergedIf);
871   verifyFormat("if (a)\n"
872                "  g();\n"
873                "else\n"
874                "  g();",
875                AllowsMergedIf);
876   verifyFormat("if (a) {\n"
877                "  g();\n"
878                "} else\n"
879                "  g();",
880                AllowsMergedIf);
881   verifyFormat("if (a)\n"
882                "  g();\n"
883                "else {\n"
884                "  g();\n"
885                "}",
886                AllowsMergedIf);
887   verifyFormat("if (a) {\n"
888                "  g();\n"
889                "} else {\n"
890                "  g();\n"
891                "}",
892                AllowsMergedIf);
893   verifyFormat("if (a)\n"
894                "  g();\n"
895                "else if (b)\n"
896                "  g();\n"
897                "else\n"
898                "  g();",
899                AllowsMergedIf);
900   verifyFormat("if (a) {\n"
901                "  g();\n"
902                "} else if (b)\n"
903                "  g();\n"
904                "else\n"
905                "  g();",
906                AllowsMergedIf);
907   verifyFormat("if (a)\n"
908                "  g();\n"
909                "else if (b) {\n"
910                "  g();\n"
911                "} else\n"
912                "  g();",
913                AllowsMergedIf);
914   verifyFormat("if (a)\n"
915                "  g();\n"
916                "else if (b)\n"
917                "  g();\n"
918                "else {\n"
919                "  g();\n"
920                "}",
921                AllowsMergedIf);
922   verifyFormat("if (a)\n"
923                "  g();\n"
924                "else if (b) {\n"
925                "  g();\n"
926                "} else {\n"
927                "  g();\n"
928                "}",
929                AllowsMergedIf);
930   verifyFormat("if (a) {\n"
931                "  g();\n"
932                "} else if (b) {\n"
933                "  g();\n"
934                "} else {\n"
935                "  g();\n"
936                "}",
937                AllowsMergedIf);
938   verifyFormat("MYIF (a)\n"
939                "  f();\n"
940                "else {\n"
941                "  g();\n"
942                "}",
943                AllowsMergedIf);
944   verifyFormat("MYIF (a)\n"
945                "  f();\n"
946                "else\n"
947                "  g();\n",
948                AllowsMergedIf);
949 
950   verifyFormat("MYIF (a) g();", AllowsMergedIf);
951   verifyFormat("MYIF (a) {\n"
952                "  g()\n"
953                "};",
954                AllowsMergedIf);
955   verifyFormat("MYIF (a)\n"
956                "  g();\n"
957                "else\n"
958                "  g();",
959                AllowsMergedIf);
960   verifyFormat("MYIF (a) {\n"
961                "  g();\n"
962                "} else\n"
963                "  g();",
964                AllowsMergedIf);
965   verifyFormat("MYIF (a)\n"
966                "  g();\n"
967                "else {\n"
968                "  g();\n"
969                "}",
970                AllowsMergedIf);
971   verifyFormat("MYIF (a) {\n"
972                "  g();\n"
973                "} else {\n"
974                "  g();\n"
975                "}",
976                AllowsMergedIf);
977   verifyFormat("MYIF (a)\n"
978                "  g();\n"
979                "else MYIF (b)\n"
980                "  g();\n"
981                "else\n"
982                "  g();",
983                AllowsMergedIf);
984   verifyFormat("MYIF (a)\n"
985                "  g();\n"
986                "else if (b)\n"
987                "  g();\n"
988                "else\n"
989                "  g();",
990                AllowsMergedIf);
991   verifyFormat("MYIF (a) {\n"
992                "  g();\n"
993                "} else MYIF (b)\n"
994                "  g();\n"
995                "else\n"
996                "  g();",
997                AllowsMergedIf);
998   verifyFormat("MYIF (a) {\n"
999                "  g();\n"
1000                "} else if (b)\n"
1001                "  g();\n"
1002                "else\n"
1003                "  g();",
1004                AllowsMergedIf);
1005   verifyFormat("MYIF (a)\n"
1006                "  g();\n"
1007                "else MYIF (b) {\n"
1008                "  g();\n"
1009                "} else\n"
1010                "  g();",
1011                AllowsMergedIf);
1012   verifyFormat("MYIF (a)\n"
1013                "  g();\n"
1014                "else if (b) {\n"
1015                "  g();\n"
1016                "} else\n"
1017                "  g();",
1018                AllowsMergedIf);
1019   verifyFormat("MYIF (a)\n"
1020                "  g();\n"
1021                "else MYIF (b)\n"
1022                "  g();\n"
1023                "else {\n"
1024                "  g();\n"
1025                "}",
1026                AllowsMergedIf);
1027   verifyFormat("MYIF (a)\n"
1028                "  g();\n"
1029                "else if (b)\n"
1030                "  g();\n"
1031                "else {\n"
1032                "  g();\n"
1033                "}",
1034                AllowsMergedIf);
1035   verifyFormat("MYIF (a)\n"
1036                "  g();\n"
1037                "else MYIF (b) {\n"
1038                "  g();\n"
1039                "} else {\n"
1040                "  g();\n"
1041                "}",
1042                AllowsMergedIf);
1043   verifyFormat("MYIF (a)\n"
1044                "  g();\n"
1045                "else if (b) {\n"
1046                "  g();\n"
1047                "} else {\n"
1048                "  g();\n"
1049                "}",
1050                AllowsMergedIf);
1051   verifyFormat("MYIF (a) {\n"
1052                "  g();\n"
1053                "} else MYIF (b) {\n"
1054                "  g();\n"
1055                "} else {\n"
1056                "  g();\n"
1057                "}",
1058                AllowsMergedIf);
1059   verifyFormat("MYIF (a) {\n"
1060                "  g();\n"
1061                "} else if (b) {\n"
1062                "  g();\n"
1063                "} else {\n"
1064                "  g();\n"
1065                "}",
1066                AllowsMergedIf);
1067 
1068   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1069       FormatStyle::SIS_OnlyFirstIf;
1070 
1071   verifyFormat("if (a) f();\n"
1072                "else {\n"
1073                "  g();\n"
1074                "}",
1075                AllowsMergedIf);
1076   verifyFormat("if (a) f();\n"
1077                "else {\n"
1078                "  if (a) f();\n"
1079                "  else {\n"
1080                "    g();\n"
1081                "  }\n"
1082                "  g();\n"
1083                "}",
1084                AllowsMergedIf);
1085 
1086   verifyFormat("if (a) g();", AllowsMergedIf);
1087   verifyFormat("if (a) {\n"
1088                "  g()\n"
1089                "};",
1090                AllowsMergedIf);
1091   verifyFormat("if (a) g();\n"
1092                "else\n"
1093                "  g();",
1094                AllowsMergedIf);
1095   verifyFormat("if (a) {\n"
1096                "  g();\n"
1097                "} else\n"
1098                "  g();",
1099                AllowsMergedIf);
1100   verifyFormat("if (a) g();\n"
1101                "else {\n"
1102                "  g();\n"
1103                "}",
1104                AllowsMergedIf);
1105   verifyFormat("if (a) {\n"
1106                "  g();\n"
1107                "} else {\n"
1108                "  g();\n"
1109                "}",
1110                AllowsMergedIf);
1111   verifyFormat("if (a) g();\n"
1112                "else if (b)\n"
1113                "  g();\n"
1114                "else\n"
1115                "  g();",
1116                AllowsMergedIf);
1117   verifyFormat("if (a) {\n"
1118                "  g();\n"
1119                "} else if (b)\n"
1120                "  g();\n"
1121                "else\n"
1122                "  g();",
1123                AllowsMergedIf);
1124   verifyFormat("if (a) g();\n"
1125                "else if (b) {\n"
1126                "  g();\n"
1127                "} else\n"
1128                "  g();",
1129                AllowsMergedIf);
1130   verifyFormat("if (a) g();\n"
1131                "else if (b)\n"
1132                "  g();\n"
1133                "else {\n"
1134                "  g();\n"
1135                "}",
1136                AllowsMergedIf);
1137   verifyFormat("if (a) g();\n"
1138                "else if (b) {\n"
1139                "  g();\n"
1140                "} else {\n"
1141                "  g();\n"
1142                "}",
1143                AllowsMergedIf);
1144   verifyFormat("if (a) {\n"
1145                "  g();\n"
1146                "} else if (b) {\n"
1147                "  g();\n"
1148                "} else {\n"
1149                "  g();\n"
1150                "}",
1151                AllowsMergedIf);
1152   verifyFormat("MYIF (a) f();\n"
1153                "else {\n"
1154                "  g();\n"
1155                "}",
1156                AllowsMergedIf);
1157   verifyFormat("MYIF (a) f();\n"
1158                "else {\n"
1159                "  if (a) f();\n"
1160                "  else {\n"
1161                "    g();\n"
1162                "  }\n"
1163                "  g();\n"
1164                "}",
1165                AllowsMergedIf);
1166 
1167   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1168   verifyFormat("MYIF (a) {\n"
1169                "  g()\n"
1170                "};",
1171                AllowsMergedIf);
1172   verifyFormat("MYIF (a) g();\n"
1173                "else\n"
1174                "  g();",
1175                AllowsMergedIf);
1176   verifyFormat("MYIF (a) {\n"
1177                "  g();\n"
1178                "} else\n"
1179                "  g();",
1180                AllowsMergedIf);
1181   verifyFormat("MYIF (a) g();\n"
1182                "else {\n"
1183                "  g();\n"
1184                "}",
1185                AllowsMergedIf);
1186   verifyFormat("MYIF (a) {\n"
1187                "  g();\n"
1188                "} else {\n"
1189                "  g();\n"
1190                "}",
1191                AllowsMergedIf);
1192   verifyFormat("MYIF (a) g();\n"
1193                "else MYIF (b)\n"
1194                "  g();\n"
1195                "else\n"
1196                "  g();",
1197                AllowsMergedIf);
1198   verifyFormat("MYIF (a) g();\n"
1199                "else if (b)\n"
1200                "  g();\n"
1201                "else\n"
1202                "  g();",
1203                AllowsMergedIf);
1204   verifyFormat("MYIF (a) {\n"
1205                "  g();\n"
1206                "} else MYIF (b)\n"
1207                "  g();\n"
1208                "else\n"
1209                "  g();",
1210                AllowsMergedIf);
1211   verifyFormat("MYIF (a) {\n"
1212                "  g();\n"
1213                "} else if (b)\n"
1214                "  g();\n"
1215                "else\n"
1216                "  g();",
1217                AllowsMergedIf);
1218   verifyFormat("MYIF (a) g();\n"
1219                "else MYIF (b) {\n"
1220                "  g();\n"
1221                "} else\n"
1222                "  g();",
1223                AllowsMergedIf);
1224   verifyFormat("MYIF (a) g();\n"
1225                "else if (b) {\n"
1226                "  g();\n"
1227                "} else\n"
1228                "  g();",
1229                AllowsMergedIf);
1230   verifyFormat("MYIF (a) g();\n"
1231                "else MYIF (b)\n"
1232                "  g();\n"
1233                "else {\n"
1234                "  g();\n"
1235                "}",
1236                AllowsMergedIf);
1237   verifyFormat("MYIF (a) g();\n"
1238                "else if (b)\n"
1239                "  g();\n"
1240                "else {\n"
1241                "  g();\n"
1242                "}",
1243                AllowsMergedIf);
1244   verifyFormat("MYIF (a) g();\n"
1245                "else MYIF (b) {\n"
1246                "  g();\n"
1247                "} else {\n"
1248                "  g();\n"
1249                "}",
1250                AllowsMergedIf);
1251   verifyFormat("MYIF (a) g();\n"
1252                "else if (b) {\n"
1253                "  g();\n"
1254                "} else {\n"
1255                "  g();\n"
1256                "}",
1257                AllowsMergedIf);
1258   verifyFormat("MYIF (a) {\n"
1259                "  g();\n"
1260                "} else MYIF (b) {\n"
1261                "  g();\n"
1262                "} else {\n"
1263                "  g();\n"
1264                "}",
1265                AllowsMergedIf);
1266   verifyFormat("MYIF (a) {\n"
1267                "  g();\n"
1268                "} else if (b) {\n"
1269                "  g();\n"
1270                "} else {\n"
1271                "  g();\n"
1272                "}",
1273                AllowsMergedIf);
1274 
1275   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1276       FormatStyle::SIS_AllIfsAndElse;
1277 
1278   verifyFormat("if (a) f();\n"
1279                "else {\n"
1280                "  g();\n"
1281                "}",
1282                AllowsMergedIf);
1283   verifyFormat("if (a) f();\n"
1284                "else {\n"
1285                "  if (a) f();\n"
1286                "  else {\n"
1287                "    g();\n"
1288                "  }\n"
1289                "  g();\n"
1290                "}",
1291                AllowsMergedIf);
1292 
1293   verifyFormat("if (a) g();", AllowsMergedIf);
1294   verifyFormat("if (a) {\n"
1295                "  g()\n"
1296                "};",
1297                AllowsMergedIf);
1298   verifyFormat("if (a) g();\n"
1299                "else g();",
1300                AllowsMergedIf);
1301   verifyFormat("if (a) {\n"
1302                "  g();\n"
1303                "} else g();",
1304                AllowsMergedIf);
1305   verifyFormat("if (a) g();\n"
1306                "else {\n"
1307                "  g();\n"
1308                "}",
1309                AllowsMergedIf);
1310   verifyFormat("if (a) {\n"
1311                "  g();\n"
1312                "} else {\n"
1313                "  g();\n"
1314                "}",
1315                AllowsMergedIf);
1316   verifyFormat("if (a) g();\n"
1317                "else if (b) g();\n"
1318                "else g();",
1319                AllowsMergedIf);
1320   verifyFormat("if (a) {\n"
1321                "  g();\n"
1322                "} else if (b) g();\n"
1323                "else g();",
1324                AllowsMergedIf);
1325   verifyFormat("if (a) g();\n"
1326                "else if (b) {\n"
1327                "  g();\n"
1328                "} else g();",
1329                AllowsMergedIf);
1330   verifyFormat("if (a) g();\n"
1331                "else if (b) g();\n"
1332                "else {\n"
1333                "  g();\n"
1334                "}",
1335                AllowsMergedIf);
1336   verifyFormat("if (a) g();\n"
1337                "else if (b) {\n"
1338                "  g();\n"
1339                "} else {\n"
1340                "  g();\n"
1341                "}",
1342                AllowsMergedIf);
1343   verifyFormat("if (a) {\n"
1344                "  g();\n"
1345                "} else if (b) {\n"
1346                "  g();\n"
1347                "} else {\n"
1348                "  g();\n"
1349                "}",
1350                AllowsMergedIf);
1351   verifyFormat("MYIF (a) f();\n"
1352                "else {\n"
1353                "  g();\n"
1354                "}",
1355                AllowsMergedIf);
1356   verifyFormat("MYIF (a) f();\n"
1357                "else {\n"
1358                "  if (a) f();\n"
1359                "  else {\n"
1360                "    g();\n"
1361                "  }\n"
1362                "  g();\n"
1363                "}",
1364                AllowsMergedIf);
1365 
1366   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1367   verifyFormat("MYIF (a) {\n"
1368                "  g()\n"
1369                "};",
1370                AllowsMergedIf);
1371   verifyFormat("MYIF (a) g();\n"
1372                "else g();",
1373                AllowsMergedIf);
1374   verifyFormat("MYIF (a) {\n"
1375                "  g();\n"
1376                "} else g();",
1377                AllowsMergedIf);
1378   verifyFormat("MYIF (a) g();\n"
1379                "else {\n"
1380                "  g();\n"
1381                "}",
1382                AllowsMergedIf);
1383   verifyFormat("MYIF (a) {\n"
1384                "  g();\n"
1385                "} else {\n"
1386                "  g();\n"
1387                "}",
1388                AllowsMergedIf);
1389   verifyFormat("MYIF (a) g();\n"
1390                "else MYIF (b) g();\n"
1391                "else g();",
1392                AllowsMergedIf);
1393   verifyFormat("MYIF (a) g();\n"
1394                "else if (b) g();\n"
1395                "else g();",
1396                AllowsMergedIf);
1397   verifyFormat("MYIF (a) {\n"
1398                "  g();\n"
1399                "} else MYIF (b) g();\n"
1400                "else g();",
1401                AllowsMergedIf);
1402   verifyFormat("MYIF (a) {\n"
1403                "  g();\n"
1404                "} else if (b) g();\n"
1405                "else g();",
1406                AllowsMergedIf);
1407   verifyFormat("MYIF (a) g();\n"
1408                "else MYIF (b) {\n"
1409                "  g();\n"
1410                "} else g();",
1411                AllowsMergedIf);
1412   verifyFormat("MYIF (a) g();\n"
1413                "else if (b) {\n"
1414                "  g();\n"
1415                "} else g();",
1416                AllowsMergedIf);
1417   verifyFormat("MYIF (a) g();\n"
1418                "else MYIF (b) g();\n"
1419                "else {\n"
1420                "  g();\n"
1421                "}",
1422                AllowsMergedIf);
1423   verifyFormat("MYIF (a) g();\n"
1424                "else if (b) g();\n"
1425                "else {\n"
1426                "  g();\n"
1427                "}",
1428                AllowsMergedIf);
1429   verifyFormat("MYIF (a) g();\n"
1430                "else MYIF (b) {\n"
1431                "  g();\n"
1432                "} else {\n"
1433                "  g();\n"
1434                "}",
1435                AllowsMergedIf);
1436   verifyFormat("MYIF (a) g();\n"
1437                "else if (b) {\n"
1438                "  g();\n"
1439                "} else {\n"
1440                "  g();\n"
1441                "}",
1442                AllowsMergedIf);
1443   verifyFormat("MYIF (a) {\n"
1444                "  g();\n"
1445                "} else MYIF (b) {\n"
1446                "  g();\n"
1447                "} else {\n"
1448                "  g();\n"
1449                "}",
1450                AllowsMergedIf);
1451   verifyFormat("MYIF (a) {\n"
1452                "  g();\n"
1453                "} else if (b) {\n"
1454                "  g();\n"
1455                "} else {\n"
1456                "  g();\n"
1457                "}",
1458                AllowsMergedIf);
1459 }
1460 
1461 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
1462   FormatStyle AllowsMergedLoops = getLLVMStyle();
1463   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
1464   verifyFormat("while (true) continue;", AllowsMergedLoops);
1465   verifyFormat("for (;;) continue;", AllowsMergedLoops);
1466   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
1467   verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
1468   verifyFormat("while (true)\n"
1469                "  ;",
1470                AllowsMergedLoops);
1471   verifyFormat("for (;;)\n"
1472                "  ;",
1473                AllowsMergedLoops);
1474   verifyFormat("for (;;)\n"
1475                "  for (;;) continue;",
1476                AllowsMergedLoops);
1477   verifyFormat("for (;;)\n"
1478                "  while (true) continue;",
1479                AllowsMergedLoops);
1480   verifyFormat("while (true)\n"
1481                "  for (;;) continue;",
1482                AllowsMergedLoops);
1483   verifyFormat("BOOST_FOREACH (int &v, vec)\n"
1484                "  for (;;) continue;",
1485                AllowsMergedLoops);
1486   verifyFormat("for (;;)\n"
1487                "  BOOST_FOREACH (int &v, vec) continue;",
1488                AllowsMergedLoops);
1489   verifyFormat("for (;;) // Can't merge this\n"
1490                "  continue;",
1491                AllowsMergedLoops);
1492   verifyFormat("for (;;) /* still don't merge */\n"
1493                "  continue;",
1494                AllowsMergedLoops);
1495   verifyFormat("do a++;\n"
1496                "while (true);",
1497                AllowsMergedLoops);
1498   verifyFormat("do /* Don't merge */\n"
1499                "  a++;\n"
1500                "while (true);",
1501                AllowsMergedLoops);
1502   verifyFormat("do // Don't merge\n"
1503                "  a++;\n"
1504                "while (true);",
1505                AllowsMergedLoops);
1506   verifyFormat("do\n"
1507                "  // Don't merge\n"
1508                "  a++;\n"
1509                "while (true);",
1510                AllowsMergedLoops);
1511   // Without braces labels are interpreted differently.
1512   verifyFormat("{\n"
1513                "  do\n"
1514                "  label:\n"
1515                "    a++;\n"
1516                "  while (true);\n"
1517                "}",
1518                AllowsMergedLoops);
1519 }
1520 
1521 TEST_F(FormatTest, FormatShortBracedStatements) {
1522   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
1523   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
1524   // Where line-lengths matter, a 2-letter synonym that maintains line length.
1525   // Not IF to avoid any confusion that IF is somehow special.
1526   AllowSimpleBracedStatements.IfMacros.push_back("FI");
1527   AllowSimpleBracedStatements.ColumnLimit = 40;
1528   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1529       FormatStyle::SBS_Always;
1530 
1531   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1532       FormatStyle::SIS_WithoutElse;
1533   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1534 
1535   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1536   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1537   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1538 
1539   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1540   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1541   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1542   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1543   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1544   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1545   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1546   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1547   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1548   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1549   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1550   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1551   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1552   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1553   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1554   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1555   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1556                AllowSimpleBracedStatements);
1557   verifyFormat("if (true) {\n"
1558                "  ffffffffffffffffffffffff();\n"
1559                "}",
1560                AllowSimpleBracedStatements);
1561   verifyFormat("if (true) {\n"
1562                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1563                "}",
1564                AllowSimpleBracedStatements);
1565   verifyFormat("if (true) { //\n"
1566                "  f();\n"
1567                "}",
1568                AllowSimpleBracedStatements);
1569   verifyFormat("if (true) {\n"
1570                "  f();\n"
1571                "  f();\n"
1572                "}",
1573                AllowSimpleBracedStatements);
1574   verifyFormat("if (true) {\n"
1575                "  f();\n"
1576                "} else {\n"
1577                "  f();\n"
1578                "}",
1579                AllowSimpleBracedStatements);
1580   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1581                AllowSimpleBracedStatements);
1582   verifyFormat("MYIF (true) {\n"
1583                "  ffffffffffffffffffffffff();\n"
1584                "}",
1585                AllowSimpleBracedStatements);
1586   verifyFormat("MYIF (true) {\n"
1587                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1588                "}",
1589                AllowSimpleBracedStatements);
1590   verifyFormat("MYIF (true) { //\n"
1591                "  f();\n"
1592                "}",
1593                AllowSimpleBracedStatements);
1594   verifyFormat("MYIF (true) {\n"
1595                "  f();\n"
1596                "  f();\n"
1597                "}",
1598                AllowSimpleBracedStatements);
1599   verifyFormat("MYIF (true) {\n"
1600                "  f();\n"
1601                "} else {\n"
1602                "  f();\n"
1603                "}",
1604                AllowSimpleBracedStatements);
1605 
1606   verifyFormat("struct A2 {\n"
1607                "  int X;\n"
1608                "};",
1609                AllowSimpleBracedStatements);
1610   verifyFormat("typedef struct A2 {\n"
1611                "  int X;\n"
1612                "} A2_t;",
1613                AllowSimpleBracedStatements);
1614   verifyFormat("template <int> struct A2 {\n"
1615                "  struct B {};\n"
1616                "};",
1617                AllowSimpleBracedStatements);
1618 
1619   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1620       FormatStyle::SIS_Never;
1621   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1622   verifyFormat("if (true) {\n"
1623                "  f();\n"
1624                "}",
1625                AllowSimpleBracedStatements);
1626   verifyFormat("if (true) {\n"
1627                "  f();\n"
1628                "} else {\n"
1629                "  f();\n"
1630                "}",
1631                AllowSimpleBracedStatements);
1632   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1633   verifyFormat("MYIF (true) {\n"
1634                "  f();\n"
1635                "}",
1636                AllowSimpleBracedStatements);
1637   verifyFormat("MYIF (true) {\n"
1638                "  f();\n"
1639                "} else {\n"
1640                "  f();\n"
1641                "}",
1642                AllowSimpleBracedStatements);
1643 
1644   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1645   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1646   verifyFormat("while (true) {\n"
1647                "  f();\n"
1648                "}",
1649                AllowSimpleBracedStatements);
1650   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1651   verifyFormat("for (;;) {\n"
1652                "  f();\n"
1653                "}",
1654                AllowSimpleBracedStatements);
1655   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1656   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1657                "  f();\n"
1658                "}",
1659                AllowSimpleBracedStatements);
1660 
1661   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1662       FormatStyle::SIS_WithoutElse;
1663   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1664   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1665       FormatStyle::BWACS_Always;
1666 
1667   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1668   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1669   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1670   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1671   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1672   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1673   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1674   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1675   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1676   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1677   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1678   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1679   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1680   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1681   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1682   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1683   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1684                AllowSimpleBracedStatements);
1685   verifyFormat("if (true)\n"
1686                "{\n"
1687                "  ffffffffffffffffffffffff();\n"
1688                "}",
1689                AllowSimpleBracedStatements);
1690   verifyFormat("if (true)\n"
1691                "{\n"
1692                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1693                "}",
1694                AllowSimpleBracedStatements);
1695   verifyFormat("if (true)\n"
1696                "{ //\n"
1697                "  f();\n"
1698                "}",
1699                AllowSimpleBracedStatements);
1700   verifyFormat("if (true)\n"
1701                "{\n"
1702                "  f();\n"
1703                "  f();\n"
1704                "}",
1705                AllowSimpleBracedStatements);
1706   verifyFormat("if (true)\n"
1707                "{\n"
1708                "  f();\n"
1709                "} else\n"
1710                "{\n"
1711                "  f();\n"
1712                "}",
1713                AllowSimpleBracedStatements);
1714   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1715                AllowSimpleBracedStatements);
1716   verifyFormat("MYIF (true)\n"
1717                "{\n"
1718                "  ffffffffffffffffffffffff();\n"
1719                "}",
1720                AllowSimpleBracedStatements);
1721   verifyFormat("MYIF (true)\n"
1722                "{\n"
1723                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1724                "}",
1725                AllowSimpleBracedStatements);
1726   verifyFormat("MYIF (true)\n"
1727                "{ //\n"
1728                "  f();\n"
1729                "}",
1730                AllowSimpleBracedStatements);
1731   verifyFormat("MYIF (true)\n"
1732                "{\n"
1733                "  f();\n"
1734                "  f();\n"
1735                "}",
1736                AllowSimpleBracedStatements);
1737   verifyFormat("MYIF (true)\n"
1738                "{\n"
1739                "  f();\n"
1740                "} else\n"
1741                "{\n"
1742                "  f();\n"
1743                "}",
1744                AllowSimpleBracedStatements);
1745 
1746   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1747       FormatStyle::SIS_Never;
1748   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1749   verifyFormat("if (true)\n"
1750                "{\n"
1751                "  f();\n"
1752                "}",
1753                AllowSimpleBracedStatements);
1754   verifyFormat("if (true)\n"
1755                "{\n"
1756                "  f();\n"
1757                "} else\n"
1758                "{\n"
1759                "  f();\n"
1760                "}",
1761                AllowSimpleBracedStatements);
1762   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1763   verifyFormat("MYIF (true)\n"
1764                "{\n"
1765                "  f();\n"
1766                "}",
1767                AllowSimpleBracedStatements);
1768   verifyFormat("MYIF (true)\n"
1769                "{\n"
1770                "  f();\n"
1771                "} else\n"
1772                "{\n"
1773                "  f();\n"
1774                "}",
1775                AllowSimpleBracedStatements);
1776 
1777   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1778   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1779   verifyFormat("while (true)\n"
1780                "{\n"
1781                "  f();\n"
1782                "}",
1783                AllowSimpleBracedStatements);
1784   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1785   verifyFormat("for (;;)\n"
1786                "{\n"
1787                "  f();\n"
1788                "}",
1789                AllowSimpleBracedStatements);
1790   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1791   verifyFormat("BOOST_FOREACH (int v, vec)\n"
1792                "{\n"
1793                "  f();\n"
1794                "}",
1795                AllowSimpleBracedStatements);
1796 }
1797 
1798 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1799   FormatStyle Style = getLLVMStyleWithColumns(60);
1800   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1801   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1802   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1803   EXPECT_EQ("#define A                                                  \\\n"
1804             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1805             "  {                                                        \\\n"
1806             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1807             "  }\n"
1808             "X;",
1809             format("#define A \\\n"
1810                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1811                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1812                    "   }\n"
1813                    "X;",
1814                    Style));
1815 }
1816 
1817 TEST_F(FormatTest, ParseIfElse) {
1818   verifyFormat("if (true)\n"
1819                "  if (true)\n"
1820                "    if (true)\n"
1821                "      f();\n"
1822                "    else\n"
1823                "      g();\n"
1824                "  else\n"
1825                "    h();\n"
1826                "else\n"
1827                "  i();");
1828   verifyFormat("if (true)\n"
1829                "  if (true)\n"
1830                "    if (true) {\n"
1831                "      if (true)\n"
1832                "        f();\n"
1833                "    } else {\n"
1834                "      g();\n"
1835                "    }\n"
1836                "  else\n"
1837                "    h();\n"
1838                "else {\n"
1839                "  i();\n"
1840                "}");
1841   verifyFormat("if (true)\n"
1842                "  if constexpr (true)\n"
1843                "    if (true) {\n"
1844                "      if constexpr (true)\n"
1845                "        f();\n"
1846                "    } else {\n"
1847                "      g();\n"
1848                "    }\n"
1849                "  else\n"
1850                "    h();\n"
1851                "else {\n"
1852                "  i();\n"
1853                "}");
1854   verifyFormat("if (true)\n"
1855                "  if CONSTEXPR (true)\n"
1856                "    if (true) {\n"
1857                "      if CONSTEXPR (true)\n"
1858                "        f();\n"
1859                "    } else {\n"
1860                "      g();\n"
1861                "    }\n"
1862                "  else\n"
1863                "    h();\n"
1864                "else {\n"
1865                "  i();\n"
1866                "}");
1867   verifyFormat("void f() {\n"
1868                "  if (a) {\n"
1869                "  } else {\n"
1870                "  }\n"
1871                "}");
1872 }
1873 
1874 TEST_F(FormatTest, ElseIf) {
1875   verifyFormat("if (a) {\n} else if (b) {\n}");
1876   verifyFormat("if (a)\n"
1877                "  f();\n"
1878                "else if (b)\n"
1879                "  g();\n"
1880                "else\n"
1881                "  h();");
1882   verifyFormat("if (a)\n"
1883                "  f();\n"
1884                "else // comment\n"
1885                "  if (b) {\n"
1886                "    g();\n"
1887                "    h();\n"
1888                "  }");
1889   verifyFormat("if constexpr (a)\n"
1890                "  f();\n"
1891                "else if constexpr (b)\n"
1892                "  g();\n"
1893                "else\n"
1894                "  h();");
1895   verifyFormat("if CONSTEXPR (a)\n"
1896                "  f();\n"
1897                "else if CONSTEXPR (b)\n"
1898                "  g();\n"
1899                "else\n"
1900                "  h();");
1901   verifyFormat("if (a) {\n"
1902                "  f();\n"
1903                "}\n"
1904                "// or else ..\n"
1905                "else {\n"
1906                "  g()\n"
1907                "}");
1908 
1909   verifyFormat("if (a) {\n"
1910                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1911                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1912                "}");
1913   verifyFormat("if (a) {\n"
1914                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1915                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1916                "}");
1917   verifyFormat("if (a) {\n"
1918                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1919                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1920                "}");
1921   verifyFormat("if (a) {\n"
1922                "} else if (\n"
1923                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1924                "}",
1925                getLLVMStyleWithColumns(62));
1926   verifyFormat("if (a) {\n"
1927                "} else if constexpr (\n"
1928                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1929                "}",
1930                getLLVMStyleWithColumns(62));
1931   verifyFormat("if (a) {\n"
1932                "} else if CONSTEXPR (\n"
1933                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1934                "}",
1935                getLLVMStyleWithColumns(62));
1936 }
1937 
1938 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
1939   FormatStyle Style = getLLVMStyle();
1940   // Check first the default LLVM style
1941   // Style.PointerAlignment = FormatStyle::PAS_Right;
1942   // Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1943   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
1944   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
1945   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
1946   verifyFormat("int *f1(int &a) const &;", Style);
1947   verifyFormat("int *f1(int &a) const & = 0;", Style);
1948   verifyFormat("int *a = f1();", Style);
1949   verifyFormat("int &b = f2();", Style);
1950   verifyFormat("int &&c = f3();", Style);
1951   verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
1952   verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
1953   verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
1954   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
1955   verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
1956   verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
1957   verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
1958   verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
1959   verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
1960   verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
1961   verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
1962   verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
1963   verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
1964   verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
1965   verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
1966   verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
1967 
1968   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1969   verifyFormat("Const unsigned int *c;\n"
1970                "const unsigned int *d;\n"
1971                "Const unsigned int &e;\n"
1972                "const unsigned int &f;\n"
1973                "const unsigned    &&g;\n"
1974                "Const unsigned      h;",
1975                Style);
1976 
1977   Style.PointerAlignment = FormatStyle::PAS_Left;
1978   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1979   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
1980   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
1981   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
1982   verifyFormat("int* f1(int& a) const& = 0;", Style);
1983   verifyFormat("int* a = f1();", Style);
1984   verifyFormat("int& b = f2();", Style);
1985   verifyFormat("int&& c = f3();", Style);
1986   verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
1987   verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
1988   verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
1989   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
1990   verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
1991   verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
1992   verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
1993   verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
1994   verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
1995   verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
1996   verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
1997   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
1998   verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
1999   verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
2000   verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
2001   verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
2002   verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
2003   verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
2004 
2005   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2006   verifyFormat("Const unsigned int* c;\n"
2007                "const unsigned int* d;\n"
2008                "Const unsigned int& e;\n"
2009                "const unsigned int& f;\n"
2010                "const unsigned&&    g;\n"
2011                "Const unsigned      h;",
2012                Style);
2013 
2014   Style.PointerAlignment = FormatStyle::PAS_Right;
2015   Style.ReferenceAlignment = FormatStyle::RAS_Left;
2016   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
2017   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
2018   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
2019   verifyFormat("int *a = f1();", Style);
2020   verifyFormat("int& b = f2();", Style);
2021   verifyFormat("int&& c = f3();", Style);
2022   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2023   verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2024   verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
2025 
2026   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2027   verifyFormat("Const unsigned int *c;\n"
2028                "const unsigned int *d;\n"
2029                "Const unsigned int& e;\n"
2030                "const unsigned int& f;\n"
2031                "const unsigned      g;\n"
2032                "Const unsigned      h;",
2033                Style);
2034 
2035   Style.PointerAlignment = FormatStyle::PAS_Left;
2036   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
2037   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
2038   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
2039   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
2040   verifyFormat("int* a = f1();", Style);
2041   verifyFormat("int & b = f2();", Style);
2042   verifyFormat("int && c = f3();", Style);
2043   verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
2044   verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
2045   verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
2046   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2047   verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
2048   verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
2049   verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
2050   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2051   verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
2052   verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
2053   verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
2054   verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
2055   verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
2056   verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
2057 
2058   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2059   verifyFormat("Const unsigned int*  c;\n"
2060                "const unsigned int*  d;\n"
2061                "Const unsigned int & e;\n"
2062                "const unsigned int & f;\n"
2063                "const unsigned &&    g;\n"
2064                "Const unsigned       h;",
2065                Style);
2066 
2067   Style.PointerAlignment = FormatStyle::PAS_Middle;
2068   Style.ReferenceAlignment = FormatStyle::RAS_Right;
2069   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
2070   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
2071   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
2072   verifyFormat("int * a = f1();", Style);
2073   verifyFormat("int &b = f2();", Style);
2074   verifyFormat("int &&c = f3();", Style);
2075   verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2076   verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2077   verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
2078 
2079   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2080   // specifically handled
2081   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2082 }
2083 
2084 TEST_F(FormatTest, FormatsForLoop) {
2085   verifyFormat(
2086       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2087       "     ++VeryVeryLongLoopVariable)\n"
2088       "  ;");
2089   verifyFormat("for (;;)\n"
2090                "  f();");
2091   verifyFormat("for (;;) {\n}");
2092   verifyFormat("for (;;) {\n"
2093                "  f();\n"
2094                "}");
2095   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2096 
2097   verifyFormat(
2098       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2099       "                                          E = UnwrappedLines.end();\n"
2100       "     I != E; ++I) {\n}");
2101 
2102   verifyFormat(
2103       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2104       "     ++IIIII) {\n}");
2105   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2106                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2107                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2108   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2109                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2110                "         E = FD->getDeclsInPrototypeScope().end();\n"
2111                "     I != E; ++I) {\n}");
2112   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2113                "         I = Container.begin(),\n"
2114                "         E = Container.end();\n"
2115                "     I != E; ++I) {\n}",
2116                getLLVMStyleWithColumns(76));
2117 
2118   verifyFormat(
2119       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2120       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2121       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2122       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2123       "     ++aaaaaaaaaaa) {\n}");
2124   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2125                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2126                "     ++i) {\n}");
2127   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2128                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2129                "}");
2130   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2131                "         aaaaaaaaaa);\n"
2132                "     iter; ++iter) {\n"
2133                "}");
2134   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2135                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2136                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2137                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2138 
2139   // These should not be formatted as Objective-C for-in loops.
2140   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2141   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2142   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2143   verifyFormat(
2144       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2145 
2146   FormatStyle NoBinPacking = getLLVMStyle();
2147   NoBinPacking.BinPackParameters = false;
2148   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2149                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2150                "                                           aaaaaaaaaaaaaaaa,\n"
2151                "                                           aaaaaaaaaaaaaaaa,\n"
2152                "                                           aaaaaaaaaaaaaaaa);\n"
2153                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2154                "}",
2155                NoBinPacking);
2156   verifyFormat(
2157       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2158       "                                          E = UnwrappedLines.end();\n"
2159       "     I != E;\n"
2160       "     ++I) {\n}",
2161       NoBinPacking);
2162 
2163   FormatStyle AlignLeft = getLLVMStyle();
2164   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2165   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2166 }
2167 
2168 TEST_F(FormatTest, RangeBasedForLoops) {
2169   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2170                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2171   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2172                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2173   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2174                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2175   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2176                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2177 }
2178 
2179 TEST_F(FormatTest, ForEachLoops) {
2180   FormatStyle Style = getLLVMStyle();
2181   EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2182   EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
2183   verifyFormat("void f() {\n"
2184                "  for (;;) {\n"
2185                "  }\n"
2186                "  foreach (Item *item, itemlist) {\n"
2187                "  }\n"
2188                "  Q_FOREACH (Item *item, itemlist) {\n"
2189                "  }\n"
2190                "  BOOST_FOREACH (Item *item, itemlist) {\n"
2191                "  }\n"
2192                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2193                "}",
2194                Style);
2195   verifyFormat("void f() {\n"
2196                "  for (;;)\n"
2197                "    int j = 1;\n"
2198                "  Q_FOREACH (int v, vec)\n"
2199                "    v *= 2;\n"
2200                "  for (;;) {\n"
2201                "    int j = 1;\n"
2202                "  }\n"
2203                "  Q_FOREACH (int v, vec) {\n"
2204                "    v *= 2;\n"
2205                "  }\n"
2206                "}",
2207                Style);
2208 
2209   FormatStyle ShortBlocks = getLLVMStyle();
2210   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2211   EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
2212   verifyFormat("void f() {\n"
2213                "  for (;;)\n"
2214                "    int j = 1;\n"
2215                "  Q_FOREACH (int &v, vec)\n"
2216                "    v *= 2;\n"
2217                "  for (;;) {\n"
2218                "    int j = 1;\n"
2219                "  }\n"
2220                "  Q_FOREACH (int &v, vec) {\n"
2221                "    int j = 1;\n"
2222                "  }\n"
2223                "}",
2224                ShortBlocks);
2225 
2226   FormatStyle ShortLoops = getLLVMStyle();
2227   ShortLoops.AllowShortLoopsOnASingleLine = true;
2228   EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2229   verifyFormat("void f() {\n"
2230                "  for (;;) int j = 1;\n"
2231                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2232                "  for (;;) {\n"
2233                "    int j = 1;\n"
2234                "  }\n"
2235                "  Q_FOREACH (int &v, vec) {\n"
2236                "    int j = 1;\n"
2237                "  }\n"
2238                "}",
2239                ShortLoops);
2240 
2241   FormatStyle ShortBlocksAndLoops = getLLVMStyle();
2242   ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2243   ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true;
2244   verifyFormat("void f() {\n"
2245                "  for (;;) int j = 1;\n"
2246                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2247                "  for (;;) { int j = 1; }\n"
2248                "  Q_FOREACH (int &v, vec) { int j = 1; }\n"
2249                "}",
2250                ShortBlocksAndLoops);
2251 
2252   Style.SpaceBeforeParens =
2253       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2254   verifyFormat("void f() {\n"
2255                "  for (;;) {\n"
2256                "  }\n"
2257                "  foreach(Item *item, itemlist) {\n"
2258                "  }\n"
2259                "  Q_FOREACH(Item *item, itemlist) {\n"
2260                "  }\n"
2261                "  BOOST_FOREACH(Item *item, itemlist) {\n"
2262                "  }\n"
2263                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2264                "}",
2265                Style);
2266 
2267   // As function-like macros.
2268   verifyFormat("#define foreach(x, y)\n"
2269                "#define Q_FOREACH(x, y)\n"
2270                "#define BOOST_FOREACH(x, y)\n"
2271                "#define UNKNOWN_FOREACH(x, y)\n");
2272 
2273   // Not as function-like macros.
2274   verifyFormat("#define foreach (x, y)\n"
2275                "#define Q_FOREACH (x, y)\n"
2276                "#define BOOST_FOREACH (x, y)\n"
2277                "#define UNKNOWN_FOREACH (x, y)\n");
2278 
2279   // handle microsoft non standard extension
2280   verifyFormat("for each (char c in x->MyStringProperty)");
2281 }
2282 
2283 TEST_F(FormatTest, FormatsWhileLoop) {
2284   verifyFormat("while (true) {\n}");
2285   verifyFormat("while (true)\n"
2286                "  f();");
2287   verifyFormat("while () {\n}");
2288   verifyFormat("while () {\n"
2289                "  f();\n"
2290                "}");
2291 }
2292 
2293 TEST_F(FormatTest, FormatsDoWhile) {
2294   verifyFormat("do {\n"
2295                "  do_something();\n"
2296                "} while (something());");
2297   verifyFormat("do\n"
2298                "  do_something();\n"
2299                "while (something());");
2300 }
2301 
2302 TEST_F(FormatTest, FormatsSwitchStatement) {
2303   verifyFormat("switch (x) {\n"
2304                "case 1:\n"
2305                "  f();\n"
2306                "  break;\n"
2307                "case kFoo:\n"
2308                "case ns::kBar:\n"
2309                "case kBaz:\n"
2310                "  break;\n"
2311                "default:\n"
2312                "  g();\n"
2313                "  break;\n"
2314                "}");
2315   verifyFormat("switch (x) {\n"
2316                "case 1: {\n"
2317                "  f();\n"
2318                "  break;\n"
2319                "}\n"
2320                "case 2: {\n"
2321                "  break;\n"
2322                "}\n"
2323                "}");
2324   verifyFormat("switch (x) {\n"
2325                "case 1: {\n"
2326                "  f();\n"
2327                "  {\n"
2328                "    g();\n"
2329                "    h();\n"
2330                "  }\n"
2331                "  break;\n"
2332                "}\n"
2333                "}");
2334   verifyFormat("switch (x) {\n"
2335                "case 1: {\n"
2336                "  f();\n"
2337                "  if (foo) {\n"
2338                "    g();\n"
2339                "    h();\n"
2340                "  }\n"
2341                "  break;\n"
2342                "}\n"
2343                "}");
2344   verifyFormat("switch (x) {\n"
2345                "case 1: {\n"
2346                "  f();\n"
2347                "  g();\n"
2348                "} break;\n"
2349                "}");
2350   verifyFormat("switch (test)\n"
2351                "  ;");
2352   verifyFormat("switch (x) {\n"
2353                "default: {\n"
2354                "  // Do nothing.\n"
2355                "}\n"
2356                "}");
2357   verifyFormat("switch (x) {\n"
2358                "// comment\n"
2359                "// if 1, do f()\n"
2360                "case 1:\n"
2361                "  f();\n"
2362                "}");
2363   verifyFormat("switch (x) {\n"
2364                "case 1:\n"
2365                "  // Do amazing stuff\n"
2366                "  {\n"
2367                "    f();\n"
2368                "    g();\n"
2369                "  }\n"
2370                "  break;\n"
2371                "}");
2372   verifyFormat("#define A          \\\n"
2373                "  switch (x) {     \\\n"
2374                "  case a:          \\\n"
2375                "    foo = b;       \\\n"
2376                "  }",
2377                getLLVMStyleWithColumns(20));
2378   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2379                "  case OP_name:                        \\\n"
2380                "    return operations::Operation##name\n",
2381                getLLVMStyleWithColumns(40));
2382   verifyFormat("switch (x) {\n"
2383                "case 1:;\n"
2384                "default:;\n"
2385                "  int i;\n"
2386                "}");
2387 
2388   verifyGoogleFormat("switch (x) {\n"
2389                      "  case 1:\n"
2390                      "    f();\n"
2391                      "    break;\n"
2392                      "  case kFoo:\n"
2393                      "  case ns::kBar:\n"
2394                      "  case kBaz:\n"
2395                      "    break;\n"
2396                      "  default:\n"
2397                      "    g();\n"
2398                      "    break;\n"
2399                      "}");
2400   verifyGoogleFormat("switch (x) {\n"
2401                      "  case 1: {\n"
2402                      "    f();\n"
2403                      "    break;\n"
2404                      "  }\n"
2405                      "}");
2406   verifyGoogleFormat("switch (test)\n"
2407                      "  ;");
2408 
2409   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2410                      "  case OP_name:              \\\n"
2411                      "    return operations::Operation##name\n");
2412   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2413                      "  // Get the correction operation class.\n"
2414                      "  switch (OpCode) {\n"
2415                      "    CASE(Add);\n"
2416                      "    CASE(Subtract);\n"
2417                      "    default:\n"
2418                      "      return operations::Unknown;\n"
2419                      "  }\n"
2420                      "#undef OPERATION_CASE\n"
2421                      "}");
2422   verifyFormat("DEBUG({\n"
2423                "  switch (x) {\n"
2424                "  case A:\n"
2425                "    f();\n"
2426                "    break;\n"
2427                "    // fallthrough\n"
2428                "  case B:\n"
2429                "    g();\n"
2430                "    break;\n"
2431                "  }\n"
2432                "});");
2433   EXPECT_EQ("DEBUG({\n"
2434             "  switch (x) {\n"
2435             "  case A:\n"
2436             "    f();\n"
2437             "    break;\n"
2438             "  // On B:\n"
2439             "  case B:\n"
2440             "    g();\n"
2441             "    break;\n"
2442             "  }\n"
2443             "});",
2444             format("DEBUG({\n"
2445                    "  switch (x) {\n"
2446                    "  case A:\n"
2447                    "    f();\n"
2448                    "    break;\n"
2449                    "  // On B:\n"
2450                    "  case B:\n"
2451                    "    g();\n"
2452                    "    break;\n"
2453                    "  }\n"
2454                    "});",
2455                    getLLVMStyle()));
2456   EXPECT_EQ("switch (n) {\n"
2457             "case 0: {\n"
2458             "  return false;\n"
2459             "}\n"
2460             "default: {\n"
2461             "  return true;\n"
2462             "}\n"
2463             "}",
2464             format("switch (n)\n"
2465                    "{\n"
2466                    "case 0: {\n"
2467                    "  return false;\n"
2468                    "}\n"
2469                    "default: {\n"
2470                    "  return true;\n"
2471                    "}\n"
2472                    "}",
2473                    getLLVMStyle()));
2474   verifyFormat("switch (a) {\n"
2475                "case (b):\n"
2476                "  return;\n"
2477                "}");
2478 
2479   verifyFormat("switch (a) {\n"
2480                "case some_namespace::\n"
2481                "    some_constant:\n"
2482                "  return;\n"
2483                "}",
2484                getLLVMStyleWithColumns(34));
2485 
2486   FormatStyle Style = getLLVMStyle();
2487   Style.IndentCaseLabels = true;
2488   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2489   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2490   Style.BraceWrapping.AfterCaseLabel = true;
2491   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2492   EXPECT_EQ("switch (n)\n"
2493             "{\n"
2494             "  case 0:\n"
2495             "  {\n"
2496             "    return false;\n"
2497             "  }\n"
2498             "  default:\n"
2499             "  {\n"
2500             "    return true;\n"
2501             "  }\n"
2502             "}",
2503             format("switch (n) {\n"
2504                    "  case 0: {\n"
2505                    "    return false;\n"
2506                    "  }\n"
2507                    "  default: {\n"
2508                    "    return true;\n"
2509                    "  }\n"
2510                    "}",
2511                    Style));
2512   Style.BraceWrapping.AfterCaseLabel = false;
2513   EXPECT_EQ("switch (n)\n"
2514             "{\n"
2515             "  case 0: {\n"
2516             "    return false;\n"
2517             "  }\n"
2518             "  default: {\n"
2519             "    return true;\n"
2520             "  }\n"
2521             "}",
2522             format("switch (n) {\n"
2523                    "  case 0:\n"
2524                    "  {\n"
2525                    "    return false;\n"
2526                    "  }\n"
2527                    "  default:\n"
2528                    "  {\n"
2529                    "    return true;\n"
2530                    "  }\n"
2531                    "}",
2532                    Style));
2533   Style.IndentCaseLabels = false;
2534   Style.IndentCaseBlocks = true;
2535   EXPECT_EQ("switch (n)\n"
2536             "{\n"
2537             "case 0:\n"
2538             "  {\n"
2539             "    return false;\n"
2540             "  }\n"
2541             "case 1:\n"
2542             "  break;\n"
2543             "default:\n"
2544             "  {\n"
2545             "    return true;\n"
2546             "  }\n"
2547             "}",
2548             format("switch (n) {\n"
2549                    "case 0: {\n"
2550                    "  return false;\n"
2551                    "}\n"
2552                    "case 1:\n"
2553                    "  break;\n"
2554                    "default: {\n"
2555                    "  return true;\n"
2556                    "}\n"
2557                    "}",
2558                    Style));
2559   Style.IndentCaseLabels = true;
2560   Style.IndentCaseBlocks = true;
2561   EXPECT_EQ("switch (n)\n"
2562             "{\n"
2563             "  case 0:\n"
2564             "    {\n"
2565             "      return false;\n"
2566             "    }\n"
2567             "  case 1:\n"
2568             "    break;\n"
2569             "  default:\n"
2570             "    {\n"
2571             "      return true;\n"
2572             "    }\n"
2573             "}",
2574             format("switch (n) {\n"
2575                    "case 0: {\n"
2576                    "  return false;\n"
2577                    "}\n"
2578                    "case 1:\n"
2579                    "  break;\n"
2580                    "default: {\n"
2581                    "  return true;\n"
2582                    "}\n"
2583                    "}",
2584                    Style));
2585 }
2586 
2587 TEST_F(FormatTest, CaseRanges) {
2588   verifyFormat("switch (x) {\n"
2589                "case 'A' ... 'Z':\n"
2590                "case 1 ... 5:\n"
2591                "case a ... b:\n"
2592                "  break;\n"
2593                "}");
2594 }
2595 
2596 TEST_F(FormatTest, ShortEnums) {
2597   FormatStyle Style = getLLVMStyle();
2598   Style.AllowShortEnumsOnASingleLine = true;
2599   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2600   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2601   Style.AllowShortEnumsOnASingleLine = false;
2602   verifyFormat("enum {\n"
2603                "  A,\n"
2604                "  B,\n"
2605                "  C\n"
2606                "} ShortEnum1, ShortEnum2;",
2607                Style);
2608   verifyFormat("typedef enum {\n"
2609                "  A,\n"
2610                "  B,\n"
2611                "  C\n"
2612                "} ShortEnum1, ShortEnum2;",
2613                Style);
2614   verifyFormat("enum {\n"
2615                "  A,\n"
2616                "} ShortEnum1, ShortEnum2;",
2617                Style);
2618   verifyFormat("typedef enum {\n"
2619                "  A,\n"
2620                "} ShortEnum1, ShortEnum2;",
2621                Style);
2622   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2623   Style.BraceWrapping.AfterEnum = true;
2624   verifyFormat("enum\n"
2625                "{\n"
2626                "  A,\n"
2627                "  B,\n"
2628                "  C\n"
2629                "} ShortEnum1, ShortEnum2;",
2630                Style);
2631   verifyFormat("typedef enum\n"
2632                "{\n"
2633                "  A,\n"
2634                "  B,\n"
2635                "  C\n"
2636                "} ShortEnum1, ShortEnum2;",
2637                Style);
2638 }
2639 
2640 TEST_F(FormatTest, ShortCaseLabels) {
2641   FormatStyle Style = getLLVMStyle();
2642   Style.AllowShortCaseLabelsOnASingleLine = true;
2643   verifyFormat("switch (a) {\n"
2644                "case 1: x = 1; break;\n"
2645                "case 2: return;\n"
2646                "case 3:\n"
2647                "case 4:\n"
2648                "case 5: return;\n"
2649                "case 6: // comment\n"
2650                "  return;\n"
2651                "case 7:\n"
2652                "  // comment\n"
2653                "  return;\n"
2654                "case 8:\n"
2655                "  x = 8; // comment\n"
2656                "  break;\n"
2657                "default: y = 1; break;\n"
2658                "}",
2659                Style);
2660   verifyFormat("switch (a) {\n"
2661                "case 0: return; // comment\n"
2662                "case 1: break;  // comment\n"
2663                "case 2: return;\n"
2664                "// comment\n"
2665                "case 3: return;\n"
2666                "// comment 1\n"
2667                "// comment 2\n"
2668                "// comment 3\n"
2669                "case 4: break; /* comment */\n"
2670                "case 5:\n"
2671                "  // comment\n"
2672                "  break;\n"
2673                "case 6: /* comment */ x = 1; break;\n"
2674                "case 7: x = /* comment */ 1; break;\n"
2675                "case 8:\n"
2676                "  x = 1; /* comment */\n"
2677                "  break;\n"
2678                "case 9:\n"
2679                "  break; // comment line 1\n"
2680                "         // comment line 2\n"
2681                "}",
2682                Style);
2683   EXPECT_EQ("switch (a) {\n"
2684             "case 1:\n"
2685             "  x = 8;\n"
2686             "  // fall through\n"
2687             "case 2: x = 8;\n"
2688             "// comment\n"
2689             "case 3:\n"
2690             "  return; /* comment line 1\n"
2691             "           * comment line 2 */\n"
2692             "case 4: i = 8;\n"
2693             "// something else\n"
2694             "#if FOO\n"
2695             "case 5: break;\n"
2696             "#endif\n"
2697             "}",
2698             format("switch (a) {\n"
2699                    "case 1: x = 8;\n"
2700                    "  // fall through\n"
2701                    "case 2:\n"
2702                    "  x = 8;\n"
2703                    "// comment\n"
2704                    "case 3:\n"
2705                    "  return; /* comment line 1\n"
2706                    "           * comment line 2 */\n"
2707                    "case 4:\n"
2708                    "  i = 8;\n"
2709                    "// something else\n"
2710                    "#if FOO\n"
2711                    "case 5: break;\n"
2712                    "#endif\n"
2713                    "}",
2714                    Style));
2715   EXPECT_EQ("switch (a) {\n"
2716             "case 0:\n"
2717             "  return; // long long long long long long long long long long "
2718             "long long comment\n"
2719             "          // line\n"
2720             "}",
2721             format("switch (a) {\n"
2722                    "case 0: return; // long long long long long long long long "
2723                    "long long long long comment line\n"
2724                    "}",
2725                    Style));
2726   EXPECT_EQ("switch (a) {\n"
2727             "case 0:\n"
2728             "  return; /* long long long long long long long long long long "
2729             "long long comment\n"
2730             "             line */\n"
2731             "}",
2732             format("switch (a) {\n"
2733                    "case 0: return; /* long long long long long long long long "
2734                    "long long long long comment line */\n"
2735                    "}",
2736                    Style));
2737   verifyFormat("switch (a) {\n"
2738                "#if FOO\n"
2739                "case 0: return 0;\n"
2740                "#endif\n"
2741                "}",
2742                Style);
2743   verifyFormat("switch (a) {\n"
2744                "case 1: {\n"
2745                "}\n"
2746                "case 2: {\n"
2747                "  return;\n"
2748                "}\n"
2749                "case 3: {\n"
2750                "  x = 1;\n"
2751                "  return;\n"
2752                "}\n"
2753                "case 4:\n"
2754                "  if (x)\n"
2755                "    return;\n"
2756                "}",
2757                Style);
2758   Style.ColumnLimit = 21;
2759   verifyFormat("switch (a) {\n"
2760                "case 1: x = 1; break;\n"
2761                "case 2: return;\n"
2762                "case 3:\n"
2763                "case 4:\n"
2764                "case 5: return;\n"
2765                "default:\n"
2766                "  y = 1;\n"
2767                "  break;\n"
2768                "}",
2769                Style);
2770   Style.ColumnLimit = 80;
2771   Style.AllowShortCaseLabelsOnASingleLine = false;
2772   Style.IndentCaseLabels = true;
2773   EXPECT_EQ("switch (n) {\n"
2774             "  default /*comments*/:\n"
2775             "    return true;\n"
2776             "  case 0:\n"
2777             "    return false;\n"
2778             "}",
2779             format("switch (n) {\n"
2780                    "default/*comments*/:\n"
2781                    "  return true;\n"
2782                    "case 0:\n"
2783                    "  return false;\n"
2784                    "}",
2785                    Style));
2786   Style.AllowShortCaseLabelsOnASingleLine = true;
2787   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2788   Style.BraceWrapping.AfterCaseLabel = true;
2789   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2790   EXPECT_EQ("switch (n)\n"
2791             "{\n"
2792             "  case 0:\n"
2793             "  {\n"
2794             "    return false;\n"
2795             "  }\n"
2796             "  default:\n"
2797             "  {\n"
2798             "    return true;\n"
2799             "  }\n"
2800             "}",
2801             format("switch (n) {\n"
2802                    "  case 0: {\n"
2803                    "    return false;\n"
2804                    "  }\n"
2805                    "  default:\n"
2806                    "  {\n"
2807                    "    return true;\n"
2808                    "  }\n"
2809                    "}",
2810                    Style));
2811 }
2812 
2813 TEST_F(FormatTest, FormatsLabels) {
2814   verifyFormat("void f() {\n"
2815                "  some_code();\n"
2816                "test_label:\n"
2817                "  some_other_code();\n"
2818                "  {\n"
2819                "    some_more_code();\n"
2820                "  another_label:\n"
2821                "    some_more_code();\n"
2822                "  }\n"
2823                "}");
2824   verifyFormat("{\n"
2825                "  some_code();\n"
2826                "test_label:\n"
2827                "  some_other_code();\n"
2828                "}");
2829   verifyFormat("{\n"
2830                "  some_code();\n"
2831                "test_label:;\n"
2832                "  int i = 0;\n"
2833                "}");
2834   FormatStyle Style = getLLVMStyle();
2835   Style.IndentGotoLabels = false;
2836   verifyFormat("void f() {\n"
2837                "  some_code();\n"
2838                "test_label:\n"
2839                "  some_other_code();\n"
2840                "  {\n"
2841                "    some_more_code();\n"
2842                "another_label:\n"
2843                "    some_more_code();\n"
2844                "  }\n"
2845                "}",
2846                Style);
2847   verifyFormat("{\n"
2848                "  some_code();\n"
2849                "test_label:\n"
2850                "  some_other_code();\n"
2851                "}",
2852                Style);
2853   verifyFormat("{\n"
2854                "  some_code();\n"
2855                "test_label:;\n"
2856                "  int i = 0;\n"
2857                "}");
2858 }
2859 
2860 TEST_F(FormatTest, MultiLineControlStatements) {
2861   FormatStyle Style = getLLVMStyleWithColumns(20);
2862   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2863   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2864   // Short lines should keep opening brace on same line.
2865   EXPECT_EQ("if (foo) {\n"
2866             "  bar();\n"
2867             "}",
2868             format("if(foo){bar();}", Style));
2869   EXPECT_EQ("if (foo) {\n"
2870             "  bar();\n"
2871             "} else {\n"
2872             "  baz();\n"
2873             "}",
2874             format("if(foo){bar();}else{baz();}", Style));
2875   EXPECT_EQ("if (foo && bar) {\n"
2876             "  baz();\n"
2877             "}",
2878             format("if(foo&&bar){baz();}", Style));
2879   EXPECT_EQ("if (foo) {\n"
2880             "  bar();\n"
2881             "} else if (baz) {\n"
2882             "  quux();\n"
2883             "}",
2884             format("if(foo){bar();}else if(baz){quux();}", Style));
2885   EXPECT_EQ(
2886       "if (foo) {\n"
2887       "  bar();\n"
2888       "} else if (baz) {\n"
2889       "  quux();\n"
2890       "} else {\n"
2891       "  foobar();\n"
2892       "}",
2893       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
2894   EXPECT_EQ("for (;;) {\n"
2895             "  foo();\n"
2896             "}",
2897             format("for(;;){foo();}"));
2898   EXPECT_EQ("while (1) {\n"
2899             "  foo();\n"
2900             "}",
2901             format("while(1){foo();}", Style));
2902   EXPECT_EQ("switch (foo) {\n"
2903             "case bar:\n"
2904             "  return;\n"
2905             "}",
2906             format("switch(foo){case bar:return;}", Style));
2907   EXPECT_EQ("try {\n"
2908             "  foo();\n"
2909             "} catch (...) {\n"
2910             "  bar();\n"
2911             "}",
2912             format("try{foo();}catch(...){bar();}", Style));
2913   EXPECT_EQ("do {\n"
2914             "  foo();\n"
2915             "} while (bar &&\n"
2916             "         baz);",
2917             format("do{foo();}while(bar&&baz);", Style));
2918   // Long lines should put opening brace on new line.
2919   EXPECT_EQ("if (foo && bar &&\n"
2920             "    baz)\n"
2921             "{\n"
2922             "  quux();\n"
2923             "}",
2924             format("if(foo&&bar&&baz){quux();}", Style));
2925   EXPECT_EQ("if (foo && bar &&\n"
2926             "    baz)\n"
2927             "{\n"
2928             "  quux();\n"
2929             "}",
2930             format("if (foo && bar &&\n"
2931                    "    baz) {\n"
2932                    "  quux();\n"
2933                    "}",
2934                    Style));
2935   EXPECT_EQ("if (foo) {\n"
2936             "  bar();\n"
2937             "} else if (baz ||\n"
2938             "           quux)\n"
2939             "{\n"
2940             "  foobar();\n"
2941             "}",
2942             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
2943   EXPECT_EQ(
2944       "if (foo) {\n"
2945       "  bar();\n"
2946       "} else if (baz ||\n"
2947       "           quux)\n"
2948       "{\n"
2949       "  foobar();\n"
2950       "} else {\n"
2951       "  barbaz();\n"
2952       "}",
2953       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2954              Style));
2955   EXPECT_EQ("for (int i = 0;\n"
2956             "     i < 10; ++i)\n"
2957             "{\n"
2958             "  foo();\n"
2959             "}",
2960             format("for(int i=0;i<10;++i){foo();}", Style));
2961   EXPECT_EQ("foreach (int i,\n"
2962             "         list)\n"
2963             "{\n"
2964             "  foo();\n"
2965             "}",
2966             format("foreach(int i, list){foo();}", Style));
2967   Style.ColumnLimit =
2968       40; // to concentrate at brace wrapping, not line wrap due to column limit
2969   EXPECT_EQ("foreach (int i, list) {\n"
2970             "  foo();\n"
2971             "}",
2972             format("foreach(int i, list){foo();}", Style));
2973   Style.ColumnLimit =
2974       20; // to concentrate at brace wrapping, not line wrap due to column limit
2975   EXPECT_EQ("while (foo || bar ||\n"
2976             "       baz)\n"
2977             "{\n"
2978             "  quux();\n"
2979             "}",
2980             format("while(foo||bar||baz){quux();}", Style));
2981   EXPECT_EQ("switch (\n"
2982             "    foo = barbaz)\n"
2983             "{\n"
2984             "case quux:\n"
2985             "  return;\n"
2986             "}",
2987             format("switch(foo=barbaz){case quux:return;}", Style));
2988   EXPECT_EQ("try {\n"
2989             "  foo();\n"
2990             "} catch (\n"
2991             "    Exception &bar)\n"
2992             "{\n"
2993             "  baz();\n"
2994             "}",
2995             format("try{foo();}catch(Exception&bar){baz();}", Style));
2996   Style.ColumnLimit =
2997       40; // to concentrate at brace wrapping, not line wrap due to column limit
2998   EXPECT_EQ("try {\n"
2999             "  foo();\n"
3000             "} catch (Exception &bar) {\n"
3001             "  baz();\n"
3002             "}",
3003             format("try{foo();}catch(Exception&bar){baz();}", Style));
3004   Style.ColumnLimit =
3005       20; // to concentrate at brace wrapping, not line wrap due to column limit
3006 
3007   Style.BraceWrapping.BeforeElse = true;
3008   EXPECT_EQ(
3009       "if (foo) {\n"
3010       "  bar();\n"
3011       "}\n"
3012       "else if (baz ||\n"
3013       "         quux)\n"
3014       "{\n"
3015       "  foobar();\n"
3016       "}\n"
3017       "else {\n"
3018       "  barbaz();\n"
3019       "}",
3020       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3021              Style));
3022 
3023   Style.BraceWrapping.BeforeCatch = true;
3024   EXPECT_EQ("try {\n"
3025             "  foo();\n"
3026             "}\n"
3027             "catch (...) {\n"
3028             "  baz();\n"
3029             "}",
3030             format("try{foo();}catch(...){baz();}", Style));
3031 
3032   Style.BraceWrapping.AfterFunction = true;
3033   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3034   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
3035   Style.ColumnLimit = 80;
3036   verifyFormat("void shortfunction() { bar(); }", Style);
3037 
3038   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
3039   verifyFormat("void shortfunction()\n"
3040                "{\n"
3041                "  bar();\n"
3042                "}",
3043                Style);
3044 }
3045 
3046 TEST_F(FormatTest, BeforeWhile) {
3047   FormatStyle Style = getLLVMStyle();
3048   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3049 
3050   verifyFormat("do {\n"
3051                "  foo();\n"
3052                "} while (1);",
3053                Style);
3054   Style.BraceWrapping.BeforeWhile = true;
3055   verifyFormat("do {\n"
3056                "  foo();\n"
3057                "}\n"
3058                "while (1);",
3059                Style);
3060 }
3061 
3062 //===----------------------------------------------------------------------===//
3063 // Tests for classes, namespaces, etc.
3064 //===----------------------------------------------------------------------===//
3065 
3066 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
3067   verifyFormat("class A {};");
3068 }
3069 
3070 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
3071   verifyFormat("class A {\n"
3072                "public:\n"
3073                "public: // comment\n"
3074                "protected:\n"
3075                "private:\n"
3076                "  void f() {}\n"
3077                "};");
3078   verifyFormat("export class A {\n"
3079                "public:\n"
3080                "public: // comment\n"
3081                "protected:\n"
3082                "private:\n"
3083                "  void f() {}\n"
3084                "};");
3085   verifyGoogleFormat("class A {\n"
3086                      " public:\n"
3087                      " protected:\n"
3088                      " private:\n"
3089                      "  void f() {}\n"
3090                      "};");
3091   verifyGoogleFormat("export class A {\n"
3092                      " public:\n"
3093                      " protected:\n"
3094                      " private:\n"
3095                      "  void f() {}\n"
3096                      "};");
3097   verifyFormat("class A {\n"
3098                "public slots:\n"
3099                "  void f1() {}\n"
3100                "public Q_SLOTS:\n"
3101                "  void f2() {}\n"
3102                "protected slots:\n"
3103                "  void f3() {}\n"
3104                "protected Q_SLOTS:\n"
3105                "  void f4() {}\n"
3106                "private slots:\n"
3107                "  void f5() {}\n"
3108                "private Q_SLOTS:\n"
3109                "  void f6() {}\n"
3110                "signals:\n"
3111                "  void g1();\n"
3112                "Q_SIGNALS:\n"
3113                "  void g2();\n"
3114                "};");
3115 
3116   // Don't interpret 'signals' the wrong way.
3117   verifyFormat("signals.set();");
3118   verifyFormat("for (Signals signals : f()) {\n}");
3119   verifyFormat("{\n"
3120                "  signals.set(); // This needs indentation.\n"
3121                "}");
3122   verifyFormat("void f() {\n"
3123                "label:\n"
3124                "  signals.baz();\n"
3125                "}");
3126 }
3127 
3128 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3129   EXPECT_EQ("class A {\n"
3130             "public:\n"
3131             "  void f();\n"
3132             "\n"
3133             "private:\n"
3134             "  void g() {}\n"
3135             "  // test\n"
3136             "protected:\n"
3137             "  int h;\n"
3138             "};",
3139             format("class A {\n"
3140                    "public:\n"
3141                    "void f();\n"
3142                    "private:\n"
3143                    "void g() {}\n"
3144                    "// test\n"
3145                    "protected:\n"
3146                    "int h;\n"
3147                    "};"));
3148   EXPECT_EQ("class A {\n"
3149             "protected:\n"
3150             "public:\n"
3151             "  void f();\n"
3152             "};",
3153             format("class A {\n"
3154                    "protected:\n"
3155                    "\n"
3156                    "public:\n"
3157                    "\n"
3158                    "  void f();\n"
3159                    "};"));
3160 
3161   // Even ensure proper spacing inside macros.
3162   EXPECT_EQ("#define B     \\\n"
3163             "  class A {   \\\n"
3164             "   protected: \\\n"
3165             "   public:    \\\n"
3166             "    void f(); \\\n"
3167             "  };",
3168             format("#define B     \\\n"
3169                    "  class A {   \\\n"
3170                    "   protected: \\\n"
3171                    "              \\\n"
3172                    "   public:    \\\n"
3173                    "              \\\n"
3174                    "    void f(); \\\n"
3175                    "  };",
3176                    getGoogleStyle()));
3177   // But don't remove empty lines after macros ending in access specifiers.
3178   EXPECT_EQ("#define A private:\n"
3179             "\n"
3180             "int i;",
3181             format("#define A         private:\n"
3182                    "\n"
3183                    "int              i;"));
3184 }
3185 
3186 TEST_F(FormatTest, FormatsClasses) {
3187   verifyFormat("class A : public B {};");
3188   verifyFormat("class A : public ::B {};");
3189 
3190   verifyFormat(
3191       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3192       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3193   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3194                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3195                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3196   verifyFormat(
3197       "class A : public B, public C, public D, public E, public F {};");
3198   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3199                "                     public C,\n"
3200                "                     public D,\n"
3201                "                     public E,\n"
3202                "                     public F,\n"
3203                "                     public G {};");
3204 
3205   verifyFormat("class\n"
3206                "    ReallyReallyLongClassName {\n"
3207                "  int i;\n"
3208                "};",
3209                getLLVMStyleWithColumns(32));
3210   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3211                "                           aaaaaaaaaaaaaaaa> {};");
3212   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3213                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3214                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3215   verifyFormat("template <class R, class C>\n"
3216                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3217                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3218   verifyFormat("class ::A::B {};");
3219 }
3220 
3221 TEST_F(FormatTest, BreakInheritanceStyle) {
3222   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3223   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3224       FormatStyle::BILS_BeforeComma;
3225   verifyFormat("class MyClass : public X {};",
3226                StyleWithInheritanceBreakBeforeComma);
3227   verifyFormat("class MyClass\n"
3228                "    : public X\n"
3229                "    , public Y {};",
3230                StyleWithInheritanceBreakBeforeComma);
3231   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3232                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3233                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3234                StyleWithInheritanceBreakBeforeComma);
3235   verifyFormat("struct aaaaaaaaaaaaa\n"
3236                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3237                "          aaaaaaaaaaaaaaaa> {};",
3238                StyleWithInheritanceBreakBeforeComma);
3239 
3240   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3241   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3242       FormatStyle::BILS_AfterColon;
3243   verifyFormat("class MyClass : public X {};",
3244                StyleWithInheritanceBreakAfterColon);
3245   verifyFormat("class MyClass : public X, public Y {};",
3246                StyleWithInheritanceBreakAfterColon);
3247   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3248                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3249                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3250                StyleWithInheritanceBreakAfterColon);
3251   verifyFormat("struct aaaaaaaaaaaaa :\n"
3252                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3253                "        aaaaaaaaaaaaaaaa> {};",
3254                StyleWithInheritanceBreakAfterColon);
3255 
3256   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3257   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3258       FormatStyle::BILS_AfterComma;
3259   verifyFormat("class MyClass : public X {};",
3260                StyleWithInheritanceBreakAfterComma);
3261   verifyFormat("class MyClass : public X,\n"
3262                "                public Y {};",
3263                StyleWithInheritanceBreakAfterComma);
3264   verifyFormat(
3265       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3266       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3267       "{};",
3268       StyleWithInheritanceBreakAfterComma);
3269   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3270                "                           aaaaaaaaaaaaaaaa> {};",
3271                StyleWithInheritanceBreakAfterComma);
3272   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3273                "    : public OnceBreak,\n"
3274                "      public AlwaysBreak,\n"
3275                "      EvenBasesFitInOneLine {};",
3276                StyleWithInheritanceBreakAfterComma);
3277 }
3278 
3279 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
3280   verifyFormat("class A {\n} a, b;");
3281   verifyFormat("struct A {\n} a, b;");
3282   verifyFormat("union A {\n} a;");
3283 }
3284 
3285 TEST_F(FormatTest, FormatsEnum) {
3286   verifyFormat("enum {\n"
3287                "  Zero,\n"
3288                "  One = 1,\n"
3289                "  Two = One + 1,\n"
3290                "  Three = (One + Two),\n"
3291                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3292                "  Five = (One, Two, Three, Four, 5)\n"
3293                "};");
3294   verifyGoogleFormat("enum {\n"
3295                      "  Zero,\n"
3296                      "  One = 1,\n"
3297                      "  Two = One + 1,\n"
3298                      "  Three = (One + Two),\n"
3299                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3300                      "  Five = (One, Two, Three, Four, 5)\n"
3301                      "};");
3302   verifyFormat("enum Enum {};");
3303   verifyFormat("enum {};");
3304   verifyFormat("enum X E {} d;");
3305   verifyFormat("enum __attribute__((...)) E {} d;");
3306   verifyFormat("enum __declspec__((...)) E {} d;");
3307   verifyFormat("enum {\n"
3308                "  Bar = Foo<int, int>::value\n"
3309                "};",
3310                getLLVMStyleWithColumns(30));
3311 
3312   verifyFormat("enum ShortEnum { A, B, C };");
3313   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3314 
3315   EXPECT_EQ("enum KeepEmptyLines {\n"
3316             "  ONE,\n"
3317             "\n"
3318             "  TWO,\n"
3319             "\n"
3320             "  THREE\n"
3321             "}",
3322             format("enum KeepEmptyLines {\n"
3323                    "  ONE,\n"
3324                    "\n"
3325                    "  TWO,\n"
3326                    "\n"
3327                    "\n"
3328                    "  THREE\n"
3329                    "}"));
3330   verifyFormat("enum E { // comment\n"
3331                "  ONE,\n"
3332                "  TWO\n"
3333                "};\n"
3334                "int i;");
3335 
3336   FormatStyle EightIndent = getLLVMStyle();
3337   EightIndent.IndentWidth = 8;
3338   verifyFormat("enum {\n"
3339                "        VOID,\n"
3340                "        CHAR,\n"
3341                "        SHORT,\n"
3342                "        INT,\n"
3343                "        LONG,\n"
3344                "        SIGNED,\n"
3345                "        UNSIGNED,\n"
3346                "        BOOL,\n"
3347                "        FLOAT,\n"
3348                "        DOUBLE,\n"
3349                "        COMPLEX\n"
3350                "};",
3351                EightIndent);
3352 
3353   // Not enums.
3354   verifyFormat("enum X f() {\n"
3355                "  a();\n"
3356                "  return 42;\n"
3357                "}");
3358   verifyFormat("enum X Type::f() {\n"
3359                "  a();\n"
3360                "  return 42;\n"
3361                "}");
3362   verifyFormat("enum ::X f() {\n"
3363                "  a();\n"
3364                "  return 42;\n"
3365                "}");
3366   verifyFormat("enum ns::X f() {\n"
3367                "  a();\n"
3368                "  return 42;\n"
3369                "}");
3370 }
3371 
3372 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3373   verifyFormat("enum Type {\n"
3374                "  One = 0; // These semicolons should be commas.\n"
3375                "  Two = 1;\n"
3376                "};");
3377   verifyFormat("namespace n {\n"
3378                "enum Type {\n"
3379                "  One,\n"
3380                "  Two, // missing };\n"
3381                "  int i;\n"
3382                "}\n"
3383                "void g() {}");
3384 }
3385 
3386 TEST_F(FormatTest, FormatsEnumStruct) {
3387   verifyFormat("enum struct {\n"
3388                "  Zero,\n"
3389                "  One = 1,\n"
3390                "  Two = One + 1,\n"
3391                "  Three = (One + Two),\n"
3392                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3393                "  Five = (One, Two, Three, Four, 5)\n"
3394                "};");
3395   verifyFormat("enum struct Enum {};");
3396   verifyFormat("enum struct {};");
3397   verifyFormat("enum struct X E {} d;");
3398   verifyFormat("enum struct __attribute__((...)) E {} d;");
3399   verifyFormat("enum struct __declspec__((...)) E {} d;");
3400   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3401 }
3402 
3403 TEST_F(FormatTest, FormatsEnumClass) {
3404   verifyFormat("enum class {\n"
3405                "  Zero,\n"
3406                "  One = 1,\n"
3407                "  Two = One + 1,\n"
3408                "  Three = (One + Two),\n"
3409                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3410                "  Five = (One, Two, Three, Four, 5)\n"
3411                "};");
3412   verifyFormat("enum class Enum {};");
3413   verifyFormat("enum class {};");
3414   verifyFormat("enum class X E {} d;");
3415   verifyFormat("enum class __attribute__((...)) E {} d;");
3416   verifyFormat("enum class __declspec__((...)) E {} d;");
3417   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3418 }
3419 
3420 TEST_F(FormatTest, FormatsEnumTypes) {
3421   verifyFormat("enum X : int {\n"
3422                "  A, // Force multiple lines.\n"
3423                "  B\n"
3424                "};");
3425   verifyFormat("enum X : int { A, B };");
3426   verifyFormat("enum X : std::uint32_t { A, B };");
3427 }
3428 
3429 TEST_F(FormatTest, FormatsTypedefEnum) {
3430   FormatStyle Style = getLLVMStyleWithColumns(40);
3431   verifyFormat("typedef enum {} EmptyEnum;");
3432   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3433   verifyFormat("typedef enum {\n"
3434                "  ZERO = 0,\n"
3435                "  ONE = 1,\n"
3436                "  TWO = 2,\n"
3437                "  THREE = 3\n"
3438                "} LongEnum;",
3439                Style);
3440   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3441   Style.BraceWrapping.AfterEnum = true;
3442   verifyFormat("typedef enum {} EmptyEnum;");
3443   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3444   verifyFormat("typedef enum\n"
3445                "{\n"
3446                "  ZERO = 0,\n"
3447                "  ONE = 1,\n"
3448                "  TWO = 2,\n"
3449                "  THREE = 3\n"
3450                "} LongEnum;",
3451                Style);
3452 }
3453 
3454 TEST_F(FormatTest, FormatsNSEnums) {
3455   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3456   verifyGoogleFormat(
3457       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3458   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3459                      "  // Information about someDecentlyLongValue.\n"
3460                      "  someDecentlyLongValue,\n"
3461                      "  // Information about anotherDecentlyLongValue.\n"
3462                      "  anotherDecentlyLongValue,\n"
3463                      "  // Information about aThirdDecentlyLongValue.\n"
3464                      "  aThirdDecentlyLongValue\n"
3465                      "};");
3466   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3467                      "  // Information about someDecentlyLongValue.\n"
3468                      "  someDecentlyLongValue,\n"
3469                      "  // Information about anotherDecentlyLongValue.\n"
3470                      "  anotherDecentlyLongValue,\n"
3471                      "  // Information about aThirdDecentlyLongValue.\n"
3472                      "  aThirdDecentlyLongValue\n"
3473                      "};");
3474   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3475                      "  a = 1,\n"
3476                      "  b = 2,\n"
3477                      "  c = 3,\n"
3478                      "};");
3479   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3480                      "  a = 1,\n"
3481                      "  b = 2,\n"
3482                      "  c = 3,\n"
3483                      "};");
3484   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3485                      "  a = 1,\n"
3486                      "  b = 2,\n"
3487                      "  c = 3,\n"
3488                      "};");
3489   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3490                      "  a = 1,\n"
3491                      "  b = 2,\n"
3492                      "  c = 3,\n"
3493                      "};");
3494 }
3495 
3496 TEST_F(FormatTest, FormatsBitfields) {
3497   verifyFormat("struct Bitfields {\n"
3498                "  unsigned sClass : 8;\n"
3499                "  unsigned ValueKind : 2;\n"
3500                "};");
3501   verifyFormat("struct A {\n"
3502                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3503                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3504                "};");
3505   verifyFormat("struct MyStruct {\n"
3506                "  uchar data;\n"
3507                "  uchar : 8;\n"
3508                "  uchar : 8;\n"
3509                "  uchar other;\n"
3510                "};");
3511   FormatStyle Style = getLLVMStyle();
3512   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3513   verifyFormat("struct Bitfields {\n"
3514                "  unsigned sClass:8;\n"
3515                "  unsigned ValueKind:2;\n"
3516                "  uchar other;\n"
3517                "};",
3518                Style);
3519   verifyFormat("struct A {\n"
3520                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3521                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3522                "};",
3523                Style);
3524   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3525   verifyFormat("struct Bitfields {\n"
3526                "  unsigned sClass :8;\n"
3527                "  unsigned ValueKind :2;\n"
3528                "  uchar other;\n"
3529                "};",
3530                Style);
3531   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3532   verifyFormat("struct Bitfields {\n"
3533                "  unsigned sClass: 8;\n"
3534                "  unsigned ValueKind: 2;\n"
3535                "  uchar other;\n"
3536                "};",
3537                Style);
3538 }
3539 
3540 TEST_F(FormatTest, FormatsNamespaces) {
3541   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3542   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3543 
3544   verifyFormat("namespace some_namespace {\n"
3545                "class A {};\n"
3546                "void f() { f(); }\n"
3547                "}",
3548                LLVMWithNoNamespaceFix);
3549   verifyFormat("namespace N::inline D {\n"
3550                "class A {};\n"
3551                "void f() { f(); }\n"
3552                "}",
3553                LLVMWithNoNamespaceFix);
3554   verifyFormat("namespace N::inline D::E {\n"
3555                "class A {};\n"
3556                "void f() { f(); }\n"
3557                "}",
3558                LLVMWithNoNamespaceFix);
3559   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3560                "class A {};\n"
3561                "void f() { f(); }\n"
3562                "}",
3563                LLVMWithNoNamespaceFix);
3564   verifyFormat("/* something */ namespace some_namespace {\n"
3565                "class A {};\n"
3566                "void f() { f(); }\n"
3567                "}",
3568                LLVMWithNoNamespaceFix);
3569   verifyFormat("namespace {\n"
3570                "class A {};\n"
3571                "void f() { f(); }\n"
3572                "}",
3573                LLVMWithNoNamespaceFix);
3574   verifyFormat("/* something */ namespace {\n"
3575                "class A {};\n"
3576                "void f() { f(); }\n"
3577                "}",
3578                LLVMWithNoNamespaceFix);
3579   verifyFormat("inline namespace X {\n"
3580                "class A {};\n"
3581                "void f() { f(); }\n"
3582                "}",
3583                LLVMWithNoNamespaceFix);
3584   verifyFormat("/* something */ inline namespace X {\n"
3585                "class A {};\n"
3586                "void f() { f(); }\n"
3587                "}",
3588                LLVMWithNoNamespaceFix);
3589   verifyFormat("export namespace X {\n"
3590                "class A {};\n"
3591                "void f() { f(); }\n"
3592                "}",
3593                LLVMWithNoNamespaceFix);
3594   verifyFormat("using namespace some_namespace;\n"
3595                "class A {};\n"
3596                "void f() { f(); }",
3597                LLVMWithNoNamespaceFix);
3598 
3599   // This code is more common than we thought; if we
3600   // layout this correctly the semicolon will go into
3601   // its own line, which is undesirable.
3602   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3603   verifyFormat("namespace {\n"
3604                "class A {};\n"
3605                "};",
3606                LLVMWithNoNamespaceFix);
3607 
3608   verifyFormat("namespace {\n"
3609                "int SomeVariable = 0; // comment\n"
3610                "} // namespace",
3611                LLVMWithNoNamespaceFix);
3612   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3613             "#define HEADER_GUARD\n"
3614             "namespace my_namespace {\n"
3615             "int i;\n"
3616             "} // my_namespace\n"
3617             "#endif // HEADER_GUARD",
3618             format("#ifndef HEADER_GUARD\n"
3619                    " #define HEADER_GUARD\n"
3620                    "   namespace my_namespace {\n"
3621                    "int i;\n"
3622                    "}    // my_namespace\n"
3623                    "#endif    // HEADER_GUARD",
3624                    LLVMWithNoNamespaceFix));
3625 
3626   EXPECT_EQ("namespace A::B {\n"
3627             "class C {};\n"
3628             "}",
3629             format("namespace A::B {\n"
3630                    "class C {};\n"
3631                    "}",
3632                    LLVMWithNoNamespaceFix));
3633 
3634   FormatStyle Style = getLLVMStyle();
3635   Style.NamespaceIndentation = FormatStyle::NI_All;
3636   EXPECT_EQ("namespace out {\n"
3637             "  int i;\n"
3638             "  namespace in {\n"
3639             "    int i;\n"
3640             "  } // namespace in\n"
3641             "} // namespace out",
3642             format("namespace out {\n"
3643                    "int i;\n"
3644                    "namespace in {\n"
3645                    "int i;\n"
3646                    "} // namespace in\n"
3647                    "} // namespace out",
3648                    Style));
3649 
3650   FormatStyle ShortInlineFunctions = getLLVMStyle();
3651   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3652   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3653       FormatStyle::SFS_Inline;
3654   verifyFormat("namespace {\n"
3655                "  void f() {\n"
3656                "    return;\n"
3657                "  }\n"
3658                "} // namespace\n",
3659                ShortInlineFunctions);
3660   verifyFormat("namespace {\n"
3661                "  int some_int;\n"
3662                "  void f() {\n"
3663                "    return;\n"
3664                "  }\n"
3665                "} // namespace\n",
3666                ShortInlineFunctions);
3667   verifyFormat("namespace interface {\n"
3668                "  void f() {\n"
3669                "    return;\n"
3670                "  }\n"
3671                "} // namespace interface\n",
3672                ShortInlineFunctions);
3673   verifyFormat("namespace {\n"
3674                "  class X {\n"
3675                "    void f() { return; }\n"
3676                "  };\n"
3677                "} // namespace\n",
3678                ShortInlineFunctions);
3679   verifyFormat("namespace {\n"
3680                "  struct X {\n"
3681                "    void f() { return; }\n"
3682                "  };\n"
3683                "} // namespace\n",
3684                ShortInlineFunctions);
3685   verifyFormat("namespace {\n"
3686                "  union X {\n"
3687                "    void f() { return; }\n"
3688                "  };\n"
3689                "} // namespace\n",
3690                ShortInlineFunctions);
3691   verifyFormat("extern \"C\" {\n"
3692                "void f() {\n"
3693                "  return;\n"
3694                "}\n"
3695                "} // namespace\n",
3696                ShortInlineFunctions);
3697   verifyFormat("namespace {\n"
3698                "  class X {\n"
3699                "    void f() { return; }\n"
3700                "  } x;\n"
3701                "} // namespace\n",
3702                ShortInlineFunctions);
3703   verifyFormat("namespace {\n"
3704                "  [[nodiscard]] class X {\n"
3705                "    void f() { return; }\n"
3706                "  };\n"
3707                "} // namespace\n",
3708                ShortInlineFunctions);
3709   verifyFormat("namespace {\n"
3710                "  static class X {\n"
3711                "    void f() { return; }\n"
3712                "  } x;\n"
3713                "} // namespace\n",
3714                ShortInlineFunctions);
3715   verifyFormat("namespace {\n"
3716                "  constexpr class X {\n"
3717                "    void f() { return; }\n"
3718                "  } x;\n"
3719                "} // namespace\n",
3720                ShortInlineFunctions);
3721 
3722   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
3723   verifyFormat("extern \"C\" {\n"
3724                "  void f() {\n"
3725                "    return;\n"
3726                "  }\n"
3727                "} // namespace\n",
3728                ShortInlineFunctions);
3729 
3730   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3731   EXPECT_EQ("namespace out {\n"
3732             "int i;\n"
3733             "namespace in {\n"
3734             "  int i;\n"
3735             "} // namespace in\n"
3736             "} // namespace out",
3737             format("namespace out {\n"
3738                    "int i;\n"
3739                    "namespace in {\n"
3740                    "int i;\n"
3741                    "} // namespace in\n"
3742                    "} // namespace out",
3743                    Style));
3744 
3745   Style.NamespaceIndentation = FormatStyle::NI_None;
3746   verifyFormat("template <class T>\n"
3747                "concept a_concept = X<>;\n"
3748                "namespace B {\n"
3749                "struct b_struct {};\n"
3750                "} // namespace B\n",
3751                Style);
3752   verifyFormat("template <int I> constexpr void foo requires(I == 42) {}\n"
3753                "namespace ns {\n"
3754                "void foo() {}\n"
3755                "} // namespace ns\n",
3756                Style);
3757 }
3758 
3759 TEST_F(FormatTest, NamespaceMacros) {
3760   FormatStyle Style = getLLVMStyle();
3761   Style.NamespaceMacros.push_back("TESTSUITE");
3762 
3763   verifyFormat("TESTSUITE(A) {\n"
3764                "int foo();\n"
3765                "} // TESTSUITE(A)",
3766                Style);
3767 
3768   verifyFormat("TESTSUITE(A, B) {\n"
3769                "int foo();\n"
3770                "} // TESTSUITE(A)",
3771                Style);
3772 
3773   // Properly indent according to NamespaceIndentation style
3774   Style.NamespaceIndentation = FormatStyle::NI_All;
3775   verifyFormat("TESTSUITE(A) {\n"
3776                "  int foo();\n"
3777                "} // TESTSUITE(A)",
3778                Style);
3779   verifyFormat("TESTSUITE(A) {\n"
3780                "  namespace B {\n"
3781                "    int foo();\n"
3782                "  } // namespace B\n"
3783                "} // TESTSUITE(A)",
3784                Style);
3785   verifyFormat("namespace A {\n"
3786                "  TESTSUITE(B) {\n"
3787                "    int foo();\n"
3788                "  } // TESTSUITE(B)\n"
3789                "} // namespace A",
3790                Style);
3791 
3792   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3793   verifyFormat("TESTSUITE(A) {\n"
3794                "TESTSUITE(B) {\n"
3795                "  int foo();\n"
3796                "} // TESTSUITE(B)\n"
3797                "} // TESTSUITE(A)",
3798                Style);
3799   verifyFormat("TESTSUITE(A) {\n"
3800                "namespace B {\n"
3801                "  int foo();\n"
3802                "} // namespace B\n"
3803                "} // TESTSUITE(A)",
3804                Style);
3805   verifyFormat("namespace A {\n"
3806                "TESTSUITE(B) {\n"
3807                "  int foo();\n"
3808                "} // TESTSUITE(B)\n"
3809                "} // namespace A",
3810                Style);
3811 
3812   // Properly merge namespace-macros blocks in CompactNamespaces mode
3813   Style.NamespaceIndentation = FormatStyle::NI_None;
3814   Style.CompactNamespaces = true;
3815   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
3816                "}} // TESTSUITE(A::B)",
3817                Style);
3818 
3819   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3820             "}} // TESTSUITE(out::in)",
3821             format("TESTSUITE(out) {\n"
3822                    "TESTSUITE(in) {\n"
3823                    "} // TESTSUITE(in)\n"
3824                    "} // TESTSUITE(out)",
3825                    Style));
3826 
3827   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3828             "}} // TESTSUITE(out::in)",
3829             format("TESTSUITE(out) {\n"
3830                    "TESTSUITE(in) {\n"
3831                    "} // TESTSUITE(in)\n"
3832                    "} // TESTSUITE(out)",
3833                    Style));
3834 
3835   // Do not merge different namespaces/macros
3836   EXPECT_EQ("namespace out {\n"
3837             "TESTSUITE(in) {\n"
3838             "} // TESTSUITE(in)\n"
3839             "} // namespace out",
3840             format("namespace out {\n"
3841                    "TESTSUITE(in) {\n"
3842                    "} // TESTSUITE(in)\n"
3843                    "} // namespace out",
3844                    Style));
3845   EXPECT_EQ("TESTSUITE(out) {\n"
3846             "namespace in {\n"
3847             "} // namespace in\n"
3848             "} // TESTSUITE(out)",
3849             format("TESTSUITE(out) {\n"
3850                    "namespace in {\n"
3851                    "} // namespace in\n"
3852                    "} // TESTSUITE(out)",
3853                    Style));
3854   Style.NamespaceMacros.push_back("FOOBAR");
3855   EXPECT_EQ("TESTSUITE(out) {\n"
3856             "FOOBAR(in) {\n"
3857             "} // FOOBAR(in)\n"
3858             "} // TESTSUITE(out)",
3859             format("TESTSUITE(out) {\n"
3860                    "FOOBAR(in) {\n"
3861                    "} // FOOBAR(in)\n"
3862                    "} // TESTSUITE(out)",
3863                    Style));
3864 }
3865 
3866 TEST_F(FormatTest, FormatsCompactNamespaces) {
3867   FormatStyle Style = getLLVMStyle();
3868   Style.CompactNamespaces = true;
3869   Style.NamespaceMacros.push_back("TESTSUITE");
3870 
3871   verifyFormat("namespace A { namespace B {\n"
3872                "}} // namespace A::B",
3873                Style);
3874 
3875   EXPECT_EQ("namespace out { namespace in {\n"
3876             "}} // namespace out::in",
3877             format("namespace out {\n"
3878                    "namespace in {\n"
3879                    "} // namespace in\n"
3880                    "} // namespace out",
3881                    Style));
3882 
3883   // Only namespaces which have both consecutive opening and end get compacted
3884   EXPECT_EQ("namespace out {\n"
3885             "namespace in1 {\n"
3886             "} // namespace in1\n"
3887             "namespace in2 {\n"
3888             "} // namespace in2\n"
3889             "} // namespace out",
3890             format("namespace out {\n"
3891                    "namespace in1 {\n"
3892                    "} // namespace in1\n"
3893                    "namespace in2 {\n"
3894                    "} // namespace in2\n"
3895                    "} // namespace out",
3896                    Style));
3897 
3898   EXPECT_EQ("namespace out {\n"
3899             "int i;\n"
3900             "namespace in {\n"
3901             "int j;\n"
3902             "} // namespace in\n"
3903             "int k;\n"
3904             "} // namespace out",
3905             format("namespace out { int i;\n"
3906                    "namespace in { int j; } // namespace in\n"
3907                    "int k; } // namespace out",
3908                    Style));
3909 
3910   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
3911             "}}} // namespace A::B::C\n",
3912             format("namespace A { namespace B {\n"
3913                    "namespace C {\n"
3914                    "}} // namespace B::C\n"
3915                    "} // namespace A\n",
3916                    Style));
3917 
3918   Style.ColumnLimit = 40;
3919   EXPECT_EQ("namespace aaaaaaaaaa {\n"
3920             "namespace bbbbbbbbbb {\n"
3921             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
3922             format("namespace aaaaaaaaaa {\n"
3923                    "namespace bbbbbbbbbb {\n"
3924                    "} // namespace bbbbbbbbbb\n"
3925                    "} // namespace aaaaaaaaaa",
3926                    Style));
3927 
3928   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
3929             "namespace cccccc {\n"
3930             "}}} // namespace aaaaaa::bbbbbb::cccccc",
3931             format("namespace aaaaaa {\n"
3932                    "namespace bbbbbb {\n"
3933                    "namespace cccccc {\n"
3934                    "} // namespace cccccc\n"
3935                    "} // namespace bbbbbb\n"
3936                    "} // namespace aaaaaa",
3937                    Style));
3938   Style.ColumnLimit = 80;
3939 
3940   // Extra semicolon after 'inner' closing brace prevents merging
3941   EXPECT_EQ("namespace out { namespace in {\n"
3942             "}; } // namespace out::in",
3943             format("namespace out {\n"
3944                    "namespace in {\n"
3945                    "}; // namespace in\n"
3946                    "} // namespace out",
3947                    Style));
3948 
3949   // Extra semicolon after 'outer' closing brace is conserved
3950   EXPECT_EQ("namespace out { namespace in {\n"
3951             "}}; // namespace out::in",
3952             format("namespace out {\n"
3953                    "namespace in {\n"
3954                    "} // namespace in\n"
3955                    "}; // namespace out",
3956                    Style));
3957 
3958   Style.NamespaceIndentation = FormatStyle::NI_All;
3959   EXPECT_EQ("namespace out { namespace in {\n"
3960             "  int i;\n"
3961             "}} // namespace out::in",
3962             format("namespace out {\n"
3963                    "namespace in {\n"
3964                    "int i;\n"
3965                    "} // namespace in\n"
3966                    "} // namespace out",
3967                    Style));
3968   EXPECT_EQ("namespace out { namespace mid {\n"
3969             "  namespace in {\n"
3970             "    int j;\n"
3971             "  } // namespace in\n"
3972             "  int k;\n"
3973             "}} // namespace out::mid",
3974             format("namespace out { namespace mid {\n"
3975                    "namespace in { int j; } // namespace in\n"
3976                    "int k; }} // namespace out::mid",
3977                    Style));
3978 
3979   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3980   EXPECT_EQ("namespace out { namespace in {\n"
3981             "  int i;\n"
3982             "}} // namespace out::in",
3983             format("namespace out {\n"
3984                    "namespace in {\n"
3985                    "int i;\n"
3986                    "} // namespace in\n"
3987                    "} // namespace out",
3988                    Style));
3989   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
3990             "  int i;\n"
3991             "}}} // namespace out::mid::in",
3992             format("namespace out {\n"
3993                    "namespace mid {\n"
3994                    "namespace in {\n"
3995                    "int i;\n"
3996                    "} // namespace in\n"
3997                    "} // namespace mid\n"
3998                    "} // namespace out",
3999                    Style));
4000 
4001   Style.CompactNamespaces = true;
4002   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
4003   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4004   Style.BraceWrapping.BeforeLambdaBody = true;
4005   verifyFormat("namespace out { namespace in {\n"
4006                "}} // namespace out::in",
4007                Style);
4008   EXPECT_EQ("namespace out { namespace in {\n"
4009             "}} // namespace out::in",
4010             format("namespace out {\n"
4011                    "namespace in {\n"
4012                    "} // namespace in\n"
4013                    "} // namespace out",
4014                    Style));
4015 }
4016 
4017 TEST_F(FormatTest, FormatsExternC) {
4018   verifyFormat("extern \"C\" {\nint a;");
4019   verifyFormat("extern \"C\" {}");
4020   verifyFormat("extern \"C\" {\n"
4021                "int foo();\n"
4022                "}");
4023   verifyFormat("extern \"C\" int foo() {}");
4024   verifyFormat("extern \"C\" int foo();");
4025   verifyFormat("extern \"C\" int foo() {\n"
4026                "  int i = 42;\n"
4027                "  return i;\n"
4028                "}");
4029 
4030   FormatStyle Style = getLLVMStyle();
4031   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4032   Style.BraceWrapping.AfterFunction = true;
4033   verifyFormat("extern \"C\" int foo() {}", Style);
4034   verifyFormat("extern \"C\" int foo();", Style);
4035   verifyFormat("extern \"C\" int foo()\n"
4036                "{\n"
4037                "  int i = 42;\n"
4038                "  return i;\n"
4039                "}",
4040                Style);
4041 
4042   Style.BraceWrapping.AfterExternBlock = true;
4043   Style.BraceWrapping.SplitEmptyRecord = false;
4044   verifyFormat("extern \"C\"\n"
4045                "{}",
4046                Style);
4047   verifyFormat("extern \"C\"\n"
4048                "{\n"
4049                "  int foo();\n"
4050                "}",
4051                Style);
4052 }
4053 
4054 TEST_F(FormatTest, IndentExternBlockStyle) {
4055   FormatStyle Style = getLLVMStyle();
4056   Style.IndentWidth = 2;
4057 
4058   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4059   verifyFormat("extern \"C\" { /*9*/\n"
4060                "}",
4061                Style);
4062   verifyFormat("extern \"C\" {\n"
4063                "  int foo10();\n"
4064                "}",
4065                Style);
4066 
4067   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4068   verifyFormat("extern \"C\" { /*11*/\n"
4069                "}",
4070                Style);
4071   verifyFormat("extern \"C\" {\n"
4072                "int foo12();\n"
4073                "}",
4074                Style);
4075 
4076   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4077   Style.BraceWrapping.AfterExternBlock = true;
4078   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4079   verifyFormat("extern \"C\"\n"
4080                "{ /*13*/\n"
4081                "}",
4082                Style);
4083   verifyFormat("extern \"C\"\n{\n"
4084                "  int foo14();\n"
4085                "}",
4086                Style);
4087 
4088   Style.BraceWrapping.AfterExternBlock = false;
4089   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4090   verifyFormat("extern \"C\" { /*15*/\n"
4091                "}",
4092                Style);
4093   verifyFormat("extern \"C\" {\n"
4094                "int foo16();\n"
4095                "}",
4096                Style);
4097 
4098   Style.BraceWrapping.AfterExternBlock = true;
4099   verifyFormat("extern \"C\"\n"
4100                "{ /*13*/\n"
4101                "}",
4102                Style);
4103   verifyFormat("extern \"C\"\n"
4104                "{\n"
4105                "int foo14();\n"
4106                "}",
4107                Style);
4108 
4109   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4110   verifyFormat("extern \"C\"\n"
4111                "{ /*13*/\n"
4112                "}",
4113                Style);
4114   verifyFormat("extern \"C\"\n"
4115                "{\n"
4116                "  int foo14();\n"
4117                "}",
4118                Style);
4119 }
4120 
4121 TEST_F(FormatTest, FormatsInlineASM) {
4122   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4123   verifyFormat("asm(\"nop\" ::: \"memory\");");
4124   verifyFormat(
4125       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4126       "    \"cpuid\\n\\t\"\n"
4127       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4128       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4129       "    : \"a\"(value));");
4130   EXPECT_EQ(
4131       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4132       "  __asm {\n"
4133       "        mov     edx,[that] // vtable in edx\n"
4134       "        mov     eax,methodIndex\n"
4135       "        call    [edx][eax*4] // stdcall\n"
4136       "  }\n"
4137       "}",
4138       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4139              "    __asm {\n"
4140              "        mov     edx,[that] // vtable in edx\n"
4141              "        mov     eax,methodIndex\n"
4142              "        call    [edx][eax*4] // stdcall\n"
4143              "    }\n"
4144              "}"));
4145   EXPECT_EQ("_asm {\n"
4146             "  xor eax, eax;\n"
4147             "  cpuid;\n"
4148             "}",
4149             format("_asm {\n"
4150                    "  xor eax, eax;\n"
4151                    "  cpuid;\n"
4152                    "}"));
4153   verifyFormat("void function() {\n"
4154                "  // comment\n"
4155                "  asm(\"\");\n"
4156                "}");
4157   EXPECT_EQ("__asm {\n"
4158             "}\n"
4159             "int i;",
4160             format("__asm   {\n"
4161                    "}\n"
4162                    "int   i;"));
4163 }
4164 
4165 TEST_F(FormatTest, FormatTryCatch) {
4166   verifyFormat("try {\n"
4167                "  throw a * b;\n"
4168                "} catch (int a) {\n"
4169                "  // Do nothing.\n"
4170                "} catch (...) {\n"
4171                "  exit(42);\n"
4172                "}");
4173 
4174   // Function-level try statements.
4175   verifyFormat("int f() try { return 4; } catch (...) {\n"
4176                "  return 5;\n"
4177                "}");
4178   verifyFormat("class A {\n"
4179                "  int a;\n"
4180                "  A() try : a(0) {\n"
4181                "  } catch (...) {\n"
4182                "    throw;\n"
4183                "  }\n"
4184                "};\n");
4185   verifyFormat("class A {\n"
4186                "  int a;\n"
4187                "  A() try : a(0), b{1} {\n"
4188                "  } catch (...) {\n"
4189                "    throw;\n"
4190                "  }\n"
4191                "};\n");
4192   verifyFormat("class A {\n"
4193                "  int a;\n"
4194                "  A() try : a(0), b{1}, c{2} {\n"
4195                "  } catch (...) {\n"
4196                "    throw;\n"
4197                "  }\n"
4198                "};\n");
4199   verifyFormat("class A {\n"
4200                "  int a;\n"
4201                "  A() try : a(0), b{1}, c{2} {\n"
4202                "    { // New scope.\n"
4203                "    }\n"
4204                "  } catch (...) {\n"
4205                "    throw;\n"
4206                "  }\n"
4207                "};\n");
4208 
4209   // Incomplete try-catch blocks.
4210   verifyIncompleteFormat("try {} catch (");
4211 }
4212 
4213 TEST_F(FormatTest, FormatTryAsAVariable) {
4214   verifyFormat("int try;");
4215   verifyFormat("int try, size;");
4216   verifyFormat("try = foo();");
4217   verifyFormat("if (try < size) {\n  return true;\n}");
4218 
4219   verifyFormat("int catch;");
4220   verifyFormat("int catch, size;");
4221   verifyFormat("catch = foo();");
4222   verifyFormat("if (catch < size) {\n  return true;\n}");
4223 
4224   FormatStyle Style = getLLVMStyle();
4225   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4226   Style.BraceWrapping.AfterFunction = true;
4227   Style.BraceWrapping.BeforeCatch = true;
4228   verifyFormat("try {\n"
4229                "  int bar = 1;\n"
4230                "}\n"
4231                "catch (...) {\n"
4232                "  int bar = 1;\n"
4233                "}",
4234                Style);
4235   verifyFormat("#if NO_EX\n"
4236                "try\n"
4237                "#endif\n"
4238                "{\n"
4239                "}\n"
4240                "#if NO_EX\n"
4241                "catch (...) {\n"
4242                "}",
4243                Style);
4244   verifyFormat("try /* abc */ {\n"
4245                "  int bar = 1;\n"
4246                "}\n"
4247                "catch (...) {\n"
4248                "  int bar = 1;\n"
4249                "}",
4250                Style);
4251   verifyFormat("try\n"
4252                "// abc\n"
4253                "{\n"
4254                "  int bar = 1;\n"
4255                "}\n"
4256                "catch (...) {\n"
4257                "  int bar = 1;\n"
4258                "}",
4259                Style);
4260 }
4261 
4262 TEST_F(FormatTest, FormatSEHTryCatch) {
4263   verifyFormat("__try {\n"
4264                "  int a = b * c;\n"
4265                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4266                "  // Do nothing.\n"
4267                "}");
4268 
4269   verifyFormat("__try {\n"
4270                "  int a = b * c;\n"
4271                "} __finally {\n"
4272                "  // Do nothing.\n"
4273                "}");
4274 
4275   verifyFormat("DEBUG({\n"
4276                "  __try {\n"
4277                "  } __finally {\n"
4278                "  }\n"
4279                "});\n");
4280 }
4281 
4282 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4283   verifyFormat("try {\n"
4284                "  f();\n"
4285                "} catch {\n"
4286                "  g();\n"
4287                "}");
4288   verifyFormat("try {\n"
4289                "  f();\n"
4290                "} catch (A a) MACRO(x) {\n"
4291                "  g();\n"
4292                "} catch (B b) MACRO(x) {\n"
4293                "  g();\n"
4294                "}");
4295 }
4296 
4297 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4298   FormatStyle Style = getLLVMStyle();
4299   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4300                           FormatStyle::BS_WebKit}) {
4301     Style.BreakBeforeBraces = BraceStyle;
4302     verifyFormat("try {\n"
4303                  "  // something\n"
4304                  "} catch (...) {\n"
4305                  "  // something\n"
4306                  "}",
4307                  Style);
4308   }
4309   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4310   verifyFormat("try {\n"
4311                "  // something\n"
4312                "}\n"
4313                "catch (...) {\n"
4314                "  // something\n"
4315                "}",
4316                Style);
4317   verifyFormat("__try {\n"
4318                "  // something\n"
4319                "}\n"
4320                "__finally {\n"
4321                "  // something\n"
4322                "}",
4323                Style);
4324   verifyFormat("@try {\n"
4325                "  // something\n"
4326                "}\n"
4327                "@finally {\n"
4328                "  // something\n"
4329                "}",
4330                Style);
4331   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4332   verifyFormat("try\n"
4333                "{\n"
4334                "  // something\n"
4335                "}\n"
4336                "catch (...)\n"
4337                "{\n"
4338                "  // something\n"
4339                "}",
4340                Style);
4341   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4342   verifyFormat("try\n"
4343                "  {\n"
4344                "  // something white\n"
4345                "  }\n"
4346                "catch (...)\n"
4347                "  {\n"
4348                "  // something white\n"
4349                "  }",
4350                Style);
4351   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4352   verifyFormat("try\n"
4353                "  {\n"
4354                "    // something\n"
4355                "  }\n"
4356                "catch (...)\n"
4357                "  {\n"
4358                "    // something\n"
4359                "  }",
4360                Style);
4361   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4362   Style.BraceWrapping.BeforeCatch = true;
4363   verifyFormat("try {\n"
4364                "  // something\n"
4365                "}\n"
4366                "catch (...) {\n"
4367                "  // something\n"
4368                "}",
4369                Style);
4370 }
4371 
4372 TEST_F(FormatTest, StaticInitializers) {
4373   verifyFormat("static SomeClass SC = {1, 'a'};");
4374 
4375   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4376                "    100000000, "
4377                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4378 
4379   // Here, everything other than the "}" would fit on a line.
4380   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4381                "    10000000000000000000000000};");
4382   EXPECT_EQ("S s = {a,\n"
4383             "\n"
4384             "       b};",
4385             format("S s = {\n"
4386                    "  a,\n"
4387                    "\n"
4388                    "  b\n"
4389                    "};"));
4390 
4391   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4392   // line. However, the formatting looks a bit off and this probably doesn't
4393   // happen often in practice.
4394   verifyFormat("static int Variable[1] = {\n"
4395                "    {1000000000000000000000000000000000000}};",
4396                getLLVMStyleWithColumns(40));
4397 }
4398 
4399 TEST_F(FormatTest, DesignatedInitializers) {
4400   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4401   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4402                "                    .bbbbbbbbbb = 2,\n"
4403                "                    .cccccccccc = 3,\n"
4404                "                    .dddddddddd = 4,\n"
4405                "                    .eeeeeeeeee = 5};");
4406   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4407                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4408                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4409                "    .ccccccccccccccccccccccccccc = 3,\n"
4410                "    .ddddddddddddddddddddddddddd = 4,\n"
4411                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4412 
4413   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4414 
4415   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4416   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4417                "                    [2] = bbbbbbbbbb,\n"
4418                "                    [3] = cccccccccc,\n"
4419                "                    [4] = dddddddddd,\n"
4420                "                    [5] = eeeeeeeeee};");
4421   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4422                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4423                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4424                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4425                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4426                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4427 }
4428 
4429 TEST_F(FormatTest, NestedStaticInitializers) {
4430   verifyFormat("static A x = {{{}}};\n");
4431   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4432                "               {init1, init2, init3, init4}}};",
4433                getLLVMStyleWithColumns(50));
4434 
4435   verifyFormat("somes Status::global_reps[3] = {\n"
4436                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4437                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4438                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4439                getLLVMStyleWithColumns(60));
4440   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4441                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4442                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4443                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4444   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4445                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4446                "rect.fTop}};");
4447 
4448   verifyFormat(
4449       "SomeArrayOfSomeType a = {\n"
4450       "    {{1, 2, 3},\n"
4451       "     {1, 2, 3},\n"
4452       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4453       "      333333333333333333333333333333},\n"
4454       "     {1, 2, 3},\n"
4455       "     {1, 2, 3}}};");
4456   verifyFormat(
4457       "SomeArrayOfSomeType a = {\n"
4458       "    {{1, 2, 3}},\n"
4459       "    {{1, 2, 3}},\n"
4460       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4461       "      333333333333333333333333333333}},\n"
4462       "    {{1, 2, 3}},\n"
4463       "    {{1, 2, 3}}};");
4464 
4465   verifyFormat("struct {\n"
4466                "  unsigned bit;\n"
4467                "  const char *const name;\n"
4468                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4469                "                 {kOsWin, \"Windows\"},\n"
4470                "                 {kOsLinux, \"Linux\"},\n"
4471                "                 {kOsCrOS, \"Chrome OS\"}};");
4472   verifyFormat("struct {\n"
4473                "  unsigned bit;\n"
4474                "  const char *const name;\n"
4475                "} kBitsToOs[] = {\n"
4476                "    {kOsMac, \"Mac\"},\n"
4477                "    {kOsWin, \"Windows\"},\n"
4478                "    {kOsLinux, \"Linux\"},\n"
4479                "    {kOsCrOS, \"Chrome OS\"},\n"
4480                "};");
4481 }
4482 
4483 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4484   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4485                "                      \\\n"
4486                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4487 }
4488 
4489 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4490   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4491                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4492 
4493   // Do break defaulted and deleted functions.
4494   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4495                "    default;",
4496                getLLVMStyleWithColumns(40));
4497   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4498                "    delete;",
4499                getLLVMStyleWithColumns(40));
4500 }
4501 
4502 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4503   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4504                getLLVMStyleWithColumns(40));
4505   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4506                getLLVMStyleWithColumns(40));
4507   EXPECT_EQ("#define Q                              \\\n"
4508             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4509             "  \"aaaaaaaa.cpp\"",
4510             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4511                    getLLVMStyleWithColumns(40)));
4512 }
4513 
4514 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4515   EXPECT_EQ("# 123 \"A string literal\"",
4516             format("   #     123    \"A string literal\""));
4517 }
4518 
4519 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4520   EXPECT_EQ("#;", format("#;"));
4521   verifyFormat("#\n;\n;\n;");
4522 }
4523 
4524 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4525   EXPECT_EQ("#line 42 \"test\"\n",
4526             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4527   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4528                                     getLLVMStyleWithColumns(12)));
4529 }
4530 
4531 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4532   EXPECT_EQ("#line 42 \"test\"",
4533             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4534   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4535 }
4536 
4537 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4538   verifyFormat("#define A \\x20");
4539   verifyFormat("#define A \\ x20");
4540   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4541   verifyFormat("#define A ''");
4542   verifyFormat("#define A ''qqq");
4543   verifyFormat("#define A `qqq");
4544   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4545   EXPECT_EQ("const char *c = STRINGIFY(\n"
4546             "\\na : b);",
4547             format("const char * c = STRINGIFY(\n"
4548                    "\\na : b);"));
4549 
4550   verifyFormat("a\r\\");
4551   verifyFormat("a\v\\");
4552   verifyFormat("a\f\\");
4553 }
4554 
4555 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4556   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4557   style.IndentWidth = 4;
4558   style.PPIndentWidth = 1;
4559 
4560   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4561   verifyFormat("#ifdef __linux__\n"
4562                "void foo() {\n"
4563                "    int x = 0;\n"
4564                "}\n"
4565                "#define FOO\n"
4566                "#endif\n"
4567                "void bar() {\n"
4568                "    int y = 0;\n"
4569                "}\n",
4570                style);
4571 
4572   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4573   verifyFormat("#ifdef __linux__\n"
4574                "void foo() {\n"
4575                "    int x = 0;\n"
4576                "}\n"
4577                "# define FOO foo\n"
4578                "#endif\n"
4579                "void bar() {\n"
4580                "    int y = 0;\n"
4581                "}\n",
4582                style);
4583 
4584   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4585   verifyFormat("#ifdef __linux__\n"
4586                "void foo() {\n"
4587                "    int x = 0;\n"
4588                "}\n"
4589                " #define FOO foo\n"
4590                "#endif\n"
4591                "void bar() {\n"
4592                "    int y = 0;\n"
4593                "}\n",
4594                style);
4595 }
4596 
4597 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4598   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4599   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4600   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4601   // FIXME: We never break before the macro name.
4602   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4603 
4604   verifyFormat("#define A A\n#define A A");
4605   verifyFormat("#define A(X) A\n#define A A");
4606 
4607   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4608   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4609 }
4610 
4611 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4612   EXPECT_EQ("// somecomment\n"
4613             "#include \"a.h\"\n"
4614             "#define A(  \\\n"
4615             "    A, B)\n"
4616             "#include \"b.h\"\n"
4617             "// somecomment\n",
4618             format("  // somecomment\n"
4619                    "  #include \"a.h\"\n"
4620                    "#define A(A,\\\n"
4621                    "    B)\n"
4622                    "    #include \"b.h\"\n"
4623                    " // somecomment\n",
4624                    getLLVMStyleWithColumns(13)));
4625 }
4626 
4627 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4628 
4629 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4630   EXPECT_EQ("#define A    \\\n"
4631             "  c;         \\\n"
4632             "  e;\n"
4633             "f;",
4634             format("#define A c; e;\n"
4635                    "f;",
4636                    getLLVMStyleWithColumns(14)));
4637 }
4638 
4639 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4640 
4641 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4642   EXPECT_EQ("int x,\n"
4643             "#define A\n"
4644             "    y;",
4645             format("int x,\n#define A\ny;"));
4646 }
4647 
4648 TEST_F(FormatTest, HashInMacroDefinition) {
4649   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4650   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4651   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4652   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4653   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4654   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4655   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4656   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4657   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4658   verifyFormat("#define A  \\\n"
4659                "  {        \\\n"
4660                "    f(#c); \\\n"
4661                "  }",
4662                getLLVMStyleWithColumns(11));
4663 
4664   verifyFormat("#define A(X)         \\\n"
4665                "  void function##X()",
4666                getLLVMStyleWithColumns(22));
4667 
4668   verifyFormat("#define A(a, b, c)   \\\n"
4669                "  void a##b##c()",
4670                getLLVMStyleWithColumns(22));
4671 
4672   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4673 }
4674 
4675 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4676   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4677   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4678 
4679   FormatStyle Style = getLLVMStyle();
4680   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4681   verifyFormat("#define true ((foo)1)", Style);
4682   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4683   verifyFormat("#define false((foo)0)", Style);
4684 }
4685 
4686 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4687   EXPECT_EQ("#define A b;", format("#define A \\\n"
4688                                    "          \\\n"
4689                                    "  b;",
4690                                    getLLVMStyleWithColumns(25)));
4691   EXPECT_EQ("#define A \\\n"
4692             "          \\\n"
4693             "  a;      \\\n"
4694             "  b;",
4695             format("#define A \\\n"
4696                    "          \\\n"
4697                    "  a;      \\\n"
4698                    "  b;",
4699                    getLLVMStyleWithColumns(11)));
4700   EXPECT_EQ("#define A \\\n"
4701             "  a;      \\\n"
4702             "          \\\n"
4703             "  b;",
4704             format("#define A \\\n"
4705                    "  a;      \\\n"
4706                    "          \\\n"
4707                    "  b;",
4708                    getLLVMStyleWithColumns(11)));
4709 }
4710 
4711 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
4712   verifyIncompleteFormat("#define A :");
4713   verifyFormat("#define SOMECASES  \\\n"
4714                "  case 1:          \\\n"
4715                "  case 2\n",
4716                getLLVMStyleWithColumns(20));
4717   verifyFormat("#define MACRO(a) \\\n"
4718                "  if (a)         \\\n"
4719                "    f();         \\\n"
4720                "  else           \\\n"
4721                "    g()",
4722                getLLVMStyleWithColumns(18));
4723   verifyFormat("#define A template <typename T>");
4724   verifyIncompleteFormat("#define STR(x) #x\n"
4725                          "f(STR(this_is_a_string_literal{));");
4726   verifyFormat("#pragma omp threadprivate( \\\n"
4727                "    y)), // expected-warning",
4728                getLLVMStyleWithColumns(28));
4729   verifyFormat("#d, = };");
4730   verifyFormat("#if \"a");
4731   verifyIncompleteFormat("({\n"
4732                          "#define b     \\\n"
4733                          "  }           \\\n"
4734                          "  a\n"
4735                          "a",
4736                          getLLVMStyleWithColumns(15));
4737   verifyFormat("#define A     \\\n"
4738                "  {           \\\n"
4739                "    {\n"
4740                "#define B     \\\n"
4741                "  }           \\\n"
4742                "  }",
4743                getLLVMStyleWithColumns(15));
4744   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
4745   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
4746   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
4747   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
4748 }
4749 
4750 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
4751   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
4752   EXPECT_EQ("class A : public QObject {\n"
4753             "  Q_OBJECT\n"
4754             "\n"
4755             "  A() {}\n"
4756             "};",
4757             format("class A  :  public QObject {\n"
4758                    "     Q_OBJECT\n"
4759                    "\n"
4760                    "  A() {\n}\n"
4761                    "}  ;"));
4762   EXPECT_EQ("MACRO\n"
4763             "/*static*/ int i;",
4764             format("MACRO\n"
4765                    " /*static*/ int   i;"));
4766   EXPECT_EQ("SOME_MACRO\n"
4767             "namespace {\n"
4768             "void f();\n"
4769             "} // namespace",
4770             format("SOME_MACRO\n"
4771                    "  namespace    {\n"
4772                    "void   f(  );\n"
4773                    "} // namespace"));
4774   // Only if the identifier contains at least 5 characters.
4775   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
4776   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
4777   // Only if everything is upper case.
4778   EXPECT_EQ("class A : public QObject {\n"
4779             "  Q_Object A() {}\n"
4780             "};",
4781             format("class A  :  public QObject {\n"
4782                    "     Q_Object\n"
4783                    "  A() {\n}\n"
4784                    "}  ;"));
4785 
4786   // Only if the next line can actually start an unwrapped line.
4787   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
4788             format("SOME_WEIRD_LOG_MACRO\n"
4789                    "<< SomeThing;"));
4790 
4791   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
4792                "(n, buffers))\n",
4793                getChromiumStyle(FormatStyle::LK_Cpp));
4794 
4795   // See PR41483
4796   EXPECT_EQ("/**/ FOO(a)\n"
4797             "FOO(b)",
4798             format("/**/ FOO(a)\n"
4799                    "FOO(b)"));
4800 }
4801 
4802 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
4803   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4804             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4805             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4806             "class X {};\n"
4807             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4808             "int *createScopDetectionPass() { return 0; }",
4809             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4810                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4811                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4812                    "  class X {};\n"
4813                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4814                    "  int *createScopDetectionPass() { return 0; }"));
4815   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
4816   // braces, so that inner block is indented one level more.
4817   EXPECT_EQ("int q() {\n"
4818             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4819             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4820             "  IPC_END_MESSAGE_MAP()\n"
4821             "}",
4822             format("int q() {\n"
4823                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4824                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4825                    "  IPC_END_MESSAGE_MAP()\n"
4826                    "}"));
4827 
4828   // Same inside macros.
4829   EXPECT_EQ("#define LIST(L) \\\n"
4830             "  L(A)          \\\n"
4831             "  L(B)          \\\n"
4832             "  L(C)",
4833             format("#define LIST(L) \\\n"
4834                    "  L(A) \\\n"
4835                    "  L(B) \\\n"
4836                    "  L(C)",
4837                    getGoogleStyle()));
4838 
4839   // These must not be recognized as macros.
4840   EXPECT_EQ("int q() {\n"
4841             "  f(x);\n"
4842             "  f(x) {}\n"
4843             "  f(x)->g();\n"
4844             "  f(x)->*g();\n"
4845             "  f(x).g();\n"
4846             "  f(x) = x;\n"
4847             "  f(x) += x;\n"
4848             "  f(x) -= x;\n"
4849             "  f(x) *= x;\n"
4850             "  f(x) /= x;\n"
4851             "  f(x) %= x;\n"
4852             "  f(x) &= x;\n"
4853             "  f(x) |= x;\n"
4854             "  f(x) ^= x;\n"
4855             "  f(x) >>= x;\n"
4856             "  f(x) <<= x;\n"
4857             "  f(x)[y].z();\n"
4858             "  LOG(INFO) << x;\n"
4859             "  ifstream(x) >> x;\n"
4860             "}\n",
4861             format("int q() {\n"
4862                    "  f(x)\n;\n"
4863                    "  f(x)\n {}\n"
4864                    "  f(x)\n->g();\n"
4865                    "  f(x)\n->*g();\n"
4866                    "  f(x)\n.g();\n"
4867                    "  f(x)\n = x;\n"
4868                    "  f(x)\n += x;\n"
4869                    "  f(x)\n -= x;\n"
4870                    "  f(x)\n *= x;\n"
4871                    "  f(x)\n /= x;\n"
4872                    "  f(x)\n %= x;\n"
4873                    "  f(x)\n &= x;\n"
4874                    "  f(x)\n |= x;\n"
4875                    "  f(x)\n ^= x;\n"
4876                    "  f(x)\n >>= x;\n"
4877                    "  f(x)\n <<= x;\n"
4878                    "  f(x)\n[y].z();\n"
4879                    "  LOG(INFO)\n << x;\n"
4880                    "  ifstream(x)\n >> x;\n"
4881                    "}\n"));
4882   EXPECT_EQ("int q() {\n"
4883             "  F(x)\n"
4884             "  if (1) {\n"
4885             "  }\n"
4886             "  F(x)\n"
4887             "  while (1) {\n"
4888             "  }\n"
4889             "  F(x)\n"
4890             "  G(x);\n"
4891             "  F(x)\n"
4892             "  try {\n"
4893             "    Q();\n"
4894             "  } catch (...) {\n"
4895             "  }\n"
4896             "}\n",
4897             format("int q() {\n"
4898                    "F(x)\n"
4899                    "if (1) {}\n"
4900                    "F(x)\n"
4901                    "while (1) {}\n"
4902                    "F(x)\n"
4903                    "G(x);\n"
4904                    "F(x)\n"
4905                    "try { Q(); } catch (...) {}\n"
4906                    "}\n"));
4907   EXPECT_EQ("class A {\n"
4908             "  A() : t(0) {}\n"
4909             "  A(int i) noexcept() : {}\n"
4910             "  A(X x)\n" // FIXME: function-level try blocks are broken.
4911             "  try : t(0) {\n"
4912             "  } catch (...) {\n"
4913             "  }\n"
4914             "};",
4915             format("class A {\n"
4916                    "  A()\n : t(0) {}\n"
4917                    "  A(int i)\n noexcept() : {}\n"
4918                    "  A(X x)\n"
4919                    "  try : t(0) {} catch (...) {}\n"
4920                    "};"));
4921   FormatStyle Style = getLLVMStyle();
4922   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4923   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
4924   Style.BraceWrapping.AfterFunction = true;
4925   EXPECT_EQ("void f()\n"
4926             "try\n"
4927             "{\n"
4928             "}",
4929             format("void f() try {\n"
4930                    "}",
4931                    Style));
4932   EXPECT_EQ("class SomeClass {\n"
4933             "public:\n"
4934             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4935             "};",
4936             format("class SomeClass {\n"
4937                    "public:\n"
4938                    "  SomeClass()\n"
4939                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4940                    "};"));
4941   EXPECT_EQ("class SomeClass {\n"
4942             "public:\n"
4943             "  SomeClass()\n"
4944             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4945             "};",
4946             format("class SomeClass {\n"
4947                    "public:\n"
4948                    "  SomeClass()\n"
4949                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4950                    "};",
4951                    getLLVMStyleWithColumns(40)));
4952 
4953   verifyFormat("MACRO(>)");
4954 
4955   // Some macros contain an implicit semicolon.
4956   Style = getLLVMStyle();
4957   Style.StatementMacros.push_back("FOO");
4958   verifyFormat("FOO(a) int b = 0;");
4959   verifyFormat("FOO(a)\n"
4960                "int b = 0;",
4961                Style);
4962   verifyFormat("FOO(a);\n"
4963                "int b = 0;",
4964                Style);
4965   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
4966                "int b = 0;",
4967                Style);
4968   verifyFormat("FOO()\n"
4969                "int b = 0;",
4970                Style);
4971   verifyFormat("FOO\n"
4972                "int b = 0;",
4973                Style);
4974   verifyFormat("void f() {\n"
4975                "  FOO(a)\n"
4976                "  return a;\n"
4977                "}",
4978                Style);
4979   verifyFormat("FOO(a)\n"
4980                "FOO(b)",
4981                Style);
4982   verifyFormat("int a = 0;\n"
4983                "FOO(b)\n"
4984                "int c = 0;",
4985                Style);
4986   verifyFormat("int a = 0;\n"
4987                "int x = FOO(a)\n"
4988                "int b = 0;",
4989                Style);
4990   verifyFormat("void foo(int a) { FOO(a) }\n"
4991                "uint32_t bar() {}",
4992                Style);
4993 }
4994 
4995 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
4996   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
4997 
4998   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
4999                ZeroColumn);
5000 }
5001 
5002 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5003   verifyFormat("#define A \\\n"
5004                "  f({     \\\n"
5005                "    g();  \\\n"
5006                "  });",
5007                getLLVMStyleWithColumns(11));
5008 }
5009 
5010 TEST_F(FormatTest, IndentPreprocessorDirectives) {
5011   FormatStyle Style = getLLVMStyleWithColumns(40);
5012   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
5013   verifyFormat("#ifdef _WIN32\n"
5014                "#define A 0\n"
5015                "#ifdef VAR2\n"
5016                "#define B 1\n"
5017                "#include <someheader.h>\n"
5018                "#define MACRO                          \\\n"
5019                "  some_very_long_func_aaaaaaaaaa();\n"
5020                "#endif\n"
5021                "#else\n"
5022                "#define A 1\n"
5023                "#endif",
5024                Style);
5025   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
5026   verifyFormat("#ifdef _WIN32\n"
5027                "#  define A 0\n"
5028                "#  ifdef VAR2\n"
5029                "#    define B 1\n"
5030                "#    include <someheader.h>\n"
5031                "#    define MACRO                      \\\n"
5032                "      some_very_long_func_aaaaaaaaaa();\n"
5033                "#  endif\n"
5034                "#else\n"
5035                "#  define A 1\n"
5036                "#endif",
5037                Style);
5038   verifyFormat("#if A\n"
5039                "#  define MACRO                        \\\n"
5040                "    void a(int x) {                    \\\n"
5041                "      b();                             \\\n"
5042                "      c();                             \\\n"
5043                "      d();                             \\\n"
5044                "      e();                             \\\n"
5045                "      f();                             \\\n"
5046                "    }\n"
5047                "#endif",
5048                Style);
5049   // Comments before include guard.
5050   verifyFormat("// file comment\n"
5051                "// file comment\n"
5052                "#ifndef HEADER_H\n"
5053                "#define HEADER_H\n"
5054                "code();\n"
5055                "#endif",
5056                Style);
5057   // Test with include guards.
5058   verifyFormat("#ifndef HEADER_H\n"
5059                "#define HEADER_H\n"
5060                "code();\n"
5061                "#endif",
5062                Style);
5063   // Include guards must have a #define with the same variable immediately
5064   // after #ifndef.
5065   verifyFormat("#ifndef NOT_GUARD\n"
5066                "#  define FOO\n"
5067                "code();\n"
5068                "#endif",
5069                Style);
5070 
5071   // Include guards must cover the entire file.
5072   verifyFormat("code();\n"
5073                "code();\n"
5074                "#ifndef NOT_GUARD\n"
5075                "#  define NOT_GUARD\n"
5076                "code();\n"
5077                "#endif",
5078                Style);
5079   verifyFormat("#ifndef NOT_GUARD\n"
5080                "#  define NOT_GUARD\n"
5081                "code();\n"
5082                "#endif\n"
5083                "code();",
5084                Style);
5085   // Test with trailing blank lines.
5086   verifyFormat("#ifndef HEADER_H\n"
5087                "#define HEADER_H\n"
5088                "code();\n"
5089                "#endif\n",
5090                Style);
5091   // Include guards don't have #else.
5092   verifyFormat("#ifndef NOT_GUARD\n"
5093                "#  define NOT_GUARD\n"
5094                "code();\n"
5095                "#else\n"
5096                "#endif",
5097                Style);
5098   verifyFormat("#ifndef NOT_GUARD\n"
5099                "#  define NOT_GUARD\n"
5100                "code();\n"
5101                "#elif FOO\n"
5102                "#endif",
5103                Style);
5104   // Non-identifier #define after potential include guard.
5105   verifyFormat("#ifndef FOO\n"
5106                "#  define 1\n"
5107                "#endif\n",
5108                Style);
5109   // #if closes past last non-preprocessor line.
5110   verifyFormat("#ifndef FOO\n"
5111                "#define FOO\n"
5112                "#if 1\n"
5113                "int i;\n"
5114                "#  define A 0\n"
5115                "#endif\n"
5116                "#endif\n",
5117                Style);
5118   // Don't crash if there is an #elif directive without a condition.
5119   verifyFormat("#if 1\n"
5120                "int x;\n"
5121                "#elif\n"
5122                "int y;\n"
5123                "#else\n"
5124                "int z;\n"
5125                "#endif",
5126                Style);
5127   // FIXME: This doesn't handle the case where there's code between the
5128   // #ifndef and #define but all other conditions hold. This is because when
5129   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5130   // previous code line yet, so we can't detect it.
5131   EXPECT_EQ("#ifndef NOT_GUARD\n"
5132             "code();\n"
5133             "#define NOT_GUARD\n"
5134             "code();\n"
5135             "#endif",
5136             format("#ifndef NOT_GUARD\n"
5137                    "code();\n"
5138                    "#  define NOT_GUARD\n"
5139                    "code();\n"
5140                    "#endif",
5141                    Style));
5142   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5143   // be outside an include guard. Examples are #pragma once and
5144   // #pragma GCC diagnostic, or anything else that does not change the meaning
5145   // of the file if it's included multiple times.
5146   EXPECT_EQ("#ifdef WIN32\n"
5147             "#  pragma once\n"
5148             "#endif\n"
5149             "#ifndef HEADER_H\n"
5150             "#  define HEADER_H\n"
5151             "code();\n"
5152             "#endif",
5153             format("#ifdef WIN32\n"
5154                    "#  pragma once\n"
5155                    "#endif\n"
5156                    "#ifndef HEADER_H\n"
5157                    "#define HEADER_H\n"
5158                    "code();\n"
5159                    "#endif",
5160                    Style));
5161   // FIXME: This does not detect when there is a single non-preprocessor line
5162   // in front of an include-guard-like structure where other conditions hold
5163   // because ScopedLineState hides the line.
5164   EXPECT_EQ("code();\n"
5165             "#ifndef HEADER_H\n"
5166             "#define HEADER_H\n"
5167             "code();\n"
5168             "#endif",
5169             format("code();\n"
5170                    "#ifndef HEADER_H\n"
5171                    "#  define HEADER_H\n"
5172                    "code();\n"
5173                    "#endif",
5174                    Style));
5175   // Keep comments aligned with #, otherwise indent comments normally. These
5176   // tests cannot use verifyFormat because messUp manipulates leading
5177   // whitespace.
5178   {
5179     const char *Expected = ""
5180                            "void f() {\n"
5181                            "#if 1\n"
5182                            "// Preprocessor aligned.\n"
5183                            "#  define A 0\n"
5184                            "  // Code. Separated by blank line.\n"
5185                            "\n"
5186                            "#  define B 0\n"
5187                            "  // Code. Not aligned with #\n"
5188                            "#  define C 0\n"
5189                            "#endif";
5190     const char *ToFormat = ""
5191                            "void f() {\n"
5192                            "#if 1\n"
5193                            "// Preprocessor aligned.\n"
5194                            "#  define A 0\n"
5195                            "// Code. Separated by blank line.\n"
5196                            "\n"
5197                            "#  define B 0\n"
5198                            "   // Code. Not aligned with #\n"
5199                            "#  define C 0\n"
5200                            "#endif";
5201     EXPECT_EQ(Expected, format(ToFormat, Style));
5202     EXPECT_EQ(Expected, format(Expected, Style));
5203   }
5204   // Keep block quotes aligned.
5205   {
5206     const char *Expected = ""
5207                            "void f() {\n"
5208                            "#if 1\n"
5209                            "/* Preprocessor aligned. */\n"
5210                            "#  define A 0\n"
5211                            "  /* Code. Separated by blank line. */\n"
5212                            "\n"
5213                            "#  define B 0\n"
5214                            "  /* Code. Not aligned with # */\n"
5215                            "#  define C 0\n"
5216                            "#endif";
5217     const char *ToFormat = ""
5218                            "void f() {\n"
5219                            "#if 1\n"
5220                            "/* Preprocessor aligned. */\n"
5221                            "#  define A 0\n"
5222                            "/* Code. Separated by blank line. */\n"
5223                            "\n"
5224                            "#  define B 0\n"
5225                            "   /* Code. Not aligned with # */\n"
5226                            "#  define C 0\n"
5227                            "#endif";
5228     EXPECT_EQ(Expected, format(ToFormat, Style));
5229     EXPECT_EQ(Expected, format(Expected, Style));
5230   }
5231   // Keep comments aligned with un-indented directives.
5232   {
5233     const char *Expected = ""
5234                            "void f() {\n"
5235                            "// Preprocessor aligned.\n"
5236                            "#define A 0\n"
5237                            "  // Code. Separated by blank line.\n"
5238                            "\n"
5239                            "#define B 0\n"
5240                            "  // Code. Not aligned with #\n"
5241                            "#define C 0\n";
5242     const char *ToFormat = ""
5243                            "void f() {\n"
5244                            "// Preprocessor aligned.\n"
5245                            "#define A 0\n"
5246                            "// Code. Separated by blank line.\n"
5247                            "\n"
5248                            "#define B 0\n"
5249                            "   // Code. Not aligned with #\n"
5250                            "#define C 0\n";
5251     EXPECT_EQ(Expected, format(ToFormat, Style));
5252     EXPECT_EQ(Expected, format(Expected, Style));
5253   }
5254   // Test AfterHash with tabs.
5255   {
5256     FormatStyle Tabbed = Style;
5257     Tabbed.UseTab = FormatStyle::UT_Always;
5258     Tabbed.IndentWidth = 8;
5259     Tabbed.TabWidth = 8;
5260     verifyFormat("#ifdef _WIN32\n"
5261                  "#\tdefine A 0\n"
5262                  "#\tifdef VAR2\n"
5263                  "#\t\tdefine B 1\n"
5264                  "#\t\tinclude <someheader.h>\n"
5265                  "#\t\tdefine MACRO          \\\n"
5266                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5267                  "#\tendif\n"
5268                  "#else\n"
5269                  "#\tdefine A 1\n"
5270                  "#endif",
5271                  Tabbed);
5272   }
5273 
5274   // Regression test: Multiline-macro inside include guards.
5275   verifyFormat("#ifndef HEADER_H\n"
5276                "#define HEADER_H\n"
5277                "#define A()        \\\n"
5278                "  int i;           \\\n"
5279                "  int j;\n"
5280                "#endif // HEADER_H",
5281                getLLVMStyleWithColumns(20));
5282 
5283   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5284   // Basic before hash indent tests
5285   verifyFormat("#ifdef _WIN32\n"
5286                "  #define A 0\n"
5287                "  #ifdef VAR2\n"
5288                "    #define B 1\n"
5289                "    #include <someheader.h>\n"
5290                "    #define MACRO                      \\\n"
5291                "      some_very_long_func_aaaaaaaaaa();\n"
5292                "  #endif\n"
5293                "#else\n"
5294                "  #define A 1\n"
5295                "#endif",
5296                Style);
5297   verifyFormat("#if A\n"
5298                "  #define MACRO                        \\\n"
5299                "    void a(int x) {                    \\\n"
5300                "      b();                             \\\n"
5301                "      c();                             \\\n"
5302                "      d();                             \\\n"
5303                "      e();                             \\\n"
5304                "      f();                             \\\n"
5305                "    }\n"
5306                "#endif",
5307                Style);
5308   // Keep comments aligned with indented directives. These
5309   // tests cannot use verifyFormat because messUp manipulates leading
5310   // whitespace.
5311   {
5312     const char *Expected = "void f() {\n"
5313                            "// Aligned to preprocessor.\n"
5314                            "#if 1\n"
5315                            "  // Aligned to code.\n"
5316                            "  int a;\n"
5317                            "  #if 1\n"
5318                            "    // Aligned to preprocessor.\n"
5319                            "    #define A 0\n"
5320                            "  // Aligned to code.\n"
5321                            "  int b;\n"
5322                            "  #endif\n"
5323                            "#endif\n"
5324                            "}";
5325     const char *ToFormat = "void f() {\n"
5326                            "// Aligned to preprocessor.\n"
5327                            "#if 1\n"
5328                            "// Aligned to code.\n"
5329                            "int a;\n"
5330                            "#if 1\n"
5331                            "// Aligned to preprocessor.\n"
5332                            "#define A 0\n"
5333                            "// Aligned to code.\n"
5334                            "int b;\n"
5335                            "#endif\n"
5336                            "#endif\n"
5337                            "}";
5338     EXPECT_EQ(Expected, format(ToFormat, Style));
5339     EXPECT_EQ(Expected, format(Expected, Style));
5340   }
5341   {
5342     const char *Expected = "void f() {\n"
5343                            "/* Aligned to preprocessor. */\n"
5344                            "#if 1\n"
5345                            "  /* Aligned to code. */\n"
5346                            "  int a;\n"
5347                            "  #if 1\n"
5348                            "    /* Aligned to preprocessor. */\n"
5349                            "    #define A 0\n"
5350                            "  /* Aligned to code. */\n"
5351                            "  int b;\n"
5352                            "  #endif\n"
5353                            "#endif\n"
5354                            "}";
5355     const char *ToFormat = "void f() {\n"
5356                            "/* Aligned to preprocessor. */\n"
5357                            "#if 1\n"
5358                            "/* Aligned to code. */\n"
5359                            "int a;\n"
5360                            "#if 1\n"
5361                            "/* Aligned to preprocessor. */\n"
5362                            "#define A 0\n"
5363                            "/* Aligned to code. */\n"
5364                            "int b;\n"
5365                            "#endif\n"
5366                            "#endif\n"
5367                            "}";
5368     EXPECT_EQ(Expected, format(ToFormat, Style));
5369     EXPECT_EQ(Expected, format(Expected, Style));
5370   }
5371 
5372   // Test single comment before preprocessor
5373   verifyFormat("// Comment\n"
5374                "\n"
5375                "#if 1\n"
5376                "#endif",
5377                Style);
5378 }
5379 
5380 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5381   verifyFormat("{\n  { a #c; }\n}");
5382 }
5383 
5384 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5385   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5386             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5387   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5388             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5389 }
5390 
5391 TEST_F(FormatTest, EscapedNewlines) {
5392   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5393   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5394             format("#define A \\\nint i;\\\n  int j;", Narrow));
5395   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5396   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5397   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5398   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5399 
5400   FormatStyle AlignLeft = getLLVMStyle();
5401   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5402   EXPECT_EQ("#define MACRO(x) \\\n"
5403             "private:         \\\n"
5404             "  int x(int a);\n",
5405             format("#define MACRO(x) \\\n"
5406                    "private:         \\\n"
5407                    "  int x(int a);\n",
5408                    AlignLeft));
5409 
5410   // CRLF line endings
5411   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5412             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5413   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5414   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5415   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5416   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5417   EXPECT_EQ("#define MACRO(x) \\\r\n"
5418             "private:         \\\r\n"
5419             "  int x(int a);\r\n",
5420             format("#define MACRO(x) \\\r\n"
5421                    "private:         \\\r\n"
5422                    "  int x(int a);\r\n",
5423                    AlignLeft));
5424 
5425   FormatStyle DontAlign = getLLVMStyle();
5426   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5427   DontAlign.MaxEmptyLinesToKeep = 3;
5428   // FIXME: can't use verifyFormat here because the newline before
5429   // "public:" is not inserted the first time it's reformatted
5430   EXPECT_EQ("#define A \\\n"
5431             "  class Foo { \\\n"
5432             "    void bar(); \\\n"
5433             "\\\n"
5434             "\\\n"
5435             "\\\n"
5436             "  public: \\\n"
5437             "    void baz(); \\\n"
5438             "  };",
5439             format("#define A \\\n"
5440                    "  class Foo { \\\n"
5441                    "    void bar(); \\\n"
5442                    "\\\n"
5443                    "\\\n"
5444                    "\\\n"
5445                    "  public: \\\n"
5446                    "    void baz(); \\\n"
5447                    "  };",
5448                    DontAlign));
5449 }
5450 
5451 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5452   verifyFormat("#define A \\\n"
5453                "  int v(  \\\n"
5454                "      a); \\\n"
5455                "  int i;",
5456                getLLVMStyleWithColumns(11));
5457 }
5458 
5459 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5460   EXPECT_EQ(
5461       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5462       "                      \\\n"
5463       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5464       "\n"
5465       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5466       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5467       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5468              "\\\n"
5469              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5470              "  \n"
5471              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5472              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5473 }
5474 
5475 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5476   EXPECT_EQ("int\n"
5477             "#define A\n"
5478             "    a;",
5479             format("int\n#define A\na;"));
5480   verifyFormat("functionCallTo(\n"
5481                "    someOtherFunction(\n"
5482                "        withSomeParameters, whichInSequence,\n"
5483                "        areLongerThanALine(andAnotherCall,\n"
5484                "#define A B\n"
5485                "                           withMoreParamters,\n"
5486                "                           whichStronglyInfluenceTheLayout),\n"
5487                "        andMoreParameters),\n"
5488                "    trailing);",
5489                getLLVMStyleWithColumns(69));
5490   verifyFormat("Foo::Foo()\n"
5491                "#ifdef BAR\n"
5492                "    : baz(0)\n"
5493                "#endif\n"
5494                "{\n"
5495                "}");
5496   verifyFormat("void f() {\n"
5497                "  if (true)\n"
5498                "#ifdef A\n"
5499                "    f(42);\n"
5500                "  x();\n"
5501                "#else\n"
5502                "    g();\n"
5503                "  x();\n"
5504                "#endif\n"
5505                "}");
5506   verifyFormat("void f(param1, param2,\n"
5507                "       param3,\n"
5508                "#ifdef A\n"
5509                "       param4(param5,\n"
5510                "#ifdef A1\n"
5511                "              param6,\n"
5512                "#ifdef A2\n"
5513                "              param7),\n"
5514                "#else\n"
5515                "              param8),\n"
5516                "       param9,\n"
5517                "#endif\n"
5518                "       param10,\n"
5519                "#endif\n"
5520                "       param11)\n"
5521                "#else\n"
5522                "       param12)\n"
5523                "#endif\n"
5524                "{\n"
5525                "  x();\n"
5526                "}",
5527                getLLVMStyleWithColumns(28));
5528   verifyFormat("#if 1\n"
5529                "int i;");
5530   verifyFormat("#if 1\n"
5531                "#endif\n"
5532                "#if 1\n"
5533                "#else\n"
5534                "#endif\n");
5535   verifyFormat("DEBUG({\n"
5536                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5537                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5538                "});\n"
5539                "#if a\n"
5540                "#else\n"
5541                "#endif");
5542 
5543   verifyIncompleteFormat("void f(\n"
5544                          "#if A\n"
5545                          ");\n"
5546                          "#else\n"
5547                          "#endif");
5548 }
5549 
5550 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5551   verifyFormat("#endif\n"
5552                "#if B");
5553 }
5554 
5555 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5556   FormatStyle SingleLine = getLLVMStyle();
5557   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5558   verifyFormat("#if 0\n"
5559                "#elif 1\n"
5560                "#endif\n"
5561                "void foo() {\n"
5562                "  if (test) foo2();\n"
5563                "}",
5564                SingleLine);
5565 }
5566 
5567 TEST_F(FormatTest, LayoutBlockInsideParens) {
5568   verifyFormat("functionCall({ int i; });");
5569   verifyFormat("functionCall({\n"
5570                "  int i;\n"
5571                "  int j;\n"
5572                "});");
5573   verifyFormat("functionCall(\n"
5574                "    {\n"
5575                "      int i;\n"
5576                "      int j;\n"
5577                "    },\n"
5578                "    aaaa, bbbb, cccc);");
5579   verifyFormat("functionA(functionB({\n"
5580                "            int i;\n"
5581                "            int j;\n"
5582                "          }),\n"
5583                "          aaaa, bbbb, cccc);");
5584   verifyFormat("functionCall(\n"
5585                "    {\n"
5586                "      int i;\n"
5587                "      int j;\n"
5588                "    },\n"
5589                "    aaaa, bbbb, // comment\n"
5590                "    cccc);");
5591   verifyFormat("functionA(functionB({\n"
5592                "            int i;\n"
5593                "            int j;\n"
5594                "          }),\n"
5595                "          aaaa, bbbb, // comment\n"
5596                "          cccc);");
5597   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5598   verifyFormat("functionCall(aaaa, bbbb, {\n"
5599                "  int i;\n"
5600                "  int j;\n"
5601                "});");
5602   verifyFormat(
5603       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5604       "    {\n"
5605       "      int i; // break\n"
5606       "    },\n"
5607       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5608       "                                     ccccccccccccccccc));");
5609   verifyFormat("DEBUG({\n"
5610                "  if (a)\n"
5611                "    f();\n"
5612                "});");
5613 }
5614 
5615 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5616   EXPECT_EQ("SOME_MACRO { int i; }\n"
5617             "int i;",
5618             format("  SOME_MACRO  {int i;}  int i;"));
5619 }
5620 
5621 TEST_F(FormatTest, LayoutNestedBlocks) {
5622   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5623                "  struct s {\n"
5624                "    int i;\n"
5625                "  };\n"
5626                "  s kBitsToOs[] = {{10}};\n"
5627                "  for (int i = 0; i < 10; ++i)\n"
5628                "    return;\n"
5629                "}");
5630   verifyFormat("call(parameter, {\n"
5631                "  something();\n"
5632                "  // Comment using all columns.\n"
5633                "  somethingelse();\n"
5634                "});",
5635                getLLVMStyleWithColumns(40));
5636   verifyFormat("DEBUG( //\n"
5637                "    { f(); }, a);");
5638   verifyFormat("DEBUG( //\n"
5639                "    {\n"
5640                "      f(); //\n"
5641                "    },\n"
5642                "    a);");
5643 
5644   EXPECT_EQ("call(parameter, {\n"
5645             "  something();\n"
5646             "  // Comment too\n"
5647             "  // looooooooooong.\n"
5648             "  somethingElse();\n"
5649             "});",
5650             format("call(parameter, {\n"
5651                    "  something();\n"
5652                    "  // Comment too looooooooooong.\n"
5653                    "  somethingElse();\n"
5654                    "});",
5655                    getLLVMStyleWithColumns(29)));
5656   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5657   EXPECT_EQ("DEBUG({ // comment\n"
5658             "  int i;\n"
5659             "});",
5660             format("DEBUG({ // comment\n"
5661                    "int  i;\n"
5662                    "});"));
5663   EXPECT_EQ("DEBUG({\n"
5664             "  int i;\n"
5665             "\n"
5666             "  // comment\n"
5667             "  int j;\n"
5668             "});",
5669             format("DEBUG({\n"
5670                    "  int  i;\n"
5671                    "\n"
5672                    "  // comment\n"
5673                    "  int  j;\n"
5674                    "});"));
5675 
5676   verifyFormat("DEBUG({\n"
5677                "  if (a)\n"
5678                "    return;\n"
5679                "});");
5680   verifyGoogleFormat("DEBUG({\n"
5681                      "  if (a) return;\n"
5682                      "});");
5683   FormatStyle Style = getGoogleStyle();
5684   Style.ColumnLimit = 45;
5685   verifyFormat("Debug(\n"
5686                "    aaaaa,\n"
5687                "    {\n"
5688                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5689                "    },\n"
5690                "    a);",
5691                Style);
5692 
5693   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5694 
5695   verifyNoCrash("^{v^{a}}");
5696 }
5697 
5698 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
5699   EXPECT_EQ("#define MACRO()                     \\\n"
5700             "  Debug(aaa, /* force line break */ \\\n"
5701             "        {                           \\\n"
5702             "          int i;                    \\\n"
5703             "          int j;                    \\\n"
5704             "        })",
5705             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
5706                    "          {  int   i;  int  j;   })",
5707                    getGoogleStyle()));
5708 
5709   EXPECT_EQ("#define A                                       \\\n"
5710             "  [] {                                          \\\n"
5711             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
5712             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
5713             "  }",
5714             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
5715                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
5716                    getGoogleStyle()));
5717 }
5718 
5719 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
5720   EXPECT_EQ("{}", format("{}"));
5721   verifyFormat("enum E {};");
5722   verifyFormat("enum E {}");
5723   FormatStyle Style = getLLVMStyle();
5724   Style.SpaceInEmptyBlock = true;
5725   EXPECT_EQ("void f() { }", format("void f() {}", Style));
5726   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
5727   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
5728   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5729   Style.BraceWrapping.BeforeElse = false;
5730   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5731   verifyFormat("if (a)\n"
5732                "{\n"
5733                "} else if (b)\n"
5734                "{\n"
5735                "} else\n"
5736                "{ }",
5737                Style);
5738   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
5739   verifyFormat("if (a) {\n"
5740                "} else if (b) {\n"
5741                "} else {\n"
5742                "}",
5743                Style);
5744   Style.BraceWrapping.BeforeElse = true;
5745   verifyFormat("if (a) { }\n"
5746                "else if (b) { }\n"
5747                "else { }",
5748                Style);
5749 }
5750 
5751 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
5752   FormatStyle Style = getLLVMStyle();
5753   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
5754   Style.MacroBlockEnd = "^[A-Z_]+_END$";
5755   verifyFormat("FOO_BEGIN\n"
5756                "  FOO_ENTRY\n"
5757                "FOO_END",
5758                Style);
5759   verifyFormat("FOO_BEGIN\n"
5760                "  NESTED_FOO_BEGIN\n"
5761                "    NESTED_FOO_ENTRY\n"
5762                "  NESTED_FOO_END\n"
5763                "FOO_END",
5764                Style);
5765   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
5766                "  int x;\n"
5767                "  x = 1;\n"
5768                "FOO_END(Baz)",
5769                Style);
5770 }
5771 
5772 //===----------------------------------------------------------------------===//
5773 // Line break tests.
5774 //===----------------------------------------------------------------------===//
5775 
5776 TEST_F(FormatTest, PreventConfusingIndents) {
5777   verifyFormat(
5778       "void f() {\n"
5779       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
5780       "                         parameter, parameter, parameter)),\n"
5781       "                     SecondLongCall(parameter));\n"
5782       "}");
5783   verifyFormat(
5784       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5785       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5786       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5787       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
5788   verifyFormat(
5789       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5790       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
5791       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5792       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
5793   verifyFormat(
5794       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5795       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
5796       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
5797       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
5798   verifyFormat("int a = bbbb && ccc &&\n"
5799                "        fffff(\n"
5800                "#define A Just forcing a new line\n"
5801                "            ddd);");
5802 }
5803 
5804 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
5805   verifyFormat(
5806       "bool aaaaaaa =\n"
5807       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
5808       "    bbbbbbbb();");
5809   verifyFormat(
5810       "bool aaaaaaa =\n"
5811       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
5812       "    bbbbbbbb();");
5813 
5814   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5815                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
5816                "    ccccccccc == ddddddddddd;");
5817   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5818                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
5819                "    ccccccccc == ddddddddddd;");
5820   verifyFormat(
5821       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
5822       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
5823       "    ccccccccc == ddddddddddd;");
5824 
5825   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5826                "                 aaaaaa) &&\n"
5827                "         bbbbbb && cccccc;");
5828   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5829                "                 aaaaaa) >>\n"
5830                "         bbbbbb;");
5831   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
5832                "    SourceMgr.getSpellingColumnNumber(\n"
5833                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
5834                "    1);");
5835 
5836   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5837                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
5838                "    cccccc) {\n}");
5839   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5840                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5841                "              cccccc) {\n}");
5842   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5843                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5844                "              cccccc) {\n}");
5845   verifyFormat("b = a &&\n"
5846                "    // Comment\n"
5847                "    b.c && d;");
5848 
5849   // If the LHS of a comparison is not a binary expression itself, the
5850   // additional linebreak confuses many people.
5851   verifyFormat(
5852       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5853       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
5854       "}");
5855   verifyFormat(
5856       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5857       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5858       "}");
5859   verifyFormat(
5860       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
5861       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5862       "}");
5863   verifyFormat(
5864       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5865       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
5866       "}");
5867   // Even explicit parentheses stress the precedence enough to make the
5868   // additional break unnecessary.
5869   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5870                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5871                "}");
5872   // This cases is borderline, but with the indentation it is still readable.
5873   verifyFormat(
5874       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5875       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5876       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
5877       "}",
5878       getLLVMStyleWithColumns(75));
5879 
5880   // If the LHS is a binary expression, we should still use the additional break
5881   // as otherwise the formatting hides the operator precedence.
5882   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5883                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5884                "    5) {\n"
5885                "}");
5886   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5887                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
5888                "    5) {\n"
5889                "}");
5890 
5891   FormatStyle OnePerLine = getLLVMStyle();
5892   OnePerLine.BinPackParameters = false;
5893   verifyFormat(
5894       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5895       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5896       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
5897       OnePerLine);
5898 
5899   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
5900                "                .aaa(aaaaaaaaaaaaa) *\n"
5901                "            aaaaaaa +\n"
5902                "        aaaaaaa;",
5903                getLLVMStyleWithColumns(40));
5904 }
5905 
5906 TEST_F(FormatTest, ExpressionIndentation) {
5907   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5908                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5909                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5910                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5911                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
5912                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
5913                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5914                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
5915                "                 ccccccccccccccccccccccccccccccccccccccccc;");
5916   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5917                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5918                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5919                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5920   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5921                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5922                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5923                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5924   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5925                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5926                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5927                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5928   verifyFormat("if () {\n"
5929                "} else if (aaaaa && bbbbb > // break\n"
5930                "                        ccccc) {\n"
5931                "}");
5932   verifyFormat("if () {\n"
5933                "} else if constexpr (aaaaa && bbbbb > // break\n"
5934                "                                  ccccc) {\n"
5935                "}");
5936   verifyFormat("if () {\n"
5937                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
5938                "                                  ccccc) {\n"
5939                "}");
5940   verifyFormat("if () {\n"
5941                "} else if (aaaaa &&\n"
5942                "           bbbbb > // break\n"
5943                "               ccccc &&\n"
5944                "           ddddd) {\n"
5945                "}");
5946 
5947   // Presence of a trailing comment used to change indentation of b.
5948   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
5949                "       b;\n"
5950                "return aaaaaaaaaaaaaaaaaaa +\n"
5951                "       b; //",
5952                getLLVMStyleWithColumns(30));
5953 }
5954 
5955 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
5956   // Not sure what the best system is here. Like this, the LHS can be found
5957   // immediately above an operator (everything with the same or a higher
5958   // indent). The RHS is aligned right of the operator and so compasses
5959   // everything until something with the same indent as the operator is found.
5960   // FIXME: Is this a good system?
5961   FormatStyle Style = getLLVMStyle();
5962   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5963   verifyFormat(
5964       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5965       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5966       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5967       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5968       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5969       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5970       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5971       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5972       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
5973       Style);
5974   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5975                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5976                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5977                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5978                Style);
5979   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5980                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5981                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5982                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5983                Style);
5984   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5985                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5986                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5987                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5988                Style);
5989   verifyFormat("if () {\n"
5990                "} else if (aaaaa\n"
5991                "           && bbbbb // break\n"
5992                "                  > ccccc) {\n"
5993                "}",
5994                Style);
5995   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5996                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5997                Style);
5998   verifyFormat("return (a)\n"
5999                "       // comment\n"
6000                "       + b;",
6001                Style);
6002   verifyFormat(
6003       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6004       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6005       "             + cc;",
6006       Style);
6007 
6008   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6009                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6010                Style);
6011 
6012   // Forced by comments.
6013   verifyFormat(
6014       "unsigned ContentSize =\n"
6015       "    sizeof(int16_t)   // DWARF ARange version number\n"
6016       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6017       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6018       "    + sizeof(int8_t); // Segment Size (in bytes)");
6019 
6020   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6021                "       == boost::fusion::at_c<1>(iiii).second;",
6022                Style);
6023 
6024   Style.ColumnLimit = 60;
6025   verifyFormat("zzzzzzzzzz\n"
6026                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6027                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6028                Style);
6029 
6030   Style.ColumnLimit = 80;
6031   Style.IndentWidth = 4;
6032   Style.TabWidth = 4;
6033   Style.UseTab = FormatStyle::UT_Always;
6034   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6035   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6036   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
6037             "\t&& (someOtherLongishConditionPart1\n"
6038             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
6039             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
6040                    "(someOtherLongishConditionPart1 || "
6041                    "someOtherEvenLongerNestedConditionPart2);",
6042                    Style));
6043 }
6044 
6045 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
6046   FormatStyle Style = getLLVMStyle();
6047   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6048   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
6049 
6050   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6051                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6052                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6053                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6054                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6055                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6056                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6057                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6058                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
6059                Style);
6060   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6061                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6062                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6063                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6064                Style);
6065   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6066                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6067                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6068                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6069                Style);
6070   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6071                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6072                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6073                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6074                Style);
6075   verifyFormat("if () {\n"
6076                "} else if (aaaaa\n"
6077                "           && bbbbb // break\n"
6078                "                  > ccccc) {\n"
6079                "}",
6080                Style);
6081   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6082                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6083                Style);
6084   verifyFormat("return (a)\n"
6085                "     // comment\n"
6086                "     + b;",
6087                Style);
6088   verifyFormat(
6089       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6090       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6091       "           + cc;",
6092       Style);
6093   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6094                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6095                "                        : 3333333333333333;",
6096                Style);
6097   verifyFormat(
6098       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6099       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6100       "                                             : eeeeeeeeeeeeeeeeee)\n"
6101       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6102       "                        : 3333333333333333;",
6103       Style);
6104   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6105                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6106                Style);
6107 
6108   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6109                "    == boost::fusion::at_c<1>(iiii).second;",
6110                Style);
6111 
6112   Style.ColumnLimit = 60;
6113   verifyFormat("zzzzzzzzzzzzz\n"
6114                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6115                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6116                Style);
6117 
6118   // Forced by comments.
6119   Style.ColumnLimit = 80;
6120   verifyFormat(
6121       "unsigned ContentSize\n"
6122       "    = sizeof(int16_t) // DWARF ARange version number\n"
6123       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6124       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6125       "    + sizeof(int8_t); // Segment Size (in bytes)",
6126       Style);
6127 
6128   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6129   verifyFormat(
6130       "unsigned ContentSize =\n"
6131       "    sizeof(int16_t)   // DWARF ARange version number\n"
6132       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6133       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6134       "    + sizeof(int8_t); // Segment Size (in bytes)",
6135       Style);
6136 
6137   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6138   verifyFormat(
6139       "unsigned ContentSize =\n"
6140       "    sizeof(int16_t)   // DWARF ARange version number\n"
6141       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6142       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6143       "    + sizeof(int8_t); // Segment Size (in bytes)",
6144       Style);
6145 }
6146 
6147 TEST_F(FormatTest, EnforcedOperatorWraps) {
6148   // Here we'd like to wrap after the || operators, but a comment is forcing an
6149   // earlier wrap.
6150   verifyFormat("bool x = aaaaa //\n"
6151                "         || bbbbb\n"
6152                "         //\n"
6153                "         || cccc;");
6154 }
6155 
6156 TEST_F(FormatTest, NoOperandAlignment) {
6157   FormatStyle Style = getLLVMStyle();
6158   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6159   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6160                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6161                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6162                Style);
6163   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6164   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6165                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6166                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6167                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6168                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6169                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6170                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6171                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6172                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6173                Style);
6174 
6175   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6176                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6177                "    + cc;",
6178                Style);
6179   verifyFormat("int a = aa\n"
6180                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6181                "        * cccccccccccccccccccccccccccccccccccc;\n",
6182                Style);
6183 
6184   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6185   verifyFormat("return (a > b\n"
6186                "    // comment1\n"
6187                "    // comment2\n"
6188                "    || c);",
6189                Style);
6190 }
6191 
6192 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6193   FormatStyle Style = getLLVMStyle();
6194   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6195   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6196                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6197                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6198                Style);
6199 }
6200 
6201 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6202   FormatStyle Style = getLLVMStyleWithColumns(40);
6203   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6204   Style.BinPackArguments = false;
6205   verifyFormat("void test() {\n"
6206                "  someFunction(\n"
6207                "      this + argument + is + quite\n"
6208                "      + long + so + it + gets + wrapped\n"
6209                "      + but + remains + bin - packed);\n"
6210                "}",
6211                Style);
6212   verifyFormat("void test() {\n"
6213                "  someFunction(arg1,\n"
6214                "               this + argument + is\n"
6215                "                   + quite + long + so\n"
6216                "                   + it + gets + wrapped\n"
6217                "                   + but + remains + bin\n"
6218                "                   - packed,\n"
6219                "               arg3);\n"
6220                "}",
6221                Style);
6222   verifyFormat("void test() {\n"
6223                "  someFunction(\n"
6224                "      arg1,\n"
6225                "      this + argument + has\n"
6226                "          + anotherFunc(nested,\n"
6227                "                        calls + whose\n"
6228                "                            + arguments\n"
6229                "                            + are + also\n"
6230                "                            + wrapped,\n"
6231                "                        in + addition)\n"
6232                "          + to + being + bin - packed,\n"
6233                "      arg3);\n"
6234                "}",
6235                Style);
6236 
6237   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6238   verifyFormat("void test() {\n"
6239                "  someFunction(\n"
6240                "      arg1,\n"
6241                "      this + argument + has +\n"
6242                "          anotherFunc(nested,\n"
6243                "                      calls + whose +\n"
6244                "                          arguments +\n"
6245                "                          are + also +\n"
6246                "                          wrapped,\n"
6247                "                      in + addition) +\n"
6248                "          to + being + bin - packed,\n"
6249                "      arg3);\n"
6250                "}",
6251                Style);
6252 }
6253 
6254 TEST_F(FormatTest, ConstructorInitializers) {
6255   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6256   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6257                getLLVMStyleWithColumns(45));
6258   verifyFormat("Constructor()\n"
6259                "    : Inttializer(FitsOnTheLine) {}",
6260                getLLVMStyleWithColumns(44));
6261   verifyFormat("Constructor()\n"
6262                "    : Inttializer(FitsOnTheLine) {}",
6263                getLLVMStyleWithColumns(43));
6264 
6265   verifyFormat("template <typename T>\n"
6266                "Constructor() : Initializer(FitsOnTheLine) {}",
6267                getLLVMStyleWithColumns(45));
6268 
6269   verifyFormat(
6270       "SomeClass::Constructor()\n"
6271       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6272 
6273   verifyFormat(
6274       "SomeClass::Constructor()\n"
6275       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6276       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6277   verifyFormat(
6278       "SomeClass::Constructor()\n"
6279       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6280       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6281   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6282                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6283                "    : aaaaaaaaaa(aaaaaa) {}");
6284 
6285   verifyFormat("Constructor()\n"
6286                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6287                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6288                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6289                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6290 
6291   verifyFormat("Constructor()\n"
6292                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6293                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6294 
6295   verifyFormat("Constructor(int Parameter = 0)\n"
6296                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6297                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6298   verifyFormat("Constructor()\n"
6299                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6300                "}",
6301                getLLVMStyleWithColumns(60));
6302   verifyFormat("Constructor()\n"
6303                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6304                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6305 
6306   // Here a line could be saved by splitting the second initializer onto two
6307   // lines, but that is not desirable.
6308   verifyFormat("Constructor()\n"
6309                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6310                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6311                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6312 
6313   FormatStyle OnePerLine = getLLVMStyle();
6314   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6315   verifyFormat("MyClass::MyClass()\n"
6316                "    : a(a),\n"
6317                "      b(b),\n"
6318                "      c(c) {}",
6319                OnePerLine);
6320   verifyFormat("MyClass::MyClass()\n"
6321                "    : a(a), // comment\n"
6322                "      b(b),\n"
6323                "      c(c) {}",
6324                OnePerLine);
6325   verifyFormat("MyClass::MyClass(int a)\n"
6326                "    : b(a),      // comment\n"
6327                "      c(a + 1) { // lined up\n"
6328                "}",
6329                OnePerLine);
6330   verifyFormat("Constructor()\n"
6331                "    : a(b, b, b) {}",
6332                OnePerLine);
6333   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6334   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6335   verifyFormat("SomeClass::Constructor()\n"
6336                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6337                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6338                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6339                OnePerLine);
6340   verifyFormat("SomeClass::Constructor()\n"
6341                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6342                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6343                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6344                OnePerLine);
6345   verifyFormat("MyClass::MyClass(int var)\n"
6346                "    : some_var_(var),            // 4 space indent\n"
6347                "      some_other_var_(var + 1) { // lined up\n"
6348                "}",
6349                OnePerLine);
6350   verifyFormat("Constructor()\n"
6351                "    : aaaaa(aaaaaa),\n"
6352                "      aaaaa(aaaaaa),\n"
6353                "      aaaaa(aaaaaa),\n"
6354                "      aaaaa(aaaaaa),\n"
6355                "      aaaaa(aaaaaa) {}",
6356                OnePerLine);
6357   verifyFormat("Constructor()\n"
6358                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6359                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6360                OnePerLine);
6361   OnePerLine.BinPackParameters = false;
6362   verifyFormat(
6363       "Constructor()\n"
6364       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6365       "          aaaaaaaaaaa().aaa(),\n"
6366       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6367       OnePerLine);
6368   OnePerLine.ColumnLimit = 60;
6369   verifyFormat("Constructor()\n"
6370                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6371                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6372                OnePerLine);
6373 
6374   EXPECT_EQ("Constructor()\n"
6375             "    : // Comment forcing unwanted break.\n"
6376             "      aaaa(aaaa) {}",
6377             format("Constructor() :\n"
6378                    "    // Comment forcing unwanted break.\n"
6379                    "    aaaa(aaaa) {}"));
6380 }
6381 
6382 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6383   FormatStyle Style = getLLVMStyleWithColumns(60);
6384   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6385   Style.BinPackParameters = false;
6386 
6387   for (int i = 0; i < 4; ++i) {
6388     // Test all combinations of parameters that should not have an effect.
6389     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6390     Style.AllowAllArgumentsOnNextLine = i & 2;
6391 
6392     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6393     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6394     verifyFormat("Constructor()\n"
6395                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6396                  Style);
6397     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6398 
6399     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6400     verifyFormat("Constructor()\n"
6401                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6402                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6403                  Style);
6404     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6405 
6406     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6407     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6408     verifyFormat("Constructor()\n"
6409                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6410                  Style);
6411 
6412     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6413     verifyFormat("Constructor()\n"
6414                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6415                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6416                  Style);
6417 
6418     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6419     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6420     verifyFormat("Constructor() :\n"
6421                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6422                  Style);
6423 
6424     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6425     verifyFormat("Constructor() :\n"
6426                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6427                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6428                  Style);
6429   }
6430 
6431   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6432   // AllowAllConstructorInitializersOnNextLine in all
6433   // BreakConstructorInitializers modes
6434   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6435   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6436   verifyFormat("SomeClassWithALongName::Constructor(\n"
6437                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6438                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6439                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6440                Style);
6441 
6442   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6443   verifyFormat("SomeClassWithALongName::Constructor(\n"
6444                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6445                "    int bbbbbbbbbbbbb,\n"
6446                "    int cccccccccccccccc)\n"
6447                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6448                Style);
6449 
6450   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6451   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6452   verifyFormat("SomeClassWithALongName::Constructor(\n"
6453                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6454                "    int bbbbbbbbbbbbb)\n"
6455                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6456                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6457                Style);
6458 
6459   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6460 
6461   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6462   verifyFormat("SomeClassWithALongName::Constructor(\n"
6463                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6464                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6465                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6466                Style);
6467 
6468   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6469   verifyFormat("SomeClassWithALongName::Constructor(\n"
6470                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6471                "    int bbbbbbbbbbbbb,\n"
6472                "    int cccccccccccccccc)\n"
6473                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6474                Style);
6475 
6476   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6477   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6478   verifyFormat("SomeClassWithALongName::Constructor(\n"
6479                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6480                "    int bbbbbbbbbbbbb)\n"
6481                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6482                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6483                Style);
6484 
6485   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6486   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6487   verifyFormat("SomeClassWithALongName::Constructor(\n"
6488                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6489                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6490                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6491                Style);
6492 
6493   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6494   verifyFormat("SomeClassWithALongName::Constructor(\n"
6495                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6496                "    int bbbbbbbbbbbbb,\n"
6497                "    int cccccccccccccccc) :\n"
6498                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6499                Style);
6500 
6501   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6502   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6503   verifyFormat("SomeClassWithALongName::Constructor(\n"
6504                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6505                "    int bbbbbbbbbbbbb) :\n"
6506                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6507                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6508                Style);
6509 }
6510 
6511 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6512   FormatStyle Style = getLLVMStyleWithColumns(60);
6513   Style.BinPackArguments = false;
6514   for (int i = 0; i < 4; ++i) {
6515     // Test all combinations of parameters that should not have an effect.
6516     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6517     Style.PackConstructorInitializers =
6518         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6519 
6520     Style.AllowAllArgumentsOnNextLine = true;
6521     verifyFormat("void foo() {\n"
6522                  "  FunctionCallWithReallyLongName(\n"
6523                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6524                  "}",
6525                  Style);
6526     Style.AllowAllArgumentsOnNextLine = false;
6527     verifyFormat("void foo() {\n"
6528                  "  FunctionCallWithReallyLongName(\n"
6529                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6530                  "      bbbbbbbbbbbb);\n"
6531                  "}",
6532                  Style);
6533 
6534     Style.AllowAllArgumentsOnNextLine = true;
6535     verifyFormat("void foo() {\n"
6536                  "  auto VariableWithReallyLongName = {\n"
6537                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6538                  "}",
6539                  Style);
6540     Style.AllowAllArgumentsOnNextLine = false;
6541     verifyFormat("void foo() {\n"
6542                  "  auto VariableWithReallyLongName = {\n"
6543                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6544                  "      bbbbbbbbbbbb};\n"
6545                  "}",
6546                  Style);
6547   }
6548 
6549   // This parameter should not affect declarations.
6550   Style.BinPackParameters = false;
6551   Style.AllowAllArgumentsOnNextLine = false;
6552   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6553   verifyFormat("void FunctionCallWithReallyLongName(\n"
6554                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6555                Style);
6556   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6557   verifyFormat("void FunctionCallWithReallyLongName(\n"
6558                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6559                "    int bbbbbbbbbbbb);",
6560                Style);
6561 }
6562 
6563 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6564   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6565   // and BAS_Align.
6566   FormatStyle Style = getLLVMStyleWithColumns(35);
6567   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6568                     "void functionDecl(int A, int B, int C);";
6569   Style.AllowAllArgumentsOnNextLine = false;
6570   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6571   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6572                       "    paramC);\n"
6573                       "void functionDecl(int A, int B,\n"
6574                       "    int C);"),
6575             format(Input, Style));
6576   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6577   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6578                       "             paramC);\n"
6579                       "void functionDecl(int A, int B,\n"
6580                       "                  int C);"),
6581             format(Input, Style));
6582   // However, BAS_AlwaysBreak should take precedence over
6583   // AllowAllArgumentsOnNextLine.
6584   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6585   EXPECT_EQ(StringRef("functionCall(\n"
6586                       "    paramA, paramB, paramC);\n"
6587                       "void functionDecl(\n"
6588                       "    int A, int B, int C);"),
6589             format(Input, Style));
6590 
6591   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6592   // first argument.
6593   Style.AllowAllArgumentsOnNextLine = true;
6594   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6595   EXPECT_EQ(StringRef("functionCall(\n"
6596                       "    paramA, paramB, paramC);\n"
6597                       "void functionDecl(\n"
6598                       "    int A, int B, int C);"),
6599             format(Input, Style));
6600   // It wouldn't fit on one line with aligned parameters so this setting
6601   // doesn't change anything for BAS_Align.
6602   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6603   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6604                       "             paramC);\n"
6605                       "void functionDecl(int A, int B,\n"
6606                       "                  int C);"),
6607             format(Input, Style));
6608   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6609   EXPECT_EQ(StringRef("functionCall(\n"
6610                       "    paramA, paramB, paramC);\n"
6611                       "void functionDecl(\n"
6612                       "    int A, int B, int C);"),
6613             format(Input, Style));
6614 }
6615 
6616 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6617   FormatStyle Style = getLLVMStyle();
6618   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6619 
6620   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6621   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6622                getStyleWithColumns(Style, 45));
6623   verifyFormat("Constructor() :\n"
6624                "    Initializer(FitsOnTheLine) {}",
6625                getStyleWithColumns(Style, 44));
6626   verifyFormat("Constructor() :\n"
6627                "    Initializer(FitsOnTheLine) {}",
6628                getStyleWithColumns(Style, 43));
6629 
6630   verifyFormat("template <typename T>\n"
6631                "Constructor() : Initializer(FitsOnTheLine) {}",
6632                getStyleWithColumns(Style, 50));
6633   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6634   verifyFormat(
6635       "SomeClass::Constructor() :\n"
6636       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6637       Style);
6638 
6639   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6640   verifyFormat(
6641       "SomeClass::Constructor() :\n"
6642       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6643       Style);
6644 
6645   verifyFormat(
6646       "SomeClass::Constructor() :\n"
6647       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6648       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6649       Style);
6650   verifyFormat(
6651       "SomeClass::Constructor() :\n"
6652       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6653       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6654       Style);
6655   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6656                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6657                "    aaaaaaaaaa(aaaaaa) {}",
6658                Style);
6659 
6660   verifyFormat("Constructor() :\n"
6661                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6662                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6663                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6664                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
6665                Style);
6666 
6667   verifyFormat("Constructor() :\n"
6668                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6669                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6670                Style);
6671 
6672   verifyFormat("Constructor(int Parameter = 0) :\n"
6673                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6674                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
6675                Style);
6676   verifyFormat("Constructor() :\n"
6677                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6678                "}",
6679                getStyleWithColumns(Style, 60));
6680   verifyFormat("Constructor() :\n"
6681                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6682                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
6683                Style);
6684 
6685   // Here a line could be saved by splitting the second initializer onto two
6686   // lines, but that is not desirable.
6687   verifyFormat("Constructor() :\n"
6688                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6689                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
6690                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6691                Style);
6692 
6693   FormatStyle OnePerLine = Style;
6694   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6695   verifyFormat("SomeClass::Constructor() :\n"
6696                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6697                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6698                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6699                OnePerLine);
6700   verifyFormat("SomeClass::Constructor() :\n"
6701                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6702                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6703                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6704                OnePerLine);
6705   verifyFormat("MyClass::MyClass(int var) :\n"
6706                "    some_var_(var),            // 4 space indent\n"
6707                "    some_other_var_(var + 1) { // lined up\n"
6708                "}",
6709                OnePerLine);
6710   verifyFormat("Constructor() :\n"
6711                "    aaaaa(aaaaaa),\n"
6712                "    aaaaa(aaaaaa),\n"
6713                "    aaaaa(aaaaaa),\n"
6714                "    aaaaa(aaaaaa),\n"
6715                "    aaaaa(aaaaaa) {}",
6716                OnePerLine);
6717   verifyFormat("Constructor() :\n"
6718                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6719                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
6720                OnePerLine);
6721   OnePerLine.BinPackParameters = false;
6722   verifyFormat("Constructor() :\n"
6723                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6724                "        aaaaaaaaaaa().aaa(),\n"
6725                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6726                OnePerLine);
6727   OnePerLine.ColumnLimit = 60;
6728   verifyFormat("Constructor() :\n"
6729                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6730                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6731                OnePerLine);
6732 
6733   EXPECT_EQ("Constructor() :\n"
6734             "    // Comment forcing unwanted break.\n"
6735             "    aaaa(aaaa) {}",
6736             format("Constructor() :\n"
6737                    "    // Comment forcing unwanted break.\n"
6738                    "    aaaa(aaaa) {}",
6739                    Style));
6740 
6741   Style.ColumnLimit = 0;
6742   verifyFormat("SomeClass::Constructor() :\n"
6743                "    a(a) {}",
6744                Style);
6745   verifyFormat("SomeClass::Constructor() noexcept :\n"
6746                "    a(a) {}",
6747                Style);
6748   verifyFormat("SomeClass::Constructor() :\n"
6749                "    a(a), b(b), c(c) {}",
6750                Style);
6751   verifyFormat("SomeClass::Constructor() :\n"
6752                "    a(a) {\n"
6753                "  foo();\n"
6754                "  bar();\n"
6755                "}",
6756                Style);
6757 
6758   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6759   verifyFormat("SomeClass::Constructor() :\n"
6760                "    a(a), b(b), c(c) {\n"
6761                "}",
6762                Style);
6763   verifyFormat("SomeClass::Constructor() :\n"
6764                "    a(a) {\n"
6765                "}",
6766                Style);
6767 
6768   Style.ColumnLimit = 80;
6769   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
6770   Style.ConstructorInitializerIndentWidth = 2;
6771   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
6772   verifyFormat("SomeClass::Constructor() :\n"
6773                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6774                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
6775                Style);
6776 
6777   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
6778   // well
6779   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
6780   verifyFormat(
6781       "class SomeClass\n"
6782       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6783       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6784       Style);
6785   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
6786   verifyFormat(
6787       "class SomeClass\n"
6788       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6789       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6790       Style);
6791   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
6792   verifyFormat(
6793       "class SomeClass :\n"
6794       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6795       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6796       Style);
6797   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
6798   verifyFormat(
6799       "class SomeClass\n"
6800       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6801       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6802       Style);
6803 }
6804 
6805 #ifndef EXPENSIVE_CHECKS
6806 // Expensive checks enables libstdc++ checking which includes validating the
6807 // state of ranges used in std::priority_queue - this blows out the
6808 // runtime/scalability of the function and makes this test unacceptably slow.
6809 TEST_F(FormatTest, MemoizationTests) {
6810   // This breaks if the memoization lookup does not take \c Indent and
6811   // \c LastSpace into account.
6812   verifyFormat(
6813       "extern CFRunLoopTimerRef\n"
6814       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
6815       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
6816       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
6817       "                     CFRunLoopTimerContext *context) {}");
6818 
6819   // Deep nesting somewhat works around our memoization.
6820   verifyFormat(
6821       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6822       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6823       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6824       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6825       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
6826       getLLVMStyleWithColumns(65));
6827   verifyFormat(
6828       "aaaaa(\n"
6829       "    aaaaa,\n"
6830       "    aaaaa(\n"
6831       "        aaaaa,\n"
6832       "        aaaaa(\n"
6833       "            aaaaa,\n"
6834       "            aaaaa(\n"
6835       "                aaaaa,\n"
6836       "                aaaaa(\n"
6837       "                    aaaaa,\n"
6838       "                    aaaaa(\n"
6839       "                        aaaaa,\n"
6840       "                        aaaaa(\n"
6841       "                            aaaaa,\n"
6842       "                            aaaaa(\n"
6843       "                                aaaaa,\n"
6844       "                                aaaaa(\n"
6845       "                                    aaaaa,\n"
6846       "                                    aaaaa(\n"
6847       "                                        aaaaa,\n"
6848       "                                        aaaaa(\n"
6849       "                                            aaaaa,\n"
6850       "                                            aaaaa(\n"
6851       "                                                aaaaa,\n"
6852       "                                                aaaaa))))))))))));",
6853       getLLVMStyleWithColumns(65));
6854   verifyFormat(
6855       "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n"
6856       "                                  a),\n"
6857       "                                a),\n"
6858       "                              a),\n"
6859       "                            a),\n"
6860       "                          a),\n"
6861       "                        a),\n"
6862       "                      a),\n"
6863       "                    a),\n"
6864       "                  a),\n"
6865       "                a),\n"
6866       "              a),\n"
6867       "            a),\n"
6868       "          a),\n"
6869       "        a),\n"
6870       "      a),\n"
6871       "    a),\n"
6872       "  a)",
6873       getLLVMStyleWithColumns(65));
6874 
6875   // This test takes VERY long when memoization is broken.
6876   FormatStyle OnePerLine = getLLVMStyle();
6877   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6878   OnePerLine.BinPackParameters = false;
6879   std::string input = "Constructor()\n"
6880                       "    : aaaa(a,\n";
6881   for (unsigned i = 0, e = 80; i != e; ++i) {
6882     input += "           a,\n";
6883   }
6884   input += "           a) {}";
6885   verifyFormat(input, OnePerLine);
6886 }
6887 #endif
6888 
6889 TEST_F(FormatTest, BreaksAsHighAsPossible) {
6890   verifyFormat(
6891       "void f() {\n"
6892       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
6893       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
6894       "    f();\n"
6895       "}");
6896   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
6897                "    Intervals[i - 1].getRange().getLast()) {\n}");
6898 }
6899 
6900 TEST_F(FormatTest, BreaksFunctionDeclarations) {
6901   // Principially, we break function declarations in a certain order:
6902   // 1) break amongst arguments.
6903   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
6904                "                              Cccccccccccccc cccccccccccccc);");
6905   verifyFormat("template <class TemplateIt>\n"
6906                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
6907                "                            TemplateIt *stop) {}");
6908 
6909   // 2) break after return type.
6910   verifyFormat(
6911       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6912       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
6913       getGoogleStyle());
6914 
6915   // 3) break after (.
6916   verifyFormat(
6917       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
6918       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
6919       getGoogleStyle());
6920 
6921   // 4) break before after nested name specifiers.
6922   verifyFormat(
6923       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6924       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
6925       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
6926       getGoogleStyle());
6927 
6928   // However, there are exceptions, if a sufficient amount of lines can be
6929   // saved.
6930   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
6931   // more adjusting.
6932   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6933                "                                  Cccccccccccccc cccccccccc,\n"
6934                "                                  Cccccccccccccc cccccccccc,\n"
6935                "                                  Cccccccccccccc cccccccccc,\n"
6936                "                                  Cccccccccccccc cccccccccc);");
6937   verifyFormat(
6938       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6939       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6940       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6941       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
6942       getGoogleStyle());
6943   verifyFormat(
6944       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6945       "                                          Cccccccccccccc cccccccccc,\n"
6946       "                                          Cccccccccccccc cccccccccc,\n"
6947       "                                          Cccccccccccccc cccccccccc,\n"
6948       "                                          Cccccccccccccc cccccccccc,\n"
6949       "                                          Cccccccccccccc cccccccccc,\n"
6950       "                                          Cccccccccccccc cccccccccc);");
6951   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6952                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6953                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6954                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6955                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
6956 
6957   // Break after multi-line parameters.
6958   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6959                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6960                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6961                "    bbbb bbbb);");
6962   verifyFormat("void SomeLoooooooooooongFunction(\n"
6963                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
6964                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6965                "    int bbbbbbbbbbbbb);");
6966 
6967   // Treat overloaded operators like other functions.
6968   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6969                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
6970   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6971                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
6972   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6973                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
6974   verifyGoogleFormat(
6975       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
6976       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6977   verifyGoogleFormat(
6978       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
6979       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6980   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6981                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6982   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
6983                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6984   verifyGoogleFormat(
6985       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
6986       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6987       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
6988   verifyGoogleFormat("template <typename T>\n"
6989                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6990                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
6991                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
6992 
6993   FormatStyle Style = getLLVMStyle();
6994   Style.PointerAlignment = FormatStyle::PAS_Left;
6995   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6996                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
6997                Style);
6998   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
6999                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7000                Style);
7001 }
7002 
7003 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
7004   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
7005   // Prefer keeping `::` followed by `operator` together.
7006   EXPECT_EQ("const aaaa::bbbbbbb &\n"
7007             "ccccccccc::operator++() {\n"
7008             "  stuff();\n"
7009             "}",
7010             format("const aaaa::bbbbbbb\n"
7011                    "&ccccccccc::operator++() { stuff(); }",
7012                    getLLVMStyleWithColumns(40)));
7013 }
7014 
7015 TEST_F(FormatTest, TrailingReturnType) {
7016   verifyFormat("auto foo() -> int;\n");
7017   // correct trailing return type spacing
7018   verifyFormat("auto operator->() -> int;\n");
7019   verifyFormat("auto operator++(int) -> int;\n");
7020 
7021   verifyFormat("struct S {\n"
7022                "  auto bar() const -> int;\n"
7023                "};");
7024   verifyFormat("template <size_t Order, typename T>\n"
7025                "auto load_img(const std::string &filename)\n"
7026                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
7027   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
7028                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
7029   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
7030   verifyFormat("template <typename T>\n"
7031                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
7032                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
7033 
7034   // Not trailing return types.
7035   verifyFormat("void f() { auto a = b->c(); }");
7036   verifyFormat("auto a = p->foo();");
7037   verifyFormat("int a = p->foo();");
7038   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
7039 }
7040 
7041 TEST_F(FormatTest, DeductionGuides) {
7042   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
7043   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
7044   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
7045   verifyFormat(
7046       "template <class... T>\n"
7047       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
7048   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
7049   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
7050   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
7051   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
7052   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
7053   verifyFormat("template <class T> x() -> x<1>;");
7054   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
7055 
7056   // Ensure not deduction guides.
7057   verifyFormat("c()->f<int>();");
7058   verifyFormat("x()->foo<1>;");
7059   verifyFormat("x = p->foo<3>();");
7060   verifyFormat("x()->x<1>();");
7061   verifyFormat("x()->x<1>;");
7062 }
7063 
7064 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
7065   // Avoid breaking before trailing 'const' or other trailing annotations, if
7066   // they are not function-like.
7067   FormatStyle Style = getGoogleStyleWithColumns(47);
7068   verifyFormat("void someLongFunction(\n"
7069                "    int someLoooooooooooooongParameter) const {\n}",
7070                getLLVMStyleWithColumns(47));
7071   verifyFormat("LoooooongReturnType\n"
7072                "someLoooooooongFunction() const {}",
7073                getLLVMStyleWithColumns(47));
7074   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
7075                "    const {}",
7076                Style);
7077   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7078                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
7079   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7080                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
7081   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7082                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
7083   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
7084                "                   aaaaaaaaaaa aaaaa) const override;");
7085   verifyGoogleFormat(
7086       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7087       "    const override;");
7088 
7089   // Even if the first parameter has to be wrapped.
7090   verifyFormat("void someLongFunction(\n"
7091                "    int someLongParameter) const {}",
7092                getLLVMStyleWithColumns(46));
7093   verifyFormat("void someLongFunction(\n"
7094                "    int someLongParameter) const {}",
7095                Style);
7096   verifyFormat("void someLongFunction(\n"
7097                "    int someLongParameter) override {}",
7098                Style);
7099   verifyFormat("void someLongFunction(\n"
7100                "    int someLongParameter) OVERRIDE {}",
7101                Style);
7102   verifyFormat("void someLongFunction(\n"
7103                "    int someLongParameter) final {}",
7104                Style);
7105   verifyFormat("void someLongFunction(\n"
7106                "    int someLongParameter) FINAL {}",
7107                Style);
7108   verifyFormat("void someLongFunction(\n"
7109                "    int parameter) const override {}",
7110                Style);
7111 
7112   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
7113   verifyFormat("void someLongFunction(\n"
7114                "    int someLongParameter) const\n"
7115                "{\n"
7116                "}",
7117                Style);
7118 
7119   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
7120   verifyFormat("void someLongFunction(\n"
7121                "    int someLongParameter) const\n"
7122                "  {\n"
7123                "  }",
7124                Style);
7125 
7126   // Unless these are unknown annotations.
7127   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
7128                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7129                "    LONG_AND_UGLY_ANNOTATION;");
7130 
7131   // Breaking before function-like trailing annotations is fine to keep them
7132   // close to their arguments.
7133   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7134                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7135   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7136                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7137   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7138                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
7139   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
7140                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
7141   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
7142 
7143   verifyFormat(
7144       "void aaaaaaaaaaaaaaaaaa()\n"
7145       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
7146       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
7147   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7148                "    __attribute__((unused));");
7149   verifyGoogleFormat(
7150       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7151       "    GUARDED_BY(aaaaaaaaaaaa);");
7152   verifyGoogleFormat(
7153       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7154       "    GUARDED_BY(aaaaaaaaaaaa);");
7155   verifyGoogleFormat(
7156       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7157       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7158   verifyGoogleFormat(
7159       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7160       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
7161 }
7162 
7163 TEST_F(FormatTest, FunctionAnnotations) {
7164   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7165                "int OldFunction(const string &parameter) {}");
7166   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7167                "string OldFunction(const string &parameter) {}");
7168   verifyFormat("template <typename T>\n"
7169                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7170                "string OldFunction(const string &parameter) {}");
7171 
7172   // Not function annotations.
7173   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7174                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
7175   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
7176                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
7177   verifyFormat("MACRO(abc).function() // wrap\n"
7178                "    << abc;");
7179   verifyFormat("MACRO(abc)->function() // wrap\n"
7180                "    << abc;");
7181   verifyFormat("MACRO(abc)::function() // wrap\n"
7182                "    << abc;");
7183 }
7184 
7185 TEST_F(FormatTest, BreaksDesireably) {
7186   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7187                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7188                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
7189   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7190                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
7191                "}");
7192 
7193   verifyFormat(
7194       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7195       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7196 
7197   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7198                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7199                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7200 
7201   verifyFormat(
7202       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7203       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7204       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7205       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7206       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7207 
7208   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7209                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7210 
7211   verifyFormat(
7212       "void f() {\n"
7213       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7214       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7215       "}");
7216   verifyFormat(
7217       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7218       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7219   verifyFormat(
7220       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7221       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7222   verifyFormat(
7223       "aaaaaa(aaa,\n"
7224       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7225       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7226       "       aaaa);");
7227   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7228                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7229                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7230 
7231   // Indent consistently independent of call expression and unary operator.
7232   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7233                "    dddddddddddddddddddddddddddddd));");
7234   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7235                "    dddddddddddddddddddddddddddddd));");
7236   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7237                "    dddddddddddddddddddddddddddddd));");
7238 
7239   // This test case breaks on an incorrect memoization, i.e. an optimization not
7240   // taking into account the StopAt value.
7241   verifyFormat(
7242       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7243       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7244       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7245       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7246 
7247   verifyFormat("{\n  {\n    {\n"
7248                "      Annotation.SpaceRequiredBefore =\n"
7249                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7250                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7251                "    }\n  }\n}");
7252 
7253   // Break on an outer level if there was a break on an inner level.
7254   EXPECT_EQ("f(g(h(a, // comment\n"
7255             "      b, c),\n"
7256             "    d, e),\n"
7257             "  x, y);",
7258             format("f(g(h(a, // comment\n"
7259                    "    b, c), d, e), x, y);"));
7260 
7261   // Prefer breaking similar line breaks.
7262   verifyFormat(
7263       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7264       "                             NSTrackingMouseEnteredAndExited |\n"
7265       "                             NSTrackingActiveAlways;");
7266 }
7267 
7268 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7269   FormatStyle NoBinPacking = getGoogleStyle();
7270   NoBinPacking.BinPackParameters = false;
7271   NoBinPacking.BinPackArguments = true;
7272   verifyFormat("void f() {\n"
7273                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7274                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7275                "}",
7276                NoBinPacking);
7277   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7278                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7279                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7280                NoBinPacking);
7281 
7282   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7283   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7284                "                        vector<int> bbbbbbbbbbbbbbb);",
7285                NoBinPacking);
7286   // FIXME: This behavior difference is probably not wanted. However, currently
7287   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7288   // template arguments from BreakBeforeParameter being set because of the
7289   // one-per-line formatting.
7290   verifyFormat(
7291       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7292       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7293       NoBinPacking);
7294   verifyFormat(
7295       "void fffffffffff(\n"
7296       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7297       "        aaaaaaaaaa);");
7298 }
7299 
7300 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7301   FormatStyle NoBinPacking = getGoogleStyle();
7302   NoBinPacking.BinPackParameters = false;
7303   NoBinPacking.BinPackArguments = false;
7304   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7305                "  aaaaaaaaaaaaaaaaaaaa,\n"
7306                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7307                NoBinPacking);
7308   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7309                "        aaaaaaaaaaaaa,\n"
7310                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7311                NoBinPacking);
7312   verifyFormat(
7313       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7314       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7315       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7316       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7317       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7318       NoBinPacking);
7319   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7320                "    .aaaaaaaaaaaaaaaaaa();",
7321                NoBinPacking);
7322   verifyFormat("void f() {\n"
7323                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7324                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7325                "}",
7326                NoBinPacking);
7327 
7328   verifyFormat(
7329       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7330       "             aaaaaaaaaaaa,\n"
7331       "             aaaaaaaaaaaa);",
7332       NoBinPacking);
7333   verifyFormat(
7334       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7335       "                               ddddddddddddddddddddddddddddd),\n"
7336       "             test);",
7337       NoBinPacking);
7338 
7339   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7340                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7341                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7342                "    aaaaaaaaaaaaaaaaaa;",
7343                NoBinPacking);
7344   verifyFormat("a(\"a\"\n"
7345                "  \"a\",\n"
7346                "  a);");
7347 
7348   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7349   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7350                "                aaaaaaaaa,\n"
7351                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7352                NoBinPacking);
7353   verifyFormat(
7354       "void f() {\n"
7355       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7356       "      .aaaaaaa();\n"
7357       "}",
7358       NoBinPacking);
7359   verifyFormat(
7360       "template <class SomeType, class SomeOtherType>\n"
7361       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7362       NoBinPacking);
7363 }
7364 
7365 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7366   FormatStyle Style = getLLVMStyleWithColumns(15);
7367   Style.ExperimentalAutoDetectBinPacking = true;
7368   EXPECT_EQ("aaa(aaaa,\n"
7369             "    aaaa,\n"
7370             "    aaaa);\n"
7371             "aaa(aaaa,\n"
7372             "    aaaa,\n"
7373             "    aaaa);",
7374             format("aaa(aaaa,\n" // one-per-line
7375                    "  aaaa,\n"
7376                    "    aaaa  );\n"
7377                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7378                    Style));
7379   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7380             "    aaaa);\n"
7381             "aaa(aaaa, aaaa,\n"
7382             "    aaaa);",
7383             format("aaa(aaaa,  aaaa,\n" // bin-packed
7384                    "    aaaa  );\n"
7385                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7386                    Style));
7387 }
7388 
7389 TEST_F(FormatTest, FormatsBuilderPattern) {
7390   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7391                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7392                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7393                "    .StartsWith(\".init\", ORDER_INIT)\n"
7394                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7395                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7396                "    .Default(ORDER_TEXT);\n");
7397 
7398   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7399                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7400   verifyFormat("aaaaaaa->aaaaaaa\n"
7401                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7402                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7403                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7404   verifyFormat(
7405       "aaaaaaa->aaaaaaa\n"
7406       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7407       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7408   verifyFormat(
7409       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7410       "    aaaaaaaaaaaaaa);");
7411   verifyFormat(
7412       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7413       "    aaaaaa->aaaaaaaaaaaa()\n"
7414       "        ->aaaaaaaaaaaaaaaa(\n"
7415       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7416       "        ->aaaaaaaaaaaaaaaaa();");
7417   verifyGoogleFormat(
7418       "void f() {\n"
7419       "  someo->Add((new util::filetools::Handler(dir))\n"
7420       "                 ->OnEvent1(NewPermanentCallback(\n"
7421       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7422       "                 ->OnEvent2(NewPermanentCallback(\n"
7423       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7424       "                 ->OnEvent3(NewPermanentCallback(\n"
7425       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7426       "                 ->OnEvent5(NewPermanentCallback(\n"
7427       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7428       "                 ->OnEvent6(NewPermanentCallback(\n"
7429       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7430       "}");
7431 
7432   verifyFormat(
7433       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7434   verifyFormat("aaaaaaaaaaaaaaa()\n"
7435                "    .aaaaaaaaaaaaaaa()\n"
7436                "    .aaaaaaaaaaaaaaa()\n"
7437                "    .aaaaaaaaaaaaaaa()\n"
7438                "    .aaaaaaaaaaaaaaa();");
7439   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7440                "    .aaaaaaaaaaaaaaa()\n"
7441                "    .aaaaaaaaaaaaaaa()\n"
7442                "    .aaaaaaaaaaaaaaa();");
7443   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7444                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7445                "    .aaaaaaaaaaaaaaa();");
7446   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7447                "    ->aaaaaaaaaaaaaae(0)\n"
7448                "    ->aaaaaaaaaaaaaaa();");
7449 
7450   // Don't linewrap after very short segments.
7451   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7452                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7453                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7454   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7455                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7456                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7457   verifyFormat("aaa()\n"
7458                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7459                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7460                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7461 
7462   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7463                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7464                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7465   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7466                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7467                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7468 
7469   // Prefer not to break after empty parentheses.
7470   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7471                "    First->LastNewlineOffset);");
7472 
7473   // Prefer not to create "hanging" indents.
7474   verifyFormat(
7475       "return !soooooooooooooome_map\n"
7476       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7477       "            .second;");
7478   verifyFormat(
7479       "return aaaaaaaaaaaaaaaa\n"
7480       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7481       "    .aaaa(aaaaaaaaaaaaaa);");
7482   // No hanging indent here.
7483   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7484                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7485   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7486                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7487   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7488                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7489                getLLVMStyleWithColumns(60));
7490   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7491                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7492                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7493                getLLVMStyleWithColumns(59));
7494   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7495                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7496                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7497 
7498   // Dont break if only closing statements before member call
7499   verifyFormat("test() {\n"
7500                "  ([]() -> {\n"
7501                "    int b = 32;\n"
7502                "    return 3;\n"
7503                "  }).foo();\n"
7504                "}");
7505   verifyFormat("test() {\n"
7506                "  (\n"
7507                "      []() -> {\n"
7508                "        int b = 32;\n"
7509                "        return 3;\n"
7510                "      },\n"
7511                "      foo, bar)\n"
7512                "      .foo();\n"
7513                "}");
7514   verifyFormat("test() {\n"
7515                "  ([]() -> {\n"
7516                "    int b = 32;\n"
7517                "    return 3;\n"
7518                "  })\n"
7519                "      .foo()\n"
7520                "      .bar();\n"
7521                "}");
7522   verifyFormat("test() {\n"
7523                "  ([]() -> {\n"
7524                "    int b = 32;\n"
7525                "    return 3;\n"
7526                "  })\n"
7527                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7528                "           \"bbbb\");\n"
7529                "}",
7530                getLLVMStyleWithColumns(30));
7531 }
7532 
7533 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7534   verifyFormat(
7535       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7536       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7537   verifyFormat(
7538       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7539       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7540 
7541   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7542                "    ccccccccccccccccccccccccc) {\n}");
7543   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7544                "    ccccccccccccccccccccccccc) {\n}");
7545 
7546   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7547                "    ccccccccccccccccccccccccc) {\n}");
7548   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7549                "    ccccccccccccccccccccccccc) {\n}");
7550 
7551   verifyFormat(
7552       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7553       "    ccccccccccccccccccccccccc) {\n}");
7554   verifyFormat(
7555       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7556       "    ccccccccccccccccccccccccc) {\n}");
7557 
7558   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7559                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7560                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7561                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7562   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7563                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7564                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7565                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7566 
7567   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7568                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7569                "    aaaaaaaaaaaaaaa != aa) {\n}");
7570   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7571                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7572                "    aaaaaaaaaaaaaaa != aa) {\n}");
7573 }
7574 
7575 TEST_F(FormatTest, BreaksAfterAssignments) {
7576   verifyFormat(
7577       "unsigned Cost =\n"
7578       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7579       "                        SI->getPointerAddressSpaceee());\n");
7580   verifyFormat(
7581       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7582       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7583 
7584   verifyFormat(
7585       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7586       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7587   verifyFormat("unsigned OriginalStartColumn =\n"
7588                "    SourceMgr.getSpellingColumnNumber(\n"
7589                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7590                "    1;");
7591 }
7592 
7593 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7594   FormatStyle Style = getLLVMStyle();
7595   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7596                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7597                Style);
7598 
7599   Style.PenaltyBreakAssignment = 20;
7600   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7601                "                                 cccccccccccccccccccccccccc;",
7602                Style);
7603 }
7604 
7605 TEST_F(FormatTest, AlignsAfterAssignments) {
7606   verifyFormat(
7607       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7608       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7609   verifyFormat(
7610       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7611       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7612   verifyFormat(
7613       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7614       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7615   verifyFormat(
7616       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7617       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7618   verifyFormat(
7619       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7620       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7621       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7622 }
7623 
7624 TEST_F(FormatTest, AlignsAfterReturn) {
7625   verifyFormat(
7626       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7627       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7628   verifyFormat(
7629       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7630       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7631   verifyFormat(
7632       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7633       "       aaaaaaaaaaaaaaaaaaaaaa();");
7634   verifyFormat(
7635       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7636       "        aaaaaaaaaaaaaaaaaaaaaa());");
7637   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7638                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7639   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7640                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7641                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7642   verifyFormat("return\n"
7643                "    // true if code is one of a or b.\n"
7644                "    code == a || code == b;");
7645 }
7646 
7647 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7648   verifyFormat(
7649       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7650       "                                                aaaaaaaaa aaaaaaa) {}");
7651   verifyFormat(
7652       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7653       "                                               aaaaaaaaaaa aaaaaaaaa);");
7654   verifyFormat(
7655       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7656       "                                             aaaaaaaaaaaaaaaaaaaaa));");
7657   FormatStyle Style = getLLVMStyle();
7658   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7659   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7660                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
7661                Style);
7662   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7663                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
7664                Style);
7665   verifyFormat("SomeLongVariableName->someFunction(\n"
7666                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
7667                Style);
7668   verifyFormat(
7669       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7670       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7671       Style);
7672   verifyFormat(
7673       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7674       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7675       Style);
7676   verifyFormat(
7677       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7678       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7679       Style);
7680 
7681   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
7682                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
7683                "        b));",
7684                Style);
7685 
7686   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7687   Style.BinPackArguments = false;
7688   Style.BinPackParameters = false;
7689   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7690                "    aaaaaaaaaaa aaaaaaaa,\n"
7691                "    aaaaaaaaa aaaaaaa,\n"
7692                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7693                Style);
7694   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7695                "    aaaaaaaaaaa aaaaaaaaa,\n"
7696                "    aaaaaaaaaaa aaaaaaaaa,\n"
7697                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7698                Style);
7699   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
7700                "    aaaaaaaaaaaaaaa,\n"
7701                "    aaaaaaaaaaaaaaaaaaaaa,\n"
7702                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7703                Style);
7704   verifyFormat(
7705       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
7706       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7707       Style);
7708   verifyFormat(
7709       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
7710       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7711       Style);
7712   verifyFormat(
7713       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7714       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7715       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
7716       "    aaaaaaaaaaaaaaaa);",
7717       Style);
7718   verifyFormat(
7719       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7720       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7721       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
7722       "    aaaaaaaaaaaaaaaa);",
7723       Style);
7724 }
7725 
7726 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
7727   FormatStyle Style = getLLVMStyleWithColumns(40);
7728   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7729                "          bbbbbbbbbbbbbbbbbbbbbb);",
7730                Style);
7731   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7732   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7733   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7734                "          bbbbbbbbbbbbbbbbbbbbbb);",
7735                Style);
7736   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7737   Style.AlignOperands = FormatStyle::OAS_Align;
7738   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7739                "          bbbbbbbbbbbbbbbbbbbbbb);",
7740                Style);
7741   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7742   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7743   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7744                "    bbbbbbbbbbbbbbbbbbbbbb);",
7745                Style);
7746 }
7747 
7748 TEST_F(FormatTest, BreaksConditionalExpressions) {
7749   verifyFormat(
7750       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7751       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7752       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7753   verifyFormat(
7754       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7755       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7756       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7757   verifyFormat(
7758       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7759       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7760   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
7761                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7762                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7763   verifyFormat(
7764       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
7765       "                                                    : aaaaaaaaaaaaa);");
7766   verifyFormat(
7767       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7768       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7769       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7770       "                   aaaaaaaaaaaaa);");
7771   verifyFormat(
7772       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7773       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7774       "                   aaaaaaaaaaaaa);");
7775   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7776                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7777                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7778                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7779                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7780   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7781                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7782                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7783                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7784                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7785                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7786                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7787   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7788                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7789                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7790                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7791                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7792   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7793                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7794                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7795   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7796                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7797                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7798                "        : aaaaaaaaaaaaaaaa;");
7799   verifyFormat(
7800       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7801       "    ? aaaaaaaaaaaaaaa\n"
7802       "    : aaaaaaaaaaaaaaa;");
7803   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7804                "          aaaaaaaaa\n"
7805                "      ? b\n"
7806                "      : c);");
7807   verifyFormat("return aaaa == bbbb\n"
7808                "           // comment\n"
7809                "           ? aaaa\n"
7810                "           : bbbb;");
7811   verifyFormat("unsigned Indent =\n"
7812                "    format(TheLine.First,\n"
7813                "           IndentForLevel[TheLine.Level] >= 0\n"
7814                "               ? IndentForLevel[TheLine.Level]\n"
7815                "               : TheLine * 2,\n"
7816                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
7817                getLLVMStyleWithColumns(60));
7818   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7819                "                  ? aaaaaaaaaaaaaaa\n"
7820                "                  : bbbbbbbbbbbbbbb //\n"
7821                "                        ? ccccccccccccccc\n"
7822                "                        : ddddddddddddddd;");
7823   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7824                "                  ? aaaaaaaaaaaaaaa\n"
7825                "                  : (bbbbbbbbbbbbbbb //\n"
7826                "                         ? ccccccccccccccc\n"
7827                "                         : ddddddddddddddd);");
7828   verifyFormat(
7829       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7830       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7831       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
7832       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
7833       "                                      : aaaaaaaaaa;");
7834   verifyFormat(
7835       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7836       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
7837       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7838 
7839   FormatStyle NoBinPacking = getLLVMStyle();
7840   NoBinPacking.BinPackArguments = false;
7841   verifyFormat(
7842       "void f() {\n"
7843       "  g(aaa,\n"
7844       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7845       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7846       "        ? aaaaaaaaaaaaaaa\n"
7847       "        : aaaaaaaaaaaaaaa);\n"
7848       "}",
7849       NoBinPacking);
7850   verifyFormat(
7851       "void f() {\n"
7852       "  g(aaa,\n"
7853       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7854       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7855       "        ?: aaaaaaaaaaaaaaa);\n"
7856       "}",
7857       NoBinPacking);
7858 
7859   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
7860                "             // comment.\n"
7861                "             ccccccccccccccccccccccccccccccccccccccc\n"
7862                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7863                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
7864 
7865   // Assignments in conditional expressions. Apparently not uncommon :-(.
7866   verifyFormat("return a != b\n"
7867                "           // comment\n"
7868                "           ? a = b\n"
7869                "           : a = b;");
7870   verifyFormat("return a != b\n"
7871                "           // comment\n"
7872                "           ? a = a != b\n"
7873                "                     // comment\n"
7874                "                     ? a = b\n"
7875                "                     : a\n"
7876                "           : a;\n");
7877   verifyFormat("return a != b\n"
7878                "           // comment\n"
7879                "           ? a\n"
7880                "           : a = a != b\n"
7881                "                     // comment\n"
7882                "                     ? a = b\n"
7883                "                     : a;");
7884 
7885   // Chained conditionals
7886   FormatStyle Style = getLLVMStyleWithColumns(70);
7887   Style.AlignOperands = FormatStyle::OAS_Align;
7888   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7889                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7890                "                        : 3333333333333333;",
7891                Style);
7892   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7893                "       : bbbbbbbbbb     ? 2222222222222222\n"
7894                "                        : 3333333333333333;",
7895                Style);
7896   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
7897                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
7898                "                          : 3333333333333333;",
7899                Style);
7900   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7901                "       : bbbbbbbbbbbbbb ? 222222\n"
7902                "                        : 333333;",
7903                Style);
7904   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7905                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7906                "       : cccccccccccccc ? 3333333333333333\n"
7907                "                        : 4444444444444444;",
7908                Style);
7909   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
7910                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7911                "                        : 3333333333333333;",
7912                Style);
7913   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7914                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7915                "                        : (aaa ? bbb : ccc);",
7916                Style);
7917   verifyFormat(
7918       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7919       "                                             : cccccccccccccccccc)\n"
7920       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7921       "                        : 3333333333333333;",
7922       Style);
7923   verifyFormat(
7924       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7925       "                                             : cccccccccccccccccc)\n"
7926       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7927       "                        : 3333333333333333;",
7928       Style);
7929   verifyFormat(
7930       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7931       "                                             : dddddddddddddddddd)\n"
7932       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7933       "                        : 3333333333333333;",
7934       Style);
7935   verifyFormat(
7936       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7937       "                                             : dddddddddddddddddd)\n"
7938       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7939       "                        : 3333333333333333;",
7940       Style);
7941   verifyFormat(
7942       "return aaaaaaaaa        ? 1111111111111111\n"
7943       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7944       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7945       "                                             : dddddddddddddddddd)\n",
7946       Style);
7947   verifyFormat(
7948       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7949       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7950       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7951       "                                             : cccccccccccccccccc);",
7952       Style);
7953   verifyFormat(
7954       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7955       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7956       "                                             : eeeeeeeeeeeeeeeeee)\n"
7957       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7958       "                        : 3333333333333333;",
7959       Style);
7960   verifyFormat(
7961       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
7962       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7963       "                                             : eeeeeeeeeeeeeeeeee)\n"
7964       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7965       "                        : 3333333333333333;",
7966       Style);
7967   verifyFormat(
7968       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7969       "                           : cccccccccccc    ? dddddddddddddddddd\n"
7970       "                                             : eeeeeeeeeeeeeeeeee)\n"
7971       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7972       "                        : 3333333333333333;",
7973       Style);
7974   verifyFormat(
7975       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7976       "                                             : cccccccccccccccccc\n"
7977       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7978       "                        : 3333333333333333;",
7979       Style);
7980   verifyFormat(
7981       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7982       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
7983       "                                             : eeeeeeeeeeeeeeeeee\n"
7984       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7985       "                        : 3333333333333333;",
7986       Style);
7987   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
7988                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
7989                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
7990                "                                   : eeeeeeeeeeeeeeeeee)\n"
7991                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7992                "                             : 3333333333333333;",
7993                Style);
7994   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
7995                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7996                "             : cccccccccccccccc ? dddddddddddddddddd\n"
7997                "                                : eeeeeeeeeeeeeeeeee\n"
7998                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7999                "                                 : 3333333333333333;",
8000                Style);
8001 
8002   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8003   Style.BreakBeforeTernaryOperators = false;
8004   // FIXME: Aligning the question marks is weird given DontAlign.
8005   // Consider disabling this alignment in this case. Also check whether this
8006   // will render the adjustment from https://reviews.llvm.org/D82199
8007   // unnecessary.
8008   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
8009                "    bbbb                ? cccccccccccccccccc :\n"
8010                "                          ddddd;\n",
8011                Style);
8012 
8013   EXPECT_EQ(
8014       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8015       "    /*\n"
8016       "     */\n"
8017       "    function() {\n"
8018       "      try {\n"
8019       "        return JJJJJJJJJJJJJJ(\n"
8020       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8021       "      }\n"
8022       "    } :\n"
8023       "    function() {};",
8024       format(
8025           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8026           "     /*\n"
8027           "      */\n"
8028           "     function() {\n"
8029           "      try {\n"
8030           "        return JJJJJJJJJJJJJJ(\n"
8031           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8032           "      }\n"
8033           "    } :\n"
8034           "    function() {};",
8035           getGoogleStyle(FormatStyle::LK_JavaScript)));
8036 }
8037 
8038 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
8039   FormatStyle Style = getLLVMStyleWithColumns(70);
8040   Style.BreakBeforeTernaryOperators = false;
8041   verifyFormat(
8042       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8043       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8044       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8045       Style);
8046   verifyFormat(
8047       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8048       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8049       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8050       Style);
8051   verifyFormat(
8052       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8053       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8054       Style);
8055   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
8056                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8057                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8058                Style);
8059   verifyFormat(
8060       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
8061       "                                                      aaaaaaaaaaaaa);",
8062       Style);
8063   verifyFormat(
8064       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8065       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8066       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8067       "                   aaaaaaaaaaaaa);",
8068       Style);
8069   verifyFormat(
8070       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8071       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8072       "                   aaaaaaaaaaaaa);",
8073       Style);
8074   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8075                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8076                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8077                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8078                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8079                Style);
8080   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8081                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8082                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8083                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8084                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8085                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8086                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8087                Style);
8088   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8089                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
8090                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8091                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8092                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8093                Style);
8094   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8095                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8096                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8097                Style);
8098   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8099                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8100                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8101                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8102                Style);
8103   verifyFormat(
8104       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8105       "    aaaaaaaaaaaaaaa :\n"
8106       "    aaaaaaaaaaaaaaa;",
8107       Style);
8108   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8109                "          aaaaaaaaa ?\n"
8110                "      b :\n"
8111                "      c);",
8112                Style);
8113   verifyFormat("unsigned Indent =\n"
8114                "    format(TheLine.First,\n"
8115                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
8116                "               IndentForLevel[TheLine.Level] :\n"
8117                "               TheLine * 2,\n"
8118                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8119                Style);
8120   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8121                "                  aaaaaaaaaaaaaaa :\n"
8122                "                  bbbbbbbbbbbbbbb ? //\n"
8123                "                      ccccccccccccccc :\n"
8124                "                      ddddddddddddddd;",
8125                Style);
8126   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8127                "                  aaaaaaaaaaaaaaa :\n"
8128                "                  (bbbbbbbbbbbbbbb ? //\n"
8129                "                       ccccccccccccccc :\n"
8130                "                       ddddddddddddddd);",
8131                Style);
8132   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8133                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
8134                "            ccccccccccccccccccccccccccc;",
8135                Style);
8136   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8137                "           aaaaa :\n"
8138                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
8139                Style);
8140 
8141   // Chained conditionals
8142   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8143                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8144                "                          3333333333333333;",
8145                Style);
8146   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8147                "       bbbbbbbbbb       ? 2222222222222222 :\n"
8148                "                          3333333333333333;",
8149                Style);
8150   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
8151                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8152                "                          3333333333333333;",
8153                Style);
8154   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8155                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
8156                "                          333333;",
8157                Style);
8158   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8159                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8160                "       cccccccccccccccc ? 3333333333333333 :\n"
8161                "                          4444444444444444;",
8162                Style);
8163   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
8164                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8165                "                          3333333333333333;",
8166                Style);
8167   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8168                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8169                "                          (aaa ? bbb : ccc);",
8170                Style);
8171   verifyFormat(
8172       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8173       "                                               cccccccccccccccccc) :\n"
8174       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8175       "                          3333333333333333;",
8176       Style);
8177   verifyFormat(
8178       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8179       "                                               cccccccccccccccccc) :\n"
8180       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8181       "                          3333333333333333;",
8182       Style);
8183   verifyFormat(
8184       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8185       "                                               dddddddddddddddddd) :\n"
8186       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8187       "                          3333333333333333;",
8188       Style);
8189   verifyFormat(
8190       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8191       "                                               dddddddddddddddddd) :\n"
8192       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8193       "                          3333333333333333;",
8194       Style);
8195   verifyFormat(
8196       "return aaaaaaaaa        ? 1111111111111111 :\n"
8197       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8198       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8199       "                                               dddddddddddddddddd)\n",
8200       Style);
8201   verifyFormat(
8202       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8203       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8204       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8205       "                                               cccccccccccccccccc);",
8206       Style);
8207   verifyFormat(
8208       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8209       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8210       "                                               eeeeeeeeeeeeeeeeee) :\n"
8211       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8212       "                          3333333333333333;",
8213       Style);
8214   verifyFormat(
8215       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8216       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8217       "                                               eeeeeeeeeeeeeeeeee) :\n"
8218       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8219       "                          3333333333333333;",
8220       Style);
8221   verifyFormat(
8222       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8223       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8224       "                                               eeeeeeeeeeeeeeeeee) :\n"
8225       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8226       "                          3333333333333333;",
8227       Style);
8228   verifyFormat(
8229       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8230       "                                               cccccccccccccccccc :\n"
8231       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8232       "                          3333333333333333;",
8233       Style);
8234   verifyFormat(
8235       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8236       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8237       "                                               eeeeeeeeeeeeeeeeee :\n"
8238       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8239       "                          3333333333333333;",
8240       Style);
8241   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8242                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8243                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8244                "                                 eeeeeeeeeeeeeeeeee) :\n"
8245                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8246                "                               3333333333333333;",
8247                Style);
8248   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8249                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8250                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8251                "                                  eeeeeeeeeeeeeeeeee :\n"
8252                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8253                "                               3333333333333333;",
8254                Style);
8255 }
8256 
8257 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8258   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8259                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8260   verifyFormat("bool a = true, b = false;");
8261 
8262   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8263                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8264                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8265                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8266   verifyFormat(
8267       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8268       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8269       "     d = e && f;");
8270   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8271                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8272   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8273                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8274   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8275                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8276 
8277   FormatStyle Style = getGoogleStyle();
8278   Style.PointerAlignment = FormatStyle::PAS_Left;
8279   Style.DerivePointerAlignment = false;
8280   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8281                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8282                "    *b = bbbbbbbbbbbbbbbbbbb;",
8283                Style);
8284   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8285                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8286                Style);
8287   verifyFormat("vector<int*> a, b;", Style);
8288   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8289 }
8290 
8291 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8292   verifyFormat("arr[foo ? bar : baz];");
8293   verifyFormat("f()[foo ? bar : baz];");
8294   verifyFormat("(a + b)[foo ? bar : baz];");
8295   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8296 }
8297 
8298 TEST_F(FormatTest, AlignsStringLiterals) {
8299   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8300                "                                      \"short literal\");");
8301   verifyFormat(
8302       "looooooooooooooooooooooooongFunction(\n"
8303       "    \"short literal\"\n"
8304       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8305   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8306                "             \" string literals\",\n"
8307                "             and, other, parameters);");
8308   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8309             "      \"5678\";",
8310             format("fun + \"1243\" /* comment */\n"
8311                    "    \"5678\";",
8312                    getLLVMStyleWithColumns(28)));
8313   EXPECT_EQ(
8314       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8315       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8316       "         \"aaaaaaaaaaaaaaaa\";",
8317       format("aaaaaa ="
8318              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8319              "aaaaaaaaaaaaaaaaaaaaa\" "
8320              "\"aaaaaaaaaaaaaaaa\";"));
8321   verifyFormat("a = a + \"a\"\n"
8322                "        \"a\"\n"
8323                "        \"a\";");
8324   verifyFormat("f(\"a\", \"b\"\n"
8325                "       \"c\");");
8326 
8327   verifyFormat(
8328       "#define LL_FORMAT \"ll\"\n"
8329       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8330       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8331 
8332   verifyFormat("#define A(X)          \\\n"
8333                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8334                "  \"ccccc\"",
8335                getLLVMStyleWithColumns(23));
8336   verifyFormat("#define A \"def\"\n"
8337                "f(\"abc\" A \"ghi\"\n"
8338                "  \"jkl\");");
8339 
8340   verifyFormat("f(L\"a\"\n"
8341                "  L\"b\");");
8342   verifyFormat("#define A(X)            \\\n"
8343                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8344                "  L\"ccccc\"",
8345                getLLVMStyleWithColumns(25));
8346 
8347   verifyFormat("f(@\"a\"\n"
8348                "  @\"b\");");
8349   verifyFormat("NSString s = @\"a\"\n"
8350                "             @\"b\"\n"
8351                "             @\"c\";");
8352   verifyFormat("NSString s = @\"a\"\n"
8353                "              \"b\"\n"
8354                "              \"c\";");
8355 }
8356 
8357 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8358   FormatStyle Style = getLLVMStyle();
8359   // No declarations or definitions should be moved to own line.
8360   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8361   verifyFormat("class A {\n"
8362                "  int f() { return 1; }\n"
8363                "  int g();\n"
8364                "};\n"
8365                "int f() { return 1; }\n"
8366                "int g();\n",
8367                Style);
8368 
8369   // All declarations and definitions should have the return type moved to its
8370   // own line.
8371   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8372   Style.TypenameMacros = {"LIST"};
8373   verifyFormat("SomeType\n"
8374                "funcdecl(LIST(uint64_t));",
8375                Style);
8376   verifyFormat("class E {\n"
8377                "  int\n"
8378                "  f() {\n"
8379                "    return 1;\n"
8380                "  }\n"
8381                "  int\n"
8382                "  g();\n"
8383                "};\n"
8384                "int\n"
8385                "f() {\n"
8386                "  return 1;\n"
8387                "}\n"
8388                "int\n"
8389                "g();\n",
8390                Style);
8391 
8392   // Top-level definitions, and no kinds of declarations should have the
8393   // return type moved to its own line.
8394   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8395   verifyFormat("class B {\n"
8396                "  int f() { return 1; }\n"
8397                "  int g();\n"
8398                "};\n"
8399                "int\n"
8400                "f() {\n"
8401                "  return 1;\n"
8402                "}\n"
8403                "int g();\n",
8404                Style);
8405 
8406   // Top-level definitions and declarations should have the return type moved
8407   // to its own line.
8408   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8409   verifyFormat("class C {\n"
8410                "  int f() { return 1; }\n"
8411                "  int g();\n"
8412                "};\n"
8413                "int\n"
8414                "f() {\n"
8415                "  return 1;\n"
8416                "}\n"
8417                "int\n"
8418                "g();\n",
8419                Style);
8420 
8421   // All definitions should have the return type moved to its own line, but no
8422   // kinds of declarations.
8423   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8424   verifyFormat("class D {\n"
8425                "  int\n"
8426                "  f() {\n"
8427                "    return 1;\n"
8428                "  }\n"
8429                "  int g();\n"
8430                "};\n"
8431                "int\n"
8432                "f() {\n"
8433                "  return 1;\n"
8434                "}\n"
8435                "int g();\n",
8436                Style);
8437   verifyFormat("const char *\n"
8438                "f(void) {\n" // Break here.
8439                "  return \"\";\n"
8440                "}\n"
8441                "const char *bar(void);\n", // No break here.
8442                Style);
8443   verifyFormat("template <class T>\n"
8444                "T *\n"
8445                "f(T &c) {\n" // Break here.
8446                "  return NULL;\n"
8447                "}\n"
8448                "template <class T> T *f(T &c);\n", // No break here.
8449                Style);
8450   verifyFormat("class C {\n"
8451                "  int\n"
8452                "  operator+() {\n"
8453                "    return 1;\n"
8454                "  }\n"
8455                "  int\n"
8456                "  operator()() {\n"
8457                "    return 1;\n"
8458                "  }\n"
8459                "};\n",
8460                Style);
8461   verifyFormat("void\n"
8462                "A::operator()() {}\n"
8463                "void\n"
8464                "A::operator>>() {}\n"
8465                "void\n"
8466                "A::operator+() {}\n"
8467                "void\n"
8468                "A::operator*() {}\n"
8469                "void\n"
8470                "A::operator->() {}\n"
8471                "void\n"
8472                "A::operator void *() {}\n"
8473                "void\n"
8474                "A::operator void &() {}\n"
8475                "void\n"
8476                "A::operator void &&() {}\n"
8477                "void\n"
8478                "A::operator char *() {}\n"
8479                "void\n"
8480                "A::operator[]() {}\n"
8481                "void\n"
8482                "A::operator!() {}\n"
8483                "void\n"
8484                "A::operator**() {}\n"
8485                "void\n"
8486                "A::operator<Foo> *() {}\n"
8487                "void\n"
8488                "A::operator<Foo> **() {}\n"
8489                "void\n"
8490                "A::operator<Foo> &() {}\n"
8491                "void\n"
8492                "A::operator void **() {}\n",
8493                Style);
8494   verifyFormat("constexpr auto\n"
8495                "operator()() const -> reference {}\n"
8496                "constexpr auto\n"
8497                "operator>>() const -> reference {}\n"
8498                "constexpr auto\n"
8499                "operator+() const -> reference {}\n"
8500                "constexpr auto\n"
8501                "operator*() const -> reference {}\n"
8502                "constexpr auto\n"
8503                "operator->() const -> reference {}\n"
8504                "constexpr auto\n"
8505                "operator++() const -> reference {}\n"
8506                "constexpr auto\n"
8507                "operator void *() const -> reference {}\n"
8508                "constexpr auto\n"
8509                "operator void **() const -> reference {}\n"
8510                "constexpr auto\n"
8511                "operator void *() const -> reference {}\n"
8512                "constexpr auto\n"
8513                "operator void &() const -> reference {}\n"
8514                "constexpr auto\n"
8515                "operator void &&() const -> reference {}\n"
8516                "constexpr auto\n"
8517                "operator char *() const -> reference {}\n"
8518                "constexpr auto\n"
8519                "operator!() const -> reference {}\n"
8520                "constexpr auto\n"
8521                "operator[]() const -> reference {}\n",
8522                Style);
8523   verifyFormat("void *operator new(std::size_t s);", // No break here.
8524                Style);
8525   verifyFormat("void *\n"
8526                "operator new(std::size_t s) {}",
8527                Style);
8528   verifyFormat("void *\n"
8529                "operator delete[](void *ptr) {}",
8530                Style);
8531   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8532   verifyFormat("const char *\n"
8533                "f(void)\n" // Break here.
8534                "{\n"
8535                "  return \"\";\n"
8536                "}\n"
8537                "const char *bar(void);\n", // No break here.
8538                Style);
8539   verifyFormat("template <class T>\n"
8540                "T *\n"     // Problem here: no line break
8541                "f(T &c)\n" // Break here.
8542                "{\n"
8543                "  return NULL;\n"
8544                "}\n"
8545                "template <class T> T *f(T &c);\n", // No break here.
8546                Style);
8547   verifyFormat("int\n"
8548                "foo(A<bool> a)\n"
8549                "{\n"
8550                "  return a;\n"
8551                "}\n",
8552                Style);
8553   verifyFormat("int\n"
8554                "foo(A<8> a)\n"
8555                "{\n"
8556                "  return a;\n"
8557                "}\n",
8558                Style);
8559   verifyFormat("int\n"
8560                "foo(A<B<bool>, 8> a)\n"
8561                "{\n"
8562                "  return a;\n"
8563                "}\n",
8564                Style);
8565   verifyFormat("int\n"
8566                "foo(A<B<8>, bool> a)\n"
8567                "{\n"
8568                "  return a;\n"
8569                "}\n",
8570                Style);
8571   verifyFormat("int\n"
8572                "foo(A<B<bool>, bool> a)\n"
8573                "{\n"
8574                "  return a;\n"
8575                "}\n",
8576                Style);
8577   verifyFormat("int\n"
8578                "foo(A<B<8>, 8> a)\n"
8579                "{\n"
8580                "  return a;\n"
8581                "}\n",
8582                Style);
8583 
8584   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8585   Style.BraceWrapping.AfterFunction = true;
8586   verifyFormat("int f(i);\n" // No break here.
8587                "int\n"       // Break here.
8588                "f(i)\n"
8589                "{\n"
8590                "  return i + 1;\n"
8591                "}\n"
8592                "int\n" // Break here.
8593                "f(i)\n"
8594                "{\n"
8595                "  return i + 1;\n"
8596                "};",
8597                Style);
8598   verifyFormat("int f(a, b, c);\n" // No break here.
8599                "int\n"             // Break here.
8600                "f(a, b, c)\n"      // Break here.
8601                "short a, b;\n"
8602                "float c;\n"
8603                "{\n"
8604                "  return a + b < c;\n"
8605                "}\n"
8606                "int\n"        // Break here.
8607                "f(a, b, c)\n" // Break here.
8608                "short a, b;\n"
8609                "float c;\n"
8610                "{\n"
8611                "  return a + b < c;\n"
8612                "};",
8613                Style);
8614   verifyFormat("byte *\n" // Break here.
8615                "f(a)\n"   // Break here.
8616                "byte a[];\n"
8617                "{\n"
8618                "  return a;\n"
8619                "}",
8620                Style);
8621   verifyFormat("bool f(int a, int) override;\n"
8622                "Bar g(int a, Bar) final;\n"
8623                "Bar h(a, Bar) final;",
8624                Style);
8625   verifyFormat("int\n"
8626                "f(a)",
8627                Style);
8628   verifyFormat("bool\n"
8629                "f(size_t = 0, bool b = false)\n"
8630                "{\n"
8631                "  return !b;\n"
8632                "}",
8633                Style);
8634 
8635   // The return breaking style doesn't affect:
8636   // * function and object definitions with attribute-like macros
8637   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8638                "    ABSL_GUARDED_BY(mutex) = {};",
8639                getGoogleStyleWithColumns(40));
8640   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8641                "    ABSL_GUARDED_BY(mutex);  // comment",
8642                getGoogleStyleWithColumns(40));
8643   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8644                "    ABSL_GUARDED_BY(mutex1)\n"
8645                "        ABSL_GUARDED_BY(mutex2);",
8646                getGoogleStyleWithColumns(40));
8647   verifyFormat("Tttttt f(int a, int b)\n"
8648                "    ABSL_GUARDED_BY(mutex1)\n"
8649                "        ABSL_GUARDED_BY(mutex2);",
8650                getGoogleStyleWithColumns(40));
8651   // * typedefs
8652   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
8653 
8654   Style = getGNUStyle();
8655 
8656   // Test for comments at the end of function declarations.
8657   verifyFormat("void\n"
8658                "foo (int a, /*abc*/ int b) // def\n"
8659                "{\n"
8660                "}\n",
8661                Style);
8662 
8663   verifyFormat("void\n"
8664                "foo (int a, /* abc */ int b) /* def */\n"
8665                "{\n"
8666                "}\n",
8667                Style);
8668 
8669   // Definitions that should not break after return type
8670   verifyFormat("void foo (int a, int b); // def\n", Style);
8671   verifyFormat("void foo (int a, int b); /* def */\n", Style);
8672   verifyFormat("void foo (int a, int b);\n", Style);
8673 }
8674 
8675 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
8676   FormatStyle NoBreak = getLLVMStyle();
8677   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
8678   FormatStyle Break = getLLVMStyle();
8679   Break.AlwaysBreakBeforeMultilineStrings = true;
8680   verifyFormat("aaaa = \"bbbb\"\n"
8681                "       \"cccc\";",
8682                NoBreak);
8683   verifyFormat("aaaa =\n"
8684                "    \"bbbb\"\n"
8685                "    \"cccc\";",
8686                Break);
8687   verifyFormat("aaaa(\"bbbb\"\n"
8688                "     \"cccc\");",
8689                NoBreak);
8690   verifyFormat("aaaa(\n"
8691                "    \"bbbb\"\n"
8692                "    \"cccc\");",
8693                Break);
8694   verifyFormat("aaaa(qqq, \"bbbb\"\n"
8695                "          \"cccc\");",
8696                NoBreak);
8697   verifyFormat("aaaa(qqq,\n"
8698                "     \"bbbb\"\n"
8699                "     \"cccc\");",
8700                Break);
8701   verifyFormat("aaaa(qqq,\n"
8702                "     L\"bbbb\"\n"
8703                "     L\"cccc\");",
8704                Break);
8705   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
8706                "                      \"bbbb\"));",
8707                Break);
8708   verifyFormat("string s = someFunction(\n"
8709                "    \"abc\"\n"
8710                "    \"abc\");",
8711                Break);
8712 
8713   // As we break before unary operators, breaking right after them is bad.
8714   verifyFormat("string foo = abc ? \"x\"\n"
8715                "                   \"blah blah blah blah blah blah\"\n"
8716                "                 : \"y\";",
8717                Break);
8718 
8719   // Don't break if there is no column gain.
8720   verifyFormat("f(\"aaaa\"\n"
8721                "  \"bbbb\");",
8722                Break);
8723 
8724   // Treat literals with escaped newlines like multi-line string literals.
8725   EXPECT_EQ("x = \"a\\\n"
8726             "b\\\n"
8727             "c\";",
8728             format("x = \"a\\\n"
8729                    "b\\\n"
8730                    "c\";",
8731                    NoBreak));
8732   EXPECT_EQ("xxxx =\n"
8733             "    \"a\\\n"
8734             "b\\\n"
8735             "c\";",
8736             format("xxxx = \"a\\\n"
8737                    "b\\\n"
8738                    "c\";",
8739                    Break));
8740 
8741   EXPECT_EQ("NSString *const kString =\n"
8742             "    @\"aaaa\"\n"
8743             "    @\"bbbb\";",
8744             format("NSString *const kString = @\"aaaa\"\n"
8745                    "@\"bbbb\";",
8746                    Break));
8747 
8748   Break.ColumnLimit = 0;
8749   verifyFormat("const char *hello = \"hello llvm\";", Break);
8750 }
8751 
8752 TEST_F(FormatTest, AlignsPipes) {
8753   verifyFormat(
8754       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8755       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8756       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8757   verifyFormat(
8758       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
8759       "                     << aaaaaaaaaaaaaaaaaaaa;");
8760   verifyFormat(
8761       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8762       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8763   verifyFormat(
8764       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
8765       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8766   verifyFormat(
8767       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
8768       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
8769       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
8770   verifyFormat(
8771       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8772       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8773       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8774   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8775                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8776                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8777                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8778   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
8779                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
8780   verifyFormat(
8781       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8782       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8783   verifyFormat(
8784       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
8785       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
8786 
8787   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
8788                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
8789   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8790                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8791                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
8792                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
8793   verifyFormat("LOG_IF(aaa == //\n"
8794                "       bbb)\n"
8795                "    << a << b;");
8796 
8797   // But sometimes, breaking before the first "<<" is desirable.
8798   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8799                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
8800   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
8801                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8802                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8803   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
8804                "    << BEF << IsTemplate << Description << E->getType();");
8805   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8806                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8807                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8808   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8809                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8810                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8811                "    << aaa;");
8812 
8813   verifyFormat(
8814       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8815       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8816 
8817   // Incomplete string literal.
8818   EXPECT_EQ("llvm::errs() << \"\n"
8819             "             << a;",
8820             format("llvm::errs() << \"\n<<a;"));
8821 
8822   verifyFormat("void f() {\n"
8823                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
8824                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
8825                "}");
8826 
8827   // Handle 'endl'.
8828   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
8829                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8830   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8831 
8832   // Handle '\n'.
8833   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
8834                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8835   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
8836                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
8837   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
8838                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
8839   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8840 }
8841 
8842 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
8843   verifyFormat("return out << \"somepacket = {\\n\"\n"
8844                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
8845                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
8846                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
8847                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
8848                "           << \"}\";");
8849 
8850   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8851                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8852                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
8853   verifyFormat(
8854       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
8855       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
8856       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
8857       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
8858       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
8859   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
8860                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8861   verifyFormat(
8862       "void f() {\n"
8863       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
8864       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
8865       "}");
8866 
8867   // Breaking before the first "<<" is generally not desirable.
8868   verifyFormat(
8869       "llvm::errs()\n"
8870       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8871       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8872       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8873       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8874       getLLVMStyleWithColumns(70));
8875   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8876                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8877                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8878                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8879                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8880                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8881                getLLVMStyleWithColumns(70));
8882 
8883   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8884                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8885                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
8886   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8887                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8888                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
8889   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
8890                "           (aaaa + aaaa);",
8891                getLLVMStyleWithColumns(40));
8892   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
8893                "                  (aaaaaaa + aaaaa));",
8894                getLLVMStyleWithColumns(40));
8895   verifyFormat(
8896       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
8897       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
8898       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
8899 }
8900 
8901 TEST_F(FormatTest, UnderstandsEquals) {
8902   verifyFormat(
8903       "aaaaaaaaaaaaaaaaa =\n"
8904       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8905   verifyFormat(
8906       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8907       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8908   verifyFormat(
8909       "if (a) {\n"
8910       "  f();\n"
8911       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8912       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
8913       "}");
8914 
8915   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8916                "        100000000 + 10000000) {\n}");
8917 }
8918 
8919 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
8920   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8921                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
8922 
8923   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8924                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
8925 
8926   verifyFormat(
8927       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
8928       "                                                          Parameter2);");
8929 
8930   verifyFormat(
8931       "ShortObject->shortFunction(\n"
8932       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
8933       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
8934 
8935   verifyFormat("loooooooooooooongFunction(\n"
8936                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
8937 
8938   verifyFormat(
8939       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
8940       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
8941 
8942   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8943                "    .WillRepeatedly(Return(SomeValue));");
8944   verifyFormat("void f() {\n"
8945                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8946                "      .Times(2)\n"
8947                "      .WillRepeatedly(Return(SomeValue));\n"
8948                "}");
8949   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
8950                "    ccccccccccccccccccccccc);");
8951   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8952                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8953                "          .aaaaa(aaaaa),\n"
8954                "      aaaaaaaaaaaaaaaaaaaaa);");
8955   verifyFormat("void f() {\n"
8956                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8957                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
8958                "}");
8959   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8960                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8961                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8962                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8963                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
8964   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8965                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8966                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8967                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
8968                "}");
8969 
8970   // Here, it is not necessary to wrap at "." or "->".
8971   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
8972                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8973   verifyFormat(
8974       "aaaaaaaaaaa->aaaaaaaaa(\n"
8975       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8976       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
8977 
8978   verifyFormat(
8979       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8980       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
8981   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
8982                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8983   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
8984                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8985 
8986   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8987                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8988                "    .a();");
8989 
8990   FormatStyle NoBinPacking = getLLVMStyle();
8991   NoBinPacking.BinPackParameters = false;
8992   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8993                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8994                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
8995                "                         aaaaaaaaaaaaaaaaaaa,\n"
8996                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8997                NoBinPacking);
8998 
8999   // If there is a subsequent call, change to hanging indentation.
9000   verifyFormat(
9001       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9002       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
9003       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9004   verifyFormat(
9005       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9006       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
9007   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9008                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9009                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9010   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9011                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9012                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9013 }
9014 
9015 TEST_F(FormatTest, WrapsTemplateDeclarations) {
9016   verifyFormat("template <typename T>\n"
9017                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9018   verifyFormat("template <typename T>\n"
9019                "// T should be one of {A, B}.\n"
9020                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9021   verifyFormat(
9022       "template <typename T>\n"
9023       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
9024   verifyFormat("template <typename T>\n"
9025                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
9026                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
9027   verifyFormat(
9028       "template <typename T>\n"
9029       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
9030       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
9031   verifyFormat(
9032       "template <typename T>\n"
9033       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
9034       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
9035       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9036   verifyFormat("template <typename T>\n"
9037                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9038                "    int aaaaaaaaaaaaaaaaaaaaaa);");
9039   verifyFormat(
9040       "template <typename T1, typename T2 = char, typename T3 = char,\n"
9041       "          typename T4 = char>\n"
9042       "void f();");
9043   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
9044                "          template <typename> class cccccccccccccccccccccc,\n"
9045                "          typename ddddddddddddd>\n"
9046                "class C {};");
9047   verifyFormat(
9048       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
9049       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9050 
9051   verifyFormat("void f() {\n"
9052                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
9053                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
9054                "}");
9055 
9056   verifyFormat("template <typename T> class C {};");
9057   verifyFormat("template <typename T> void f();");
9058   verifyFormat("template <typename T> void f() {}");
9059   verifyFormat(
9060       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9061       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9062       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
9063       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9064       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9065       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
9066       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
9067       getLLVMStyleWithColumns(72));
9068   EXPECT_EQ("static_cast<A< //\n"
9069             "    B> *>(\n"
9070             "\n"
9071             ");",
9072             format("static_cast<A<//\n"
9073                    "    B>*>(\n"
9074                    "\n"
9075                    "    );"));
9076   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9077                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
9078 
9079   FormatStyle AlwaysBreak = getLLVMStyle();
9080   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9081   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
9082   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
9083   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
9084   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9085                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9086                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
9087   verifyFormat("template <template <typename> class Fooooooo,\n"
9088                "          template <typename> class Baaaaaaar>\n"
9089                "struct C {};",
9090                AlwaysBreak);
9091   verifyFormat("template <typename T> // T can be A, B or C.\n"
9092                "struct C {};",
9093                AlwaysBreak);
9094   verifyFormat("template <enum E> class A {\n"
9095                "public:\n"
9096                "  E *f();\n"
9097                "};");
9098 
9099   FormatStyle NeverBreak = getLLVMStyle();
9100   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
9101   verifyFormat("template <typename T> class C {};", NeverBreak);
9102   verifyFormat("template <typename T> void f();", NeverBreak);
9103   verifyFormat("template <typename T> void f() {}", NeverBreak);
9104   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9105                "bbbbbbbbbbbbbbbbbbbb) {}",
9106                NeverBreak);
9107   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9108                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9109                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
9110                NeverBreak);
9111   verifyFormat("template <template <typename> class Fooooooo,\n"
9112                "          template <typename> class Baaaaaaar>\n"
9113                "struct C {};",
9114                NeverBreak);
9115   verifyFormat("template <typename T> // T can be A, B or C.\n"
9116                "struct C {};",
9117                NeverBreak);
9118   verifyFormat("template <enum E> class A {\n"
9119                "public:\n"
9120                "  E *f();\n"
9121                "};",
9122                NeverBreak);
9123   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
9124   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9125                "bbbbbbbbbbbbbbbbbbbb) {}",
9126                NeverBreak);
9127 }
9128 
9129 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
9130   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9131   Style.ColumnLimit = 60;
9132   EXPECT_EQ("// Baseline - no comments.\n"
9133             "template <\n"
9134             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9135             "void f() {}",
9136             format("// Baseline - no comments.\n"
9137                    "template <\n"
9138                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9139                    "void f() {}",
9140                    Style));
9141 
9142   EXPECT_EQ("template <\n"
9143             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9144             "void f() {}",
9145             format("template <\n"
9146                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9147                    "void f() {}",
9148                    Style));
9149 
9150   EXPECT_EQ(
9151       "template <\n"
9152       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
9153       "void f() {}",
9154       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
9155              "void f() {}",
9156              Style));
9157 
9158   EXPECT_EQ(
9159       "template <\n"
9160       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9161       "                                               // multiline\n"
9162       "void f() {}",
9163       format("template <\n"
9164              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9165              "                                              // multiline\n"
9166              "void f() {}",
9167              Style));
9168 
9169   EXPECT_EQ(
9170       "template <typename aaaaaaaaaa<\n"
9171       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
9172       "void f() {}",
9173       format(
9174           "template <\n"
9175           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
9176           "void f() {}",
9177           Style));
9178 }
9179 
9180 TEST_F(FormatTest, WrapsTemplateParameters) {
9181   FormatStyle Style = getLLVMStyle();
9182   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9183   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9184   verifyFormat(
9185       "template <typename... a> struct q {};\n"
9186       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9187       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9188       "    y;",
9189       Style);
9190   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9191   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9192   verifyFormat(
9193       "template <typename... a> struct r {};\n"
9194       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9195       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9196       "    y;",
9197       Style);
9198   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9199   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9200   verifyFormat("template <typename... a> struct s {};\n"
9201                "extern s<\n"
9202                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9203                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9204                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9205                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9206                "    y;",
9207                Style);
9208   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9209   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9210   verifyFormat("template <typename... a> struct t {};\n"
9211                "extern t<\n"
9212                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9213                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9214                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9215                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9216                "    y;",
9217                Style);
9218 }
9219 
9220 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9221   verifyFormat(
9222       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9223       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9224   verifyFormat(
9225       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9226       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9227       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9228 
9229   // FIXME: Should we have the extra indent after the second break?
9230   verifyFormat(
9231       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9232       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9233       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9234 
9235   verifyFormat(
9236       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9237       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9238 
9239   // Breaking at nested name specifiers is generally not desirable.
9240   verifyFormat(
9241       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9242       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9243 
9244   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9245                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9246                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9247                "                   aaaaaaaaaaaaaaaaaaaaa);",
9248                getLLVMStyleWithColumns(74));
9249 
9250   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9251                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9252                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9253 }
9254 
9255 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9256   verifyFormat("A<int> a;");
9257   verifyFormat("A<A<A<int>>> a;");
9258   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9259   verifyFormat("bool x = a < 1 || 2 > a;");
9260   verifyFormat("bool x = 5 < f<int>();");
9261   verifyFormat("bool x = f<int>() > 5;");
9262   verifyFormat("bool x = 5 < a<int>::x;");
9263   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9264   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9265 
9266   verifyGoogleFormat("A<A<int>> a;");
9267   verifyGoogleFormat("A<A<A<int>>> a;");
9268   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9269   verifyGoogleFormat("A<A<int> > a;");
9270   verifyGoogleFormat("A<A<A<int> > > a;");
9271   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9272   verifyGoogleFormat("A<::A<int>> a;");
9273   verifyGoogleFormat("A<::A> a;");
9274   verifyGoogleFormat("A< ::A> a;");
9275   verifyGoogleFormat("A< ::A<int> > a;");
9276   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9277   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9278   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9279   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9280   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9281             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9282 
9283   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9284 
9285   // template closer followed by a token that starts with > or =
9286   verifyFormat("bool b = a<1> > 1;");
9287   verifyFormat("bool b = a<1> >= 1;");
9288   verifyFormat("int i = a<1> >> 1;");
9289   FormatStyle Style = getLLVMStyle();
9290   Style.SpaceBeforeAssignmentOperators = false;
9291   verifyFormat("bool b= a<1> == 1;", Style);
9292   verifyFormat("a<int> = 1;", Style);
9293   verifyFormat("a<int> >>= 1;", Style);
9294 
9295   verifyFormat("test < a | b >> c;");
9296   verifyFormat("test<test<a | b>> c;");
9297   verifyFormat("test >> a >> b;");
9298   verifyFormat("test << a >> b;");
9299 
9300   verifyFormat("f<int>();");
9301   verifyFormat("template <typename T> void f() {}");
9302   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9303   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9304                "sizeof(char)>::type>;");
9305   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9306   verifyFormat("f(a.operator()<A>());");
9307   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9308                "      .template operator()<A>());",
9309                getLLVMStyleWithColumns(35));
9310 
9311   // Not template parameters.
9312   verifyFormat("return a < b && c > d;");
9313   verifyFormat("void f() {\n"
9314                "  while (a < b && c > d) {\n"
9315                "  }\n"
9316                "}");
9317   verifyFormat("template <typename... Types>\n"
9318                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9319 
9320   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9321                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9322                getLLVMStyleWithColumns(60));
9323   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9324   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9325   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9326   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9327 }
9328 
9329 TEST_F(FormatTest, UnderstandsShiftOperators) {
9330   verifyFormat("if (i < x >> 1)");
9331   verifyFormat("while (i < x >> 1)");
9332   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9333   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9334   verifyFormat(
9335       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9336   verifyFormat("Foo.call<Bar<Function>>()");
9337   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9338   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9339                "++i, v = v >> 1)");
9340   verifyFormat("if (w<u<v<x>>, 1>::t)");
9341 }
9342 
9343 TEST_F(FormatTest, BitshiftOperatorWidth) {
9344   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9345             "                   bar */",
9346             format("int    a=1<<2;  /* foo\n"
9347                    "                   bar */"));
9348 
9349   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9350             "                     bar */",
9351             format("int  b  =256>>1 ;  /* foo\n"
9352                    "                      bar */"));
9353 }
9354 
9355 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9356   verifyFormat("COMPARE(a, ==, b);");
9357   verifyFormat("auto s = sizeof...(Ts) - 1;");
9358 }
9359 
9360 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9361   verifyFormat("int A::*x;");
9362   verifyFormat("int (S::*func)(void *);");
9363   verifyFormat("void f() { int (S::*func)(void *); }");
9364   verifyFormat("typedef bool *(Class::*Member)() const;");
9365   verifyFormat("void f() {\n"
9366                "  (a->*f)();\n"
9367                "  a->*x;\n"
9368                "  (a.*f)();\n"
9369                "  ((*a).*f)();\n"
9370                "  a.*x;\n"
9371                "}");
9372   verifyFormat("void f() {\n"
9373                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9374                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9375                "}");
9376   verifyFormat(
9377       "(aaaaaaaaaa->*bbbbbbb)(\n"
9378       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9379   FormatStyle Style = getLLVMStyle();
9380   Style.PointerAlignment = FormatStyle::PAS_Left;
9381   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9382 }
9383 
9384 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9385   verifyFormat("int a = -2;");
9386   verifyFormat("f(-1, -2, -3);");
9387   verifyFormat("a[-1] = 5;");
9388   verifyFormat("int a = 5 + -2;");
9389   verifyFormat("if (i == -1) {\n}");
9390   verifyFormat("if (i != -1) {\n}");
9391   verifyFormat("if (i > -1) {\n}");
9392   verifyFormat("if (i < -1) {\n}");
9393   verifyFormat("++(a->f());");
9394   verifyFormat("--(a->f());");
9395   verifyFormat("(a->f())++;");
9396   verifyFormat("a[42]++;");
9397   verifyFormat("if (!(a->f())) {\n}");
9398   verifyFormat("if (!+i) {\n}");
9399   verifyFormat("~&a;");
9400 
9401   verifyFormat("a-- > b;");
9402   verifyFormat("b ? -a : c;");
9403   verifyFormat("n * sizeof char16;");
9404   verifyFormat("n * alignof char16;", getGoogleStyle());
9405   verifyFormat("sizeof(char);");
9406   verifyFormat("alignof(char);", getGoogleStyle());
9407 
9408   verifyFormat("return -1;");
9409   verifyFormat("throw -1;");
9410   verifyFormat("switch (a) {\n"
9411                "case -1:\n"
9412                "  break;\n"
9413                "}");
9414   verifyFormat("#define X -1");
9415   verifyFormat("#define X -kConstant");
9416 
9417   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9418   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9419 
9420   verifyFormat("int a = /* confusing comment */ -1;");
9421   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9422   verifyFormat("int a = i /* confusing comment */++;");
9423 
9424   verifyFormat("co_yield -1;");
9425   verifyFormat("co_return -1;");
9426 
9427   // Check that * is not treated as a binary operator when we set
9428   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9429   FormatStyle PASLeftStyle = getLLVMStyle();
9430   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9431   verifyFormat("co_return *a;", PASLeftStyle);
9432   verifyFormat("co_await *a;", PASLeftStyle);
9433   verifyFormat("co_yield *a", PASLeftStyle);
9434   verifyFormat("return *a;", PASLeftStyle);
9435 }
9436 
9437 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9438   verifyFormat("if (!aaaaaaaaaa( // break\n"
9439                "        aaaaa)) {\n"
9440                "}");
9441   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9442                "    aaaaa));");
9443   verifyFormat("*aaa = aaaaaaa( // break\n"
9444                "    bbbbbb);");
9445 }
9446 
9447 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9448   verifyFormat("bool operator<();");
9449   verifyFormat("bool operator>();");
9450   verifyFormat("bool operator=();");
9451   verifyFormat("bool operator==();");
9452   verifyFormat("bool operator!=();");
9453   verifyFormat("int operator+();");
9454   verifyFormat("int operator++();");
9455   verifyFormat("int operator++(int) volatile noexcept;");
9456   verifyFormat("bool operator,();");
9457   verifyFormat("bool operator();");
9458   verifyFormat("bool operator()();");
9459   verifyFormat("bool operator[]();");
9460   verifyFormat("operator bool();");
9461   verifyFormat("operator int();");
9462   verifyFormat("operator void *();");
9463   verifyFormat("operator SomeType<int>();");
9464   verifyFormat("operator SomeType<int, int>();");
9465   verifyFormat("operator SomeType<SomeType<int>>();");
9466   verifyFormat("operator< <>();");
9467   verifyFormat("operator<< <>();");
9468   verifyFormat("< <>");
9469 
9470   verifyFormat("void *operator new(std::size_t size);");
9471   verifyFormat("void *operator new[](std::size_t size);");
9472   verifyFormat("void operator delete(void *ptr);");
9473   verifyFormat("void operator delete[](void *ptr);");
9474   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9475                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9476   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9477                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9478 
9479   verifyFormat(
9480       "ostream &operator<<(ostream &OutputStream,\n"
9481       "                    SomeReallyLongType WithSomeReallyLongValue);");
9482   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9483                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9484                "  return left.group < right.group;\n"
9485                "}");
9486   verifyFormat("SomeType &operator=(const SomeType &S);");
9487   verifyFormat("f.template operator()<int>();");
9488 
9489   verifyGoogleFormat("operator void*();");
9490   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9491   verifyGoogleFormat("operator ::A();");
9492 
9493   verifyFormat("using A::operator+;");
9494   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9495                "int i;");
9496 
9497   // Calling an operator as a member function.
9498   verifyFormat("void f() { a.operator*(); }");
9499   verifyFormat("void f() { a.operator*(b & b); }");
9500   verifyFormat("void f() { a->operator&(a * b); }");
9501   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9502   // TODO: Calling an operator as a non-member function is hard to distinguish.
9503   // https://llvm.org/PR50629
9504   // verifyFormat("void f() { operator*(a & a); }");
9505   // verifyFormat("void f() { operator&(a, b * b); }");
9506 
9507   verifyFormat("::operator delete(foo);");
9508   verifyFormat("::operator new(n * sizeof(foo));");
9509   verifyFormat("foo() { ::operator delete(foo); }");
9510   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9511 }
9512 
9513 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9514   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9515   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9516   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9517   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9518   verifyFormat("Deleted &operator=(const Deleted &) &;");
9519   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9520   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9521   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9522   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9523   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9524   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9525   verifyFormat("void Fn(T const &) const &;");
9526   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9527   verifyFormat("template <typename T>\n"
9528                "void F(T) && = delete;",
9529                getGoogleStyle());
9530 
9531   FormatStyle AlignLeft = getLLVMStyle();
9532   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9533   verifyFormat("void A::b() && {}", AlignLeft);
9534   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9535   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9536                AlignLeft);
9537   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9538   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9539   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9540   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9541   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9542   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9543   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9544   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9545 
9546   FormatStyle Spaces = getLLVMStyle();
9547   Spaces.SpacesInCStyleCastParentheses = true;
9548   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9549   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9550   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9551   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9552 
9553   Spaces.SpacesInCStyleCastParentheses = false;
9554   Spaces.SpacesInParentheses = true;
9555   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9556   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9557                Spaces);
9558   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9559   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9560 
9561   FormatStyle BreakTemplate = getLLVMStyle();
9562   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9563 
9564   verifyFormat("struct f {\n"
9565                "  template <class T>\n"
9566                "  int &foo(const std::string &str) &noexcept {}\n"
9567                "};",
9568                BreakTemplate);
9569 
9570   verifyFormat("struct f {\n"
9571                "  template <class T>\n"
9572                "  int &foo(const std::string &str) &&noexcept {}\n"
9573                "};",
9574                BreakTemplate);
9575 
9576   verifyFormat("struct f {\n"
9577                "  template <class T>\n"
9578                "  int &foo(const std::string &str) const &noexcept {}\n"
9579                "};",
9580                BreakTemplate);
9581 
9582   verifyFormat("struct f {\n"
9583                "  template <class T>\n"
9584                "  int &foo(const std::string &str) const &noexcept {}\n"
9585                "};",
9586                BreakTemplate);
9587 
9588   verifyFormat("struct f {\n"
9589                "  template <class T>\n"
9590                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
9591                "};",
9592                BreakTemplate);
9593 
9594   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
9595   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
9596       FormatStyle::BTDS_Yes;
9597   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
9598 
9599   verifyFormat("struct f {\n"
9600                "  template <class T>\n"
9601                "  int& foo(const std::string& str) & noexcept {}\n"
9602                "};",
9603                AlignLeftBreakTemplate);
9604 
9605   verifyFormat("struct f {\n"
9606                "  template <class T>\n"
9607                "  int& foo(const std::string& str) && noexcept {}\n"
9608                "};",
9609                AlignLeftBreakTemplate);
9610 
9611   verifyFormat("struct f {\n"
9612                "  template <class T>\n"
9613                "  int& foo(const std::string& str) const& noexcept {}\n"
9614                "};",
9615                AlignLeftBreakTemplate);
9616 
9617   verifyFormat("struct f {\n"
9618                "  template <class T>\n"
9619                "  int& foo(const std::string& str) const&& noexcept {}\n"
9620                "};",
9621                AlignLeftBreakTemplate);
9622 
9623   verifyFormat("struct f {\n"
9624                "  template <class T>\n"
9625                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
9626                "};",
9627                AlignLeftBreakTemplate);
9628 
9629   // The `&` in `Type&` should not be confused with a trailing `&` of
9630   // DEPRECATED(reason) member function.
9631   verifyFormat("struct f {\n"
9632                "  template <class T>\n"
9633                "  DEPRECATED(reason)\n"
9634                "  Type &foo(arguments) {}\n"
9635                "};",
9636                BreakTemplate);
9637 
9638   verifyFormat("struct f {\n"
9639                "  template <class T>\n"
9640                "  DEPRECATED(reason)\n"
9641                "  Type& foo(arguments) {}\n"
9642                "};",
9643                AlignLeftBreakTemplate);
9644 
9645   verifyFormat("void (*foopt)(int) = &func;");
9646 }
9647 
9648 TEST_F(FormatTest, UnderstandsNewAndDelete) {
9649   verifyFormat("void f() {\n"
9650                "  A *a = new A;\n"
9651                "  A *a = new (placement) A;\n"
9652                "  delete a;\n"
9653                "  delete (A *)a;\n"
9654                "}");
9655   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9656                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9657   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9658                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9659                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9660   verifyFormat("delete[] h->p;");
9661 
9662   verifyFormat("void operator delete(void *foo) ATTRIB;");
9663   verifyFormat("void operator new(void *foo) ATTRIB;");
9664   verifyFormat("void operator delete[](void *foo) ATTRIB;");
9665   verifyFormat("void operator delete(void *ptr) noexcept;");
9666 }
9667 
9668 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
9669   verifyFormat("int *f(int *a) {}");
9670   verifyFormat("int main(int argc, char **argv) {}");
9671   verifyFormat("Test::Test(int b) : a(b * b) {}");
9672   verifyIndependentOfContext("f(a, *a);");
9673   verifyFormat("void g() { f(*a); }");
9674   verifyIndependentOfContext("int a = b * 10;");
9675   verifyIndependentOfContext("int a = 10 * b;");
9676   verifyIndependentOfContext("int a = b * c;");
9677   verifyIndependentOfContext("int a += b * c;");
9678   verifyIndependentOfContext("int a -= b * c;");
9679   verifyIndependentOfContext("int a *= b * c;");
9680   verifyIndependentOfContext("int a /= b * c;");
9681   verifyIndependentOfContext("int a = *b;");
9682   verifyIndependentOfContext("int a = *b * c;");
9683   verifyIndependentOfContext("int a = b * *c;");
9684   verifyIndependentOfContext("int a = b * (10);");
9685   verifyIndependentOfContext("S << b * (10);");
9686   verifyIndependentOfContext("return 10 * b;");
9687   verifyIndependentOfContext("return *b * *c;");
9688   verifyIndependentOfContext("return a & ~b;");
9689   verifyIndependentOfContext("f(b ? *c : *d);");
9690   verifyIndependentOfContext("int a = b ? *c : *d;");
9691   verifyIndependentOfContext("*b = a;");
9692   verifyIndependentOfContext("a * ~b;");
9693   verifyIndependentOfContext("a * !b;");
9694   verifyIndependentOfContext("a * +b;");
9695   verifyIndependentOfContext("a * -b;");
9696   verifyIndependentOfContext("a * ++b;");
9697   verifyIndependentOfContext("a * --b;");
9698   verifyIndependentOfContext("a[4] * b;");
9699   verifyIndependentOfContext("a[a * a] = 1;");
9700   verifyIndependentOfContext("f() * b;");
9701   verifyIndependentOfContext("a * [self dostuff];");
9702   verifyIndependentOfContext("int x = a * (a + b);");
9703   verifyIndependentOfContext("(a *)(a + b);");
9704   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
9705   verifyIndependentOfContext("int *pa = (int *)&a;");
9706   verifyIndependentOfContext("return sizeof(int **);");
9707   verifyIndependentOfContext("return sizeof(int ******);");
9708   verifyIndependentOfContext("return (int **&)a;");
9709   verifyIndependentOfContext("f((*PointerToArray)[10]);");
9710   verifyFormat("void f(Type (*parameter)[10]) {}");
9711   verifyFormat("void f(Type (&parameter)[10]) {}");
9712   verifyGoogleFormat("return sizeof(int**);");
9713   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
9714   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
9715   verifyFormat("auto a = [](int **&, int ***) {};");
9716   verifyFormat("auto PointerBinding = [](const char *S) {};");
9717   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
9718   verifyFormat("[](const decltype(*a) &value) {}");
9719   verifyFormat("[](const typeof(*a) &value) {}");
9720   verifyFormat("[](const _Atomic(a *) &value) {}");
9721   verifyFormat("[](const __underlying_type(a) &value) {}");
9722   verifyFormat("decltype(a * b) F();");
9723   verifyFormat("typeof(a * b) F();");
9724   verifyFormat("#define MACRO() [](A *a) { return 1; }");
9725   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
9726   verifyIndependentOfContext("typedef void (*f)(int *a);");
9727   verifyIndependentOfContext("int i{a * b};");
9728   verifyIndependentOfContext("aaa && aaa->f();");
9729   verifyIndependentOfContext("int x = ~*p;");
9730   verifyFormat("Constructor() : a(a), area(width * height) {}");
9731   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
9732   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
9733   verifyFormat("void f() { f(a, c * d); }");
9734   verifyFormat("void f() { f(new a(), c * d); }");
9735   verifyFormat("void f(const MyOverride &override);");
9736   verifyFormat("void f(const MyFinal &final);");
9737   verifyIndependentOfContext("bool a = f() && override.f();");
9738   verifyIndependentOfContext("bool a = f() && final.f();");
9739 
9740   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
9741 
9742   verifyIndependentOfContext("A<int *> a;");
9743   verifyIndependentOfContext("A<int **> a;");
9744   verifyIndependentOfContext("A<int *, int *> a;");
9745   verifyIndependentOfContext("A<int *[]> a;");
9746   verifyIndependentOfContext(
9747       "const char *const p = reinterpret_cast<const char *const>(q);");
9748   verifyIndependentOfContext("A<int **, int **> a;");
9749   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
9750   verifyFormat("for (char **a = b; *a; ++a) {\n}");
9751   verifyFormat("for (; a && b;) {\n}");
9752   verifyFormat("bool foo = true && [] { return false; }();");
9753 
9754   verifyFormat(
9755       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9756       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9757 
9758   verifyGoogleFormat("int const* a = &b;");
9759   verifyGoogleFormat("**outparam = 1;");
9760   verifyGoogleFormat("*outparam = a * b;");
9761   verifyGoogleFormat("int main(int argc, char** argv) {}");
9762   verifyGoogleFormat("A<int*> a;");
9763   verifyGoogleFormat("A<int**> a;");
9764   verifyGoogleFormat("A<int*, int*> a;");
9765   verifyGoogleFormat("A<int**, int**> a;");
9766   verifyGoogleFormat("f(b ? *c : *d);");
9767   verifyGoogleFormat("int a = b ? *c : *d;");
9768   verifyGoogleFormat("Type* t = **x;");
9769   verifyGoogleFormat("Type* t = *++*x;");
9770   verifyGoogleFormat("*++*x;");
9771   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
9772   verifyGoogleFormat("Type* t = x++ * y;");
9773   verifyGoogleFormat(
9774       "const char* const p = reinterpret_cast<const char* const>(q);");
9775   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
9776   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
9777   verifyGoogleFormat("template <typename T>\n"
9778                      "void f(int i = 0, SomeType** temps = NULL);");
9779 
9780   FormatStyle Left = getLLVMStyle();
9781   Left.PointerAlignment = FormatStyle::PAS_Left;
9782   verifyFormat("x = *a(x) = *a(y);", Left);
9783   verifyFormat("for (;; *a = b) {\n}", Left);
9784   verifyFormat("return *this += 1;", Left);
9785   verifyFormat("throw *x;", Left);
9786   verifyFormat("delete *x;", Left);
9787   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
9788   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
9789   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
9790   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
9791   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
9792   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
9793   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
9794   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
9795   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
9796 
9797   verifyIndependentOfContext("a = *(x + y);");
9798   verifyIndependentOfContext("a = &(x + y);");
9799   verifyIndependentOfContext("*(x + y).call();");
9800   verifyIndependentOfContext("&(x + y)->call();");
9801   verifyFormat("void f() { &(*I).first; }");
9802 
9803   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
9804   verifyFormat("f(* /* confusing comment */ foo);");
9805   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
9806   verifyFormat("void foo(int * // this is the first paramters\n"
9807                "         ,\n"
9808                "         int second);");
9809   verifyFormat("double term = a * // first\n"
9810                "              b;");
9811   verifyFormat(
9812       "int *MyValues = {\n"
9813       "    *A, // Operator detection might be confused by the '{'\n"
9814       "    *BB // Operator detection might be confused by previous comment\n"
9815       "};");
9816 
9817   verifyIndependentOfContext("if (int *a = &b)");
9818   verifyIndependentOfContext("if (int &a = *b)");
9819   verifyIndependentOfContext("if (a & b[i])");
9820   verifyIndependentOfContext("if constexpr (a & b[i])");
9821   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
9822   verifyIndependentOfContext("if (a * (b * c))");
9823   verifyIndependentOfContext("if constexpr (a * (b * c))");
9824   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
9825   verifyIndependentOfContext("if (a::b::c::d & b[i])");
9826   verifyIndependentOfContext("if (*b[i])");
9827   verifyIndependentOfContext("if (int *a = (&b))");
9828   verifyIndependentOfContext("while (int *a = &b)");
9829   verifyIndependentOfContext("while (a * (b * c))");
9830   verifyIndependentOfContext("size = sizeof *a;");
9831   verifyIndependentOfContext("if (a && (b = c))");
9832   verifyFormat("void f() {\n"
9833                "  for (const int &v : Values) {\n"
9834                "  }\n"
9835                "}");
9836   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
9837   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
9838   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
9839 
9840   verifyFormat("#define A (!a * b)");
9841   verifyFormat("#define MACRO     \\\n"
9842                "  int *i = a * b; \\\n"
9843                "  void f(a *b);",
9844                getLLVMStyleWithColumns(19));
9845 
9846   verifyIndependentOfContext("A = new SomeType *[Length];");
9847   verifyIndependentOfContext("A = new SomeType *[Length]();");
9848   verifyIndependentOfContext("T **t = new T *;");
9849   verifyIndependentOfContext("T **t = new T *();");
9850   verifyGoogleFormat("A = new SomeType*[Length]();");
9851   verifyGoogleFormat("A = new SomeType*[Length];");
9852   verifyGoogleFormat("T** t = new T*;");
9853   verifyGoogleFormat("T** t = new T*();");
9854 
9855   verifyFormat("STATIC_ASSERT((a & b) == 0);");
9856   verifyFormat("STATIC_ASSERT(0 == (a & b));");
9857   verifyFormat("template <bool a, bool b> "
9858                "typename t::if<x && y>::type f() {}");
9859   verifyFormat("template <int *y> f() {}");
9860   verifyFormat("vector<int *> v;");
9861   verifyFormat("vector<int *const> v;");
9862   verifyFormat("vector<int *const **const *> v;");
9863   verifyFormat("vector<int *volatile> v;");
9864   verifyFormat("vector<a *_Nonnull> v;");
9865   verifyFormat("vector<a *_Nullable> v;");
9866   verifyFormat("vector<a *_Null_unspecified> v;");
9867   verifyFormat("vector<a *__ptr32> v;");
9868   verifyFormat("vector<a *__ptr64> v;");
9869   verifyFormat("vector<a *__capability> v;");
9870   FormatStyle TypeMacros = getLLVMStyle();
9871   TypeMacros.TypenameMacros = {"LIST"};
9872   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
9873   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
9874   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
9875   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
9876   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
9877 
9878   FormatStyle CustomQualifier = getLLVMStyle();
9879   // Add identifiers that should not be parsed as a qualifier by default.
9880   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9881   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
9882   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
9883   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
9884   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
9885   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
9886   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
9887   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
9888   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
9889   verifyFormat("vector<a * _NotAQualifier> v;");
9890   verifyFormat("vector<a * __not_a_qualifier> v;");
9891   verifyFormat("vector<a * b> v;");
9892   verifyFormat("foo<b && false>();");
9893   verifyFormat("foo<b & 1>();");
9894   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
9895   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
9896   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
9897   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
9898   verifyFormat(
9899       "template <class T, class = typename std::enable_if<\n"
9900       "                       std::is_integral<T>::value &&\n"
9901       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
9902       "void F();",
9903       getLLVMStyleWithColumns(70));
9904   verifyFormat("template <class T,\n"
9905                "          class = typename std::enable_if<\n"
9906                "              std::is_integral<T>::value &&\n"
9907                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
9908                "          class U>\n"
9909                "void F();",
9910                getLLVMStyleWithColumns(70));
9911   verifyFormat(
9912       "template <class T,\n"
9913       "          class = typename ::std::enable_if<\n"
9914       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
9915       "void F();",
9916       getGoogleStyleWithColumns(68));
9917 
9918   verifyIndependentOfContext("MACRO(int *i);");
9919   verifyIndependentOfContext("MACRO(auto *a);");
9920   verifyIndependentOfContext("MACRO(const A *a);");
9921   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
9922   verifyIndependentOfContext("MACRO(decltype(A) *a);");
9923   verifyIndependentOfContext("MACRO(typeof(A) *a);");
9924   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
9925   verifyIndependentOfContext("MACRO(A *const a);");
9926   verifyIndependentOfContext("MACRO(A *restrict a);");
9927   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
9928   verifyIndependentOfContext("MACRO(A *__restrict a);");
9929   verifyIndependentOfContext("MACRO(A *volatile a);");
9930   verifyIndependentOfContext("MACRO(A *__volatile a);");
9931   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
9932   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
9933   verifyIndependentOfContext("MACRO(A *_Nullable a);");
9934   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
9935   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
9936   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
9937   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
9938   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
9939   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
9940   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
9941   verifyIndependentOfContext("MACRO(A *__capability);");
9942   verifyIndependentOfContext("MACRO(A &__capability);");
9943   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
9944   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
9945   // If we add __my_qualifier to AttributeMacros it should always be parsed as
9946   // a type declaration:
9947   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
9948   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
9949   // Also check that TypenameMacros prevents parsing it as multiplication:
9950   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
9951   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
9952 
9953   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
9954   verifyFormat("void f() { f(float{1}, a * a); }");
9955   verifyFormat("void f() { f(float(1), a * a); }");
9956 
9957   verifyFormat("f((void (*)(int))g);");
9958   verifyFormat("f((void (&)(int))g);");
9959   verifyFormat("f((void (^)(int))g);");
9960 
9961   // FIXME: Is there a way to make this work?
9962   // verifyIndependentOfContext("MACRO(A *a);");
9963   verifyFormat("MACRO(A &B);");
9964   verifyFormat("MACRO(A *B);");
9965   verifyFormat("void f() { MACRO(A * B); }");
9966   verifyFormat("void f() { MACRO(A & B); }");
9967 
9968   // This lambda was mis-formatted after D88956 (treating it as a binop):
9969   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
9970   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
9971   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
9972   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
9973 
9974   verifyFormat("DatumHandle const *operator->() const { return input_; }");
9975   verifyFormat("return options != nullptr && operator==(*options);");
9976 
9977   EXPECT_EQ("#define OP(x)                                    \\\n"
9978             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
9979             "    return s << a.DebugString();                 \\\n"
9980             "  }",
9981             format("#define OP(x) \\\n"
9982                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
9983                    "    return s << a.DebugString(); \\\n"
9984                    "  }",
9985                    getLLVMStyleWithColumns(50)));
9986 
9987   // FIXME: We cannot handle this case yet; we might be able to figure out that
9988   // foo<x> d > v; doesn't make sense.
9989   verifyFormat("foo<a<b && c> d> v;");
9990 
9991   FormatStyle PointerMiddle = getLLVMStyle();
9992   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9993   verifyFormat("delete *x;", PointerMiddle);
9994   verifyFormat("int * x;", PointerMiddle);
9995   verifyFormat("int *[] x;", PointerMiddle);
9996   verifyFormat("template <int * y> f() {}", PointerMiddle);
9997   verifyFormat("int * f(int * a) {}", PointerMiddle);
9998   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
9999   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10000   verifyFormat("A<int *> a;", PointerMiddle);
10001   verifyFormat("A<int **> a;", PointerMiddle);
10002   verifyFormat("A<int *, int *> a;", PointerMiddle);
10003   verifyFormat("A<int *[]> a;", PointerMiddle);
10004   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10005   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10006   verifyFormat("T ** t = new T *;", PointerMiddle);
10007 
10008   // Member function reference qualifiers aren't binary operators.
10009   verifyFormat("string // break\n"
10010                "operator()() & {}");
10011   verifyFormat("string // break\n"
10012                "operator()() && {}");
10013   verifyGoogleFormat("template <typename T>\n"
10014                      "auto x() & -> int {}");
10015 
10016   // Should be binary operators when used as an argument expression (overloaded
10017   // operator invoked as a member function).
10018   verifyFormat("void f() { a.operator()(a * a); }");
10019   verifyFormat("void f() { a->operator()(a & a); }");
10020   verifyFormat("void f() { a.operator()(*a & *a); }");
10021   verifyFormat("void f() { a->operator()(*a * *a); }");
10022 
10023   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10024   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10025 }
10026 
10027 TEST_F(FormatTest, UnderstandsAttributes) {
10028   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10029   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10030                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10031   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10032   FormatStyle AfterType = getLLVMStyle();
10033   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10034   verifyFormat("__attribute__((nodebug)) void\n"
10035                "foo() {}\n",
10036                AfterType);
10037   verifyFormat("__unused void\n"
10038                "foo() {}",
10039                AfterType);
10040 
10041   FormatStyle CustomAttrs = getLLVMStyle();
10042   CustomAttrs.AttributeMacros.push_back("__unused");
10043   CustomAttrs.AttributeMacros.push_back("__attr1");
10044   CustomAttrs.AttributeMacros.push_back("__attr2");
10045   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10046   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10047   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10048   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10049   // Check that it is parsed as a multiplication without AttributeMacros and
10050   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10051   verifyFormat("vector<SomeType * __attr1> v;");
10052   verifyFormat("vector<SomeType __attr1 *> v;");
10053   verifyFormat("vector<SomeType __attr1 *const> v;");
10054   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10055   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10056   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10057   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10058   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10059   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10060   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10061   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10062 
10063   // Check that these are not parsed as function declarations:
10064   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10065   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10066   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10067   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10068   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10069   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10070   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10071   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10072   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10073   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10074 }
10075 
10076 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10077   // Check that qualifiers on pointers don't break parsing of casts.
10078   verifyFormat("x = (foo *const)*v;");
10079   verifyFormat("x = (foo *volatile)*v;");
10080   verifyFormat("x = (foo *restrict)*v;");
10081   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10082   verifyFormat("x = (foo *_Nonnull)*v;");
10083   verifyFormat("x = (foo *_Nullable)*v;");
10084   verifyFormat("x = (foo *_Null_unspecified)*v;");
10085   verifyFormat("x = (foo *_Nonnull)*v;");
10086   verifyFormat("x = (foo *[[clang::attr]])*v;");
10087   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10088   verifyFormat("x = (foo *__ptr32)*v;");
10089   verifyFormat("x = (foo *__ptr64)*v;");
10090   verifyFormat("x = (foo *__capability)*v;");
10091 
10092   // Check that we handle multiple trailing qualifiers and skip them all to
10093   // determine that the expression is a cast to a pointer type.
10094   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10095   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10096   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10097   StringRef AllQualifiers =
10098       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10099       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10100   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10101   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10102 
10103   // Also check that address-of is not parsed as a binary bitwise-and:
10104   verifyFormat("x = (foo *const)&v;");
10105   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10106   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10107 
10108   // Check custom qualifiers:
10109   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10110   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10111   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10112   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10113   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10114                CustomQualifier);
10115   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10116                CustomQualifier);
10117 
10118   // Check that unknown identifiers result in binary operator parsing:
10119   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10120   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10121 }
10122 
10123 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10124   verifyFormat("SomeType s [[unused]] (InitValue);");
10125   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10126   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10127   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10128   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10129   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10130                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10131   verifyFormat("[[nodiscard]] bool f() { return false; }");
10132   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10133   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10134   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10135   verifyFormat("[[nodiscard]] ::qualified_type f();");
10136 
10137   // Make sure we do not mistake attributes for array subscripts.
10138   verifyFormat("int a() {}\n"
10139                "[[unused]] int b() {}\n");
10140   verifyFormat("NSArray *arr;\n"
10141                "arr[[Foo() bar]];");
10142 
10143   // On the other hand, we still need to correctly find array subscripts.
10144   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10145 
10146   // Make sure that we do not mistake Objective-C method inside array literals
10147   // as attributes, even if those method names are also keywords.
10148   verifyFormat("@[ [foo bar] ];");
10149   verifyFormat("@[ [NSArray class] ];");
10150   verifyFormat("@[ [foo enum] ];");
10151 
10152   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10153 
10154   // Make sure we do not parse attributes as lambda introducers.
10155   FormatStyle MultiLineFunctions = getLLVMStyle();
10156   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10157   verifyFormat("[[unused]] int b() {\n"
10158                "  return 42;\n"
10159                "}\n",
10160                MultiLineFunctions);
10161 }
10162 
10163 TEST_F(FormatTest, AttributeClass) {
10164   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10165   verifyFormat("class S {\n"
10166                "  S(S&&) = default;\n"
10167                "};",
10168                Style);
10169   verifyFormat("class [[nodiscard]] S {\n"
10170                "  S(S&&) = default;\n"
10171                "};",
10172                Style);
10173   verifyFormat("class __attribute((maybeunused)) S {\n"
10174                "  S(S&&) = default;\n"
10175                "};",
10176                Style);
10177   verifyFormat("struct S {\n"
10178                "  S(S&&) = default;\n"
10179                "};",
10180                Style);
10181   verifyFormat("struct [[nodiscard]] S {\n"
10182                "  S(S&&) = default;\n"
10183                "};",
10184                Style);
10185 }
10186 
10187 TEST_F(FormatTest, AttributesAfterMacro) {
10188   FormatStyle Style = getLLVMStyle();
10189   verifyFormat("MACRO;\n"
10190                "__attribute__((maybe_unused)) int foo() {\n"
10191                "  //...\n"
10192                "}");
10193 
10194   verifyFormat("MACRO;\n"
10195                "[[nodiscard]] int foo() {\n"
10196                "  //...\n"
10197                "}");
10198 
10199   EXPECT_EQ("MACRO\n\n"
10200             "__attribute__((maybe_unused)) int foo() {\n"
10201             "  //...\n"
10202             "}",
10203             format("MACRO\n\n"
10204                    "__attribute__((maybe_unused)) int foo() {\n"
10205                    "  //...\n"
10206                    "}"));
10207 
10208   EXPECT_EQ("MACRO\n\n"
10209             "[[nodiscard]] int foo() {\n"
10210             "  //...\n"
10211             "}",
10212             format("MACRO\n\n"
10213                    "[[nodiscard]] int foo() {\n"
10214                    "  //...\n"
10215                    "}"));
10216 }
10217 
10218 TEST_F(FormatTest, AttributePenaltyBreaking) {
10219   FormatStyle Style = getLLVMStyle();
10220   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10221                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10222                Style);
10223   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10224                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10225                Style);
10226   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10227                "shared_ptr<ALongTypeName> &C d) {\n}",
10228                Style);
10229 }
10230 
10231 TEST_F(FormatTest, UnderstandsEllipsis) {
10232   FormatStyle Style = getLLVMStyle();
10233   verifyFormat("int printf(const char *fmt, ...);");
10234   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10235   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10236 
10237   verifyFormat("template <int *...PP> a;", Style);
10238 
10239   Style.PointerAlignment = FormatStyle::PAS_Left;
10240   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10241 
10242   verifyFormat("template <int*... PP> a;", Style);
10243 
10244   Style.PointerAlignment = FormatStyle::PAS_Middle;
10245   verifyFormat("template <int *... PP> a;", Style);
10246 }
10247 
10248 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10249   EXPECT_EQ("int *a;\n"
10250             "int *a;\n"
10251             "int *a;",
10252             format("int *a;\n"
10253                    "int* a;\n"
10254                    "int *a;",
10255                    getGoogleStyle()));
10256   EXPECT_EQ("int* a;\n"
10257             "int* a;\n"
10258             "int* a;",
10259             format("int* a;\n"
10260                    "int* a;\n"
10261                    "int *a;",
10262                    getGoogleStyle()));
10263   EXPECT_EQ("int *a;\n"
10264             "int *a;\n"
10265             "int *a;",
10266             format("int *a;\n"
10267                    "int * a;\n"
10268                    "int *  a;",
10269                    getGoogleStyle()));
10270   EXPECT_EQ("auto x = [] {\n"
10271             "  int *a;\n"
10272             "  int *a;\n"
10273             "  int *a;\n"
10274             "};",
10275             format("auto x=[]{int *a;\n"
10276                    "int * a;\n"
10277                    "int *  a;};",
10278                    getGoogleStyle()));
10279 }
10280 
10281 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10282   verifyFormat("int f(int &&a) {}");
10283   verifyFormat("int f(int a, char &&b) {}");
10284   verifyFormat("void f() { int &&a = b; }");
10285   verifyGoogleFormat("int f(int a, char&& b) {}");
10286   verifyGoogleFormat("void f() { int&& a = b; }");
10287 
10288   verifyIndependentOfContext("A<int &&> a;");
10289   verifyIndependentOfContext("A<int &&, int &&> a;");
10290   verifyGoogleFormat("A<int&&> a;");
10291   verifyGoogleFormat("A<int&&, int&&> a;");
10292 
10293   // Not rvalue references:
10294   verifyFormat("template <bool B, bool C> class A {\n"
10295                "  static_assert(B && C, \"Something is wrong\");\n"
10296                "};");
10297   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10298   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10299   verifyFormat("#define A(a, b) (a && b)");
10300 }
10301 
10302 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10303   verifyFormat("void f() {\n"
10304                "  x[aaaaaaaaa -\n"
10305                "    b] = 23;\n"
10306                "}",
10307                getLLVMStyleWithColumns(15));
10308 }
10309 
10310 TEST_F(FormatTest, FormatsCasts) {
10311   verifyFormat("Type *A = static_cast<Type *>(P);");
10312   verifyFormat("Type *A = (Type *)P;");
10313   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10314   verifyFormat("int a = (int)(2.0f);");
10315   verifyFormat("int a = (int)2.0f;");
10316   verifyFormat("x[(int32)y];");
10317   verifyFormat("x = (int32)y;");
10318   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10319   verifyFormat("int a = (int)*b;");
10320   verifyFormat("int a = (int)2.0f;");
10321   verifyFormat("int a = (int)~0;");
10322   verifyFormat("int a = (int)++a;");
10323   verifyFormat("int a = (int)sizeof(int);");
10324   verifyFormat("int a = (int)+2;");
10325   verifyFormat("my_int a = (my_int)2.0f;");
10326   verifyFormat("my_int a = (my_int)sizeof(int);");
10327   verifyFormat("return (my_int)aaa;");
10328   verifyFormat("#define x ((int)-1)");
10329   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10330   verifyFormat("#define p(q) ((int *)&q)");
10331   verifyFormat("fn(a)(b) + 1;");
10332 
10333   verifyFormat("void f() { my_int a = (my_int)*b; }");
10334   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10335   verifyFormat("my_int a = (my_int)~0;");
10336   verifyFormat("my_int a = (my_int)++a;");
10337   verifyFormat("my_int a = (my_int)-2;");
10338   verifyFormat("my_int a = (my_int)1;");
10339   verifyFormat("my_int a = (my_int *)1;");
10340   verifyFormat("my_int a = (const my_int)-1;");
10341   verifyFormat("my_int a = (const my_int *)-1;");
10342   verifyFormat("my_int a = (my_int)(my_int)-1;");
10343   verifyFormat("my_int a = (ns::my_int)-2;");
10344   verifyFormat("case (my_int)ONE:");
10345   verifyFormat("auto x = (X)this;");
10346   // Casts in Obj-C style calls used to not be recognized as such.
10347   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10348 
10349   // FIXME: single value wrapped with paren will be treated as cast.
10350   verifyFormat("void f(int i = (kValue)*kMask) {}");
10351 
10352   verifyFormat("{ (void)F; }");
10353 
10354   // Don't break after a cast's
10355   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10356                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10357                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10358 
10359   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10360   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10361   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10362   verifyFormat("bool *y = (bool *)(void *)(x);");
10363   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10364   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10365   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10366   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10367 
10368   // These are not casts.
10369   verifyFormat("void f(int *) {}");
10370   verifyFormat("f(foo)->b;");
10371   verifyFormat("f(foo).b;");
10372   verifyFormat("f(foo)(b);");
10373   verifyFormat("f(foo)[b];");
10374   verifyFormat("[](foo) { return 4; }(bar);");
10375   verifyFormat("(*funptr)(foo)[4];");
10376   verifyFormat("funptrs[4](foo)[4];");
10377   verifyFormat("void f(int *);");
10378   verifyFormat("void f(int *) = 0;");
10379   verifyFormat("void f(SmallVector<int>) {}");
10380   verifyFormat("void f(SmallVector<int>);");
10381   verifyFormat("void f(SmallVector<int>) = 0;");
10382   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10383   verifyFormat("int a = sizeof(int) * b;");
10384   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10385   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10386   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10387   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10388 
10389   // These are not casts, but at some point were confused with casts.
10390   verifyFormat("virtual void foo(int *) override;");
10391   verifyFormat("virtual void foo(char &) const;");
10392   verifyFormat("virtual void foo(int *a, char *) const;");
10393   verifyFormat("int a = sizeof(int *) + b;");
10394   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10395   verifyFormat("bool b = f(g<int>) && c;");
10396   verifyFormat("typedef void (*f)(int i) func;");
10397   verifyFormat("void operator++(int) noexcept;");
10398   verifyFormat("void operator++(int &) noexcept;");
10399   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10400                "&) noexcept;");
10401   verifyFormat(
10402       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10403   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10404   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10405   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10406   verifyFormat("void operator delete(foo &) noexcept;");
10407   verifyFormat("void operator delete(foo) noexcept;");
10408   verifyFormat("void operator delete(int) noexcept;");
10409   verifyFormat("void operator delete(int &) noexcept;");
10410   verifyFormat("void operator delete(int &) volatile noexcept;");
10411   verifyFormat("void operator delete(int &) const");
10412   verifyFormat("void operator delete(int &) = default");
10413   verifyFormat("void operator delete(int &) = delete");
10414   verifyFormat("void operator delete(int &) [[noreturn]]");
10415   verifyFormat("void operator delete(int &) throw();");
10416   verifyFormat("void operator delete(int &) throw(int);");
10417   verifyFormat("auto operator delete(int &) -> int;");
10418   verifyFormat("auto operator delete(int &) override");
10419   verifyFormat("auto operator delete(int &) final");
10420 
10421   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10422                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10423   // FIXME: The indentation here is not ideal.
10424   verifyFormat(
10425       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10426       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10427       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10428 }
10429 
10430 TEST_F(FormatTest, FormatsFunctionTypes) {
10431   verifyFormat("A<bool()> a;");
10432   verifyFormat("A<SomeType()> a;");
10433   verifyFormat("A<void (*)(int, std::string)> a;");
10434   verifyFormat("A<void *(int)>;");
10435   verifyFormat("void *(*a)(int *, SomeType *);");
10436   verifyFormat("int (*func)(void *);");
10437   verifyFormat("void f() { int (*func)(void *); }");
10438   verifyFormat("template <class CallbackClass>\n"
10439                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10440 
10441   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10442   verifyGoogleFormat("void* (*a)(int);");
10443   verifyGoogleFormat(
10444       "template <class CallbackClass>\n"
10445       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10446 
10447   // Other constructs can look somewhat like function types:
10448   verifyFormat("A<sizeof(*x)> a;");
10449   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10450   verifyFormat("some_var = function(*some_pointer_var)[0];");
10451   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10452   verifyFormat("int x = f(&h)();");
10453   verifyFormat("returnsFunction(&param1, &param2)(param);");
10454   verifyFormat("std::function<\n"
10455                "    LooooooooooongTemplatedType<\n"
10456                "        SomeType>*(\n"
10457                "        LooooooooooooooooongType type)>\n"
10458                "    function;",
10459                getGoogleStyleWithColumns(40));
10460 }
10461 
10462 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10463   verifyFormat("A (*foo_)[6];");
10464   verifyFormat("vector<int> (*foo_)[6];");
10465 }
10466 
10467 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10468   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10469                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10470   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10471                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10472   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10473                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10474 
10475   // Different ways of ()-initializiation.
10476   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10477                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10478   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10479                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10480   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10481                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10482   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10483                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10484 
10485   // Lambdas should not confuse the variable declaration heuristic.
10486   verifyFormat("LooooooooooooooooongType\n"
10487                "    variable(nullptr, [](A *a) {});",
10488                getLLVMStyleWithColumns(40));
10489 }
10490 
10491 TEST_F(FormatTest, BreaksLongDeclarations) {
10492   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10493                "    AnotherNameForTheLongType;");
10494   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10495                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10496   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10497                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10498   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10499                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10500   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10501                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10502   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10503                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10504   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10505                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10506   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10507                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10508   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10509                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10510   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10511                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10512   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10513                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10514   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10515                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10516   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10517                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10518   FormatStyle Indented = getLLVMStyle();
10519   Indented.IndentWrappedFunctionNames = true;
10520   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10521                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10522                Indented);
10523   verifyFormat(
10524       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10525       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10526       Indented);
10527   verifyFormat(
10528       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10529       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10530       Indented);
10531   verifyFormat(
10532       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10533       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10534       Indented);
10535 
10536   // FIXME: Without the comment, this breaks after "(".
10537   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10538                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10539                getGoogleStyle());
10540 
10541   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
10542                "                  int LoooooooooooooooooooongParam2) {}");
10543   verifyFormat(
10544       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
10545       "                                   SourceLocation L, IdentifierIn *II,\n"
10546       "                                   Type *T) {}");
10547   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
10548                "ReallyReaaallyLongFunctionName(\n"
10549                "    const std::string &SomeParameter,\n"
10550                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10551                "        &ReallyReallyLongParameterName,\n"
10552                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10553                "        &AnotherLongParameterName) {}");
10554   verifyFormat("template <typename A>\n"
10555                "SomeLoooooooooooooooooooooongType<\n"
10556                "    typename some_namespace::SomeOtherType<A>::Type>\n"
10557                "Function() {}");
10558 
10559   verifyGoogleFormat(
10560       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
10561       "    aaaaaaaaaaaaaaaaaaaaaaa;");
10562   verifyGoogleFormat(
10563       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
10564       "                                   SourceLocation L) {}");
10565   verifyGoogleFormat(
10566       "some_namespace::LongReturnType\n"
10567       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
10568       "    int first_long_parameter, int second_parameter) {}");
10569 
10570   verifyGoogleFormat("template <typename T>\n"
10571                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10572                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
10573   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10574                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
10575 
10576   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
10577                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10578                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10579   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10580                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10581                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
10582   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10583                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
10584                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
10585                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10586 
10587   verifyFormat("template <typename T> // Templates on own line.\n"
10588                "static int            // Some comment.\n"
10589                "MyFunction(int a);",
10590                getLLVMStyle());
10591 }
10592 
10593 TEST_F(FormatTest, FormatsAccessModifiers) {
10594   FormatStyle Style = getLLVMStyle();
10595   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
10596             FormatStyle::ELBAMS_LogicalBlock);
10597   verifyFormat("struct foo {\n"
10598                "private:\n"
10599                "  void f() {}\n"
10600                "\n"
10601                "private:\n"
10602                "  int i;\n"
10603                "\n"
10604                "protected:\n"
10605                "  int j;\n"
10606                "};\n",
10607                Style);
10608   verifyFormat("struct foo {\n"
10609                "private:\n"
10610                "  void f() {}\n"
10611                "\n"
10612                "private:\n"
10613                "  int i;\n"
10614                "\n"
10615                "protected:\n"
10616                "  int j;\n"
10617                "};\n",
10618                "struct foo {\n"
10619                "private:\n"
10620                "  void f() {}\n"
10621                "private:\n"
10622                "  int i;\n"
10623                "protected:\n"
10624                "  int j;\n"
10625                "};\n",
10626                Style);
10627   verifyFormat("struct foo { /* comment */\n"
10628                "private:\n"
10629                "  int i;\n"
10630                "  // comment\n"
10631                "private:\n"
10632                "  int j;\n"
10633                "};\n",
10634                Style);
10635   verifyFormat("struct foo {\n"
10636                "#ifdef FOO\n"
10637                "#endif\n"
10638                "private:\n"
10639                "  int i;\n"
10640                "#ifdef FOO\n"
10641                "private:\n"
10642                "#endif\n"
10643                "  int j;\n"
10644                "};\n",
10645                Style);
10646   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10647   verifyFormat("struct foo {\n"
10648                "private:\n"
10649                "  void f() {}\n"
10650                "private:\n"
10651                "  int i;\n"
10652                "protected:\n"
10653                "  int j;\n"
10654                "};\n",
10655                Style);
10656   verifyFormat("struct foo {\n"
10657                "private:\n"
10658                "  void f() {}\n"
10659                "private:\n"
10660                "  int i;\n"
10661                "protected:\n"
10662                "  int j;\n"
10663                "};\n",
10664                "struct foo {\n"
10665                "\n"
10666                "private:\n"
10667                "  void f() {}\n"
10668                "\n"
10669                "private:\n"
10670                "  int i;\n"
10671                "\n"
10672                "protected:\n"
10673                "  int j;\n"
10674                "};\n",
10675                Style);
10676   verifyFormat("struct foo { /* comment */\n"
10677                "private:\n"
10678                "  int i;\n"
10679                "  // comment\n"
10680                "private:\n"
10681                "  int j;\n"
10682                "};\n",
10683                "struct foo { /* comment */\n"
10684                "\n"
10685                "private:\n"
10686                "  int i;\n"
10687                "  // comment\n"
10688                "\n"
10689                "private:\n"
10690                "  int j;\n"
10691                "};\n",
10692                Style);
10693   verifyFormat("struct foo {\n"
10694                "#ifdef FOO\n"
10695                "#endif\n"
10696                "private:\n"
10697                "  int i;\n"
10698                "#ifdef FOO\n"
10699                "private:\n"
10700                "#endif\n"
10701                "  int j;\n"
10702                "};\n",
10703                "struct foo {\n"
10704                "#ifdef FOO\n"
10705                "#endif\n"
10706                "\n"
10707                "private:\n"
10708                "  int i;\n"
10709                "#ifdef FOO\n"
10710                "\n"
10711                "private:\n"
10712                "#endif\n"
10713                "  int j;\n"
10714                "};\n",
10715                Style);
10716   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10717   verifyFormat("struct foo {\n"
10718                "private:\n"
10719                "  void f() {}\n"
10720                "\n"
10721                "private:\n"
10722                "  int i;\n"
10723                "\n"
10724                "protected:\n"
10725                "  int j;\n"
10726                "};\n",
10727                Style);
10728   verifyFormat("struct foo {\n"
10729                "private:\n"
10730                "  void f() {}\n"
10731                "\n"
10732                "private:\n"
10733                "  int i;\n"
10734                "\n"
10735                "protected:\n"
10736                "  int j;\n"
10737                "};\n",
10738                "struct foo {\n"
10739                "private:\n"
10740                "  void f() {}\n"
10741                "private:\n"
10742                "  int i;\n"
10743                "protected:\n"
10744                "  int j;\n"
10745                "};\n",
10746                Style);
10747   verifyFormat("struct foo { /* comment */\n"
10748                "private:\n"
10749                "  int i;\n"
10750                "  // comment\n"
10751                "\n"
10752                "private:\n"
10753                "  int j;\n"
10754                "};\n",
10755                "struct foo { /* comment */\n"
10756                "private:\n"
10757                "  int i;\n"
10758                "  // comment\n"
10759                "\n"
10760                "private:\n"
10761                "  int j;\n"
10762                "};\n",
10763                Style);
10764   verifyFormat("struct foo {\n"
10765                "#ifdef FOO\n"
10766                "#endif\n"
10767                "\n"
10768                "private:\n"
10769                "  int i;\n"
10770                "#ifdef FOO\n"
10771                "\n"
10772                "private:\n"
10773                "#endif\n"
10774                "  int j;\n"
10775                "};\n",
10776                "struct foo {\n"
10777                "#ifdef FOO\n"
10778                "#endif\n"
10779                "private:\n"
10780                "  int i;\n"
10781                "#ifdef FOO\n"
10782                "private:\n"
10783                "#endif\n"
10784                "  int j;\n"
10785                "};\n",
10786                Style);
10787   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10788   EXPECT_EQ("struct foo {\n"
10789             "\n"
10790             "private:\n"
10791             "  void f() {}\n"
10792             "\n"
10793             "private:\n"
10794             "  int i;\n"
10795             "\n"
10796             "protected:\n"
10797             "  int j;\n"
10798             "};\n",
10799             format("struct foo {\n"
10800                    "\n"
10801                    "private:\n"
10802                    "  void f() {}\n"
10803                    "\n"
10804                    "private:\n"
10805                    "  int i;\n"
10806                    "\n"
10807                    "protected:\n"
10808                    "  int j;\n"
10809                    "};\n",
10810                    Style));
10811   verifyFormat("struct foo {\n"
10812                "private:\n"
10813                "  void f() {}\n"
10814                "private:\n"
10815                "  int i;\n"
10816                "protected:\n"
10817                "  int j;\n"
10818                "};\n",
10819                Style);
10820   EXPECT_EQ("struct foo { /* comment */\n"
10821             "\n"
10822             "private:\n"
10823             "  int i;\n"
10824             "  // comment\n"
10825             "\n"
10826             "private:\n"
10827             "  int j;\n"
10828             "};\n",
10829             format("struct foo { /* comment */\n"
10830                    "\n"
10831                    "private:\n"
10832                    "  int i;\n"
10833                    "  // comment\n"
10834                    "\n"
10835                    "private:\n"
10836                    "  int j;\n"
10837                    "};\n",
10838                    Style));
10839   verifyFormat("struct foo { /* comment */\n"
10840                "private:\n"
10841                "  int i;\n"
10842                "  // comment\n"
10843                "private:\n"
10844                "  int j;\n"
10845                "};\n",
10846                Style);
10847   EXPECT_EQ("struct foo {\n"
10848             "#ifdef FOO\n"
10849             "#endif\n"
10850             "\n"
10851             "private:\n"
10852             "  int i;\n"
10853             "#ifdef FOO\n"
10854             "\n"
10855             "private:\n"
10856             "#endif\n"
10857             "  int j;\n"
10858             "};\n",
10859             format("struct foo {\n"
10860                    "#ifdef FOO\n"
10861                    "#endif\n"
10862                    "\n"
10863                    "private:\n"
10864                    "  int i;\n"
10865                    "#ifdef FOO\n"
10866                    "\n"
10867                    "private:\n"
10868                    "#endif\n"
10869                    "  int j;\n"
10870                    "};\n",
10871                    Style));
10872   verifyFormat("struct foo {\n"
10873                "#ifdef FOO\n"
10874                "#endif\n"
10875                "private:\n"
10876                "  int i;\n"
10877                "#ifdef FOO\n"
10878                "private:\n"
10879                "#endif\n"
10880                "  int j;\n"
10881                "};\n",
10882                Style);
10883 
10884   FormatStyle NoEmptyLines = getLLVMStyle();
10885   NoEmptyLines.MaxEmptyLinesToKeep = 0;
10886   verifyFormat("struct foo {\n"
10887                "private:\n"
10888                "  void f() {}\n"
10889                "\n"
10890                "private:\n"
10891                "  int i;\n"
10892                "\n"
10893                "public:\n"
10894                "protected:\n"
10895                "  int j;\n"
10896                "};\n",
10897                NoEmptyLines);
10898 
10899   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10900   verifyFormat("struct foo {\n"
10901                "private:\n"
10902                "  void f() {}\n"
10903                "private:\n"
10904                "  int i;\n"
10905                "public:\n"
10906                "protected:\n"
10907                "  int j;\n"
10908                "};\n",
10909                NoEmptyLines);
10910 
10911   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10912   verifyFormat("struct foo {\n"
10913                "private:\n"
10914                "  void f() {}\n"
10915                "\n"
10916                "private:\n"
10917                "  int i;\n"
10918                "\n"
10919                "public:\n"
10920                "\n"
10921                "protected:\n"
10922                "  int j;\n"
10923                "};\n",
10924                NoEmptyLines);
10925 }
10926 
10927 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
10928 
10929   FormatStyle Style = getLLVMStyle();
10930   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
10931   verifyFormat("struct foo {\n"
10932                "private:\n"
10933                "  void f() {}\n"
10934                "\n"
10935                "private:\n"
10936                "  int i;\n"
10937                "\n"
10938                "protected:\n"
10939                "  int j;\n"
10940                "};\n",
10941                Style);
10942 
10943   // Check if lines are removed.
10944   verifyFormat("struct foo {\n"
10945                "private:\n"
10946                "  void f() {}\n"
10947                "\n"
10948                "private:\n"
10949                "  int i;\n"
10950                "\n"
10951                "protected:\n"
10952                "  int j;\n"
10953                "};\n",
10954                "struct foo {\n"
10955                "private:\n"
10956                "\n"
10957                "  void f() {}\n"
10958                "\n"
10959                "private:\n"
10960                "\n"
10961                "  int i;\n"
10962                "\n"
10963                "protected:\n"
10964                "\n"
10965                "  int j;\n"
10966                "};\n",
10967                Style);
10968 
10969   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10970   verifyFormat("struct foo {\n"
10971                "private:\n"
10972                "\n"
10973                "  void f() {}\n"
10974                "\n"
10975                "private:\n"
10976                "\n"
10977                "  int i;\n"
10978                "\n"
10979                "protected:\n"
10980                "\n"
10981                "  int j;\n"
10982                "};\n",
10983                Style);
10984 
10985   // Check if lines are added.
10986   verifyFormat("struct foo {\n"
10987                "private:\n"
10988                "\n"
10989                "  void f() {}\n"
10990                "\n"
10991                "private:\n"
10992                "\n"
10993                "  int i;\n"
10994                "\n"
10995                "protected:\n"
10996                "\n"
10997                "  int j;\n"
10998                "};\n",
10999                "struct foo {\n"
11000                "private:\n"
11001                "  void f() {}\n"
11002                "\n"
11003                "private:\n"
11004                "  int i;\n"
11005                "\n"
11006                "protected:\n"
11007                "  int j;\n"
11008                "};\n",
11009                Style);
11010 
11011   // Leave tests rely on the code layout, test::messUp can not be used.
11012   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11013   Style.MaxEmptyLinesToKeep = 0u;
11014   verifyFormat("struct foo {\n"
11015                "private:\n"
11016                "  void f() {}\n"
11017                "\n"
11018                "private:\n"
11019                "  int i;\n"
11020                "\n"
11021                "protected:\n"
11022                "  int j;\n"
11023                "};\n",
11024                Style);
11025 
11026   // Check if MaxEmptyLinesToKeep is respected.
11027   EXPECT_EQ("struct foo {\n"
11028             "private:\n"
11029             "  void f() {}\n"
11030             "\n"
11031             "private:\n"
11032             "  int i;\n"
11033             "\n"
11034             "protected:\n"
11035             "  int j;\n"
11036             "};\n",
11037             format("struct foo {\n"
11038                    "private:\n"
11039                    "\n\n\n"
11040                    "  void f() {}\n"
11041                    "\n"
11042                    "private:\n"
11043                    "\n\n\n"
11044                    "  int i;\n"
11045                    "\n"
11046                    "protected:\n"
11047                    "\n\n\n"
11048                    "  int j;\n"
11049                    "};\n",
11050                    Style));
11051 
11052   Style.MaxEmptyLinesToKeep = 1u;
11053   EXPECT_EQ("struct foo {\n"
11054             "private:\n"
11055             "\n"
11056             "  void f() {}\n"
11057             "\n"
11058             "private:\n"
11059             "\n"
11060             "  int i;\n"
11061             "\n"
11062             "protected:\n"
11063             "\n"
11064             "  int j;\n"
11065             "};\n",
11066             format("struct foo {\n"
11067                    "private:\n"
11068                    "\n"
11069                    "  void f() {}\n"
11070                    "\n"
11071                    "private:\n"
11072                    "\n"
11073                    "  int i;\n"
11074                    "\n"
11075                    "protected:\n"
11076                    "\n"
11077                    "  int j;\n"
11078                    "};\n",
11079                    Style));
11080   // Check if no lines are kept.
11081   EXPECT_EQ("struct foo {\n"
11082             "private:\n"
11083             "  void f() {}\n"
11084             "\n"
11085             "private:\n"
11086             "  int i;\n"
11087             "\n"
11088             "protected:\n"
11089             "  int j;\n"
11090             "};\n",
11091             format("struct foo {\n"
11092                    "private:\n"
11093                    "  void f() {}\n"
11094                    "\n"
11095                    "private:\n"
11096                    "  int i;\n"
11097                    "\n"
11098                    "protected:\n"
11099                    "  int j;\n"
11100                    "};\n",
11101                    Style));
11102   // Check if MaxEmptyLinesToKeep is respected.
11103   EXPECT_EQ("struct foo {\n"
11104             "private:\n"
11105             "\n"
11106             "  void f() {}\n"
11107             "\n"
11108             "private:\n"
11109             "\n"
11110             "  int i;\n"
11111             "\n"
11112             "protected:\n"
11113             "\n"
11114             "  int j;\n"
11115             "};\n",
11116             format("struct foo {\n"
11117                    "private:\n"
11118                    "\n\n\n"
11119                    "  void f() {}\n"
11120                    "\n"
11121                    "private:\n"
11122                    "\n\n\n"
11123                    "  int i;\n"
11124                    "\n"
11125                    "protected:\n"
11126                    "\n\n\n"
11127                    "  int j;\n"
11128                    "};\n",
11129                    Style));
11130 
11131   Style.MaxEmptyLinesToKeep = 10u;
11132   EXPECT_EQ("struct foo {\n"
11133             "private:\n"
11134             "\n\n\n"
11135             "  void f() {}\n"
11136             "\n"
11137             "private:\n"
11138             "\n\n\n"
11139             "  int i;\n"
11140             "\n"
11141             "protected:\n"
11142             "\n\n\n"
11143             "  int j;\n"
11144             "};\n",
11145             format("struct foo {\n"
11146                    "private:\n"
11147                    "\n\n\n"
11148                    "  void f() {}\n"
11149                    "\n"
11150                    "private:\n"
11151                    "\n\n\n"
11152                    "  int i;\n"
11153                    "\n"
11154                    "protected:\n"
11155                    "\n\n\n"
11156                    "  int j;\n"
11157                    "};\n",
11158                    Style));
11159 
11160   // Test with comments.
11161   Style = getLLVMStyle();
11162   verifyFormat("struct foo {\n"
11163                "private:\n"
11164                "  // comment\n"
11165                "  void f() {}\n"
11166                "\n"
11167                "private: /* comment */\n"
11168                "  int i;\n"
11169                "};\n",
11170                Style);
11171   verifyFormat("struct foo {\n"
11172                "private:\n"
11173                "  // comment\n"
11174                "  void f() {}\n"
11175                "\n"
11176                "private: /* comment */\n"
11177                "  int i;\n"
11178                "};\n",
11179                "struct foo {\n"
11180                "private:\n"
11181                "\n"
11182                "  // comment\n"
11183                "  void f() {}\n"
11184                "\n"
11185                "private: /* comment */\n"
11186                "\n"
11187                "  int i;\n"
11188                "};\n",
11189                Style);
11190 
11191   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11192   verifyFormat("struct foo {\n"
11193                "private:\n"
11194                "\n"
11195                "  // comment\n"
11196                "  void f() {}\n"
11197                "\n"
11198                "private: /* comment */\n"
11199                "\n"
11200                "  int i;\n"
11201                "};\n",
11202                "struct foo {\n"
11203                "private:\n"
11204                "  // comment\n"
11205                "  void f() {}\n"
11206                "\n"
11207                "private: /* comment */\n"
11208                "  int i;\n"
11209                "};\n",
11210                Style);
11211   verifyFormat("struct foo {\n"
11212                "private:\n"
11213                "\n"
11214                "  // comment\n"
11215                "  void f() {}\n"
11216                "\n"
11217                "private: /* comment */\n"
11218                "\n"
11219                "  int i;\n"
11220                "};\n",
11221                Style);
11222 
11223   // Test with preprocessor defines.
11224   Style = getLLVMStyle();
11225   verifyFormat("struct foo {\n"
11226                "private:\n"
11227                "#ifdef FOO\n"
11228                "#endif\n"
11229                "  void f() {}\n"
11230                "};\n",
11231                Style);
11232   verifyFormat("struct foo {\n"
11233                "private:\n"
11234                "#ifdef FOO\n"
11235                "#endif\n"
11236                "  void f() {}\n"
11237                "};\n",
11238                "struct foo {\n"
11239                "private:\n"
11240                "\n"
11241                "#ifdef FOO\n"
11242                "#endif\n"
11243                "  void f() {}\n"
11244                "};\n",
11245                Style);
11246 
11247   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11248   verifyFormat("struct foo {\n"
11249                "private:\n"
11250                "\n"
11251                "#ifdef FOO\n"
11252                "#endif\n"
11253                "  void f() {}\n"
11254                "};\n",
11255                "struct foo {\n"
11256                "private:\n"
11257                "#ifdef FOO\n"
11258                "#endif\n"
11259                "  void f() {}\n"
11260                "};\n",
11261                Style);
11262   verifyFormat("struct foo {\n"
11263                "private:\n"
11264                "\n"
11265                "#ifdef FOO\n"
11266                "#endif\n"
11267                "  void f() {}\n"
11268                "};\n",
11269                Style);
11270 }
11271 
11272 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11273   // Combined tests of EmptyLineAfterAccessModifier and
11274   // EmptyLineBeforeAccessModifier.
11275   FormatStyle Style = getLLVMStyle();
11276   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11277   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11278   verifyFormat("struct foo {\n"
11279                "private:\n"
11280                "\n"
11281                "protected:\n"
11282                "};\n",
11283                Style);
11284 
11285   Style.MaxEmptyLinesToKeep = 10u;
11286   // Both remove all new lines.
11287   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11288   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11289   verifyFormat("struct foo {\n"
11290                "private:\n"
11291                "protected:\n"
11292                "};\n",
11293                "struct foo {\n"
11294                "private:\n"
11295                "\n\n\n"
11296                "protected:\n"
11297                "};\n",
11298                Style);
11299 
11300   // Leave tests rely on the code layout, test::messUp can not be used.
11301   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11302   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11303   Style.MaxEmptyLinesToKeep = 10u;
11304   EXPECT_EQ("struct foo {\n"
11305             "private:\n"
11306             "\n\n\n"
11307             "protected:\n"
11308             "};\n",
11309             format("struct foo {\n"
11310                    "private:\n"
11311                    "\n\n\n"
11312                    "protected:\n"
11313                    "};\n",
11314                    Style));
11315   Style.MaxEmptyLinesToKeep = 3u;
11316   EXPECT_EQ("struct foo {\n"
11317             "private:\n"
11318             "\n\n\n"
11319             "protected:\n"
11320             "};\n",
11321             format("struct foo {\n"
11322                    "private:\n"
11323                    "\n\n\n"
11324                    "protected:\n"
11325                    "};\n",
11326                    Style));
11327   Style.MaxEmptyLinesToKeep = 1u;
11328   EXPECT_EQ("struct foo {\n"
11329             "private:\n"
11330             "\n\n\n"
11331             "protected:\n"
11332             "};\n",
11333             format("struct foo {\n"
11334                    "private:\n"
11335                    "\n\n\n"
11336                    "protected:\n"
11337                    "};\n",
11338                    Style)); // Based on new lines in original document and not
11339                             // on the setting.
11340 
11341   Style.MaxEmptyLinesToKeep = 10u;
11342   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11343   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11344   // Newlines are kept if they are greater than zero,
11345   // test::messUp removes all new lines which changes the logic
11346   EXPECT_EQ("struct foo {\n"
11347             "private:\n"
11348             "\n\n\n"
11349             "protected:\n"
11350             "};\n",
11351             format("struct foo {\n"
11352                    "private:\n"
11353                    "\n\n\n"
11354                    "protected:\n"
11355                    "};\n",
11356                    Style));
11357 
11358   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11359   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11360   // test::messUp removes all new lines which changes the logic
11361   EXPECT_EQ("struct foo {\n"
11362             "private:\n"
11363             "\n\n\n"
11364             "protected:\n"
11365             "};\n",
11366             format("struct foo {\n"
11367                    "private:\n"
11368                    "\n\n\n"
11369                    "protected:\n"
11370                    "};\n",
11371                    Style));
11372 
11373   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11374   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11375   EXPECT_EQ("struct foo {\n"
11376             "private:\n"
11377             "\n\n\n"
11378             "protected:\n"
11379             "};\n",
11380             format("struct foo {\n"
11381                    "private:\n"
11382                    "\n\n\n"
11383                    "protected:\n"
11384                    "};\n",
11385                    Style)); // test::messUp removes all new lines which changes
11386                             // the logic.
11387 
11388   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11389   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11390   verifyFormat("struct foo {\n"
11391                "private:\n"
11392                "protected:\n"
11393                "};\n",
11394                "struct foo {\n"
11395                "private:\n"
11396                "\n\n\n"
11397                "protected:\n"
11398                "};\n",
11399                Style);
11400 
11401   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11402   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11403   EXPECT_EQ("struct foo {\n"
11404             "private:\n"
11405             "\n\n\n"
11406             "protected:\n"
11407             "};\n",
11408             format("struct foo {\n"
11409                    "private:\n"
11410                    "\n\n\n"
11411                    "protected:\n"
11412                    "};\n",
11413                    Style)); // test::messUp removes all new lines which changes
11414                             // the logic.
11415 
11416   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11417   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11418   verifyFormat("struct foo {\n"
11419                "private:\n"
11420                "protected:\n"
11421                "};\n",
11422                "struct foo {\n"
11423                "private:\n"
11424                "\n\n\n"
11425                "protected:\n"
11426                "};\n",
11427                Style);
11428 
11429   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11430   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11431   verifyFormat("struct foo {\n"
11432                "private:\n"
11433                "protected:\n"
11434                "};\n",
11435                "struct foo {\n"
11436                "private:\n"
11437                "\n\n\n"
11438                "protected:\n"
11439                "};\n",
11440                Style);
11441 
11442   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11443   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11444   verifyFormat("struct foo {\n"
11445                "private:\n"
11446                "protected:\n"
11447                "};\n",
11448                "struct foo {\n"
11449                "private:\n"
11450                "\n\n\n"
11451                "protected:\n"
11452                "};\n",
11453                Style);
11454 
11455   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11456   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11457   verifyFormat("struct foo {\n"
11458                "private:\n"
11459                "protected:\n"
11460                "};\n",
11461                "struct foo {\n"
11462                "private:\n"
11463                "\n\n\n"
11464                "protected:\n"
11465                "};\n",
11466                Style);
11467 }
11468 
11469 TEST_F(FormatTest, FormatsArrays) {
11470   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11471                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11472   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11473                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11474   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11475                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11476   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11477                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11478   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11479                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11480   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11481                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11482                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11483   verifyFormat(
11484       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11485       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11486       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11487   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11488                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11489 
11490   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11491                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11492   verifyFormat(
11493       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11494       "                                  .aaaaaaa[0]\n"
11495       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11496   verifyFormat("a[::b::c];");
11497 
11498   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11499 
11500   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11501   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11502 }
11503 
11504 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11505   verifyFormat("(a)->b();");
11506   verifyFormat("--a;");
11507 }
11508 
11509 TEST_F(FormatTest, HandlesIncludeDirectives) {
11510   verifyFormat("#include <string>\n"
11511                "#include <a/b/c.h>\n"
11512                "#include \"a/b/string\"\n"
11513                "#include \"string.h\"\n"
11514                "#include \"string.h\"\n"
11515                "#include <a-a>\n"
11516                "#include < path with space >\n"
11517                "#include_next <test.h>"
11518                "#include \"abc.h\" // this is included for ABC\n"
11519                "#include \"some long include\" // with a comment\n"
11520                "#include \"some very long include path\"\n"
11521                "#include <some/very/long/include/path>\n",
11522                getLLVMStyleWithColumns(35));
11523   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11524   EXPECT_EQ("#include <a>", format("#include<a>"));
11525 
11526   verifyFormat("#import <string>");
11527   verifyFormat("#import <a/b/c.h>");
11528   verifyFormat("#import \"a/b/string\"");
11529   verifyFormat("#import \"string.h\"");
11530   verifyFormat("#import \"string.h\"");
11531   verifyFormat("#if __has_include(<strstream>)\n"
11532                "#include <strstream>\n"
11533                "#endif");
11534 
11535   verifyFormat("#define MY_IMPORT <a/b>");
11536 
11537   verifyFormat("#if __has_include(<a/b>)");
11538   verifyFormat("#if __has_include_next(<a/b>)");
11539   verifyFormat("#define F __has_include(<a/b>)");
11540   verifyFormat("#define F __has_include_next(<a/b>)");
11541 
11542   // Protocol buffer definition or missing "#".
11543   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
11544                getLLVMStyleWithColumns(30));
11545 
11546   FormatStyle Style = getLLVMStyle();
11547   Style.AlwaysBreakBeforeMultilineStrings = true;
11548   Style.ColumnLimit = 0;
11549   verifyFormat("#import \"abc.h\"", Style);
11550 
11551   // But 'import' might also be a regular C++ namespace.
11552   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11553                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11554 }
11555 
11556 //===----------------------------------------------------------------------===//
11557 // Error recovery tests.
11558 //===----------------------------------------------------------------------===//
11559 
11560 TEST_F(FormatTest, IncompleteParameterLists) {
11561   FormatStyle NoBinPacking = getLLVMStyle();
11562   NoBinPacking.BinPackParameters = false;
11563   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
11564                "                        double *min_x,\n"
11565                "                        double *max_x,\n"
11566                "                        double *min_y,\n"
11567                "                        double *max_y,\n"
11568                "                        double *min_z,\n"
11569                "                        double *max_z, ) {}",
11570                NoBinPacking);
11571 }
11572 
11573 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
11574   verifyFormat("void f() { return; }\n42");
11575   verifyFormat("void f() {\n"
11576                "  if (0)\n"
11577                "    return;\n"
11578                "}\n"
11579                "42");
11580   verifyFormat("void f() { return }\n42");
11581   verifyFormat("void f() {\n"
11582                "  if (0)\n"
11583                "    return\n"
11584                "}\n"
11585                "42");
11586 }
11587 
11588 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
11589   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
11590   EXPECT_EQ("void f() {\n"
11591             "  if (a)\n"
11592             "    return\n"
11593             "}",
11594             format("void  f  (  )  {  if  ( a )  return  }"));
11595   EXPECT_EQ("namespace N {\n"
11596             "void f()\n"
11597             "}",
11598             format("namespace  N  {  void f()  }"));
11599   EXPECT_EQ("namespace N {\n"
11600             "void f() {}\n"
11601             "void g()\n"
11602             "} // namespace N",
11603             format("namespace N  { void f( ) { } void g( ) }"));
11604 }
11605 
11606 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
11607   verifyFormat("int aaaaaaaa =\n"
11608                "    // Overlylongcomment\n"
11609                "    b;",
11610                getLLVMStyleWithColumns(20));
11611   verifyFormat("function(\n"
11612                "    ShortArgument,\n"
11613                "    LoooooooooooongArgument);\n",
11614                getLLVMStyleWithColumns(20));
11615 }
11616 
11617 TEST_F(FormatTest, IncorrectAccessSpecifier) {
11618   verifyFormat("public:");
11619   verifyFormat("class A {\n"
11620                "public\n"
11621                "  void f() {}\n"
11622                "};");
11623   verifyFormat("public\n"
11624                "int qwerty;");
11625   verifyFormat("public\n"
11626                "B {}");
11627   verifyFormat("public\n"
11628                "{}");
11629   verifyFormat("public\n"
11630                "B { int x; }");
11631 }
11632 
11633 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
11634   verifyFormat("{");
11635   verifyFormat("#})");
11636   verifyNoCrash("(/**/[:!] ?[).");
11637 }
11638 
11639 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
11640   // Found by oss-fuzz:
11641   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
11642   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
11643   Style.ColumnLimit = 60;
11644   verifyNoCrash(
11645       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
11646       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
11647       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
11648       Style);
11649 }
11650 
11651 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
11652   verifyFormat("do {\n}");
11653   verifyFormat("do {\n}\n"
11654                "f();");
11655   verifyFormat("do {\n}\n"
11656                "wheeee(fun);");
11657   verifyFormat("do {\n"
11658                "  f();\n"
11659                "}");
11660 }
11661 
11662 TEST_F(FormatTest, IncorrectCodeMissingParens) {
11663   verifyFormat("if {\n  foo;\n  foo();\n}");
11664   verifyFormat("switch {\n  foo;\n  foo();\n}");
11665   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
11666   verifyFormat("while {\n  foo;\n  foo();\n}");
11667   verifyFormat("do {\n  foo;\n  foo();\n} while;");
11668 }
11669 
11670 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
11671   verifyIncompleteFormat("namespace {\n"
11672                          "class Foo { Foo (\n"
11673                          "};\n"
11674                          "} // namespace");
11675 }
11676 
11677 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
11678   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
11679   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
11680   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
11681   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
11682 
11683   EXPECT_EQ("{\n"
11684             "  {\n"
11685             "    breakme(\n"
11686             "        qwe);\n"
11687             "  }\n",
11688             format("{\n"
11689                    "    {\n"
11690                    " breakme(qwe);\n"
11691                    "}\n",
11692                    getLLVMStyleWithColumns(10)));
11693 }
11694 
11695 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
11696   verifyFormat("int x = {\n"
11697                "    avariable,\n"
11698                "    b(alongervariable)};",
11699                getLLVMStyleWithColumns(25));
11700 }
11701 
11702 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
11703   verifyFormat("return (a)(b){1, 2, 3};");
11704 }
11705 
11706 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
11707   verifyFormat("vector<int> x{1, 2, 3, 4};");
11708   verifyFormat("vector<int> x{\n"
11709                "    1,\n"
11710                "    2,\n"
11711                "    3,\n"
11712                "    4,\n"
11713                "};");
11714   verifyFormat("vector<T> x{{}, {}, {}, {}};");
11715   verifyFormat("f({1, 2});");
11716   verifyFormat("auto v = Foo{-1};");
11717   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
11718   verifyFormat("Class::Class : member{1, 2, 3} {}");
11719   verifyFormat("new vector<int>{1, 2, 3};");
11720   verifyFormat("new int[3]{1, 2, 3};");
11721   verifyFormat("new int{1};");
11722   verifyFormat("return {arg1, arg2};");
11723   verifyFormat("return {arg1, SomeType{parameter}};");
11724   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
11725   verifyFormat("new T{arg1, arg2};");
11726   verifyFormat("f(MyMap[{composite, key}]);");
11727   verifyFormat("class Class {\n"
11728                "  T member = {arg1, arg2};\n"
11729                "};");
11730   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
11731   verifyFormat("const struct A a = {.a = 1, .b = 2};");
11732   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
11733   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
11734   verifyFormat("int a = std::is_integral<int>{} + 0;");
11735 
11736   verifyFormat("int foo(int i) { return fo1{}(i); }");
11737   verifyFormat("int foo(int i) { return fo1{}(i); }");
11738   verifyFormat("auto i = decltype(x){};");
11739   verifyFormat("auto i = typeof(x){};");
11740   verifyFormat("auto i = _Atomic(x){};");
11741   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
11742   verifyFormat("Node n{1, Node{1000}, //\n"
11743                "       2};");
11744   verifyFormat("Aaaa aaaaaaa{\n"
11745                "    {\n"
11746                "        aaaa,\n"
11747                "    },\n"
11748                "};");
11749   verifyFormat("class C : public D {\n"
11750                "  SomeClass SC{2};\n"
11751                "};");
11752   verifyFormat("class C : public A {\n"
11753                "  class D : public B {\n"
11754                "    void f() { int i{2}; }\n"
11755                "  };\n"
11756                "};");
11757   verifyFormat("#define A {a, a},");
11758   // Don't confuse braced list initializers with compound statements.
11759   verifyFormat(
11760       "class A {\n"
11761       "  A() : a{} {}\n"
11762       "  A(int b) : b(b) {}\n"
11763       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
11764       "  int a, b;\n"
11765       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
11766       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
11767       "{}\n"
11768       "};");
11769 
11770   // Avoid breaking between equal sign and opening brace
11771   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
11772   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
11773   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
11774                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
11775                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
11776                "     {\"ccccccccccccccccccccc\", 2}};",
11777                AvoidBreakingFirstArgument);
11778 
11779   // Binpacking only if there is no trailing comma
11780   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
11781                "                      cccccccccc, dddddddddd};",
11782                getLLVMStyleWithColumns(50));
11783   verifyFormat("const Aaaaaa aaaaa = {\n"
11784                "    aaaaaaaaaaa,\n"
11785                "    bbbbbbbbbbb,\n"
11786                "    ccccccccccc,\n"
11787                "    ddddddddddd,\n"
11788                "};",
11789                getLLVMStyleWithColumns(50));
11790 
11791   // Cases where distinguising braced lists and blocks is hard.
11792   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
11793   verifyFormat("void f() {\n"
11794                "  return; // comment\n"
11795                "}\n"
11796                "SomeType t;");
11797   verifyFormat("void f() {\n"
11798                "  if (a) {\n"
11799                "    f();\n"
11800                "  }\n"
11801                "}\n"
11802                "SomeType t;");
11803 
11804   // In combination with BinPackArguments = false.
11805   FormatStyle NoBinPacking = getLLVMStyle();
11806   NoBinPacking.BinPackArguments = false;
11807   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
11808                "                      bbbbb,\n"
11809                "                      ccccc,\n"
11810                "                      ddddd,\n"
11811                "                      eeeee,\n"
11812                "                      ffffff,\n"
11813                "                      ggggg,\n"
11814                "                      hhhhhh,\n"
11815                "                      iiiiii,\n"
11816                "                      jjjjjj,\n"
11817                "                      kkkkkk};",
11818                NoBinPacking);
11819   verifyFormat("const Aaaaaa aaaaa = {\n"
11820                "    aaaaa,\n"
11821                "    bbbbb,\n"
11822                "    ccccc,\n"
11823                "    ddddd,\n"
11824                "    eeeee,\n"
11825                "    ffffff,\n"
11826                "    ggggg,\n"
11827                "    hhhhhh,\n"
11828                "    iiiiii,\n"
11829                "    jjjjjj,\n"
11830                "    kkkkkk,\n"
11831                "};",
11832                NoBinPacking);
11833   verifyFormat(
11834       "const Aaaaaa aaaaa = {\n"
11835       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
11836       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
11837       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
11838       "};",
11839       NoBinPacking);
11840 
11841   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11842   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
11843             "    CDDDP83848_BMCR_REGISTER,\n"
11844             "    CDDDP83848_BMSR_REGISTER,\n"
11845             "    CDDDP83848_RBR_REGISTER};",
11846             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
11847                    "                                CDDDP83848_BMSR_REGISTER,\n"
11848                    "                                CDDDP83848_RBR_REGISTER};",
11849                    NoBinPacking));
11850 
11851   // FIXME: The alignment of these trailing comments might be bad. Then again,
11852   // this might be utterly useless in real code.
11853   verifyFormat("Constructor::Constructor()\n"
11854                "    : some_value{         //\n"
11855                "                 aaaaaaa, //\n"
11856                "                 bbbbbbb} {}");
11857 
11858   // In braced lists, the first comment is always assumed to belong to the
11859   // first element. Thus, it can be moved to the next or previous line as
11860   // appropriate.
11861   EXPECT_EQ("function({// First element:\n"
11862             "          1,\n"
11863             "          // Second element:\n"
11864             "          2});",
11865             format("function({\n"
11866                    "    // First element:\n"
11867                    "    1,\n"
11868                    "    // Second element:\n"
11869                    "    2});"));
11870   EXPECT_EQ("std::vector<int> MyNumbers{\n"
11871             "    // First element:\n"
11872             "    1,\n"
11873             "    // Second element:\n"
11874             "    2};",
11875             format("std::vector<int> MyNumbers{// First element:\n"
11876                    "                           1,\n"
11877                    "                           // Second element:\n"
11878                    "                           2};",
11879                    getLLVMStyleWithColumns(30)));
11880   // A trailing comma should still lead to an enforced line break and no
11881   // binpacking.
11882   EXPECT_EQ("vector<int> SomeVector = {\n"
11883             "    // aaa\n"
11884             "    1,\n"
11885             "    2,\n"
11886             "};",
11887             format("vector<int> SomeVector = { // aaa\n"
11888                    "    1, 2, };"));
11889 
11890   // C++11 brace initializer list l-braces should not be treated any differently
11891   // when breaking before lambda bodies is enabled
11892   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
11893   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
11894   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
11895   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
11896   verifyFormat(
11897       "std::runtime_error{\n"
11898       "    \"Long string which will force a break onto the next line...\"};",
11899       BreakBeforeLambdaBody);
11900 
11901   FormatStyle ExtraSpaces = getLLVMStyle();
11902   ExtraSpaces.Cpp11BracedListStyle = false;
11903   ExtraSpaces.ColumnLimit = 75;
11904   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
11905   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
11906   verifyFormat("f({ 1, 2 });", ExtraSpaces);
11907   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
11908   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
11909   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
11910   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
11911   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
11912   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
11913   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
11914   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
11915   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
11916   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
11917   verifyFormat("class Class {\n"
11918                "  T member = { arg1, arg2 };\n"
11919                "};",
11920                ExtraSpaces);
11921   verifyFormat(
11922       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11923       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
11924       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
11925       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
11926       ExtraSpaces);
11927   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
11928   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
11929                ExtraSpaces);
11930   verifyFormat(
11931       "someFunction(OtherParam,\n"
11932       "             BracedList{ // comment 1 (Forcing interesting break)\n"
11933       "                         param1, param2,\n"
11934       "                         // comment 2\n"
11935       "                         param3, param4 });",
11936       ExtraSpaces);
11937   verifyFormat(
11938       "std::this_thread::sleep_for(\n"
11939       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
11940       ExtraSpaces);
11941   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
11942                "    aaaaaaa,\n"
11943                "    aaaaaaaaaa,\n"
11944                "    aaaaa,\n"
11945                "    aaaaaaaaaaaaaaa,\n"
11946                "    aaa,\n"
11947                "    aaaaaaaaaa,\n"
11948                "    a,\n"
11949                "    aaaaaaaaaaaaaaaaaaaaa,\n"
11950                "    aaaaaaaaaaaa,\n"
11951                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
11952                "    aaaaaaa,\n"
11953                "    a};");
11954   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
11955   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
11956   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
11957 
11958   // Avoid breaking between initializer/equal sign and opening brace
11959   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
11960   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
11961                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11962                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11963                "  { \"ccccccccccccccccccccc\", 2 }\n"
11964                "};",
11965                ExtraSpaces);
11966   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
11967                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11968                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11969                "  { \"ccccccccccccccccccccc\", 2 }\n"
11970                "};",
11971                ExtraSpaces);
11972 
11973   FormatStyle SpaceBeforeBrace = getLLVMStyle();
11974   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
11975   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
11976   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
11977 
11978   FormatStyle SpaceBetweenBraces = getLLVMStyle();
11979   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
11980   SpaceBetweenBraces.SpacesInParentheses = true;
11981   SpaceBetweenBraces.SpacesInSquareBrackets = true;
11982   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
11983   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
11984   verifyFormat("vector< int > x{ // comment 1\n"
11985                "                 1, 2, 3, 4 };",
11986                SpaceBetweenBraces);
11987   SpaceBetweenBraces.ColumnLimit = 20;
11988   EXPECT_EQ("vector< int > x{\n"
11989             "    1, 2, 3, 4 };",
11990             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11991   SpaceBetweenBraces.ColumnLimit = 24;
11992   EXPECT_EQ("vector< int > x{ 1, 2,\n"
11993             "                 3, 4 };",
11994             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11995   EXPECT_EQ("vector< int > x{\n"
11996             "    1,\n"
11997             "    2,\n"
11998             "    3,\n"
11999             "    4,\n"
12000             "};",
12001             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12002   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12003   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12004   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12005 }
12006 
12007 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12008   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12009                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12010                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12011                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12012                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12013                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12014   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12015                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12016                "                 1, 22, 333, 4444, 55555, //\n"
12017                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12018                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12019   verifyFormat(
12020       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12021       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12022       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12023       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12024       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12025       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12026       "                 7777777};");
12027   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12028                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12029                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12030   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12031                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12032                "    // Separating comment.\n"
12033                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12034   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12035                "    // Leading comment\n"
12036                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12037                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12038   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12039                "                 1, 1, 1, 1};",
12040                getLLVMStyleWithColumns(39));
12041   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12042                "                 1, 1, 1, 1};",
12043                getLLVMStyleWithColumns(38));
12044   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12045                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12046                getLLVMStyleWithColumns(43));
12047   verifyFormat(
12048       "static unsigned SomeValues[10][3] = {\n"
12049       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12050       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12051   verifyFormat("static auto fields = new vector<string>{\n"
12052                "    \"aaaaaaaaaaaaa\",\n"
12053                "    \"aaaaaaaaaaaaa\",\n"
12054                "    \"aaaaaaaaaaaa\",\n"
12055                "    \"aaaaaaaaaaaaaa\",\n"
12056                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12057                "    \"aaaaaaaaaaaa\",\n"
12058                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12059                "};");
12060   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12061   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12062                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12063                "                 3, cccccccccccccccccccccc};",
12064                getLLVMStyleWithColumns(60));
12065 
12066   // Trailing commas.
12067   verifyFormat("vector<int> x = {\n"
12068                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12069                "};",
12070                getLLVMStyleWithColumns(39));
12071   verifyFormat("vector<int> x = {\n"
12072                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12073                "};",
12074                getLLVMStyleWithColumns(39));
12075   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12076                "                 1, 1, 1, 1,\n"
12077                "                 /**/ /**/};",
12078                getLLVMStyleWithColumns(39));
12079 
12080   // Trailing comment in the first line.
12081   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12082                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12083                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12084                "    11111111,   22222222,   333333333,   44444444};");
12085   // Trailing comment in the last line.
12086   verifyFormat("int aaaaa[] = {\n"
12087                "    1, 2, 3, // comment\n"
12088                "    4, 5, 6  // comment\n"
12089                "};");
12090 
12091   // With nested lists, we should either format one item per line or all nested
12092   // lists one on line.
12093   // FIXME: For some nested lists, we can do better.
12094   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12095                "        {aaaaaaaaaaaaaaaaaaa},\n"
12096                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12097                "        {aaaaaaaaaaaaaaaaa}};",
12098                getLLVMStyleWithColumns(60));
12099   verifyFormat(
12100       "SomeStruct my_struct_array = {\n"
12101       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12102       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12103       "    {aaa, aaa},\n"
12104       "    {aaa, aaa},\n"
12105       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12106       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12107       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12108 
12109   // No column layout should be used here.
12110   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12111                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12112 
12113   verifyNoCrash("a<,");
12114 
12115   // No braced initializer here.
12116   verifyFormat("void f() {\n"
12117                "  struct Dummy {};\n"
12118                "  f(v);\n"
12119                "}");
12120 
12121   // Long lists should be formatted in columns even if they are nested.
12122   verifyFormat(
12123       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12124       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12125       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12126       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12127       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12128       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12129 
12130   // Allow "single-column" layout even if that violates the column limit. There
12131   // isn't going to be a better way.
12132   verifyFormat("std::vector<int> a = {\n"
12133                "    aaaaaaaa,\n"
12134                "    aaaaaaaa,\n"
12135                "    aaaaaaaa,\n"
12136                "    aaaaaaaa,\n"
12137                "    aaaaaaaaaa,\n"
12138                "    aaaaaaaa,\n"
12139                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12140                getLLVMStyleWithColumns(30));
12141   verifyFormat("vector<int> aaaa = {\n"
12142                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12143                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12144                "    aaaaaa.aaaaaaa,\n"
12145                "    aaaaaa.aaaaaaa,\n"
12146                "    aaaaaa.aaaaaaa,\n"
12147                "    aaaaaa.aaaaaaa,\n"
12148                "};");
12149 
12150   // Don't create hanging lists.
12151   verifyFormat("someFunction(Param, {List1, List2,\n"
12152                "                     List3});",
12153                getLLVMStyleWithColumns(35));
12154   verifyFormat("someFunction(Param, Param,\n"
12155                "             {List1, List2,\n"
12156                "              List3});",
12157                getLLVMStyleWithColumns(35));
12158   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12159                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12160 }
12161 
12162 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12163   FormatStyle DoNotMerge = getLLVMStyle();
12164   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12165 
12166   verifyFormat("void f() { return 42; }");
12167   verifyFormat("void f() {\n"
12168                "  return 42;\n"
12169                "}",
12170                DoNotMerge);
12171   verifyFormat("void f() {\n"
12172                "  // Comment\n"
12173                "}");
12174   verifyFormat("{\n"
12175                "#error {\n"
12176                "  int a;\n"
12177                "}");
12178   verifyFormat("{\n"
12179                "  int a;\n"
12180                "#error {\n"
12181                "}");
12182   verifyFormat("void f() {} // comment");
12183   verifyFormat("void f() { int a; } // comment");
12184   verifyFormat("void f() {\n"
12185                "} // comment",
12186                DoNotMerge);
12187   verifyFormat("void f() {\n"
12188                "  int a;\n"
12189                "} // comment",
12190                DoNotMerge);
12191   verifyFormat("void f() {\n"
12192                "} // comment",
12193                getLLVMStyleWithColumns(15));
12194 
12195   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12196   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12197 
12198   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12199   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12200   verifyFormat("class C {\n"
12201                "  C()\n"
12202                "      : iiiiiiii(nullptr),\n"
12203                "        kkkkkkk(nullptr),\n"
12204                "        mmmmmmm(nullptr),\n"
12205                "        nnnnnnn(nullptr) {}\n"
12206                "};",
12207                getGoogleStyle());
12208 
12209   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12210   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12211   EXPECT_EQ("class C {\n"
12212             "  A() : b(0) {}\n"
12213             "};",
12214             format("class C{A():b(0){}};", NoColumnLimit));
12215   EXPECT_EQ("A()\n"
12216             "    : b(0) {\n"
12217             "}",
12218             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12219 
12220   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12221   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12222       FormatStyle::SFS_None;
12223   EXPECT_EQ("A()\n"
12224             "    : b(0) {\n"
12225             "}",
12226             format("A():b(0){}", DoNotMergeNoColumnLimit));
12227   EXPECT_EQ("A()\n"
12228             "    : b(0) {\n"
12229             "}",
12230             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12231 
12232   verifyFormat("#define A          \\\n"
12233                "  void f() {       \\\n"
12234                "    int i;         \\\n"
12235                "  }",
12236                getLLVMStyleWithColumns(20));
12237   verifyFormat("#define A           \\\n"
12238                "  void f() { int i; }",
12239                getLLVMStyleWithColumns(21));
12240   verifyFormat("#define A            \\\n"
12241                "  void f() {         \\\n"
12242                "    int i;           \\\n"
12243                "  }                  \\\n"
12244                "  int j;",
12245                getLLVMStyleWithColumns(22));
12246   verifyFormat("#define A             \\\n"
12247                "  void f() { int i; } \\\n"
12248                "  int j;",
12249                getLLVMStyleWithColumns(23));
12250 }
12251 
12252 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12253   FormatStyle MergeEmptyOnly = getLLVMStyle();
12254   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12255   verifyFormat("class C {\n"
12256                "  int f() {}\n"
12257                "};",
12258                MergeEmptyOnly);
12259   verifyFormat("class C {\n"
12260                "  int f() {\n"
12261                "    return 42;\n"
12262                "  }\n"
12263                "};",
12264                MergeEmptyOnly);
12265   verifyFormat("int f() {}", MergeEmptyOnly);
12266   verifyFormat("int f() {\n"
12267                "  return 42;\n"
12268                "}",
12269                MergeEmptyOnly);
12270 
12271   // Also verify behavior when BraceWrapping.AfterFunction = true
12272   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12273   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12274   verifyFormat("int f() {}", MergeEmptyOnly);
12275   verifyFormat("class C {\n"
12276                "  int f() {}\n"
12277                "};",
12278                MergeEmptyOnly);
12279 }
12280 
12281 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12282   FormatStyle MergeInlineOnly = getLLVMStyle();
12283   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12284   verifyFormat("class C {\n"
12285                "  int f() { return 42; }\n"
12286                "};",
12287                MergeInlineOnly);
12288   verifyFormat("int f() {\n"
12289                "  return 42;\n"
12290                "}",
12291                MergeInlineOnly);
12292 
12293   // SFS_Inline implies SFS_Empty
12294   verifyFormat("class C {\n"
12295                "  int f() {}\n"
12296                "};",
12297                MergeInlineOnly);
12298   verifyFormat("int f() {}", MergeInlineOnly);
12299 
12300   // Also verify behavior when BraceWrapping.AfterFunction = true
12301   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12302   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12303   verifyFormat("class C {\n"
12304                "  int f() { return 42; }\n"
12305                "};",
12306                MergeInlineOnly);
12307   verifyFormat("int f()\n"
12308                "{\n"
12309                "  return 42;\n"
12310                "}",
12311                MergeInlineOnly);
12312 
12313   // SFS_Inline implies SFS_Empty
12314   verifyFormat("int f() {}", MergeInlineOnly);
12315   verifyFormat("class C {\n"
12316                "  int f() {}\n"
12317                "};",
12318                MergeInlineOnly);
12319 }
12320 
12321 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12322   FormatStyle MergeInlineOnly = getLLVMStyle();
12323   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12324       FormatStyle::SFS_InlineOnly;
12325   verifyFormat("class C {\n"
12326                "  int f() { return 42; }\n"
12327                "};",
12328                MergeInlineOnly);
12329   verifyFormat("int f() {\n"
12330                "  return 42;\n"
12331                "}",
12332                MergeInlineOnly);
12333 
12334   // SFS_InlineOnly does not imply SFS_Empty
12335   verifyFormat("class C {\n"
12336                "  int f() {}\n"
12337                "};",
12338                MergeInlineOnly);
12339   verifyFormat("int f() {\n"
12340                "}",
12341                MergeInlineOnly);
12342 
12343   // Also verify behavior when BraceWrapping.AfterFunction = true
12344   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12345   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12346   verifyFormat("class C {\n"
12347                "  int f() { return 42; }\n"
12348                "};",
12349                MergeInlineOnly);
12350   verifyFormat("int f()\n"
12351                "{\n"
12352                "  return 42;\n"
12353                "}",
12354                MergeInlineOnly);
12355 
12356   // SFS_InlineOnly does not imply SFS_Empty
12357   verifyFormat("int f()\n"
12358                "{\n"
12359                "}",
12360                MergeInlineOnly);
12361   verifyFormat("class C {\n"
12362                "  int f() {}\n"
12363                "};",
12364                MergeInlineOnly);
12365 }
12366 
12367 TEST_F(FormatTest, SplitEmptyFunction) {
12368   FormatStyle Style = getLLVMStyleWithColumns(40);
12369   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12370   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12371   Style.BraceWrapping.AfterFunction = true;
12372   Style.BraceWrapping.SplitEmptyFunction = false;
12373 
12374   verifyFormat("int f()\n"
12375                "{}",
12376                Style);
12377   verifyFormat("int f()\n"
12378                "{\n"
12379                "  return 42;\n"
12380                "}",
12381                Style);
12382   verifyFormat("int f()\n"
12383                "{\n"
12384                "  // some comment\n"
12385                "}",
12386                Style);
12387 
12388   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12389   verifyFormat("int f() {}", Style);
12390   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12391                "{}",
12392                Style);
12393   verifyFormat("int f()\n"
12394                "{\n"
12395                "  return 0;\n"
12396                "}",
12397                Style);
12398 
12399   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12400   verifyFormat("class Foo {\n"
12401                "  int f() {}\n"
12402                "};\n",
12403                Style);
12404   verifyFormat("class Foo {\n"
12405                "  int f() { return 0; }\n"
12406                "};\n",
12407                Style);
12408   verifyFormat("class Foo {\n"
12409                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12410                "  {}\n"
12411                "};\n",
12412                Style);
12413   verifyFormat("class Foo {\n"
12414                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12415                "  {\n"
12416                "    return 0;\n"
12417                "  }\n"
12418                "};\n",
12419                Style);
12420 
12421   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12422   verifyFormat("int f() {}", Style);
12423   verifyFormat("int f() { return 0; }", Style);
12424   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12425                "{}",
12426                Style);
12427   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12428                "{\n"
12429                "  return 0;\n"
12430                "}",
12431                Style);
12432 }
12433 
12434 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12435   FormatStyle Style = getLLVMStyleWithColumns(40);
12436   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12437   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12438   Style.BraceWrapping.AfterFunction = true;
12439   Style.BraceWrapping.SplitEmptyFunction = true;
12440   Style.BraceWrapping.SplitEmptyRecord = false;
12441 
12442   verifyFormat("class C {};", Style);
12443   verifyFormat("struct C {};", Style);
12444   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12445                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12446                "{\n"
12447                "}",
12448                Style);
12449   verifyFormat("class C {\n"
12450                "  C()\n"
12451                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12452                "        bbbbbbbbbbbbbbbbbbb()\n"
12453                "  {\n"
12454                "  }\n"
12455                "  void\n"
12456                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12457                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12458                "  {\n"
12459                "  }\n"
12460                "};",
12461                Style);
12462 }
12463 
12464 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12465   FormatStyle Style = getLLVMStyle();
12466   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12467   verifyFormat("#ifdef A\n"
12468                "int f() {}\n"
12469                "#else\n"
12470                "int g() {}\n"
12471                "#endif",
12472                Style);
12473 }
12474 
12475 TEST_F(FormatTest, SplitEmptyClass) {
12476   FormatStyle Style = getLLVMStyle();
12477   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12478   Style.BraceWrapping.AfterClass = true;
12479   Style.BraceWrapping.SplitEmptyRecord = false;
12480 
12481   verifyFormat("class Foo\n"
12482                "{};",
12483                Style);
12484   verifyFormat("/* something */ class Foo\n"
12485                "{};",
12486                Style);
12487   verifyFormat("template <typename X> class Foo\n"
12488                "{};",
12489                Style);
12490   verifyFormat("class Foo\n"
12491                "{\n"
12492                "  Foo();\n"
12493                "};",
12494                Style);
12495   verifyFormat("typedef class Foo\n"
12496                "{\n"
12497                "} Foo_t;",
12498                Style);
12499 
12500   Style.BraceWrapping.SplitEmptyRecord = true;
12501   Style.BraceWrapping.AfterStruct = true;
12502   verifyFormat("class rep\n"
12503                "{\n"
12504                "};",
12505                Style);
12506   verifyFormat("struct rep\n"
12507                "{\n"
12508                "};",
12509                Style);
12510   verifyFormat("template <typename T> class rep\n"
12511                "{\n"
12512                "};",
12513                Style);
12514   verifyFormat("template <typename T> struct rep\n"
12515                "{\n"
12516                "};",
12517                Style);
12518   verifyFormat("class rep\n"
12519                "{\n"
12520                "  int x;\n"
12521                "};",
12522                Style);
12523   verifyFormat("struct rep\n"
12524                "{\n"
12525                "  int x;\n"
12526                "};",
12527                Style);
12528   verifyFormat("template <typename T> class rep\n"
12529                "{\n"
12530                "  int x;\n"
12531                "};",
12532                Style);
12533   verifyFormat("template <typename T> struct rep\n"
12534                "{\n"
12535                "  int x;\n"
12536                "};",
12537                Style);
12538   verifyFormat("template <typename T> class rep // Foo\n"
12539                "{\n"
12540                "  int x;\n"
12541                "};",
12542                Style);
12543   verifyFormat("template <typename T> struct rep // Bar\n"
12544                "{\n"
12545                "  int x;\n"
12546                "};",
12547                Style);
12548 
12549   verifyFormat("template <typename T> class rep<T>\n"
12550                "{\n"
12551                "  int x;\n"
12552                "};",
12553                Style);
12554 
12555   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12556                "{\n"
12557                "  int x;\n"
12558                "};",
12559                Style);
12560   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12561                "{\n"
12562                "};",
12563                Style);
12564 
12565   verifyFormat("#include \"stdint.h\"\n"
12566                "namespace rep {}",
12567                Style);
12568   verifyFormat("#include <stdint.h>\n"
12569                "namespace rep {}",
12570                Style);
12571   verifyFormat("#include <stdint.h>\n"
12572                "namespace rep {}",
12573                "#include <stdint.h>\n"
12574                "namespace rep {\n"
12575                "\n"
12576                "\n"
12577                "}",
12578                Style);
12579 }
12580 
12581 TEST_F(FormatTest, SplitEmptyStruct) {
12582   FormatStyle Style = getLLVMStyle();
12583   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12584   Style.BraceWrapping.AfterStruct = true;
12585   Style.BraceWrapping.SplitEmptyRecord = false;
12586 
12587   verifyFormat("struct Foo\n"
12588                "{};",
12589                Style);
12590   verifyFormat("/* something */ struct Foo\n"
12591                "{};",
12592                Style);
12593   verifyFormat("template <typename X> struct Foo\n"
12594                "{};",
12595                Style);
12596   verifyFormat("struct Foo\n"
12597                "{\n"
12598                "  Foo();\n"
12599                "};",
12600                Style);
12601   verifyFormat("typedef struct Foo\n"
12602                "{\n"
12603                "} Foo_t;",
12604                Style);
12605   // typedef struct Bar {} Bar_t;
12606 }
12607 
12608 TEST_F(FormatTest, SplitEmptyUnion) {
12609   FormatStyle Style = getLLVMStyle();
12610   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12611   Style.BraceWrapping.AfterUnion = true;
12612   Style.BraceWrapping.SplitEmptyRecord = false;
12613 
12614   verifyFormat("union Foo\n"
12615                "{};",
12616                Style);
12617   verifyFormat("/* something */ union Foo\n"
12618                "{};",
12619                Style);
12620   verifyFormat("union Foo\n"
12621                "{\n"
12622                "  A,\n"
12623                "};",
12624                Style);
12625   verifyFormat("typedef union Foo\n"
12626                "{\n"
12627                "} Foo_t;",
12628                Style);
12629 }
12630 
12631 TEST_F(FormatTest, SplitEmptyNamespace) {
12632   FormatStyle Style = getLLVMStyle();
12633   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12634   Style.BraceWrapping.AfterNamespace = true;
12635   Style.BraceWrapping.SplitEmptyNamespace = false;
12636 
12637   verifyFormat("namespace Foo\n"
12638                "{};",
12639                Style);
12640   verifyFormat("/* something */ namespace Foo\n"
12641                "{};",
12642                Style);
12643   verifyFormat("inline namespace Foo\n"
12644                "{};",
12645                Style);
12646   verifyFormat("/* something */ inline namespace Foo\n"
12647                "{};",
12648                Style);
12649   verifyFormat("export namespace Foo\n"
12650                "{};",
12651                Style);
12652   verifyFormat("namespace Foo\n"
12653                "{\n"
12654                "void Bar();\n"
12655                "};",
12656                Style);
12657 }
12658 
12659 TEST_F(FormatTest, NeverMergeShortRecords) {
12660   FormatStyle Style = getLLVMStyle();
12661 
12662   verifyFormat("class Foo {\n"
12663                "  Foo();\n"
12664                "};",
12665                Style);
12666   verifyFormat("typedef class Foo {\n"
12667                "  Foo();\n"
12668                "} Foo_t;",
12669                Style);
12670   verifyFormat("struct Foo {\n"
12671                "  Foo();\n"
12672                "};",
12673                Style);
12674   verifyFormat("typedef struct Foo {\n"
12675                "  Foo();\n"
12676                "} Foo_t;",
12677                Style);
12678   verifyFormat("union Foo {\n"
12679                "  A,\n"
12680                "};",
12681                Style);
12682   verifyFormat("typedef union Foo {\n"
12683                "  A,\n"
12684                "} Foo_t;",
12685                Style);
12686   verifyFormat("namespace Foo {\n"
12687                "void Bar();\n"
12688                "};",
12689                Style);
12690 
12691   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12692   Style.BraceWrapping.AfterClass = true;
12693   Style.BraceWrapping.AfterStruct = true;
12694   Style.BraceWrapping.AfterUnion = true;
12695   Style.BraceWrapping.AfterNamespace = true;
12696   verifyFormat("class Foo\n"
12697                "{\n"
12698                "  Foo();\n"
12699                "};",
12700                Style);
12701   verifyFormat("typedef class Foo\n"
12702                "{\n"
12703                "  Foo();\n"
12704                "} Foo_t;",
12705                Style);
12706   verifyFormat("struct Foo\n"
12707                "{\n"
12708                "  Foo();\n"
12709                "};",
12710                Style);
12711   verifyFormat("typedef struct Foo\n"
12712                "{\n"
12713                "  Foo();\n"
12714                "} Foo_t;",
12715                Style);
12716   verifyFormat("union Foo\n"
12717                "{\n"
12718                "  A,\n"
12719                "};",
12720                Style);
12721   verifyFormat("typedef union Foo\n"
12722                "{\n"
12723                "  A,\n"
12724                "} Foo_t;",
12725                Style);
12726   verifyFormat("namespace Foo\n"
12727                "{\n"
12728                "void Bar();\n"
12729                "};",
12730                Style);
12731 }
12732 
12733 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
12734   // Elaborate type variable declarations.
12735   verifyFormat("struct foo a = {bar};\nint n;");
12736   verifyFormat("class foo a = {bar};\nint n;");
12737   verifyFormat("union foo a = {bar};\nint n;");
12738 
12739   // Elaborate types inside function definitions.
12740   verifyFormat("struct foo f() {}\nint n;");
12741   verifyFormat("class foo f() {}\nint n;");
12742   verifyFormat("union foo f() {}\nint n;");
12743 
12744   // Templates.
12745   verifyFormat("template <class X> void f() {}\nint n;");
12746   verifyFormat("template <struct X> void f() {}\nint n;");
12747   verifyFormat("template <union X> void f() {}\nint n;");
12748 
12749   // Actual definitions...
12750   verifyFormat("struct {\n} n;");
12751   verifyFormat(
12752       "template <template <class T, class Y>, class Z> class X {\n} n;");
12753   verifyFormat("union Z {\n  int n;\n} x;");
12754   verifyFormat("class MACRO Z {\n} n;");
12755   verifyFormat("class MACRO(X) Z {\n} n;");
12756   verifyFormat("class __attribute__(X) Z {\n} n;");
12757   verifyFormat("class __declspec(X) Z {\n} n;");
12758   verifyFormat("class A##B##C {\n} n;");
12759   verifyFormat("class alignas(16) Z {\n} n;");
12760   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
12761   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
12762 
12763   // Redefinition from nested context:
12764   verifyFormat("class A::B::C {\n} n;");
12765 
12766   // Template definitions.
12767   verifyFormat(
12768       "template <typename F>\n"
12769       "Matcher(const Matcher<F> &Other,\n"
12770       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
12771       "                             !is_same<F, T>::value>::type * = 0)\n"
12772       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
12773 
12774   // FIXME: This is still incorrectly handled at the formatter side.
12775   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
12776   verifyFormat("int i = SomeFunction(a<b, a> b);");
12777 
12778   // FIXME:
12779   // This now gets parsed incorrectly as class definition.
12780   // verifyFormat("class A<int> f() {\n}\nint n;");
12781 
12782   // Elaborate types where incorrectly parsing the structural element would
12783   // break the indent.
12784   verifyFormat("if (true)\n"
12785                "  class X x;\n"
12786                "else\n"
12787                "  f();\n");
12788 
12789   // This is simply incomplete. Formatting is not important, but must not crash.
12790   verifyFormat("class A:");
12791 }
12792 
12793 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
12794   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
12795             format("#error Leave     all         white!!!!! space* alone!\n"));
12796   EXPECT_EQ(
12797       "#warning Leave     all         white!!!!! space* alone!\n",
12798       format("#warning Leave     all         white!!!!! space* alone!\n"));
12799   EXPECT_EQ("#error 1", format("  #  error   1"));
12800   EXPECT_EQ("#warning 1", format("  #  warning 1"));
12801 }
12802 
12803 TEST_F(FormatTest, FormatHashIfExpressions) {
12804   verifyFormat("#if AAAA && BBBB");
12805   verifyFormat("#if (AAAA && BBBB)");
12806   verifyFormat("#elif (AAAA && BBBB)");
12807   // FIXME: Come up with a better indentation for #elif.
12808   verifyFormat(
12809       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
12810       "    defined(BBBBBBBB)\n"
12811       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
12812       "    defined(BBBBBBBB)\n"
12813       "#endif",
12814       getLLVMStyleWithColumns(65));
12815 }
12816 
12817 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
12818   FormatStyle AllowsMergedIf = getGoogleStyle();
12819   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
12820       FormatStyle::SIS_WithoutElse;
12821   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
12822   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
12823   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
12824   EXPECT_EQ("if (true) return 42;",
12825             format("if (true)\nreturn 42;", AllowsMergedIf));
12826   FormatStyle ShortMergedIf = AllowsMergedIf;
12827   ShortMergedIf.ColumnLimit = 25;
12828   verifyFormat("#define A \\\n"
12829                "  if (true) return 42;",
12830                ShortMergedIf);
12831   verifyFormat("#define A \\\n"
12832                "  f();    \\\n"
12833                "  if (true)\n"
12834                "#define B",
12835                ShortMergedIf);
12836   verifyFormat("#define A \\\n"
12837                "  f();    \\\n"
12838                "  if (true)\n"
12839                "g();",
12840                ShortMergedIf);
12841   verifyFormat("{\n"
12842                "#ifdef A\n"
12843                "  // Comment\n"
12844                "  if (true) continue;\n"
12845                "#endif\n"
12846                "  // Comment\n"
12847                "  if (true) continue;\n"
12848                "}",
12849                ShortMergedIf);
12850   ShortMergedIf.ColumnLimit = 33;
12851   verifyFormat("#define A \\\n"
12852                "  if constexpr (true) return 42;",
12853                ShortMergedIf);
12854   verifyFormat("#define A \\\n"
12855                "  if CONSTEXPR (true) return 42;",
12856                ShortMergedIf);
12857   ShortMergedIf.ColumnLimit = 29;
12858   verifyFormat("#define A                   \\\n"
12859                "  if (aaaaaaaaaa) return 1; \\\n"
12860                "  return 2;",
12861                ShortMergedIf);
12862   ShortMergedIf.ColumnLimit = 28;
12863   verifyFormat("#define A         \\\n"
12864                "  if (aaaaaaaaaa) \\\n"
12865                "    return 1;     \\\n"
12866                "  return 2;",
12867                ShortMergedIf);
12868   verifyFormat("#define A                \\\n"
12869                "  if constexpr (aaaaaaa) \\\n"
12870                "    return 1;            \\\n"
12871                "  return 2;",
12872                ShortMergedIf);
12873   verifyFormat("#define A                \\\n"
12874                "  if CONSTEXPR (aaaaaaa) \\\n"
12875                "    return 1;            \\\n"
12876                "  return 2;",
12877                ShortMergedIf);
12878 }
12879 
12880 TEST_F(FormatTest, FormatStarDependingOnContext) {
12881   verifyFormat("void f(int *a);");
12882   verifyFormat("void f() { f(fint * b); }");
12883   verifyFormat("class A {\n  void f(int *a);\n};");
12884   verifyFormat("class A {\n  int *a;\n};");
12885   verifyFormat("namespace a {\n"
12886                "namespace b {\n"
12887                "class A {\n"
12888                "  void f() {}\n"
12889                "  int *a;\n"
12890                "};\n"
12891                "} // namespace b\n"
12892                "} // namespace a");
12893 }
12894 
12895 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
12896   verifyFormat("while");
12897   verifyFormat("operator");
12898 }
12899 
12900 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
12901   // This code would be painfully slow to format if we didn't skip it.
12902   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
12903                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12904                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12905                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12906                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12907                    "A(1, 1)\n"
12908                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
12909                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12910                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12911                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12912                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12913                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12914                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12915                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12916                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12917                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
12918   // Deeply nested part is untouched, rest is formatted.
12919   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
12920             format(std::string("int    i;\n") + Code + "int    j;\n",
12921                    getLLVMStyle(), SC_ExpectIncomplete));
12922 }
12923 
12924 //===----------------------------------------------------------------------===//
12925 // Objective-C tests.
12926 //===----------------------------------------------------------------------===//
12927 
12928 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
12929   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
12930   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
12931             format("-(NSUInteger)indexOfObject:(id)anObject;"));
12932   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
12933   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
12934   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
12935             format("-(NSInteger)Method3:(id)anObject;"));
12936   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
12937             format("-(NSInteger)Method4:(id)anObject;"));
12938   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
12939             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
12940   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
12941             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
12942   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12943             "forAllCells:(BOOL)flag;",
12944             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12945                    "forAllCells:(BOOL)flag;"));
12946 
12947   // Very long objectiveC method declaration.
12948   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
12949                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
12950   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
12951                "                    inRange:(NSRange)range\n"
12952                "                   outRange:(NSRange)out_range\n"
12953                "                  outRange1:(NSRange)out_range1\n"
12954                "                  outRange2:(NSRange)out_range2\n"
12955                "                  outRange3:(NSRange)out_range3\n"
12956                "                  outRange4:(NSRange)out_range4\n"
12957                "                  outRange5:(NSRange)out_range5\n"
12958                "                  outRange6:(NSRange)out_range6\n"
12959                "                  outRange7:(NSRange)out_range7\n"
12960                "                  outRange8:(NSRange)out_range8\n"
12961                "                  outRange9:(NSRange)out_range9;");
12962 
12963   // When the function name has to be wrapped.
12964   FormatStyle Style = getLLVMStyle();
12965   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
12966   // and always indents instead.
12967   Style.IndentWrappedFunctionNames = false;
12968   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12969                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
12970                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
12971                "}",
12972                Style);
12973   Style.IndentWrappedFunctionNames = true;
12974   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12975                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
12976                "               anotherName:(NSString)dddddddddddddd {\n"
12977                "}",
12978                Style);
12979 
12980   verifyFormat("- (int)sum:(vector<int>)numbers;");
12981   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
12982   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
12983   // protocol lists (but not for template classes):
12984   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
12985 
12986   verifyFormat("- (int (*)())foo:(int (*)())f;");
12987   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
12988 
12989   // If there's no return type (very rare in practice!), LLVM and Google style
12990   // agree.
12991   verifyFormat("- foo;");
12992   verifyFormat("- foo:(int)f;");
12993   verifyGoogleFormat("- foo:(int)foo;");
12994 }
12995 
12996 TEST_F(FormatTest, BreaksStringLiterals) {
12997   EXPECT_EQ("\"some text \"\n"
12998             "\"other\";",
12999             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13000   EXPECT_EQ("\"some text \"\n"
13001             "\"other\";",
13002             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13003   EXPECT_EQ(
13004       "#define A  \\\n"
13005       "  \"some \"  \\\n"
13006       "  \"text \"  \\\n"
13007       "  \"other\";",
13008       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13009   EXPECT_EQ(
13010       "#define A  \\\n"
13011       "  \"so \"    \\\n"
13012       "  \"text \"  \\\n"
13013       "  \"other\";",
13014       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13015 
13016   EXPECT_EQ("\"some text\"",
13017             format("\"some text\"", getLLVMStyleWithColumns(1)));
13018   EXPECT_EQ("\"some text\"",
13019             format("\"some text\"", getLLVMStyleWithColumns(11)));
13020   EXPECT_EQ("\"some \"\n"
13021             "\"text\"",
13022             format("\"some text\"", getLLVMStyleWithColumns(10)));
13023   EXPECT_EQ("\"some \"\n"
13024             "\"text\"",
13025             format("\"some text\"", getLLVMStyleWithColumns(7)));
13026   EXPECT_EQ("\"some\"\n"
13027             "\" tex\"\n"
13028             "\"t\"",
13029             format("\"some text\"", getLLVMStyleWithColumns(6)));
13030   EXPECT_EQ("\"some\"\n"
13031             "\" tex\"\n"
13032             "\" and\"",
13033             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13034   EXPECT_EQ("\"some\"\n"
13035             "\"/tex\"\n"
13036             "\"/and\"",
13037             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13038 
13039   EXPECT_EQ("variable =\n"
13040             "    \"long string \"\n"
13041             "    \"literal\";",
13042             format("variable = \"long string literal\";",
13043                    getLLVMStyleWithColumns(20)));
13044 
13045   EXPECT_EQ("variable = f(\n"
13046             "    \"long string \"\n"
13047             "    \"literal\",\n"
13048             "    short,\n"
13049             "    loooooooooooooooooooong);",
13050             format("variable = f(\"long string literal\", short, "
13051                    "loooooooooooooooooooong);",
13052                    getLLVMStyleWithColumns(20)));
13053 
13054   EXPECT_EQ(
13055       "f(g(\"long string \"\n"
13056       "    \"literal\"),\n"
13057       "  b);",
13058       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13059   EXPECT_EQ("f(g(\"long string \"\n"
13060             "    \"literal\",\n"
13061             "    a),\n"
13062             "  b);",
13063             format("f(g(\"long string literal\", a), b);",
13064                    getLLVMStyleWithColumns(20)));
13065   EXPECT_EQ(
13066       "f(\"one two\".split(\n"
13067       "    variable));",
13068       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13069   EXPECT_EQ("f(\"one two three four five six \"\n"
13070             "  \"seven\".split(\n"
13071             "      really_looooong_variable));",
13072             format("f(\"one two three four five six seven\"."
13073                    "split(really_looooong_variable));",
13074                    getLLVMStyleWithColumns(33)));
13075 
13076   EXPECT_EQ("f(\"some \"\n"
13077             "  \"text\",\n"
13078             "  other);",
13079             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13080 
13081   // Only break as a last resort.
13082   verifyFormat(
13083       "aaaaaaaaaaaaaaaaaaaa(\n"
13084       "    aaaaaaaaaaaaaaaaaaaa,\n"
13085       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13086 
13087   EXPECT_EQ("\"splitmea\"\n"
13088             "\"trandomp\"\n"
13089             "\"oint\"",
13090             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13091 
13092   EXPECT_EQ("\"split/\"\n"
13093             "\"pathat/\"\n"
13094             "\"slashes\"",
13095             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13096 
13097   EXPECT_EQ("\"split/\"\n"
13098             "\"pathat/\"\n"
13099             "\"slashes\"",
13100             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13101   EXPECT_EQ("\"split at \"\n"
13102             "\"spaces/at/\"\n"
13103             "\"slashes.at.any$\"\n"
13104             "\"non-alphanumeric%\"\n"
13105             "\"1111111111characte\"\n"
13106             "\"rs\"",
13107             format("\"split at "
13108                    "spaces/at/"
13109                    "slashes.at."
13110                    "any$non-"
13111                    "alphanumeric%"
13112                    "1111111111characte"
13113                    "rs\"",
13114                    getLLVMStyleWithColumns(20)));
13115 
13116   // Verify that splitting the strings understands
13117   // Style::AlwaysBreakBeforeMultilineStrings.
13118   EXPECT_EQ("aaaaaaaaaaaa(\n"
13119             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13120             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13121             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13122                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13123                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13124                    getGoogleStyle()));
13125   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13126             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13127             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13128                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13129                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13130                    getGoogleStyle()));
13131   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13132             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13133             format("llvm::outs() << "
13134                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13135                    "aaaaaaaaaaaaaaaaaaa\";"));
13136   EXPECT_EQ("ffff(\n"
13137             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13138             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13139             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13140                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13141                    getGoogleStyle()));
13142 
13143   FormatStyle Style = getLLVMStyleWithColumns(12);
13144   Style.BreakStringLiterals = false;
13145   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13146 
13147   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13148   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13149   EXPECT_EQ("#define A \\\n"
13150             "  \"some \" \\\n"
13151             "  \"text \" \\\n"
13152             "  \"other\";",
13153             format("#define A \"some text other\";", AlignLeft));
13154 }
13155 
13156 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13157   EXPECT_EQ("C a = \"some more \"\n"
13158             "      \"text\";",
13159             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13160 }
13161 
13162 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13163   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13164   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13165   EXPECT_EQ("int i = a(b());",
13166             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13167 }
13168 
13169 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13170   EXPECT_EQ(
13171       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13172       "(\n"
13173       "    \"x\t\");",
13174       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13175              "aaaaaaa("
13176              "\"x\t\");"));
13177 }
13178 
13179 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13180   EXPECT_EQ(
13181       "u8\"utf8 string \"\n"
13182       "u8\"literal\";",
13183       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13184   EXPECT_EQ(
13185       "u\"utf16 string \"\n"
13186       "u\"literal\";",
13187       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13188   EXPECT_EQ(
13189       "U\"utf32 string \"\n"
13190       "U\"literal\";",
13191       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13192   EXPECT_EQ("L\"wide string \"\n"
13193             "L\"literal\";",
13194             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13195   EXPECT_EQ("@\"NSString \"\n"
13196             "@\"literal\";",
13197             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13198   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13199 
13200   // This input makes clang-format try to split the incomplete unicode escape
13201   // sequence, which used to lead to a crasher.
13202   verifyNoCrash(
13203       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13204       getLLVMStyleWithColumns(60));
13205 }
13206 
13207 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13208   FormatStyle Style = getGoogleStyleWithColumns(15);
13209   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13210   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13211   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13212   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13213   EXPECT_EQ("u8R\"x(raw literal)x\";",
13214             format("u8R\"x(raw literal)x\";", Style));
13215 }
13216 
13217 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13218   FormatStyle Style = getLLVMStyleWithColumns(20);
13219   EXPECT_EQ(
13220       "_T(\"aaaaaaaaaaaaaa\")\n"
13221       "_T(\"aaaaaaaaaaaaaa\")\n"
13222       "_T(\"aaaaaaaaaaaa\")",
13223       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13224   EXPECT_EQ("f(x,\n"
13225             "  _T(\"aaaaaaaaaaaa\")\n"
13226             "  _T(\"aaa\"),\n"
13227             "  z);",
13228             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13229 
13230   // FIXME: Handle embedded spaces in one iteration.
13231   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13232   //            "_T(\"aaaaaaaaaaaaa\")\n"
13233   //            "_T(\"aaaaaaaaaaaaa\")\n"
13234   //            "_T(\"a\")",
13235   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13236   //                   getLLVMStyleWithColumns(20)));
13237   EXPECT_EQ(
13238       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13239       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13240   EXPECT_EQ("f(\n"
13241             "#if !TEST\n"
13242             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13243             "#endif\n"
13244             ");",
13245             format("f(\n"
13246                    "#if !TEST\n"
13247                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13248                    "#endif\n"
13249                    ");"));
13250   EXPECT_EQ("f(\n"
13251             "\n"
13252             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13253             format("f(\n"
13254                    "\n"
13255                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13256   // Regression test for accessing tokens past the end of a vector in the
13257   // TokenLexer.
13258   verifyNoCrash(R"(_T(
13259 "
13260 )
13261 )");
13262 }
13263 
13264 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13265   // In a function call with two operands, the second can be broken with no line
13266   // break before it.
13267   EXPECT_EQ(
13268       "func(a, \"long long \"\n"
13269       "        \"long long\");",
13270       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13271   // In a function call with three operands, the second must be broken with a
13272   // line break before it.
13273   EXPECT_EQ("func(a,\n"
13274             "     \"long long long \"\n"
13275             "     \"long\",\n"
13276             "     c);",
13277             format("func(a, \"long long long long\", c);",
13278                    getLLVMStyleWithColumns(24)));
13279   // In a function call with three operands, the third must be broken with a
13280   // line break before it.
13281   EXPECT_EQ("func(a, b,\n"
13282             "     \"long long long \"\n"
13283             "     \"long\");",
13284             format("func(a, b, \"long long long long\");",
13285                    getLLVMStyleWithColumns(24)));
13286   // In a function call with three operands, both the second and the third must
13287   // be broken with a line break before them.
13288   EXPECT_EQ("func(a,\n"
13289             "     \"long long long \"\n"
13290             "     \"long\",\n"
13291             "     \"long long long \"\n"
13292             "     \"long\");",
13293             format("func(a, \"long long long long\", \"long long long long\");",
13294                    getLLVMStyleWithColumns(24)));
13295   // In a chain of << with two operands, the second can be broken with no line
13296   // break before it.
13297   EXPECT_EQ("a << \"line line \"\n"
13298             "     \"line\";",
13299             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13300   // In a chain of << with three operands, the second can be broken with no line
13301   // break before it.
13302   EXPECT_EQ(
13303       "abcde << \"line \"\n"
13304       "         \"line line\"\n"
13305       "      << c;",
13306       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13307   // In a chain of << with three operands, the third must be broken with a line
13308   // break before it.
13309   EXPECT_EQ(
13310       "a << b\n"
13311       "  << \"line line \"\n"
13312       "     \"line\";",
13313       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13314   // In a chain of << with three operands, the second can be broken with no line
13315   // break before it and the third must be broken with a line break before it.
13316   EXPECT_EQ("abcd << \"line line \"\n"
13317             "        \"line\"\n"
13318             "     << \"line line \"\n"
13319             "        \"line\";",
13320             format("abcd << \"line line line\" << \"line line line\";",
13321                    getLLVMStyleWithColumns(20)));
13322   // In a chain of binary operators with two operands, the second can be broken
13323   // with no line break before it.
13324   EXPECT_EQ(
13325       "abcd + \"line line \"\n"
13326       "       \"line line\";",
13327       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13328   // In a chain of binary operators with three operands, the second must be
13329   // broken with a line break before it.
13330   EXPECT_EQ("abcd +\n"
13331             "    \"line line \"\n"
13332             "    \"line line\" +\n"
13333             "    e;",
13334             format("abcd + \"line line line line\" + e;",
13335                    getLLVMStyleWithColumns(20)));
13336   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13337   // the first must be broken with a line break before it.
13338   FormatStyle Style = getLLVMStyleWithColumns(25);
13339   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13340   EXPECT_EQ("someFunction(\n"
13341             "    \"long long long \"\n"
13342             "    \"long\",\n"
13343             "    a);",
13344             format("someFunction(\"long long long long\", a);", Style));
13345 }
13346 
13347 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13348   EXPECT_EQ(
13349       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13350       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13351       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13352       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13353              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13354              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13355 }
13356 
13357 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13358   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13359             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13360   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13361             "multiline raw string literal xxxxxxxxxxxxxx\n"
13362             ")x\",\n"
13363             "              a),\n"
13364             "            b);",
13365             format("fffffffffff(g(R\"x(\n"
13366                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13367                    ")x\", a), b);",
13368                    getGoogleStyleWithColumns(20)));
13369   EXPECT_EQ("fffffffffff(\n"
13370             "    g(R\"x(qqq\n"
13371             "multiline raw string literal xxxxxxxxxxxxxx\n"
13372             ")x\",\n"
13373             "      a),\n"
13374             "    b);",
13375             format("fffffffffff(g(R\"x(qqq\n"
13376                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13377                    ")x\", a), b);",
13378                    getGoogleStyleWithColumns(20)));
13379 
13380   EXPECT_EQ("fffffffffff(R\"x(\n"
13381             "multiline raw string literal xxxxxxxxxxxxxx\n"
13382             ")x\");",
13383             format("fffffffffff(R\"x(\n"
13384                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13385                    ")x\");",
13386                    getGoogleStyleWithColumns(20)));
13387   EXPECT_EQ("fffffffffff(R\"x(\n"
13388             "multiline raw string literal xxxxxxxxxxxxxx\n"
13389             ")x\" + bbbbbb);",
13390             format("fffffffffff(R\"x(\n"
13391                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13392                    ")x\" +   bbbbbb);",
13393                    getGoogleStyleWithColumns(20)));
13394   EXPECT_EQ("fffffffffff(\n"
13395             "    R\"x(\n"
13396             "multiline raw string literal xxxxxxxxxxxxxx\n"
13397             ")x\" +\n"
13398             "    bbbbbb);",
13399             format("fffffffffff(\n"
13400                    " R\"x(\n"
13401                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13402                    ")x\" + bbbbbb);",
13403                    getGoogleStyleWithColumns(20)));
13404   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13405             format("fffffffffff(\n"
13406                    " R\"(single line raw string)\" + bbbbbb);"));
13407 }
13408 
13409 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13410   verifyFormat("string a = \"unterminated;");
13411   EXPECT_EQ("function(\"unterminated,\n"
13412             "         OtherParameter);",
13413             format("function(  \"unterminated,\n"
13414                    "    OtherParameter);"));
13415 }
13416 
13417 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13418   FormatStyle Style = getLLVMStyle();
13419   Style.Standard = FormatStyle::LS_Cpp03;
13420   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13421             format("#define x(_a) printf(\"foo\"_a);", Style));
13422 }
13423 
13424 TEST_F(FormatTest, CppLexVersion) {
13425   FormatStyle Style = getLLVMStyle();
13426   // Formatting of x * y differs if x is a type.
13427   verifyFormat("void foo() { MACRO(a * b); }", Style);
13428   verifyFormat("void foo() { MACRO(int *b); }", Style);
13429 
13430   // LLVM style uses latest lexer.
13431   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13432   Style.Standard = FormatStyle::LS_Cpp17;
13433   // But in c++17, char8_t isn't a keyword.
13434   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13435 }
13436 
13437 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13438 
13439 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13440   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13441             "             \"ddeeefff\");",
13442             format("someFunction(\"aaabbbcccdddeeefff\");",
13443                    getLLVMStyleWithColumns(25)));
13444   EXPECT_EQ("someFunction1234567890(\n"
13445             "    \"aaabbbcccdddeeefff\");",
13446             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13447                    getLLVMStyleWithColumns(26)));
13448   EXPECT_EQ("someFunction1234567890(\n"
13449             "    \"aaabbbcccdddeeeff\"\n"
13450             "    \"f\");",
13451             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13452                    getLLVMStyleWithColumns(25)));
13453   EXPECT_EQ("someFunction1234567890(\n"
13454             "    \"aaabbbcccdddeeeff\"\n"
13455             "    \"f\");",
13456             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13457                    getLLVMStyleWithColumns(24)));
13458   EXPECT_EQ("someFunction(\n"
13459             "    \"aaabbbcc ddde \"\n"
13460             "    \"efff\");",
13461             format("someFunction(\"aaabbbcc ddde efff\");",
13462                    getLLVMStyleWithColumns(25)));
13463   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13464             "             \"ddeeefff\");",
13465             format("someFunction(\"aaabbbccc ddeeefff\");",
13466                    getLLVMStyleWithColumns(25)));
13467   EXPECT_EQ("someFunction1234567890(\n"
13468             "    \"aaabb \"\n"
13469             "    \"cccdddeeefff\");",
13470             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13471                    getLLVMStyleWithColumns(25)));
13472   EXPECT_EQ("#define A          \\\n"
13473             "  string s =       \\\n"
13474             "      \"123456789\"  \\\n"
13475             "      \"0\";         \\\n"
13476             "  int i;",
13477             format("#define A string s = \"1234567890\"; int i;",
13478                    getLLVMStyleWithColumns(20)));
13479   EXPECT_EQ("someFunction(\n"
13480             "    \"aaabbbcc \"\n"
13481             "    \"dddeeefff\");",
13482             format("someFunction(\"aaabbbcc dddeeefff\");",
13483                    getLLVMStyleWithColumns(25)));
13484 }
13485 
13486 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13487   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13488   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13489   EXPECT_EQ("\"test\"\n"
13490             "\"\\n\"",
13491             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
13492   EXPECT_EQ("\"tes\\\\\"\n"
13493             "\"n\"",
13494             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
13495   EXPECT_EQ("\"\\\\\\\\\"\n"
13496             "\"\\n\"",
13497             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
13498   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
13499   EXPECT_EQ("\"\\uff01\"\n"
13500             "\"test\"",
13501             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
13502   EXPECT_EQ("\"\\Uff01ff02\"",
13503             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
13504   EXPECT_EQ("\"\\x000000000001\"\n"
13505             "\"next\"",
13506             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
13507   EXPECT_EQ("\"\\x000000000001next\"",
13508             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
13509   EXPECT_EQ("\"\\x000000000001\"",
13510             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
13511   EXPECT_EQ("\"test\"\n"
13512             "\"\\000000\"\n"
13513             "\"000001\"",
13514             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
13515   EXPECT_EQ("\"test\\000\"\n"
13516             "\"00000000\"\n"
13517             "\"1\"",
13518             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
13519 }
13520 
13521 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
13522   verifyFormat("void f() {\n"
13523                "  return g() {}\n"
13524                "  void h() {}");
13525   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
13526                "g();\n"
13527                "}");
13528 }
13529 
13530 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
13531   verifyFormat(
13532       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
13533 }
13534 
13535 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
13536   verifyFormat("class X {\n"
13537                "  void f() {\n"
13538                "  }\n"
13539                "};",
13540                getLLVMStyleWithColumns(12));
13541 }
13542 
13543 TEST_F(FormatTest, ConfigurableIndentWidth) {
13544   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
13545   EightIndent.IndentWidth = 8;
13546   EightIndent.ContinuationIndentWidth = 8;
13547   verifyFormat("void f() {\n"
13548                "        someFunction();\n"
13549                "        if (true) {\n"
13550                "                f();\n"
13551                "        }\n"
13552                "}",
13553                EightIndent);
13554   verifyFormat("class X {\n"
13555                "        void f() {\n"
13556                "        }\n"
13557                "};",
13558                EightIndent);
13559   verifyFormat("int x[] = {\n"
13560                "        call(),\n"
13561                "        call()};",
13562                EightIndent);
13563 }
13564 
13565 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
13566   verifyFormat("double\n"
13567                "f();",
13568                getLLVMStyleWithColumns(8));
13569 }
13570 
13571 TEST_F(FormatTest, ConfigurableUseOfTab) {
13572   FormatStyle Tab = getLLVMStyleWithColumns(42);
13573   Tab.IndentWidth = 8;
13574   Tab.UseTab = FormatStyle::UT_Always;
13575   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13576 
13577   EXPECT_EQ("if (aaaaaaaa && // q\n"
13578             "    bb)\t\t// w\n"
13579             "\t;",
13580             format("if (aaaaaaaa &&// q\n"
13581                    "bb)// w\n"
13582                    ";",
13583                    Tab));
13584   EXPECT_EQ("if (aaa && bbb) // w\n"
13585             "\t;",
13586             format("if(aaa&&bbb)// w\n"
13587                    ";",
13588                    Tab));
13589 
13590   verifyFormat("class X {\n"
13591                "\tvoid f() {\n"
13592                "\t\tsomeFunction(parameter1,\n"
13593                "\t\t\t     parameter2);\n"
13594                "\t}\n"
13595                "};",
13596                Tab);
13597   verifyFormat("#define A                        \\\n"
13598                "\tvoid f() {               \\\n"
13599                "\t\tsomeFunction(    \\\n"
13600                "\t\t    parameter1,  \\\n"
13601                "\t\t    parameter2); \\\n"
13602                "\t}",
13603                Tab);
13604   verifyFormat("int a;\t      // x\n"
13605                "int bbbbbbbb; // x\n",
13606                Tab);
13607 
13608   Tab.TabWidth = 4;
13609   Tab.IndentWidth = 8;
13610   verifyFormat("class TabWidth4Indent8 {\n"
13611                "\t\tvoid f() {\n"
13612                "\t\t\t\tsomeFunction(parameter1,\n"
13613                "\t\t\t\t\t\t\t parameter2);\n"
13614                "\t\t}\n"
13615                "};",
13616                Tab);
13617 
13618   Tab.TabWidth = 4;
13619   Tab.IndentWidth = 4;
13620   verifyFormat("class TabWidth4Indent4 {\n"
13621                "\tvoid f() {\n"
13622                "\t\tsomeFunction(parameter1,\n"
13623                "\t\t\t\t\t parameter2);\n"
13624                "\t}\n"
13625                "};",
13626                Tab);
13627 
13628   Tab.TabWidth = 8;
13629   Tab.IndentWidth = 4;
13630   verifyFormat("class TabWidth8Indent4 {\n"
13631                "    void f() {\n"
13632                "\tsomeFunction(parameter1,\n"
13633                "\t\t     parameter2);\n"
13634                "    }\n"
13635                "};",
13636                Tab);
13637 
13638   Tab.TabWidth = 8;
13639   Tab.IndentWidth = 8;
13640   EXPECT_EQ("/*\n"
13641             "\t      a\t\tcomment\n"
13642             "\t      in multiple lines\n"
13643             "       */",
13644             format("   /*\t \t \n"
13645                    " \t \t a\t\tcomment\t \t\n"
13646                    " \t \t in multiple lines\t\n"
13647                    " \t  */",
13648                    Tab));
13649 
13650   Tab.UseTab = FormatStyle::UT_ForIndentation;
13651   verifyFormat("{\n"
13652                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13653                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13654                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13655                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13656                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13657                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13658                "};",
13659                Tab);
13660   verifyFormat("enum AA {\n"
13661                "\ta1, // Force multiple lines\n"
13662                "\ta2,\n"
13663                "\ta3\n"
13664                "};",
13665                Tab);
13666   EXPECT_EQ("if (aaaaaaaa && // q\n"
13667             "    bb)         // w\n"
13668             "\t;",
13669             format("if (aaaaaaaa &&// q\n"
13670                    "bb)// w\n"
13671                    ";",
13672                    Tab));
13673   verifyFormat("class X {\n"
13674                "\tvoid f() {\n"
13675                "\t\tsomeFunction(parameter1,\n"
13676                "\t\t             parameter2);\n"
13677                "\t}\n"
13678                "};",
13679                Tab);
13680   verifyFormat("{\n"
13681                "\tQ(\n"
13682                "\t    {\n"
13683                "\t\t    int a;\n"
13684                "\t\t    someFunction(aaaaaaaa,\n"
13685                "\t\t                 bbbbbbb);\n"
13686                "\t    },\n"
13687                "\t    p);\n"
13688                "}",
13689                Tab);
13690   EXPECT_EQ("{\n"
13691             "\t/* aaaa\n"
13692             "\t   bbbb */\n"
13693             "}",
13694             format("{\n"
13695                    "/* aaaa\n"
13696                    "   bbbb */\n"
13697                    "}",
13698                    Tab));
13699   EXPECT_EQ("{\n"
13700             "\t/*\n"
13701             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13702             "\t  bbbbbbbbbbbbb\n"
13703             "\t*/\n"
13704             "}",
13705             format("{\n"
13706                    "/*\n"
13707                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13708                    "*/\n"
13709                    "}",
13710                    Tab));
13711   EXPECT_EQ("{\n"
13712             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13713             "\t// bbbbbbbbbbbbb\n"
13714             "}",
13715             format("{\n"
13716                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13717                    "}",
13718                    Tab));
13719   EXPECT_EQ("{\n"
13720             "\t/*\n"
13721             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13722             "\t  bbbbbbbbbbbbb\n"
13723             "\t*/\n"
13724             "}",
13725             format("{\n"
13726                    "\t/*\n"
13727                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13728                    "\t*/\n"
13729                    "}",
13730                    Tab));
13731   EXPECT_EQ("{\n"
13732             "\t/*\n"
13733             "\n"
13734             "\t*/\n"
13735             "}",
13736             format("{\n"
13737                    "\t/*\n"
13738                    "\n"
13739                    "\t*/\n"
13740                    "}",
13741                    Tab));
13742   EXPECT_EQ("{\n"
13743             "\t/*\n"
13744             " asdf\n"
13745             "\t*/\n"
13746             "}",
13747             format("{\n"
13748                    "\t/*\n"
13749                    " asdf\n"
13750                    "\t*/\n"
13751                    "}",
13752                    Tab));
13753 
13754   verifyFormat("void f() {\n"
13755                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
13756                "\t            : bbbbbbbbbbbbbbbbbb\n"
13757                "}",
13758                Tab);
13759   FormatStyle TabNoBreak = Tab;
13760   TabNoBreak.BreakBeforeTernaryOperators = false;
13761   verifyFormat("void f() {\n"
13762                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
13763                "\t              bbbbbbbbbbbbbbbbbb\n"
13764                "}",
13765                TabNoBreak);
13766   verifyFormat("void f() {\n"
13767                "\treturn true ?\n"
13768                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
13769                "\t           bbbbbbbbbbbbbbbbbbbb\n"
13770                "}",
13771                TabNoBreak);
13772 
13773   Tab.UseTab = FormatStyle::UT_Never;
13774   EXPECT_EQ("/*\n"
13775             "              a\t\tcomment\n"
13776             "              in multiple lines\n"
13777             "       */",
13778             format("   /*\t \t \n"
13779                    " \t \t a\t\tcomment\t \t\n"
13780                    " \t \t in multiple lines\t\n"
13781                    " \t  */",
13782                    Tab));
13783   EXPECT_EQ("/* some\n"
13784             "   comment */",
13785             format(" \t \t /* some\n"
13786                    " \t \t    comment */",
13787                    Tab));
13788   EXPECT_EQ("int a; /* some\n"
13789             "   comment */",
13790             format(" \t \t int a; /* some\n"
13791                    " \t \t    comment */",
13792                    Tab));
13793 
13794   EXPECT_EQ("int a; /* some\n"
13795             "comment */",
13796             format(" \t \t int\ta; /* some\n"
13797                    " \t \t    comment */",
13798                    Tab));
13799   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13800             "    comment */",
13801             format(" \t \t f(\"\t\t\"); /* some\n"
13802                    " \t \t    comment */",
13803                    Tab));
13804   EXPECT_EQ("{\n"
13805             "        /*\n"
13806             "         * Comment\n"
13807             "         */\n"
13808             "        int i;\n"
13809             "}",
13810             format("{\n"
13811                    "\t/*\n"
13812                    "\t * Comment\n"
13813                    "\t */\n"
13814                    "\t int i;\n"
13815                    "}",
13816                    Tab));
13817 
13818   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13819   Tab.TabWidth = 8;
13820   Tab.IndentWidth = 8;
13821   EXPECT_EQ("if (aaaaaaaa && // q\n"
13822             "    bb)         // w\n"
13823             "\t;",
13824             format("if (aaaaaaaa &&// q\n"
13825                    "bb)// w\n"
13826                    ";",
13827                    Tab));
13828   EXPECT_EQ("if (aaa && bbb) // w\n"
13829             "\t;",
13830             format("if(aaa&&bbb)// w\n"
13831                    ";",
13832                    Tab));
13833   verifyFormat("class X {\n"
13834                "\tvoid f() {\n"
13835                "\t\tsomeFunction(parameter1,\n"
13836                "\t\t\t     parameter2);\n"
13837                "\t}\n"
13838                "};",
13839                Tab);
13840   verifyFormat("#define A                        \\\n"
13841                "\tvoid f() {               \\\n"
13842                "\t\tsomeFunction(    \\\n"
13843                "\t\t    parameter1,  \\\n"
13844                "\t\t    parameter2); \\\n"
13845                "\t}",
13846                Tab);
13847   Tab.TabWidth = 4;
13848   Tab.IndentWidth = 8;
13849   verifyFormat("class TabWidth4Indent8 {\n"
13850                "\t\tvoid f() {\n"
13851                "\t\t\t\tsomeFunction(parameter1,\n"
13852                "\t\t\t\t\t\t\t parameter2);\n"
13853                "\t\t}\n"
13854                "};",
13855                Tab);
13856   Tab.TabWidth = 4;
13857   Tab.IndentWidth = 4;
13858   verifyFormat("class TabWidth4Indent4 {\n"
13859                "\tvoid f() {\n"
13860                "\t\tsomeFunction(parameter1,\n"
13861                "\t\t\t\t\t parameter2);\n"
13862                "\t}\n"
13863                "};",
13864                Tab);
13865   Tab.TabWidth = 8;
13866   Tab.IndentWidth = 4;
13867   verifyFormat("class TabWidth8Indent4 {\n"
13868                "    void f() {\n"
13869                "\tsomeFunction(parameter1,\n"
13870                "\t\t     parameter2);\n"
13871                "    }\n"
13872                "};",
13873                Tab);
13874   Tab.TabWidth = 8;
13875   Tab.IndentWidth = 8;
13876   EXPECT_EQ("/*\n"
13877             "\t      a\t\tcomment\n"
13878             "\t      in multiple lines\n"
13879             "       */",
13880             format("   /*\t \t \n"
13881                    " \t \t a\t\tcomment\t \t\n"
13882                    " \t \t in multiple lines\t\n"
13883                    " \t  */",
13884                    Tab));
13885   verifyFormat("{\n"
13886                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13887                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13888                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13889                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13890                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13891                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13892                "};",
13893                Tab);
13894   verifyFormat("enum AA {\n"
13895                "\ta1, // Force multiple lines\n"
13896                "\ta2,\n"
13897                "\ta3\n"
13898                "};",
13899                Tab);
13900   EXPECT_EQ("if (aaaaaaaa && // q\n"
13901             "    bb)         // w\n"
13902             "\t;",
13903             format("if (aaaaaaaa &&// q\n"
13904                    "bb)// w\n"
13905                    ";",
13906                    Tab));
13907   verifyFormat("class X {\n"
13908                "\tvoid f() {\n"
13909                "\t\tsomeFunction(parameter1,\n"
13910                "\t\t\t     parameter2);\n"
13911                "\t}\n"
13912                "};",
13913                Tab);
13914   verifyFormat("{\n"
13915                "\tQ(\n"
13916                "\t    {\n"
13917                "\t\t    int a;\n"
13918                "\t\t    someFunction(aaaaaaaa,\n"
13919                "\t\t\t\t bbbbbbb);\n"
13920                "\t    },\n"
13921                "\t    p);\n"
13922                "}",
13923                Tab);
13924   EXPECT_EQ("{\n"
13925             "\t/* aaaa\n"
13926             "\t   bbbb */\n"
13927             "}",
13928             format("{\n"
13929                    "/* aaaa\n"
13930                    "   bbbb */\n"
13931                    "}",
13932                    Tab));
13933   EXPECT_EQ("{\n"
13934             "\t/*\n"
13935             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13936             "\t  bbbbbbbbbbbbb\n"
13937             "\t*/\n"
13938             "}",
13939             format("{\n"
13940                    "/*\n"
13941                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13942                    "*/\n"
13943                    "}",
13944                    Tab));
13945   EXPECT_EQ("{\n"
13946             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13947             "\t// bbbbbbbbbbbbb\n"
13948             "}",
13949             format("{\n"
13950                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13951                    "}",
13952                    Tab));
13953   EXPECT_EQ("{\n"
13954             "\t/*\n"
13955             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13956             "\t  bbbbbbbbbbbbb\n"
13957             "\t*/\n"
13958             "}",
13959             format("{\n"
13960                    "\t/*\n"
13961                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13962                    "\t*/\n"
13963                    "}",
13964                    Tab));
13965   EXPECT_EQ("{\n"
13966             "\t/*\n"
13967             "\n"
13968             "\t*/\n"
13969             "}",
13970             format("{\n"
13971                    "\t/*\n"
13972                    "\n"
13973                    "\t*/\n"
13974                    "}",
13975                    Tab));
13976   EXPECT_EQ("{\n"
13977             "\t/*\n"
13978             " asdf\n"
13979             "\t*/\n"
13980             "}",
13981             format("{\n"
13982                    "\t/*\n"
13983                    " asdf\n"
13984                    "\t*/\n"
13985                    "}",
13986                    Tab));
13987   EXPECT_EQ("/* some\n"
13988             "   comment */",
13989             format(" \t \t /* some\n"
13990                    " \t \t    comment */",
13991                    Tab));
13992   EXPECT_EQ("int a; /* some\n"
13993             "   comment */",
13994             format(" \t \t int a; /* some\n"
13995                    " \t \t    comment */",
13996                    Tab));
13997   EXPECT_EQ("int a; /* some\n"
13998             "comment */",
13999             format(" \t \t int\ta; /* some\n"
14000                    " \t \t    comment */",
14001                    Tab));
14002   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14003             "    comment */",
14004             format(" \t \t f(\"\t\t\"); /* some\n"
14005                    " \t \t    comment */",
14006                    Tab));
14007   EXPECT_EQ("{\n"
14008             "\t/*\n"
14009             "\t * Comment\n"
14010             "\t */\n"
14011             "\tint i;\n"
14012             "}",
14013             format("{\n"
14014                    "\t/*\n"
14015                    "\t * Comment\n"
14016                    "\t */\n"
14017                    "\t int i;\n"
14018                    "}",
14019                    Tab));
14020   Tab.TabWidth = 2;
14021   Tab.IndentWidth = 2;
14022   EXPECT_EQ("{\n"
14023             "\t/* aaaa\n"
14024             "\t\t bbbb */\n"
14025             "}",
14026             format("{\n"
14027                    "/* aaaa\n"
14028                    "\t bbbb */\n"
14029                    "}",
14030                    Tab));
14031   EXPECT_EQ("{\n"
14032             "\t/*\n"
14033             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14034             "\t\tbbbbbbbbbbbbb\n"
14035             "\t*/\n"
14036             "}",
14037             format("{\n"
14038                    "/*\n"
14039                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14040                    "*/\n"
14041                    "}",
14042                    Tab));
14043   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14044   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14045   Tab.TabWidth = 4;
14046   Tab.IndentWidth = 4;
14047   verifyFormat("class Assign {\n"
14048                "\tvoid f() {\n"
14049                "\t\tint         x      = 123;\n"
14050                "\t\tint         random = 4;\n"
14051                "\t\tstd::string alphabet =\n"
14052                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14053                "\t}\n"
14054                "};",
14055                Tab);
14056 
14057   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14058   Tab.TabWidth = 8;
14059   Tab.IndentWidth = 8;
14060   EXPECT_EQ("if (aaaaaaaa && // q\n"
14061             "    bb)         // w\n"
14062             "\t;",
14063             format("if (aaaaaaaa &&// q\n"
14064                    "bb)// w\n"
14065                    ";",
14066                    Tab));
14067   EXPECT_EQ("if (aaa && bbb) // w\n"
14068             "\t;",
14069             format("if(aaa&&bbb)// w\n"
14070                    ";",
14071                    Tab));
14072   verifyFormat("class X {\n"
14073                "\tvoid f() {\n"
14074                "\t\tsomeFunction(parameter1,\n"
14075                "\t\t             parameter2);\n"
14076                "\t}\n"
14077                "};",
14078                Tab);
14079   verifyFormat("#define A                        \\\n"
14080                "\tvoid f() {               \\\n"
14081                "\t\tsomeFunction(    \\\n"
14082                "\t\t    parameter1,  \\\n"
14083                "\t\t    parameter2); \\\n"
14084                "\t}",
14085                Tab);
14086   Tab.TabWidth = 4;
14087   Tab.IndentWidth = 8;
14088   verifyFormat("class TabWidth4Indent8 {\n"
14089                "\t\tvoid f() {\n"
14090                "\t\t\t\tsomeFunction(parameter1,\n"
14091                "\t\t\t\t             parameter2);\n"
14092                "\t\t}\n"
14093                "};",
14094                Tab);
14095   Tab.TabWidth = 4;
14096   Tab.IndentWidth = 4;
14097   verifyFormat("class TabWidth4Indent4 {\n"
14098                "\tvoid f() {\n"
14099                "\t\tsomeFunction(parameter1,\n"
14100                "\t\t             parameter2);\n"
14101                "\t}\n"
14102                "};",
14103                Tab);
14104   Tab.TabWidth = 8;
14105   Tab.IndentWidth = 4;
14106   verifyFormat("class TabWidth8Indent4 {\n"
14107                "    void f() {\n"
14108                "\tsomeFunction(parameter1,\n"
14109                "\t             parameter2);\n"
14110                "    }\n"
14111                "};",
14112                Tab);
14113   Tab.TabWidth = 8;
14114   Tab.IndentWidth = 8;
14115   EXPECT_EQ("/*\n"
14116             "              a\t\tcomment\n"
14117             "              in multiple lines\n"
14118             "       */",
14119             format("   /*\t \t \n"
14120                    " \t \t a\t\tcomment\t \t\n"
14121                    " \t \t in multiple lines\t\n"
14122                    " \t  */",
14123                    Tab));
14124   verifyFormat("{\n"
14125                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14126                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14127                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14128                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14129                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14130                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14131                "};",
14132                Tab);
14133   verifyFormat("enum AA {\n"
14134                "\ta1, // Force multiple lines\n"
14135                "\ta2,\n"
14136                "\ta3\n"
14137                "};",
14138                Tab);
14139   EXPECT_EQ("if (aaaaaaaa && // q\n"
14140             "    bb)         // w\n"
14141             "\t;",
14142             format("if (aaaaaaaa &&// q\n"
14143                    "bb)// w\n"
14144                    ";",
14145                    Tab));
14146   verifyFormat("class X {\n"
14147                "\tvoid f() {\n"
14148                "\t\tsomeFunction(parameter1,\n"
14149                "\t\t             parameter2);\n"
14150                "\t}\n"
14151                "};",
14152                Tab);
14153   verifyFormat("{\n"
14154                "\tQ(\n"
14155                "\t    {\n"
14156                "\t\t    int a;\n"
14157                "\t\t    someFunction(aaaaaaaa,\n"
14158                "\t\t                 bbbbbbb);\n"
14159                "\t    },\n"
14160                "\t    p);\n"
14161                "}",
14162                Tab);
14163   EXPECT_EQ("{\n"
14164             "\t/* aaaa\n"
14165             "\t   bbbb */\n"
14166             "}",
14167             format("{\n"
14168                    "/* aaaa\n"
14169                    "   bbbb */\n"
14170                    "}",
14171                    Tab));
14172   EXPECT_EQ("{\n"
14173             "\t/*\n"
14174             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14175             "\t  bbbbbbbbbbbbb\n"
14176             "\t*/\n"
14177             "}",
14178             format("{\n"
14179                    "/*\n"
14180                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14181                    "*/\n"
14182                    "}",
14183                    Tab));
14184   EXPECT_EQ("{\n"
14185             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14186             "\t// bbbbbbbbbbbbb\n"
14187             "}",
14188             format("{\n"
14189                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14190                    "}",
14191                    Tab));
14192   EXPECT_EQ("{\n"
14193             "\t/*\n"
14194             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14195             "\t  bbbbbbbbbbbbb\n"
14196             "\t*/\n"
14197             "}",
14198             format("{\n"
14199                    "\t/*\n"
14200                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14201                    "\t*/\n"
14202                    "}",
14203                    Tab));
14204   EXPECT_EQ("{\n"
14205             "\t/*\n"
14206             "\n"
14207             "\t*/\n"
14208             "}",
14209             format("{\n"
14210                    "\t/*\n"
14211                    "\n"
14212                    "\t*/\n"
14213                    "}",
14214                    Tab));
14215   EXPECT_EQ("{\n"
14216             "\t/*\n"
14217             " asdf\n"
14218             "\t*/\n"
14219             "}",
14220             format("{\n"
14221                    "\t/*\n"
14222                    " asdf\n"
14223                    "\t*/\n"
14224                    "}",
14225                    Tab));
14226   EXPECT_EQ("/* some\n"
14227             "   comment */",
14228             format(" \t \t /* some\n"
14229                    " \t \t    comment */",
14230                    Tab));
14231   EXPECT_EQ("int a; /* some\n"
14232             "   comment */",
14233             format(" \t \t int a; /* some\n"
14234                    " \t \t    comment */",
14235                    Tab));
14236   EXPECT_EQ("int a; /* some\n"
14237             "comment */",
14238             format(" \t \t int\ta; /* some\n"
14239                    " \t \t    comment */",
14240                    Tab));
14241   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14242             "    comment */",
14243             format(" \t \t f(\"\t\t\"); /* some\n"
14244                    " \t \t    comment */",
14245                    Tab));
14246   EXPECT_EQ("{\n"
14247             "\t/*\n"
14248             "\t * Comment\n"
14249             "\t */\n"
14250             "\tint i;\n"
14251             "}",
14252             format("{\n"
14253                    "\t/*\n"
14254                    "\t * Comment\n"
14255                    "\t */\n"
14256                    "\t int i;\n"
14257                    "}",
14258                    Tab));
14259   Tab.TabWidth = 2;
14260   Tab.IndentWidth = 2;
14261   EXPECT_EQ("{\n"
14262             "\t/* aaaa\n"
14263             "\t   bbbb */\n"
14264             "}",
14265             format("{\n"
14266                    "/* aaaa\n"
14267                    "   bbbb */\n"
14268                    "}",
14269                    Tab));
14270   EXPECT_EQ("{\n"
14271             "\t/*\n"
14272             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14273             "\t  bbbbbbbbbbbbb\n"
14274             "\t*/\n"
14275             "}",
14276             format("{\n"
14277                    "/*\n"
14278                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14279                    "*/\n"
14280                    "}",
14281                    Tab));
14282   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14283   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14284   Tab.TabWidth = 4;
14285   Tab.IndentWidth = 4;
14286   verifyFormat("class Assign {\n"
14287                "\tvoid f() {\n"
14288                "\t\tint         x      = 123;\n"
14289                "\t\tint         random = 4;\n"
14290                "\t\tstd::string alphabet =\n"
14291                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14292                "\t}\n"
14293                "};",
14294                Tab);
14295   Tab.AlignOperands = FormatStyle::OAS_Align;
14296   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14297                "                 cccccccccccccccccccc;",
14298                Tab);
14299   // no alignment
14300   verifyFormat("int aaaaaaaaaa =\n"
14301                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14302                Tab);
14303   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14304                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14305                "                        : 333333333333333;",
14306                Tab);
14307   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14308   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14309   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14310                "               + cccccccccccccccccccc;",
14311                Tab);
14312 }
14313 
14314 TEST_F(FormatTest, ZeroTabWidth) {
14315   FormatStyle Tab = getLLVMStyleWithColumns(42);
14316   Tab.IndentWidth = 8;
14317   Tab.UseTab = FormatStyle::UT_Never;
14318   Tab.TabWidth = 0;
14319   EXPECT_EQ("void a(){\n"
14320             "    // line starts with '\t'\n"
14321             "};",
14322             format("void a(){\n"
14323                    "\t// line starts with '\t'\n"
14324                    "};",
14325                    Tab));
14326 
14327   EXPECT_EQ("void a(){\n"
14328             "    // line starts with '\t'\n"
14329             "};",
14330             format("void a(){\n"
14331                    "\t\t// line starts with '\t'\n"
14332                    "};",
14333                    Tab));
14334 
14335   Tab.UseTab = FormatStyle::UT_ForIndentation;
14336   EXPECT_EQ("void a(){\n"
14337             "    // line starts with '\t'\n"
14338             "};",
14339             format("void a(){\n"
14340                    "\t// line starts with '\t'\n"
14341                    "};",
14342                    Tab));
14343 
14344   EXPECT_EQ("void a(){\n"
14345             "    // line starts with '\t'\n"
14346             "};",
14347             format("void a(){\n"
14348                    "\t\t// line starts with '\t'\n"
14349                    "};",
14350                    Tab));
14351 
14352   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14353   EXPECT_EQ("void a(){\n"
14354             "    // line starts with '\t'\n"
14355             "};",
14356             format("void a(){\n"
14357                    "\t// line starts with '\t'\n"
14358                    "};",
14359                    Tab));
14360 
14361   EXPECT_EQ("void a(){\n"
14362             "    // line starts with '\t'\n"
14363             "};",
14364             format("void a(){\n"
14365                    "\t\t// line starts with '\t'\n"
14366                    "};",
14367                    Tab));
14368 
14369   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14370   EXPECT_EQ("void a(){\n"
14371             "    // line starts with '\t'\n"
14372             "};",
14373             format("void a(){\n"
14374                    "\t// line starts with '\t'\n"
14375                    "};",
14376                    Tab));
14377 
14378   EXPECT_EQ("void a(){\n"
14379             "    // line starts with '\t'\n"
14380             "};",
14381             format("void a(){\n"
14382                    "\t\t// line starts with '\t'\n"
14383                    "};",
14384                    Tab));
14385 
14386   Tab.UseTab = FormatStyle::UT_Always;
14387   EXPECT_EQ("void a(){\n"
14388             "// line starts with '\t'\n"
14389             "};",
14390             format("void a(){\n"
14391                    "\t// line starts with '\t'\n"
14392                    "};",
14393                    Tab));
14394 
14395   EXPECT_EQ("void a(){\n"
14396             "// line starts with '\t'\n"
14397             "};",
14398             format("void a(){\n"
14399                    "\t\t// line starts with '\t'\n"
14400                    "};",
14401                    Tab));
14402 }
14403 
14404 TEST_F(FormatTest, CalculatesOriginalColumn) {
14405   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14406             "q\"; /* some\n"
14407             "       comment */",
14408             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14409                    "q\"; /* some\n"
14410                    "       comment */",
14411                    getLLVMStyle()));
14412   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14413             "/* some\n"
14414             "   comment */",
14415             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14416                    " /* some\n"
14417                    "    comment */",
14418                    getLLVMStyle()));
14419   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14420             "qqq\n"
14421             "/* some\n"
14422             "   comment */",
14423             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14424                    "qqq\n"
14425                    " /* some\n"
14426                    "    comment */",
14427                    getLLVMStyle()));
14428   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14429             "wwww; /* some\n"
14430             "         comment */",
14431             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14432                    "wwww; /* some\n"
14433                    "         comment */",
14434                    getLLVMStyle()));
14435 }
14436 
14437 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14438   FormatStyle NoSpace = getLLVMStyle();
14439   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14440 
14441   verifyFormat("while(true)\n"
14442                "  continue;",
14443                NoSpace);
14444   verifyFormat("for(;;)\n"
14445                "  continue;",
14446                NoSpace);
14447   verifyFormat("if(true)\n"
14448                "  f();\n"
14449                "else if(true)\n"
14450                "  f();",
14451                NoSpace);
14452   verifyFormat("do {\n"
14453                "  do_something();\n"
14454                "} while(something());",
14455                NoSpace);
14456   verifyFormat("switch(x) {\n"
14457                "default:\n"
14458                "  break;\n"
14459                "}",
14460                NoSpace);
14461   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14462   verifyFormat("size_t x = sizeof(x);", NoSpace);
14463   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14464   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14465   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14466   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14467   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14468   verifyFormat("alignas(128) char a[128];", NoSpace);
14469   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14470   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14471   verifyFormat("int f() throw(Deprecated);", NoSpace);
14472   verifyFormat("typedef void (*cb)(int);", NoSpace);
14473   verifyFormat("T A::operator()();", NoSpace);
14474   verifyFormat("X A::operator++(T);", NoSpace);
14475   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14476 
14477   FormatStyle Space = getLLVMStyle();
14478   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14479 
14480   verifyFormat("int f ();", Space);
14481   verifyFormat("void f (int a, T b) {\n"
14482                "  while (true)\n"
14483                "    continue;\n"
14484                "}",
14485                Space);
14486   verifyFormat("if (true)\n"
14487                "  f ();\n"
14488                "else if (true)\n"
14489                "  f ();",
14490                Space);
14491   verifyFormat("do {\n"
14492                "  do_something ();\n"
14493                "} while (something ());",
14494                Space);
14495   verifyFormat("switch (x) {\n"
14496                "default:\n"
14497                "  break;\n"
14498                "}",
14499                Space);
14500   verifyFormat("A::A () : a (1) {}", Space);
14501   verifyFormat("void f () __attribute__ ((asdf));", Space);
14502   verifyFormat("*(&a + 1);\n"
14503                "&((&a)[1]);\n"
14504                "a[(b + c) * d];\n"
14505                "(((a + 1) * 2) + 3) * 4;",
14506                Space);
14507   verifyFormat("#define A(x) x", Space);
14508   verifyFormat("#define A (x) x", Space);
14509   verifyFormat("#if defined(x)\n"
14510                "#endif",
14511                Space);
14512   verifyFormat("auto i = std::make_unique<int> (5);", Space);
14513   verifyFormat("size_t x = sizeof (x);", Space);
14514   verifyFormat("auto f (int x) -> decltype (x);", Space);
14515   verifyFormat("auto f (int x) -> typeof (x);", Space);
14516   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
14517   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
14518   verifyFormat("int f (T x) noexcept (x.create ());", Space);
14519   verifyFormat("alignas (128) char a[128];", Space);
14520   verifyFormat("size_t x = alignof (MyType);", Space);
14521   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
14522   verifyFormat("int f () throw (Deprecated);", Space);
14523   verifyFormat("typedef void (*cb) (int);", Space);
14524   // FIXME these tests regressed behaviour.
14525   // verifyFormat("T A::operator() ();", Space);
14526   // verifyFormat("X A::operator++ (T);", Space);
14527   verifyFormat("auto lambda = [] () { return 0; };", Space);
14528   verifyFormat("int x = int (y);", Space);
14529 
14530   FormatStyle SomeSpace = getLLVMStyle();
14531   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
14532 
14533   verifyFormat("[]() -> float {}", SomeSpace);
14534   verifyFormat("[] (auto foo) {}", SomeSpace);
14535   verifyFormat("[foo]() -> int {}", SomeSpace);
14536   verifyFormat("int f();", SomeSpace);
14537   verifyFormat("void f (int a, T b) {\n"
14538                "  while (true)\n"
14539                "    continue;\n"
14540                "}",
14541                SomeSpace);
14542   verifyFormat("if (true)\n"
14543                "  f();\n"
14544                "else if (true)\n"
14545                "  f();",
14546                SomeSpace);
14547   verifyFormat("do {\n"
14548                "  do_something();\n"
14549                "} while (something());",
14550                SomeSpace);
14551   verifyFormat("switch (x) {\n"
14552                "default:\n"
14553                "  break;\n"
14554                "}",
14555                SomeSpace);
14556   verifyFormat("A::A() : a (1) {}", SomeSpace);
14557   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
14558   verifyFormat("*(&a + 1);\n"
14559                "&((&a)[1]);\n"
14560                "a[(b + c) * d];\n"
14561                "(((a + 1) * 2) + 3) * 4;",
14562                SomeSpace);
14563   verifyFormat("#define A(x) x", SomeSpace);
14564   verifyFormat("#define A (x) x", SomeSpace);
14565   verifyFormat("#if defined(x)\n"
14566                "#endif",
14567                SomeSpace);
14568   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
14569   verifyFormat("size_t x = sizeof (x);", SomeSpace);
14570   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
14571   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
14572   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
14573   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
14574   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
14575   verifyFormat("alignas (128) char a[128];", SomeSpace);
14576   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
14577   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14578                SomeSpace);
14579   verifyFormat("int f() throw (Deprecated);", SomeSpace);
14580   verifyFormat("typedef void (*cb) (int);", SomeSpace);
14581   verifyFormat("T A::operator()();", SomeSpace);
14582   // FIXME these tests regressed behaviour.
14583   // verifyFormat("X A::operator++ (T);", SomeSpace);
14584   verifyFormat("int x = int (y);", SomeSpace);
14585   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
14586 
14587   FormatStyle SpaceControlStatements = getLLVMStyle();
14588   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14589   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
14590 
14591   verifyFormat("while (true)\n"
14592                "  continue;",
14593                SpaceControlStatements);
14594   verifyFormat("if (true)\n"
14595                "  f();\n"
14596                "else if (true)\n"
14597                "  f();",
14598                SpaceControlStatements);
14599   verifyFormat("for (;;) {\n"
14600                "  do_something();\n"
14601                "}",
14602                SpaceControlStatements);
14603   verifyFormat("do {\n"
14604                "  do_something();\n"
14605                "} while (something());",
14606                SpaceControlStatements);
14607   verifyFormat("switch (x) {\n"
14608                "default:\n"
14609                "  break;\n"
14610                "}",
14611                SpaceControlStatements);
14612 
14613   FormatStyle SpaceFuncDecl = getLLVMStyle();
14614   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14615   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
14616 
14617   verifyFormat("int f ();", SpaceFuncDecl);
14618   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
14619   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
14620   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
14621   verifyFormat("#define A(x) x", SpaceFuncDecl);
14622   verifyFormat("#define A (x) x", SpaceFuncDecl);
14623   verifyFormat("#if defined(x)\n"
14624                "#endif",
14625                SpaceFuncDecl);
14626   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
14627   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
14628   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
14629   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
14630   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
14631   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
14632   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
14633   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
14634   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
14635   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14636                SpaceFuncDecl);
14637   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
14638   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
14639   // FIXME these tests regressed behaviour.
14640   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
14641   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
14642   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
14643   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
14644   verifyFormat("int x = int(y);", SpaceFuncDecl);
14645   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14646                SpaceFuncDecl);
14647 
14648   FormatStyle SpaceFuncDef = getLLVMStyle();
14649   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14650   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
14651 
14652   verifyFormat("int f();", SpaceFuncDef);
14653   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
14654   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
14655   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
14656   verifyFormat("#define A(x) x", SpaceFuncDef);
14657   verifyFormat("#define A (x) x", SpaceFuncDef);
14658   verifyFormat("#if defined(x)\n"
14659                "#endif",
14660                SpaceFuncDef);
14661   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
14662   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
14663   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
14664   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
14665   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
14666   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
14667   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
14668   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
14669   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
14670   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14671                SpaceFuncDef);
14672   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
14673   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
14674   verifyFormat("T A::operator()();", SpaceFuncDef);
14675   verifyFormat("X A::operator++(T);", SpaceFuncDef);
14676   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
14677   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
14678   verifyFormat("int x = int(y);", SpaceFuncDef);
14679   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14680                SpaceFuncDef);
14681 
14682   FormatStyle SpaceIfMacros = getLLVMStyle();
14683   SpaceIfMacros.IfMacros.clear();
14684   SpaceIfMacros.IfMacros.push_back("MYIF");
14685   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14686   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
14687   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
14688   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
14689   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
14690 
14691   FormatStyle SpaceForeachMacros = getLLVMStyle();
14692   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
14693             FormatStyle::SBS_Never);
14694   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
14695   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14696   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
14697   verifyFormat("for (;;) {\n"
14698                "}",
14699                SpaceForeachMacros);
14700   verifyFormat("foreach (Item *item, itemlist) {\n"
14701                "}",
14702                SpaceForeachMacros);
14703   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
14704                "}",
14705                SpaceForeachMacros);
14706   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
14707                "}",
14708                SpaceForeachMacros);
14709   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
14710 
14711   FormatStyle SomeSpace2 = getLLVMStyle();
14712   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14713   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
14714   verifyFormat("[]() -> float {}", SomeSpace2);
14715   verifyFormat("[] (auto foo) {}", SomeSpace2);
14716   verifyFormat("[foo]() -> int {}", SomeSpace2);
14717   verifyFormat("int f();", SomeSpace2);
14718   verifyFormat("void f (int a, T b) {\n"
14719                "  while (true)\n"
14720                "    continue;\n"
14721                "}",
14722                SomeSpace2);
14723   verifyFormat("if (true)\n"
14724                "  f();\n"
14725                "else if (true)\n"
14726                "  f();",
14727                SomeSpace2);
14728   verifyFormat("do {\n"
14729                "  do_something();\n"
14730                "} while (something());",
14731                SomeSpace2);
14732   verifyFormat("switch (x) {\n"
14733                "default:\n"
14734                "  break;\n"
14735                "}",
14736                SomeSpace2);
14737   verifyFormat("A::A() : a (1) {}", SomeSpace2);
14738   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
14739   verifyFormat("*(&a + 1);\n"
14740                "&((&a)[1]);\n"
14741                "a[(b + c) * d];\n"
14742                "(((a + 1) * 2) + 3) * 4;",
14743                SomeSpace2);
14744   verifyFormat("#define A(x) x", SomeSpace2);
14745   verifyFormat("#define A (x) x", SomeSpace2);
14746   verifyFormat("#if defined(x)\n"
14747                "#endif",
14748                SomeSpace2);
14749   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
14750   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
14751   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
14752   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
14753   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
14754   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
14755   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
14756   verifyFormat("alignas (128) char a[128];", SomeSpace2);
14757   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
14758   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14759                SomeSpace2);
14760   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
14761   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
14762   verifyFormat("T A::operator()();", SomeSpace2);
14763   // verifyFormat("X A::operator++ (T);", SomeSpace2);
14764   verifyFormat("int x = int (y);", SomeSpace2);
14765   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
14766 
14767   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
14768   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14769   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
14770       .AfterOverloadedOperator = true;
14771 
14772   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
14773   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
14774   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
14775   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
14776 
14777   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
14778       .AfterOverloadedOperator = false;
14779 
14780   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
14781   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
14782   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
14783   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
14784 }
14785 
14786 TEST_F(FormatTest, SpaceAfterLogicalNot) {
14787   FormatStyle Spaces = getLLVMStyle();
14788   Spaces.SpaceAfterLogicalNot = true;
14789 
14790   verifyFormat("bool x = ! y", Spaces);
14791   verifyFormat("if (! isFailure())", Spaces);
14792   verifyFormat("if (! (a && b))", Spaces);
14793   verifyFormat("\"Error!\"", Spaces);
14794   verifyFormat("! ! x", Spaces);
14795 }
14796 
14797 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
14798   FormatStyle Spaces = getLLVMStyle();
14799 
14800   Spaces.SpacesInParentheses = true;
14801   verifyFormat("do_something( ::globalVar );", Spaces);
14802   verifyFormat("call( x, y, z );", Spaces);
14803   verifyFormat("call();", Spaces);
14804   verifyFormat("std::function<void( int, int )> callback;", Spaces);
14805   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
14806                Spaces);
14807   verifyFormat("while ( (bool)1 )\n"
14808                "  continue;",
14809                Spaces);
14810   verifyFormat("for ( ;; )\n"
14811                "  continue;",
14812                Spaces);
14813   verifyFormat("if ( true )\n"
14814                "  f();\n"
14815                "else if ( true )\n"
14816                "  f();",
14817                Spaces);
14818   verifyFormat("do {\n"
14819                "  do_something( (int)i );\n"
14820                "} while ( something() );",
14821                Spaces);
14822   verifyFormat("switch ( x ) {\n"
14823                "default:\n"
14824                "  break;\n"
14825                "}",
14826                Spaces);
14827 
14828   Spaces.SpacesInParentheses = false;
14829   Spaces.SpacesInCStyleCastParentheses = true;
14830   verifyFormat("Type *A = ( Type * )P;", Spaces);
14831   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
14832   verifyFormat("x = ( int32 )y;", Spaces);
14833   verifyFormat("int a = ( int )(2.0f);", Spaces);
14834   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
14835   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
14836   verifyFormat("#define x (( int )-1)", Spaces);
14837 
14838   // Run the first set of tests again with:
14839   Spaces.SpacesInParentheses = false;
14840   Spaces.SpaceInEmptyParentheses = true;
14841   Spaces.SpacesInCStyleCastParentheses = true;
14842   verifyFormat("call(x, y, z);", Spaces);
14843   verifyFormat("call( );", Spaces);
14844   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14845   verifyFormat("while (( bool )1)\n"
14846                "  continue;",
14847                Spaces);
14848   verifyFormat("for (;;)\n"
14849                "  continue;",
14850                Spaces);
14851   verifyFormat("if (true)\n"
14852                "  f( );\n"
14853                "else if (true)\n"
14854                "  f( );",
14855                Spaces);
14856   verifyFormat("do {\n"
14857                "  do_something(( int )i);\n"
14858                "} while (something( ));",
14859                Spaces);
14860   verifyFormat("switch (x) {\n"
14861                "default:\n"
14862                "  break;\n"
14863                "}",
14864                Spaces);
14865 
14866   // Run the first set of tests again with:
14867   Spaces.SpaceAfterCStyleCast = true;
14868   verifyFormat("call(x, y, z);", Spaces);
14869   verifyFormat("call( );", Spaces);
14870   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14871   verifyFormat("while (( bool ) 1)\n"
14872                "  continue;",
14873                Spaces);
14874   verifyFormat("for (;;)\n"
14875                "  continue;",
14876                Spaces);
14877   verifyFormat("if (true)\n"
14878                "  f( );\n"
14879                "else if (true)\n"
14880                "  f( );",
14881                Spaces);
14882   verifyFormat("do {\n"
14883                "  do_something(( int ) i);\n"
14884                "} while (something( ));",
14885                Spaces);
14886   verifyFormat("switch (x) {\n"
14887                "default:\n"
14888                "  break;\n"
14889                "}",
14890                Spaces);
14891   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
14892   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
14893   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
14894   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
14895   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
14896 
14897   // Run subset of tests again with:
14898   Spaces.SpacesInCStyleCastParentheses = false;
14899   Spaces.SpaceAfterCStyleCast = true;
14900   verifyFormat("while ((bool) 1)\n"
14901                "  continue;",
14902                Spaces);
14903   verifyFormat("do {\n"
14904                "  do_something((int) i);\n"
14905                "} while (something( ));",
14906                Spaces);
14907 
14908   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
14909   verifyFormat("size_t idx = (size_t) a;", Spaces);
14910   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
14911   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14912   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14913   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14914   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14915   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
14916   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
14917   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
14918   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
14919   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
14920   Spaces.ColumnLimit = 80;
14921   Spaces.IndentWidth = 4;
14922   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14923   verifyFormat("void foo( ) {\n"
14924                "    size_t foo = (*(function))(\n"
14925                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14926                "BarrrrrrrrrrrrLong,\n"
14927                "        FoooooooooLooooong);\n"
14928                "}",
14929                Spaces);
14930   Spaces.SpaceAfterCStyleCast = false;
14931   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
14932   verifyFormat("size_t idx = (size_t)a;", Spaces);
14933   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
14934   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14935   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14936   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14937   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14938 
14939   verifyFormat("void foo( ) {\n"
14940                "    size_t foo = (*(function))(\n"
14941                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14942                "BarrrrrrrrrrrrLong,\n"
14943                "        FoooooooooLooooong);\n"
14944                "}",
14945                Spaces);
14946 }
14947 
14948 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
14949   verifyFormat("int a[5];");
14950   verifyFormat("a[3] += 42;");
14951 
14952   FormatStyle Spaces = getLLVMStyle();
14953   Spaces.SpacesInSquareBrackets = true;
14954   // Not lambdas.
14955   verifyFormat("int a[ 5 ];", Spaces);
14956   verifyFormat("a[ 3 ] += 42;", Spaces);
14957   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
14958   verifyFormat("double &operator[](int i) { return 0; }\n"
14959                "int i;",
14960                Spaces);
14961   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
14962   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
14963   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
14964   // Lambdas.
14965   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
14966   verifyFormat("return [ i, args... ] {};", Spaces);
14967   verifyFormat("int foo = [ &bar ]() {};", Spaces);
14968   verifyFormat("int foo = [ = ]() {};", Spaces);
14969   verifyFormat("int foo = [ & ]() {};", Spaces);
14970   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
14971   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
14972 }
14973 
14974 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
14975   FormatStyle NoSpaceStyle = getLLVMStyle();
14976   verifyFormat("int a[5];", NoSpaceStyle);
14977   verifyFormat("a[3] += 42;", NoSpaceStyle);
14978 
14979   verifyFormat("int a[1];", NoSpaceStyle);
14980   verifyFormat("int 1 [a];", NoSpaceStyle);
14981   verifyFormat("int a[1][2];", NoSpaceStyle);
14982   verifyFormat("a[7] = 5;", NoSpaceStyle);
14983   verifyFormat("int a = (f())[23];", NoSpaceStyle);
14984   verifyFormat("f([] {})", NoSpaceStyle);
14985 
14986   FormatStyle Space = getLLVMStyle();
14987   Space.SpaceBeforeSquareBrackets = true;
14988   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
14989   verifyFormat("return [i, args...] {};", Space);
14990 
14991   verifyFormat("int a [5];", Space);
14992   verifyFormat("a [3] += 42;", Space);
14993   verifyFormat("constexpr char hello []{\"hello\"};", Space);
14994   verifyFormat("double &operator[](int i) { return 0; }\n"
14995                "int i;",
14996                Space);
14997   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
14998   verifyFormat("int i = a [a][a]->f();", Space);
14999   verifyFormat("int i = (*b) [a]->f();", Space);
15000 
15001   verifyFormat("int a [1];", Space);
15002   verifyFormat("int 1 [a];", Space);
15003   verifyFormat("int a [1][2];", Space);
15004   verifyFormat("a [7] = 5;", Space);
15005   verifyFormat("int a = (f()) [23];", Space);
15006   verifyFormat("f([] {})", Space);
15007 }
15008 
15009 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15010   verifyFormat("int a = 5;");
15011   verifyFormat("a += 42;");
15012   verifyFormat("a or_eq 8;");
15013 
15014   FormatStyle Spaces = getLLVMStyle();
15015   Spaces.SpaceBeforeAssignmentOperators = false;
15016   verifyFormat("int a= 5;", Spaces);
15017   verifyFormat("a+= 42;", Spaces);
15018   verifyFormat("a or_eq 8;", Spaces);
15019 }
15020 
15021 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15022   verifyFormat("class Foo : public Bar {};");
15023   verifyFormat("Foo::Foo() : foo(1) {}");
15024   verifyFormat("for (auto a : b) {\n}");
15025   verifyFormat("int x = a ? b : c;");
15026   verifyFormat("{\n"
15027                "label0:\n"
15028                "  int x = 0;\n"
15029                "}");
15030   verifyFormat("switch (x) {\n"
15031                "case 1:\n"
15032                "default:\n"
15033                "}");
15034   verifyFormat("switch (allBraces) {\n"
15035                "case 1: {\n"
15036                "  break;\n"
15037                "}\n"
15038                "case 2: {\n"
15039                "  [[fallthrough]];\n"
15040                "}\n"
15041                "default: {\n"
15042                "  break;\n"
15043                "}\n"
15044                "}");
15045 
15046   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15047   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15048   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15049   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15050   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15051   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15052   verifyFormat("{\n"
15053                "label1:\n"
15054                "  int x = 0;\n"
15055                "}",
15056                CtorInitializerStyle);
15057   verifyFormat("switch (x) {\n"
15058                "case 1:\n"
15059                "default:\n"
15060                "}",
15061                CtorInitializerStyle);
15062   verifyFormat("switch (allBraces) {\n"
15063                "case 1: {\n"
15064                "  break;\n"
15065                "}\n"
15066                "case 2: {\n"
15067                "  [[fallthrough]];\n"
15068                "}\n"
15069                "default: {\n"
15070                "  break;\n"
15071                "}\n"
15072                "}",
15073                CtorInitializerStyle);
15074   CtorInitializerStyle.BreakConstructorInitializers =
15075       FormatStyle::BCIS_AfterColon;
15076   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15077                "    aaaaaaaaaaaaaaaa(1),\n"
15078                "    bbbbbbbbbbbbbbbb(2) {}",
15079                CtorInitializerStyle);
15080   CtorInitializerStyle.BreakConstructorInitializers =
15081       FormatStyle::BCIS_BeforeComma;
15082   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15083                "    : aaaaaaaaaaaaaaaa(1)\n"
15084                "    , bbbbbbbbbbbbbbbb(2) {}",
15085                CtorInitializerStyle);
15086   CtorInitializerStyle.BreakConstructorInitializers =
15087       FormatStyle::BCIS_BeforeColon;
15088   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15089                "    : aaaaaaaaaaaaaaaa(1),\n"
15090                "      bbbbbbbbbbbbbbbb(2) {}",
15091                CtorInitializerStyle);
15092   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15093   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15094                ": aaaaaaaaaaaaaaaa(1),\n"
15095                "  bbbbbbbbbbbbbbbb(2) {}",
15096                CtorInitializerStyle);
15097 
15098   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15099   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15100   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15101   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15102   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15103   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15104   verifyFormat("{\n"
15105                "label2:\n"
15106                "  int x = 0;\n"
15107                "}",
15108                InheritanceStyle);
15109   verifyFormat("switch (x) {\n"
15110                "case 1:\n"
15111                "default:\n"
15112                "}",
15113                InheritanceStyle);
15114   verifyFormat("switch (allBraces) {\n"
15115                "case 1: {\n"
15116                "  break;\n"
15117                "}\n"
15118                "case 2: {\n"
15119                "  [[fallthrough]];\n"
15120                "}\n"
15121                "default: {\n"
15122                "  break;\n"
15123                "}\n"
15124                "}",
15125                InheritanceStyle);
15126   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15127   verifyFormat("class Foooooooooooooooooooooo\n"
15128                "    : public aaaaaaaaaaaaaaaaaa,\n"
15129                "      public bbbbbbbbbbbbbbbbbb {\n"
15130                "}",
15131                InheritanceStyle);
15132   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15133   verifyFormat("class Foooooooooooooooooooooo:\n"
15134                "    public aaaaaaaaaaaaaaaaaa,\n"
15135                "    public bbbbbbbbbbbbbbbbbb {\n"
15136                "}",
15137                InheritanceStyle);
15138   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15139   verifyFormat("class Foooooooooooooooooooooo\n"
15140                "    : public aaaaaaaaaaaaaaaaaa\n"
15141                "    , public bbbbbbbbbbbbbbbbbb {\n"
15142                "}",
15143                InheritanceStyle);
15144   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15145   verifyFormat("class Foooooooooooooooooooooo\n"
15146                "    : public aaaaaaaaaaaaaaaaaa,\n"
15147                "      public bbbbbbbbbbbbbbbbbb {\n"
15148                "}",
15149                InheritanceStyle);
15150   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15151   verifyFormat("class Foooooooooooooooooooooo\n"
15152                ": public aaaaaaaaaaaaaaaaaa,\n"
15153                "  public bbbbbbbbbbbbbbbbbb {}",
15154                InheritanceStyle);
15155 
15156   FormatStyle ForLoopStyle = getLLVMStyle();
15157   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15158   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15159   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15160   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15161   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15162   verifyFormat("{\n"
15163                "label2:\n"
15164                "  int x = 0;\n"
15165                "}",
15166                ForLoopStyle);
15167   verifyFormat("switch (x) {\n"
15168                "case 1:\n"
15169                "default:\n"
15170                "}",
15171                ForLoopStyle);
15172   verifyFormat("switch (allBraces) {\n"
15173                "case 1: {\n"
15174                "  break;\n"
15175                "}\n"
15176                "case 2: {\n"
15177                "  [[fallthrough]];\n"
15178                "}\n"
15179                "default: {\n"
15180                "  break;\n"
15181                "}\n"
15182                "}",
15183                ForLoopStyle);
15184 
15185   FormatStyle CaseStyle = getLLVMStyle();
15186   CaseStyle.SpaceBeforeCaseColon = true;
15187   verifyFormat("class Foo : public Bar {};", CaseStyle);
15188   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15189   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15190   verifyFormat("int x = a ? b : c;", CaseStyle);
15191   verifyFormat("switch (x) {\n"
15192                "case 1 :\n"
15193                "default :\n"
15194                "}",
15195                CaseStyle);
15196   verifyFormat("switch (allBraces) {\n"
15197                "case 1 : {\n"
15198                "  break;\n"
15199                "}\n"
15200                "case 2 : {\n"
15201                "  [[fallthrough]];\n"
15202                "}\n"
15203                "default : {\n"
15204                "  break;\n"
15205                "}\n"
15206                "}",
15207                CaseStyle);
15208 
15209   FormatStyle NoSpaceStyle = getLLVMStyle();
15210   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15211   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15212   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15213   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15214   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15215   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15216   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15217   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15218   verifyFormat("{\n"
15219                "label3:\n"
15220                "  int x = 0;\n"
15221                "}",
15222                NoSpaceStyle);
15223   verifyFormat("switch (x) {\n"
15224                "case 1:\n"
15225                "default:\n"
15226                "}",
15227                NoSpaceStyle);
15228   verifyFormat("switch (allBraces) {\n"
15229                "case 1: {\n"
15230                "  break;\n"
15231                "}\n"
15232                "case 2: {\n"
15233                "  [[fallthrough]];\n"
15234                "}\n"
15235                "default: {\n"
15236                "  break;\n"
15237                "}\n"
15238                "}",
15239                NoSpaceStyle);
15240 
15241   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15242   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15243   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15244   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15245   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15246   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15247   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15248   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15249   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15250   verifyFormat("{\n"
15251                "label3:\n"
15252                "  int x = 0;\n"
15253                "}",
15254                InvertedSpaceStyle);
15255   verifyFormat("switch (x) {\n"
15256                "case 1 :\n"
15257                "case 2 : {\n"
15258                "  break;\n"
15259                "}\n"
15260                "default :\n"
15261                "  break;\n"
15262                "}",
15263                InvertedSpaceStyle);
15264   verifyFormat("switch (allBraces) {\n"
15265                "case 1 : {\n"
15266                "  break;\n"
15267                "}\n"
15268                "case 2 : {\n"
15269                "  [[fallthrough]];\n"
15270                "}\n"
15271                "default : {\n"
15272                "  break;\n"
15273                "}\n"
15274                "}",
15275                InvertedSpaceStyle);
15276 }
15277 
15278 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15279   FormatStyle Style = getLLVMStyle();
15280 
15281   Style.PointerAlignment = FormatStyle::PAS_Left;
15282   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15283   verifyFormat("void* const* x = NULL;", Style);
15284 
15285 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15286   do {                                                                         \
15287     Style.PointerAlignment = FormatStyle::Pointers;                            \
15288     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15289     verifyFormat(Code, Style);                                                 \
15290   } while (false)
15291 
15292   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15293   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15294   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15295 
15296   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15297   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15298   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15299 
15300   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15301   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15302   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15303 
15304   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15305   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15306   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15307 
15308   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15309   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15310                         SAPQ_Default);
15311   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15312                         SAPQ_Default);
15313 
15314   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15315   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15316                         SAPQ_Before);
15317   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15318                         SAPQ_Before);
15319 
15320   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15321   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15322   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15323                         SAPQ_After);
15324 
15325   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15326   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15327   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15328 
15329 #undef verifyQualifierSpaces
15330 
15331   FormatStyle Spaces = getLLVMStyle();
15332   Spaces.AttributeMacros.push_back("qualified");
15333   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15334   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15335   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15336   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15337   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15338   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15339   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15340   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15341   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15342   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15343   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15344   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15345   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15346 
15347   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15348   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15349   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15350   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15351   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15352   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15353   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15354   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15355   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15356   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15357   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15358   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15359   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15360   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15361   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15362 
15363   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15364   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15365   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15366   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15367   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15368   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15369   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15370   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15371 }
15372 
15373 TEST_F(FormatTest, AlignConsecutiveMacros) {
15374   FormatStyle Style = getLLVMStyle();
15375   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15376   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15377   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15378 
15379   verifyFormat("#define a 3\n"
15380                "#define bbbb 4\n"
15381                "#define ccc (5)",
15382                Style);
15383 
15384   verifyFormat("#define f(x) (x * x)\n"
15385                "#define fff(x, y, z) (x * y + z)\n"
15386                "#define ffff(x, y) (x - y)",
15387                Style);
15388 
15389   verifyFormat("#define foo(x, y) (x + y)\n"
15390                "#define bar (5, 6)(2 + 2)",
15391                Style);
15392 
15393   verifyFormat("#define a 3\n"
15394                "#define bbbb 4\n"
15395                "#define ccc (5)\n"
15396                "#define f(x) (x * x)\n"
15397                "#define fff(x, y, z) (x * y + z)\n"
15398                "#define ffff(x, y) (x - y)",
15399                Style);
15400 
15401   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15402   verifyFormat("#define a    3\n"
15403                "#define bbbb 4\n"
15404                "#define ccc  (5)",
15405                Style);
15406 
15407   verifyFormat("#define f(x)         (x * x)\n"
15408                "#define fff(x, y, z) (x * y + z)\n"
15409                "#define ffff(x, y)   (x - y)",
15410                Style);
15411 
15412   verifyFormat("#define foo(x, y) (x + y)\n"
15413                "#define bar       (5, 6)(2 + 2)",
15414                Style);
15415 
15416   verifyFormat("#define a            3\n"
15417                "#define bbbb         4\n"
15418                "#define ccc          (5)\n"
15419                "#define f(x)         (x * x)\n"
15420                "#define fff(x, y, z) (x * y + z)\n"
15421                "#define ffff(x, y)   (x - y)",
15422                Style);
15423 
15424   verifyFormat("#define a         5\n"
15425                "#define foo(x, y) (x + y)\n"
15426                "#define CCC       (6)\n"
15427                "auto lambda = []() {\n"
15428                "  auto  ii = 0;\n"
15429                "  float j  = 0;\n"
15430                "  return 0;\n"
15431                "};\n"
15432                "int   i  = 0;\n"
15433                "float i2 = 0;\n"
15434                "auto  v  = type{\n"
15435                "    i = 1,   //\n"
15436                "    (i = 2), //\n"
15437                "    i = 3    //\n"
15438                "};",
15439                Style);
15440 
15441   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15442   Style.ColumnLimit = 20;
15443 
15444   verifyFormat("#define a          \\\n"
15445                "  \"aabbbbbbbbbbbb\"\n"
15446                "#define D          \\\n"
15447                "  \"aabbbbbbbbbbbb\" \\\n"
15448                "  \"ccddeeeeeeeee\"\n"
15449                "#define B          \\\n"
15450                "  \"QQQQQQQQQQQQQ\"  \\\n"
15451                "  \"FFFFFFFFFFFFF\"  \\\n"
15452                "  \"LLLLLLLL\"\n",
15453                Style);
15454 
15455   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15456   verifyFormat("#define a          \\\n"
15457                "  \"aabbbbbbbbbbbb\"\n"
15458                "#define D          \\\n"
15459                "  \"aabbbbbbbbbbbb\" \\\n"
15460                "  \"ccddeeeeeeeee\"\n"
15461                "#define B          \\\n"
15462                "  \"QQQQQQQQQQQQQ\"  \\\n"
15463                "  \"FFFFFFFFFFFFF\"  \\\n"
15464                "  \"LLLLLLLL\"\n",
15465                Style);
15466 
15467   // Test across comments
15468   Style.MaxEmptyLinesToKeep = 10;
15469   Style.ReflowComments = false;
15470   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
15471   EXPECT_EQ("#define a    3\n"
15472             "// line comment\n"
15473             "#define bbbb 4\n"
15474             "#define ccc  (5)",
15475             format("#define a 3\n"
15476                    "// line comment\n"
15477                    "#define bbbb 4\n"
15478                    "#define ccc (5)",
15479                    Style));
15480 
15481   EXPECT_EQ("#define a    3\n"
15482             "/* block comment */\n"
15483             "#define bbbb 4\n"
15484             "#define ccc  (5)",
15485             format("#define a  3\n"
15486                    "/* block comment */\n"
15487                    "#define bbbb 4\n"
15488                    "#define ccc (5)",
15489                    Style));
15490 
15491   EXPECT_EQ("#define a    3\n"
15492             "/* multi-line *\n"
15493             " * block comment */\n"
15494             "#define bbbb 4\n"
15495             "#define ccc  (5)",
15496             format("#define a 3\n"
15497                    "/* multi-line *\n"
15498                    " * block comment */\n"
15499                    "#define bbbb 4\n"
15500                    "#define ccc (5)",
15501                    Style));
15502 
15503   EXPECT_EQ("#define a    3\n"
15504             "// multi-line line comment\n"
15505             "//\n"
15506             "#define bbbb 4\n"
15507             "#define ccc  (5)",
15508             format("#define a  3\n"
15509                    "// multi-line line comment\n"
15510                    "//\n"
15511                    "#define bbbb 4\n"
15512                    "#define ccc (5)",
15513                    Style));
15514 
15515   EXPECT_EQ("#define a 3\n"
15516             "// empty lines still break.\n"
15517             "\n"
15518             "#define bbbb 4\n"
15519             "#define ccc  (5)",
15520             format("#define a     3\n"
15521                    "// empty lines still break.\n"
15522                    "\n"
15523                    "#define bbbb     4\n"
15524                    "#define ccc  (5)",
15525                    Style));
15526 
15527   // Test across empty lines
15528   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
15529   EXPECT_EQ("#define a    3\n"
15530             "\n"
15531             "#define bbbb 4\n"
15532             "#define ccc  (5)",
15533             format("#define a 3\n"
15534                    "\n"
15535                    "#define bbbb 4\n"
15536                    "#define ccc (5)",
15537                    Style));
15538 
15539   EXPECT_EQ("#define a    3\n"
15540             "\n"
15541             "\n"
15542             "\n"
15543             "#define bbbb 4\n"
15544             "#define ccc  (5)",
15545             format("#define a        3\n"
15546                    "\n"
15547                    "\n"
15548                    "\n"
15549                    "#define bbbb 4\n"
15550                    "#define ccc (5)",
15551                    Style));
15552 
15553   EXPECT_EQ("#define a 3\n"
15554             "// comments should break alignment\n"
15555             "//\n"
15556             "#define bbbb 4\n"
15557             "#define ccc  (5)",
15558             format("#define a        3\n"
15559                    "// comments should break alignment\n"
15560                    "//\n"
15561                    "#define bbbb 4\n"
15562                    "#define ccc (5)",
15563                    Style));
15564 
15565   // Test across empty lines and comments
15566   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
15567   verifyFormat("#define a    3\n"
15568                "\n"
15569                "// line comment\n"
15570                "#define bbbb 4\n"
15571                "#define ccc  (5)",
15572                Style);
15573 
15574   EXPECT_EQ("#define a    3\n"
15575             "\n"
15576             "\n"
15577             "/* multi-line *\n"
15578             " * block comment */\n"
15579             "\n"
15580             "\n"
15581             "#define bbbb 4\n"
15582             "#define ccc  (5)",
15583             format("#define a 3\n"
15584                    "\n"
15585                    "\n"
15586                    "/* multi-line *\n"
15587                    " * block comment */\n"
15588                    "\n"
15589                    "\n"
15590                    "#define bbbb 4\n"
15591                    "#define ccc (5)",
15592                    Style));
15593 
15594   EXPECT_EQ("#define a    3\n"
15595             "\n"
15596             "\n"
15597             "/* multi-line *\n"
15598             " * block comment */\n"
15599             "\n"
15600             "\n"
15601             "#define bbbb 4\n"
15602             "#define ccc  (5)",
15603             format("#define a 3\n"
15604                    "\n"
15605                    "\n"
15606                    "/* multi-line *\n"
15607                    " * block comment */\n"
15608                    "\n"
15609                    "\n"
15610                    "#define bbbb 4\n"
15611                    "#define ccc       (5)",
15612                    Style));
15613 }
15614 
15615 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
15616   FormatStyle Alignment = getLLVMStyle();
15617   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15618   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
15619 
15620   Alignment.MaxEmptyLinesToKeep = 10;
15621   /* Test alignment across empty lines */
15622   EXPECT_EQ("int a           = 5;\n"
15623             "\n"
15624             "int oneTwoThree = 123;",
15625             format("int a       = 5;\n"
15626                    "\n"
15627                    "int oneTwoThree= 123;",
15628                    Alignment));
15629   EXPECT_EQ("int a           = 5;\n"
15630             "int one         = 1;\n"
15631             "\n"
15632             "int oneTwoThree = 123;",
15633             format("int a = 5;\n"
15634                    "int one = 1;\n"
15635                    "\n"
15636                    "int oneTwoThree = 123;",
15637                    Alignment));
15638   EXPECT_EQ("int a           = 5;\n"
15639             "int one         = 1;\n"
15640             "\n"
15641             "int oneTwoThree = 123;\n"
15642             "int oneTwo      = 12;",
15643             format("int a = 5;\n"
15644                    "int one = 1;\n"
15645                    "\n"
15646                    "int oneTwoThree = 123;\n"
15647                    "int oneTwo = 12;",
15648                    Alignment));
15649 
15650   /* Test across comments */
15651   EXPECT_EQ("int a = 5;\n"
15652             "/* block comment */\n"
15653             "int oneTwoThree = 123;",
15654             format("int a = 5;\n"
15655                    "/* block comment */\n"
15656                    "int oneTwoThree=123;",
15657                    Alignment));
15658 
15659   EXPECT_EQ("int a = 5;\n"
15660             "// line comment\n"
15661             "int oneTwoThree = 123;",
15662             format("int a = 5;\n"
15663                    "// line comment\n"
15664                    "int oneTwoThree=123;",
15665                    Alignment));
15666 
15667   /* Test across comments and newlines */
15668   EXPECT_EQ("int a = 5;\n"
15669             "\n"
15670             "/* block comment */\n"
15671             "int oneTwoThree = 123;",
15672             format("int a = 5;\n"
15673                    "\n"
15674                    "/* block comment */\n"
15675                    "int oneTwoThree=123;",
15676                    Alignment));
15677 
15678   EXPECT_EQ("int a = 5;\n"
15679             "\n"
15680             "// line comment\n"
15681             "int oneTwoThree = 123;",
15682             format("int a = 5;\n"
15683                    "\n"
15684                    "// line comment\n"
15685                    "int oneTwoThree=123;",
15686                    Alignment));
15687 }
15688 
15689 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
15690   FormatStyle Alignment = getLLVMStyle();
15691   Alignment.AlignConsecutiveDeclarations =
15692       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15693   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15694 
15695   Alignment.MaxEmptyLinesToKeep = 10;
15696   /* Test alignment across empty lines */
15697   EXPECT_EQ("int         a = 5;\n"
15698             "\n"
15699             "float const oneTwoThree = 123;",
15700             format("int a = 5;\n"
15701                    "\n"
15702                    "float const oneTwoThree = 123;",
15703                    Alignment));
15704   EXPECT_EQ("int         a = 5;\n"
15705             "float const one = 1;\n"
15706             "\n"
15707             "int         oneTwoThree = 123;",
15708             format("int a = 5;\n"
15709                    "float const one = 1;\n"
15710                    "\n"
15711                    "int oneTwoThree = 123;",
15712                    Alignment));
15713 
15714   /* Test across comments */
15715   EXPECT_EQ("float const a = 5;\n"
15716             "/* block comment */\n"
15717             "int         oneTwoThree = 123;",
15718             format("float const a = 5;\n"
15719                    "/* block comment */\n"
15720                    "int oneTwoThree=123;",
15721                    Alignment));
15722 
15723   EXPECT_EQ("float const a = 5;\n"
15724             "// line comment\n"
15725             "int         oneTwoThree = 123;",
15726             format("float const a = 5;\n"
15727                    "// line comment\n"
15728                    "int oneTwoThree=123;",
15729                    Alignment));
15730 
15731   /* Test across comments and newlines */
15732   EXPECT_EQ("float const a = 5;\n"
15733             "\n"
15734             "/* block comment */\n"
15735             "int         oneTwoThree = 123;",
15736             format("float const a = 5;\n"
15737                    "\n"
15738                    "/* block comment */\n"
15739                    "int         oneTwoThree=123;",
15740                    Alignment));
15741 
15742   EXPECT_EQ("float const a = 5;\n"
15743             "\n"
15744             "// line comment\n"
15745             "int         oneTwoThree = 123;",
15746             format("float const a = 5;\n"
15747                    "\n"
15748                    "// line comment\n"
15749                    "int oneTwoThree=123;",
15750                    Alignment));
15751 }
15752 
15753 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
15754   FormatStyle Alignment = getLLVMStyle();
15755   Alignment.AlignConsecutiveBitFields =
15756       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15757 
15758   Alignment.MaxEmptyLinesToKeep = 10;
15759   /* Test alignment across empty lines */
15760   EXPECT_EQ("int a            : 5;\n"
15761             "\n"
15762             "int longbitfield : 6;",
15763             format("int a : 5;\n"
15764                    "\n"
15765                    "int longbitfield : 6;",
15766                    Alignment));
15767   EXPECT_EQ("int a            : 5;\n"
15768             "int one          : 1;\n"
15769             "\n"
15770             "int longbitfield : 6;",
15771             format("int a : 5;\n"
15772                    "int one : 1;\n"
15773                    "\n"
15774                    "int longbitfield : 6;",
15775                    Alignment));
15776 
15777   /* Test across comments */
15778   EXPECT_EQ("int a            : 5;\n"
15779             "/* block comment */\n"
15780             "int longbitfield : 6;",
15781             format("int a : 5;\n"
15782                    "/* block comment */\n"
15783                    "int longbitfield : 6;",
15784                    Alignment));
15785   EXPECT_EQ("int a            : 5;\n"
15786             "int one          : 1;\n"
15787             "// line comment\n"
15788             "int longbitfield : 6;",
15789             format("int a : 5;\n"
15790                    "int one : 1;\n"
15791                    "// line comment\n"
15792                    "int longbitfield : 6;",
15793                    Alignment));
15794 
15795   /* Test across comments and newlines */
15796   EXPECT_EQ("int a            : 5;\n"
15797             "/* block comment */\n"
15798             "\n"
15799             "int longbitfield : 6;",
15800             format("int a : 5;\n"
15801                    "/* block comment */\n"
15802                    "\n"
15803                    "int longbitfield : 6;",
15804                    Alignment));
15805   EXPECT_EQ("int a            : 5;\n"
15806             "int one          : 1;\n"
15807             "\n"
15808             "// line comment\n"
15809             "\n"
15810             "int longbitfield : 6;",
15811             format("int a : 5;\n"
15812                    "int one : 1;\n"
15813                    "\n"
15814                    "// line comment \n"
15815                    "\n"
15816                    "int longbitfield : 6;",
15817                    Alignment));
15818 }
15819 
15820 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
15821   FormatStyle Alignment = getLLVMStyle();
15822   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15823   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
15824 
15825   Alignment.MaxEmptyLinesToKeep = 10;
15826   /* Test alignment across empty lines */
15827   EXPECT_EQ("int a = 5;\n"
15828             "\n"
15829             "int oneTwoThree = 123;",
15830             format("int a       = 5;\n"
15831                    "\n"
15832                    "int oneTwoThree= 123;",
15833                    Alignment));
15834   EXPECT_EQ("int a   = 5;\n"
15835             "int one = 1;\n"
15836             "\n"
15837             "int oneTwoThree = 123;",
15838             format("int a = 5;\n"
15839                    "int one = 1;\n"
15840                    "\n"
15841                    "int oneTwoThree = 123;",
15842                    Alignment));
15843 
15844   /* Test across comments */
15845   EXPECT_EQ("int a           = 5;\n"
15846             "/* block comment */\n"
15847             "int oneTwoThree = 123;",
15848             format("int a = 5;\n"
15849                    "/* block comment */\n"
15850                    "int oneTwoThree=123;",
15851                    Alignment));
15852 
15853   EXPECT_EQ("int a           = 5;\n"
15854             "// line comment\n"
15855             "int oneTwoThree = 123;",
15856             format("int a = 5;\n"
15857                    "// line comment\n"
15858                    "int oneTwoThree=123;",
15859                    Alignment));
15860 
15861   EXPECT_EQ("int a           = 5;\n"
15862             "/*\n"
15863             " * multi-line block comment\n"
15864             " */\n"
15865             "int oneTwoThree = 123;",
15866             format("int a = 5;\n"
15867                    "/*\n"
15868                    " * multi-line block comment\n"
15869                    " */\n"
15870                    "int oneTwoThree=123;",
15871                    Alignment));
15872 
15873   EXPECT_EQ("int a           = 5;\n"
15874             "//\n"
15875             "// multi-line line comment\n"
15876             "//\n"
15877             "int oneTwoThree = 123;",
15878             format("int a = 5;\n"
15879                    "//\n"
15880                    "// multi-line line comment\n"
15881                    "//\n"
15882                    "int oneTwoThree=123;",
15883                    Alignment));
15884 
15885   /* Test across comments and newlines */
15886   EXPECT_EQ("int a = 5;\n"
15887             "\n"
15888             "/* block comment */\n"
15889             "int oneTwoThree = 123;",
15890             format("int a = 5;\n"
15891                    "\n"
15892                    "/* block comment */\n"
15893                    "int oneTwoThree=123;",
15894                    Alignment));
15895 
15896   EXPECT_EQ("int a = 5;\n"
15897             "\n"
15898             "// line comment\n"
15899             "int oneTwoThree = 123;",
15900             format("int a = 5;\n"
15901                    "\n"
15902                    "// line comment\n"
15903                    "int oneTwoThree=123;",
15904                    Alignment));
15905 }
15906 
15907 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
15908   FormatStyle Alignment = getLLVMStyle();
15909   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15910   Alignment.AlignConsecutiveAssignments =
15911       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15912   verifyFormat("int a           = 5;\n"
15913                "int oneTwoThree = 123;",
15914                Alignment);
15915   verifyFormat("int a           = method();\n"
15916                "int oneTwoThree = 133;",
15917                Alignment);
15918   verifyFormat("a &= 5;\n"
15919                "bcd *= 5;\n"
15920                "ghtyf += 5;\n"
15921                "dvfvdb -= 5;\n"
15922                "a /= 5;\n"
15923                "vdsvsv %= 5;\n"
15924                "sfdbddfbdfbb ^= 5;\n"
15925                "dvsdsv |= 5;\n"
15926                "int dsvvdvsdvvv = 123;",
15927                Alignment);
15928   verifyFormat("int i = 1, j = 10;\n"
15929                "something = 2000;",
15930                Alignment);
15931   verifyFormat("something = 2000;\n"
15932                "int i = 1, j = 10;\n",
15933                Alignment);
15934   verifyFormat("something = 2000;\n"
15935                "another   = 911;\n"
15936                "int i = 1, j = 10;\n"
15937                "oneMore = 1;\n"
15938                "i       = 2;",
15939                Alignment);
15940   verifyFormat("int a   = 5;\n"
15941                "int one = 1;\n"
15942                "method();\n"
15943                "int oneTwoThree = 123;\n"
15944                "int oneTwo      = 12;",
15945                Alignment);
15946   verifyFormat("int oneTwoThree = 123;\n"
15947                "int oneTwo      = 12;\n"
15948                "method();\n",
15949                Alignment);
15950   verifyFormat("int oneTwoThree = 123; // comment\n"
15951                "int oneTwo      = 12;  // comment",
15952                Alignment);
15953 
15954   // Bug 25167
15955   /* Uncomment when fixed
15956     verifyFormat("#if A\n"
15957                  "#else\n"
15958                  "int aaaaaaaa = 12;\n"
15959                  "#endif\n"
15960                  "#if B\n"
15961                  "#else\n"
15962                  "int a = 12;\n"
15963                  "#endif\n",
15964                  Alignment);
15965     verifyFormat("enum foo {\n"
15966                  "#if A\n"
15967                  "#else\n"
15968                  "  aaaaaaaa = 12;\n"
15969                  "#endif\n"
15970                  "#if B\n"
15971                  "#else\n"
15972                  "  a = 12;\n"
15973                  "#endif\n"
15974                  "};\n",
15975                  Alignment);
15976   */
15977 
15978   Alignment.MaxEmptyLinesToKeep = 10;
15979   /* Test alignment across empty lines */
15980   EXPECT_EQ("int a           = 5;\n"
15981             "\n"
15982             "int oneTwoThree = 123;",
15983             format("int a       = 5;\n"
15984                    "\n"
15985                    "int oneTwoThree= 123;",
15986                    Alignment));
15987   EXPECT_EQ("int a           = 5;\n"
15988             "int one         = 1;\n"
15989             "\n"
15990             "int oneTwoThree = 123;",
15991             format("int a = 5;\n"
15992                    "int one = 1;\n"
15993                    "\n"
15994                    "int oneTwoThree = 123;",
15995                    Alignment));
15996   EXPECT_EQ("int a           = 5;\n"
15997             "int one         = 1;\n"
15998             "\n"
15999             "int oneTwoThree = 123;\n"
16000             "int oneTwo      = 12;",
16001             format("int a = 5;\n"
16002                    "int one = 1;\n"
16003                    "\n"
16004                    "int oneTwoThree = 123;\n"
16005                    "int oneTwo = 12;",
16006                    Alignment));
16007 
16008   /* Test across comments */
16009   EXPECT_EQ("int a           = 5;\n"
16010             "/* block comment */\n"
16011             "int oneTwoThree = 123;",
16012             format("int a = 5;\n"
16013                    "/* block comment */\n"
16014                    "int oneTwoThree=123;",
16015                    Alignment));
16016 
16017   EXPECT_EQ("int a           = 5;\n"
16018             "// line comment\n"
16019             "int oneTwoThree = 123;",
16020             format("int a = 5;\n"
16021                    "// line comment\n"
16022                    "int oneTwoThree=123;",
16023                    Alignment));
16024 
16025   /* Test across comments and newlines */
16026   EXPECT_EQ("int a           = 5;\n"
16027             "\n"
16028             "/* block comment */\n"
16029             "int oneTwoThree = 123;",
16030             format("int a = 5;\n"
16031                    "\n"
16032                    "/* block comment */\n"
16033                    "int oneTwoThree=123;",
16034                    Alignment));
16035 
16036   EXPECT_EQ("int a           = 5;\n"
16037             "\n"
16038             "// line comment\n"
16039             "int oneTwoThree = 123;",
16040             format("int a = 5;\n"
16041                    "\n"
16042                    "// line comment\n"
16043                    "int oneTwoThree=123;",
16044                    Alignment));
16045 
16046   EXPECT_EQ("int a           = 5;\n"
16047             "//\n"
16048             "// multi-line line comment\n"
16049             "//\n"
16050             "int oneTwoThree = 123;",
16051             format("int a = 5;\n"
16052                    "//\n"
16053                    "// multi-line line comment\n"
16054                    "//\n"
16055                    "int oneTwoThree=123;",
16056                    Alignment));
16057 
16058   EXPECT_EQ("int a           = 5;\n"
16059             "/*\n"
16060             " *  multi-line block comment\n"
16061             " */\n"
16062             "int oneTwoThree = 123;",
16063             format("int a = 5;\n"
16064                    "/*\n"
16065                    " *  multi-line block comment\n"
16066                    " */\n"
16067                    "int oneTwoThree=123;",
16068                    Alignment));
16069 
16070   EXPECT_EQ("int a           = 5;\n"
16071             "\n"
16072             "/* block comment */\n"
16073             "\n"
16074             "\n"
16075             "\n"
16076             "int oneTwoThree = 123;",
16077             format("int a = 5;\n"
16078                    "\n"
16079                    "/* block comment */\n"
16080                    "\n"
16081                    "\n"
16082                    "\n"
16083                    "int oneTwoThree=123;",
16084                    Alignment));
16085 
16086   EXPECT_EQ("int a           = 5;\n"
16087             "\n"
16088             "// line comment\n"
16089             "\n"
16090             "\n"
16091             "\n"
16092             "int oneTwoThree = 123;",
16093             format("int a = 5;\n"
16094                    "\n"
16095                    "// line comment\n"
16096                    "\n"
16097                    "\n"
16098                    "\n"
16099                    "int oneTwoThree=123;",
16100                    Alignment));
16101 
16102   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16103   verifyFormat("#define A \\\n"
16104                "  int aaaa       = 12; \\\n"
16105                "  int b          = 23; \\\n"
16106                "  int ccc        = 234; \\\n"
16107                "  int dddddddddd = 2345;",
16108                Alignment);
16109   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16110   verifyFormat("#define A               \\\n"
16111                "  int aaaa       = 12;  \\\n"
16112                "  int b          = 23;  \\\n"
16113                "  int ccc        = 234; \\\n"
16114                "  int dddddddddd = 2345;",
16115                Alignment);
16116   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16117   verifyFormat("#define A                                                      "
16118                "                \\\n"
16119                "  int aaaa       = 12;                                         "
16120                "                \\\n"
16121                "  int b          = 23;                                         "
16122                "                \\\n"
16123                "  int ccc        = 234;                                        "
16124                "                \\\n"
16125                "  int dddddddddd = 2345;",
16126                Alignment);
16127   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16128                "k = 4, int l = 5,\n"
16129                "                  int m = 6) {\n"
16130                "  int j      = 10;\n"
16131                "  otherThing = 1;\n"
16132                "}",
16133                Alignment);
16134   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16135                "  int i   = 1;\n"
16136                "  int j   = 2;\n"
16137                "  int big = 10000;\n"
16138                "}",
16139                Alignment);
16140   verifyFormat("class C {\n"
16141                "public:\n"
16142                "  int i            = 1;\n"
16143                "  virtual void f() = 0;\n"
16144                "};",
16145                Alignment);
16146   verifyFormat("int i = 1;\n"
16147                "if (SomeType t = getSomething()) {\n"
16148                "}\n"
16149                "int j   = 2;\n"
16150                "int big = 10000;",
16151                Alignment);
16152   verifyFormat("int j = 7;\n"
16153                "for (int k = 0; k < N; ++k) {\n"
16154                "}\n"
16155                "int j   = 2;\n"
16156                "int big = 10000;\n"
16157                "}",
16158                Alignment);
16159   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16160   verifyFormat("int i = 1;\n"
16161                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16162                "    = someLooooooooooooooooongFunction();\n"
16163                "int j = 2;",
16164                Alignment);
16165   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16166   verifyFormat("int i = 1;\n"
16167                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16168                "    someLooooooooooooooooongFunction();\n"
16169                "int j = 2;",
16170                Alignment);
16171 
16172   verifyFormat("auto lambda = []() {\n"
16173                "  auto i = 0;\n"
16174                "  return 0;\n"
16175                "};\n"
16176                "int i  = 0;\n"
16177                "auto v = type{\n"
16178                "    i = 1,   //\n"
16179                "    (i = 2), //\n"
16180                "    i = 3    //\n"
16181                "};",
16182                Alignment);
16183 
16184   verifyFormat(
16185       "int i      = 1;\n"
16186       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16187       "                          loooooooooooooooooooooongParameterB);\n"
16188       "int j      = 2;",
16189       Alignment);
16190 
16191   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16192                "          typename B   = very_long_type_name_1,\n"
16193                "          typename T_2 = very_long_type_name_2>\n"
16194                "auto foo() {}\n",
16195                Alignment);
16196   verifyFormat("int a, b = 1;\n"
16197                "int c  = 2;\n"
16198                "int dd = 3;\n",
16199                Alignment);
16200   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16201                "float b[1][] = {{3.f}};\n",
16202                Alignment);
16203   verifyFormat("for (int i = 0; i < 1; i++)\n"
16204                "  int x = 1;\n",
16205                Alignment);
16206   verifyFormat("for (i = 0; i < 1; i++)\n"
16207                "  x = 1;\n"
16208                "y = 1;\n",
16209                Alignment);
16210 
16211   Alignment.ReflowComments = true;
16212   Alignment.ColumnLimit = 50;
16213   EXPECT_EQ("int x   = 0;\n"
16214             "int yy  = 1; /// specificlennospace\n"
16215             "int zzz = 2;\n",
16216             format("int x   = 0;\n"
16217                    "int yy  = 1; ///specificlennospace\n"
16218                    "int zzz = 2;\n",
16219                    Alignment));
16220 }
16221 
16222 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16223   FormatStyle Alignment = getLLVMStyle();
16224   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16225   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16226   verifyFormat("int a = 5;\n"
16227                "int oneTwoThree = 123;",
16228                Alignment);
16229   verifyFormat("int a = 5;\n"
16230                "int oneTwoThree = 123;",
16231                Alignment);
16232 
16233   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16234   verifyFormat("int a           = 5;\n"
16235                "int oneTwoThree = 123;",
16236                Alignment);
16237   verifyFormat("int a           = method();\n"
16238                "int oneTwoThree = 133;",
16239                Alignment);
16240   verifyFormat("a &= 5;\n"
16241                "bcd *= 5;\n"
16242                "ghtyf += 5;\n"
16243                "dvfvdb -= 5;\n"
16244                "a /= 5;\n"
16245                "vdsvsv %= 5;\n"
16246                "sfdbddfbdfbb ^= 5;\n"
16247                "dvsdsv |= 5;\n"
16248                "int dsvvdvsdvvv = 123;",
16249                Alignment);
16250   verifyFormat("int i = 1, j = 10;\n"
16251                "something = 2000;",
16252                Alignment);
16253   verifyFormat("something = 2000;\n"
16254                "int i = 1, j = 10;\n",
16255                Alignment);
16256   verifyFormat("something = 2000;\n"
16257                "another   = 911;\n"
16258                "int i = 1, j = 10;\n"
16259                "oneMore = 1;\n"
16260                "i       = 2;",
16261                Alignment);
16262   verifyFormat("int a   = 5;\n"
16263                "int one = 1;\n"
16264                "method();\n"
16265                "int oneTwoThree = 123;\n"
16266                "int oneTwo      = 12;",
16267                Alignment);
16268   verifyFormat("int oneTwoThree = 123;\n"
16269                "int oneTwo      = 12;\n"
16270                "method();\n",
16271                Alignment);
16272   verifyFormat("int oneTwoThree = 123; // comment\n"
16273                "int oneTwo      = 12;  // comment",
16274                Alignment);
16275   verifyFormat("int f()         = default;\n"
16276                "int &operator() = default;\n"
16277                "int &operator=() {",
16278                Alignment);
16279   verifyFormat("int f()         = delete;\n"
16280                "int &operator() = delete;\n"
16281                "int &operator=() {",
16282                Alignment);
16283   verifyFormat("int f()         = default; // comment\n"
16284                "int &operator() = default; // comment\n"
16285                "int &operator=() {",
16286                Alignment);
16287   verifyFormat("int f()         = default;\n"
16288                "int &operator() = default;\n"
16289                "int &operator==() {",
16290                Alignment);
16291   verifyFormat("int f()         = default;\n"
16292                "int &operator() = default;\n"
16293                "int &operator<=() {",
16294                Alignment);
16295   verifyFormat("int f()         = default;\n"
16296                "int &operator() = default;\n"
16297                "int &operator!=() {",
16298                Alignment);
16299   verifyFormat("int f()         = default;\n"
16300                "int &operator() = default;\n"
16301                "int &operator=();",
16302                Alignment);
16303   verifyFormat("int f()         = delete;\n"
16304                "int &operator() = delete;\n"
16305                "int &operator=();",
16306                Alignment);
16307   verifyFormat("/* long long padding */ int f() = default;\n"
16308                "int &operator()                 = default;\n"
16309                "int &operator/**/ =();",
16310                Alignment);
16311   // https://llvm.org/PR33697
16312   FormatStyle AlignmentWithPenalty = getLLVMStyle();
16313   AlignmentWithPenalty.AlignConsecutiveAssignments =
16314       FormatStyle::ACS_Consecutive;
16315   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
16316   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
16317                "  void f() = delete;\n"
16318                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
16319                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
16320                "};\n",
16321                AlignmentWithPenalty);
16322 
16323   // Bug 25167
16324   /* Uncomment when fixed
16325     verifyFormat("#if A\n"
16326                  "#else\n"
16327                  "int aaaaaaaa = 12;\n"
16328                  "#endif\n"
16329                  "#if B\n"
16330                  "#else\n"
16331                  "int a = 12;\n"
16332                  "#endif\n",
16333                  Alignment);
16334     verifyFormat("enum foo {\n"
16335                  "#if A\n"
16336                  "#else\n"
16337                  "  aaaaaaaa = 12;\n"
16338                  "#endif\n"
16339                  "#if B\n"
16340                  "#else\n"
16341                  "  a = 12;\n"
16342                  "#endif\n"
16343                  "};\n",
16344                  Alignment);
16345   */
16346 
16347   EXPECT_EQ("int a = 5;\n"
16348             "\n"
16349             "int oneTwoThree = 123;",
16350             format("int a       = 5;\n"
16351                    "\n"
16352                    "int oneTwoThree= 123;",
16353                    Alignment));
16354   EXPECT_EQ("int a   = 5;\n"
16355             "int one = 1;\n"
16356             "\n"
16357             "int oneTwoThree = 123;",
16358             format("int a = 5;\n"
16359                    "int one = 1;\n"
16360                    "\n"
16361                    "int oneTwoThree = 123;",
16362                    Alignment));
16363   EXPECT_EQ("int a   = 5;\n"
16364             "int one = 1;\n"
16365             "\n"
16366             "int oneTwoThree = 123;\n"
16367             "int oneTwo      = 12;",
16368             format("int a = 5;\n"
16369                    "int one = 1;\n"
16370                    "\n"
16371                    "int oneTwoThree = 123;\n"
16372                    "int oneTwo = 12;",
16373                    Alignment));
16374   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16375   verifyFormat("#define A \\\n"
16376                "  int aaaa       = 12; \\\n"
16377                "  int b          = 23; \\\n"
16378                "  int ccc        = 234; \\\n"
16379                "  int dddddddddd = 2345;",
16380                Alignment);
16381   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16382   verifyFormat("#define A               \\\n"
16383                "  int aaaa       = 12;  \\\n"
16384                "  int b          = 23;  \\\n"
16385                "  int ccc        = 234; \\\n"
16386                "  int dddddddddd = 2345;",
16387                Alignment);
16388   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16389   verifyFormat("#define A                                                      "
16390                "                \\\n"
16391                "  int aaaa       = 12;                                         "
16392                "                \\\n"
16393                "  int b          = 23;                                         "
16394                "                \\\n"
16395                "  int ccc        = 234;                                        "
16396                "                \\\n"
16397                "  int dddddddddd = 2345;",
16398                Alignment);
16399   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16400                "k = 4, int l = 5,\n"
16401                "                  int m = 6) {\n"
16402                "  int j      = 10;\n"
16403                "  otherThing = 1;\n"
16404                "}",
16405                Alignment);
16406   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16407                "  int i   = 1;\n"
16408                "  int j   = 2;\n"
16409                "  int big = 10000;\n"
16410                "}",
16411                Alignment);
16412   verifyFormat("class C {\n"
16413                "public:\n"
16414                "  int i            = 1;\n"
16415                "  virtual void f() = 0;\n"
16416                "};",
16417                Alignment);
16418   verifyFormat("int i = 1;\n"
16419                "if (SomeType t = getSomething()) {\n"
16420                "}\n"
16421                "int j   = 2;\n"
16422                "int big = 10000;",
16423                Alignment);
16424   verifyFormat("int j = 7;\n"
16425                "for (int k = 0; k < N; ++k) {\n"
16426                "}\n"
16427                "int j   = 2;\n"
16428                "int big = 10000;\n"
16429                "}",
16430                Alignment);
16431   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16432   verifyFormat("int i = 1;\n"
16433                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16434                "    = someLooooooooooooooooongFunction();\n"
16435                "int j = 2;",
16436                Alignment);
16437   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16438   verifyFormat("int i = 1;\n"
16439                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16440                "    someLooooooooooooooooongFunction();\n"
16441                "int j = 2;",
16442                Alignment);
16443 
16444   verifyFormat("auto lambda = []() {\n"
16445                "  auto i = 0;\n"
16446                "  return 0;\n"
16447                "};\n"
16448                "int i  = 0;\n"
16449                "auto v = type{\n"
16450                "    i = 1,   //\n"
16451                "    (i = 2), //\n"
16452                "    i = 3    //\n"
16453                "};",
16454                Alignment);
16455 
16456   verifyFormat(
16457       "int i      = 1;\n"
16458       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16459       "                          loooooooooooooooooooooongParameterB);\n"
16460       "int j      = 2;",
16461       Alignment);
16462 
16463   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16464                "          typename B   = very_long_type_name_1,\n"
16465                "          typename T_2 = very_long_type_name_2>\n"
16466                "auto foo() {}\n",
16467                Alignment);
16468   verifyFormat("int a, b = 1;\n"
16469                "int c  = 2;\n"
16470                "int dd = 3;\n",
16471                Alignment);
16472   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16473                "float b[1][] = {{3.f}};\n",
16474                Alignment);
16475   verifyFormat("for (int i = 0; i < 1; i++)\n"
16476                "  int x = 1;\n",
16477                Alignment);
16478   verifyFormat("for (i = 0; i < 1; i++)\n"
16479                "  x = 1;\n"
16480                "y = 1;\n",
16481                Alignment);
16482 
16483   Alignment.ReflowComments = true;
16484   Alignment.ColumnLimit = 50;
16485   EXPECT_EQ("int x   = 0;\n"
16486             "int yy  = 1; /// specificlennospace\n"
16487             "int zzz = 2;\n",
16488             format("int x   = 0;\n"
16489                    "int yy  = 1; ///specificlennospace\n"
16490                    "int zzz = 2;\n",
16491                    Alignment));
16492 }
16493 
16494 TEST_F(FormatTest, AlignConsecutiveBitFields) {
16495   FormatStyle Alignment = getLLVMStyle();
16496   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
16497   verifyFormat("int const a     : 5;\n"
16498                "int oneTwoThree : 23;",
16499                Alignment);
16500 
16501   // Initializers are allowed starting with c++2a
16502   verifyFormat("int const a     : 5 = 1;\n"
16503                "int oneTwoThree : 23 = 0;",
16504                Alignment);
16505 
16506   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16507   verifyFormat("int const a           : 5;\n"
16508                "int       oneTwoThree : 23;",
16509                Alignment);
16510 
16511   verifyFormat("int const a           : 5;  // comment\n"
16512                "int       oneTwoThree : 23; // comment",
16513                Alignment);
16514 
16515   verifyFormat("int const a           : 5 = 1;\n"
16516                "int       oneTwoThree : 23 = 0;",
16517                Alignment);
16518 
16519   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16520   verifyFormat("int const a           : 5  = 1;\n"
16521                "int       oneTwoThree : 23 = 0;",
16522                Alignment);
16523   verifyFormat("int const a           : 5  = {1};\n"
16524                "int       oneTwoThree : 23 = 0;",
16525                Alignment);
16526 
16527   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
16528   verifyFormat("int const a          :5;\n"
16529                "int       oneTwoThree:23;",
16530                Alignment);
16531 
16532   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
16533   verifyFormat("int const a           :5;\n"
16534                "int       oneTwoThree :23;",
16535                Alignment);
16536 
16537   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
16538   verifyFormat("int const a          : 5;\n"
16539                "int       oneTwoThree: 23;",
16540                Alignment);
16541 
16542   // Known limitations: ':' is only recognized as a bitfield colon when
16543   // followed by a number.
16544   /*
16545   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
16546                "int a           : 5;",
16547                Alignment);
16548   */
16549 }
16550 
16551 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
16552   FormatStyle Alignment = getLLVMStyle();
16553   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16554   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16555   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16556   verifyFormat("float const a = 5;\n"
16557                "int oneTwoThree = 123;",
16558                Alignment);
16559   verifyFormat("int a = 5;\n"
16560                "float const oneTwoThree = 123;",
16561                Alignment);
16562 
16563   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16564   verifyFormat("float const a = 5;\n"
16565                "int         oneTwoThree = 123;",
16566                Alignment);
16567   verifyFormat("int         a = method();\n"
16568                "float const oneTwoThree = 133;",
16569                Alignment);
16570   verifyFormat("int i = 1, j = 10;\n"
16571                "something = 2000;",
16572                Alignment);
16573   verifyFormat("something = 2000;\n"
16574                "int i = 1, j = 10;\n",
16575                Alignment);
16576   verifyFormat("float      something = 2000;\n"
16577                "double     another = 911;\n"
16578                "int        i = 1, j = 10;\n"
16579                "const int *oneMore = 1;\n"
16580                "unsigned   i = 2;",
16581                Alignment);
16582   verifyFormat("float a = 5;\n"
16583                "int   one = 1;\n"
16584                "method();\n"
16585                "const double       oneTwoThree = 123;\n"
16586                "const unsigned int oneTwo = 12;",
16587                Alignment);
16588   verifyFormat("int      oneTwoThree{0}; // comment\n"
16589                "unsigned oneTwo;         // comment",
16590                Alignment);
16591   verifyFormat("unsigned int       *a;\n"
16592                "int                *b;\n"
16593                "unsigned int Const *c;\n"
16594                "unsigned int const *d;\n"
16595                "unsigned int Const &e;\n"
16596                "unsigned int const &f;",
16597                Alignment);
16598   verifyFormat("Const unsigned int *c;\n"
16599                "const unsigned int *d;\n"
16600                "Const unsigned int &e;\n"
16601                "const unsigned int &f;\n"
16602                "const unsigned      g;\n"
16603                "Const unsigned      h;",
16604                Alignment);
16605   EXPECT_EQ("float const a = 5;\n"
16606             "\n"
16607             "int oneTwoThree = 123;",
16608             format("float const   a = 5;\n"
16609                    "\n"
16610                    "int           oneTwoThree= 123;",
16611                    Alignment));
16612   EXPECT_EQ("float a = 5;\n"
16613             "int   one = 1;\n"
16614             "\n"
16615             "unsigned oneTwoThree = 123;",
16616             format("float    a = 5;\n"
16617                    "int      one = 1;\n"
16618                    "\n"
16619                    "unsigned oneTwoThree = 123;",
16620                    Alignment));
16621   EXPECT_EQ("float a = 5;\n"
16622             "int   one = 1;\n"
16623             "\n"
16624             "unsigned oneTwoThree = 123;\n"
16625             "int      oneTwo = 12;",
16626             format("float    a = 5;\n"
16627                    "int one = 1;\n"
16628                    "\n"
16629                    "unsigned oneTwoThree = 123;\n"
16630                    "int oneTwo = 12;",
16631                    Alignment));
16632   // Function prototype alignment
16633   verifyFormat("int    a();\n"
16634                "double b();",
16635                Alignment);
16636   verifyFormat("int    a(int x);\n"
16637                "double b();",
16638                Alignment);
16639   unsigned OldColumnLimit = Alignment.ColumnLimit;
16640   // We need to set ColumnLimit to zero, in order to stress nested alignments,
16641   // otherwise the function parameters will be re-flowed onto a single line.
16642   Alignment.ColumnLimit = 0;
16643   EXPECT_EQ("int    a(int   x,\n"
16644             "         float y);\n"
16645             "double b(int    x,\n"
16646             "         double y);",
16647             format("int a(int x,\n"
16648                    " float y);\n"
16649                    "double b(int x,\n"
16650                    " double y);",
16651                    Alignment));
16652   // This ensures that function parameters of function declarations are
16653   // correctly indented when their owning functions are indented.
16654   // The failure case here is for 'double y' to not be indented enough.
16655   EXPECT_EQ("double a(int x);\n"
16656             "int    b(int    y,\n"
16657             "         double z);",
16658             format("double a(int x);\n"
16659                    "int b(int y,\n"
16660                    " double z);",
16661                    Alignment));
16662   // Set ColumnLimit low so that we induce wrapping immediately after
16663   // the function name and opening paren.
16664   Alignment.ColumnLimit = 13;
16665   verifyFormat("int function(\n"
16666                "    int  x,\n"
16667                "    bool y);",
16668                Alignment);
16669   Alignment.ColumnLimit = OldColumnLimit;
16670   // Ensure function pointers don't screw up recursive alignment
16671   verifyFormat("int    a(int x, void (*fp)(int y));\n"
16672                "double b();",
16673                Alignment);
16674   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16675   // Ensure recursive alignment is broken by function braces, so that the
16676   // "a = 1" does not align with subsequent assignments inside the function
16677   // body.
16678   verifyFormat("int func(int a = 1) {\n"
16679                "  int b  = 2;\n"
16680                "  int cc = 3;\n"
16681                "}",
16682                Alignment);
16683   verifyFormat("float      something = 2000;\n"
16684                "double     another   = 911;\n"
16685                "int        i = 1, j = 10;\n"
16686                "const int *oneMore = 1;\n"
16687                "unsigned   i       = 2;",
16688                Alignment);
16689   verifyFormat("int      oneTwoThree = {0}; // comment\n"
16690                "unsigned oneTwo      = 0;   // comment",
16691                Alignment);
16692   // Make sure that scope is correctly tracked, in the absence of braces
16693   verifyFormat("for (int i = 0; i < n; i++)\n"
16694                "  j = i;\n"
16695                "double x = 1;\n",
16696                Alignment);
16697   verifyFormat("if (int i = 0)\n"
16698                "  j = i;\n"
16699                "double x = 1;\n",
16700                Alignment);
16701   // Ensure operator[] and operator() are comprehended
16702   verifyFormat("struct test {\n"
16703                "  long long int foo();\n"
16704                "  int           operator[](int a);\n"
16705                "  double        bar();\n"
16706                "};\n",
16707                Alignment);
16708   verifyFormat("struct test {\n"
16709                "  long long int foo();\n"
16710                "  int           operator()(int a);\n"
16711                "  double        bar();\n"
16712                "};\n",
16713                Alignment);
16714   // http://llvm.org/PR52914
16715   verifyFormat("char *a[]     = {\"a\", // comment\n"
16716                "                 \"bb\"};\n"
16717                "int   bbbbbbb = 0;",
16718                Alignment);
16719 
16720   // PAS_Right
16721   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16722             "  int const i   = 1;\n"
16723             "  int      *j   = 2;\n"
16724             "  int       big = 10000;\n"
16725             "\n"
16726             "  unsigned oneTwoThree = 123;\n"
16727             "  int      oneTwo      = 12;\n"
16728             "  method();\n"
16729             "  float k  = 2;\n"
16730             "  int   ll = 10000;\n"
16731             "}",
16732             format("void SomeFunction(int parameter= 0) {\n"
16733                    " int const  i= 1;\n"
16734                    "  int *j=2;\n"
16735                    " int big  =  10000;\n"
16736                    "\n"
16737                    "unsigned oneTwoThree  =123;\n"
16738                    "int oneTwo = 12;\n"
16739                    "  method();\n"
16740                    "float k= 2;\n"
16741                    "int ll=10000;\n"
16742                    "}",
16743                    Alignment));
16744   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16745             "  int const i   = 1;\n"
16746             "  int     **j   = 2, ***k;\n"
16747             "  int      &k   = i;\n"
16748             "  int     &&l   = i + j;\n"
16749             "  int       big = 10000;\n"
16750             "\n"
16751             "  unsigned oneTwoThree = 123;\n"
16752             "  int      oneTwo      = 12;\n"
16753             "  method();\n"
16754             "  float k  = 2;\n"
16755             "  int   ll = 10000;\n"
16756             "}",
16757             format("void SomeFunction(int parameter= 0) {\n"
16758                    " int const  i= 1;\n"
16759                    "  int **j=2,***k;\n"
16760                    "int &k=i;\n"
16761                    "int &&l=i+j;\n"
16762                    " int big  =  10000;\n"
16763                    "\n"
16764                    "unsigned oneTwoThree  =123;\n"
16765                    "int oneTwo = 12;\n"
16766                    "  method();\n"
16767                    "float k= 2;\n"
16768                    "int ll=10000;\n"
16769                    "}",
16770                    Alignment));
16771   // variables are aligned at their name, pointers are at the right most
16772   // position
16773   verifyFormat("int   *a;\n"
16774                "int  **b;\n"
16775                "int ***c;\n"
16776                "int    foobar;\n",
16777                Alignment);
16778 
16779   // PAS_Left
16780   FormatStyle AlignmentLeft = Alignment;
16781   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
16782   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16783             "  int const i   = 1;\n"
16784             "  int*      j   = 2;\n"
16785             "  int       big = 10000;\n"
16786             "\n"
16787             "  unsigned oneTwoThree = 123;\n"
16788             "  int      oneTwo      = 12;\n"
16789             "  method();\n"
16790             "  float k  = 2;\n"
16791             "  int   ll = 10000;\n"
16792             "}",
16793             format("void SomeFunction(int parameter= 0) {\n"
16794                    " int const  i= 1;\n"
16795                    "  int *j=2;\n"
16796                    " int big  =  10000;\n"
16797                    "\n"
16798                    "unsigned oneTwoThree  =123;\n"
16799                    "int oneTwo = 12;\n"
16800                    "  method();\n"
16801                    "float k= 2;\n"
16802                    "int ll=10000;\n"
16803                    "}",
16804                    AlignmentLeft));
16805   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16806             "  int const i   = 1;\n"
16807             "  int**     j   = 2;\n"
16808             "  int&      k   = i;\n"
16809             "  int&&     l   = i + j;\n"
16810             "  int       big = 10000;\n"
16811             "\n"
16812             "  unsigned oneTwoThree = 123;\n"
16813             "  int      oneTwo      = 12;\n"
16814             "  method();\n"
16815             "  float k  = 2;\n"
16816             "  int   ll = 10000;\n"
16817             "}",
16818             format("void SomeFunction(int parameter= 0) {\n"
16819                    " int const  i= 1;\n"
16820                    "  int **j=2;\n"
16821                    "int &k=i;\n"
16822                    "int &&l=i+j;\n"
16823                    " int big  =  10000;\n"
16824                    "\n"
16825                    "unsigned oneTwoThree  =123;\n"
16826                    "int oneTwo = 12;\n"
16827                    "  method();\n"
16828                    "float k= 2;\n"
16829                    "int ll=10000;\n"
16830                    "}",
16831                    AlignmentLeft));
16832   // variables are aligned at their name, pointers are at the left most position
16833   verifyFormat("int*   a;\n"
16834                "int**  b;\n"
16835                "int*** c;\n"
16836                "int    foobar;\n",
16837                AlignmentLeft);
16838 
16839   // PAS_Middle
16840   FormatStyle AlignmentMiddle = Alignment;
16841   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
16842   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16843             "  int const i   = 1;\n"
16844             "  int *     j   = 2;\n"
16845             "  int       big = 10000;\n"
16846             "\n"
16847             "  unsigned oneTwoThree = 123;\n"
16848             "  int      oneTwo      = 12;\n"
16849             "  method();\n"
16850             "  float k  = 2;\n"
16851             "  int   ll = 10000;\n"
16852             "}",
16853             format("void SomeFunction(int parameter= 0) {\n"
16854                    " int const  i= 1;\n"
16855                    "  int *j=2;\n"
16856                    " int big  =  10000;\n"
16857                    "\n"
16858                    "unsigned oneTwoThree  =123;\n"
16859                    "int oneTwo = 12;\n"
16860                    "  method();\n"
16861                    "float k= 2;\n"
16862                    "int ll=10000;\n"
16863                    "}",
16864                    AlignmentMiddle));
16865   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16866             "  int const i   = 1;\n"
16867             "  int **    j   = 2, ***k;\n"
16868             "  int &     k   = i;\n"
16869             "  int &&    l   = i + j;\n"
16870             "  int       big = 10000;\n"
16871             "\n"
16872             "  unsigned oneTwoThree = 123;\n"
16873             "  int      oneTwo      = 12;\n"
16874             "  method();\n"
16875             "  float k  = 2;\n"
16876             "  int   ll = 10000;\n"
16877             "}",
16878             format("void SomeFunction(int parameter= 0) {\n"
16879                    " int const  i= 1;\n"
16880                    "  int **j=2,***k;\n"
16881                    "int &k=i;\n"
16882                    "int &&l=i+j;\n"
16883                    " int big  =  10000;\n"
16884                    "\n"
16885                    "unsigned oneTwoThree  =123;\n"
16886                    "int oneTwo = 12;\n"
16887                    "  method();\n"
16888                    "float k= 2;\n"
16889                    "int ll=10000;\n"
16890                    "}",
16891                    AlignmentMiddle));
16892   // variables are aligned at their name, pointers are in the middle
16893   verifyFormat("int *   a;\n"
16894                "int *   b;\n"
16895                "int *** c;\n"
16896                "int     foobar;\n",
16897                AlignmentMiddle);
16898 
16899   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16900   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16901   verifyFormat("#define A \\\n"
16902                "  int       aaaa = 12; \\\n"
16903                "  float     b = 23; \\\n"
16904                "  const int ccc = 234; \\\n"
16905                "  unsigned  dddddddddd = 2345;",
16906                Alignment);
16907   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16908   verifyFormat("#define A              \\\n"
16909                "  int       aaaa = 12; \\\n"
16910                "  float     b = 23;    \\\n"
16911                "  const int ccc = 234; \\\n"
16912                "  unsigned  dddddddddd = 2345;",
16913                Alignment);
16914   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16915   Alignment.ColumnLimit = 30;
16916   verifyFormat("#define A                    \\\n"
16917                "  int       aaaa = 12;       \\\n"
16918                "  float     b = 23;          \\\n"
16919                "  const int ccc = 234;       \\\n"
16920                "  int       dddddddddd = 2345;",
16921                Alignment);
16922   Alignment.ColumnLimit = 80;
16923   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16924                "k = 4, int l = 5,\n"
16925                "                  int m = 6) {\n"
16926                "  const int j = 10;\n"
16927                "  otherThing = 1;\n"
16928                "}",
16929                Alignment);
16930   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16931                "  int const i = 1;\n"
16932                "  int      *j = 2;\n"
16933                "  int       big = 10000;\n"
16934                "}",
16935                Alignment);
16936   verifyFormat("class C {\n"
16937                "public:\n"
16938                "  int          i = 1;\n"
16939                "  virtual void f() = 0;\n"
16940                "};",
16941                Alignment);
16942   verifyFormat("float i = 1;\n"
16943                "if (SomeType t = getSomething()) {\n"
16944                "}\n"
16945                "const unsigned j = 2;\n"
16946                "int            big = 10000;",
16947                Alignment);
16948   verifyFormat("float j = 7;\n"
16949                "for (int k = 0; k < N; ++k) {\n"
16950                "}\n"
16951                "unsigned j = 2;\n"
16952                "int      big = 10000;\n"
16953                "}",
16954                Alignment);
16955   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16956   verifyFormat("float              i = 1;\n"
16957                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16958                "    = someLooooooooooooooooongFunction();\n"
16959                "int j = 2;",
16960                Alignment);
16961   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16962   verifyFormat("int                i = 1;\n"
16963                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16964                "    someLooooooooooooooooongFunction();\n"
16965                "int j = 2;",
16966                Alignment);
16967 
16968   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16969   verifyFormat("auto lambda = []() {\n"
16970                "  auto  ii = 0;\n"
16971                "  float j  = 0;\n"
16972                "  return 0;\n"
16973                "};\n"
16974                "int   i  = 0;\n"
16975                "float i2 = 0;\n"
16976                "auto  v  = type{\n"
16977                "    i = 1,   //\n"
16978                "    (i = 2), //\n"
16979                "    i = 3    //\n"
16980                "};",
16981                Alignment);
16982   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16983 
16984   verifyFormat(
16985       "int      i = 1;\n"
16986       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16987       "                          loooooooooooooooooooooongParameterB);\n"
16988       "int      j = 2;",
16989       Alignment);
16990 
16991   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
16992   // We expect declarations and assignments to align, as long as it doesn't
16993   // exceed the column limit, starting a new alignment sequence whenever it
16994   // happens.
16995   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16996   Alignment.ColumnLimit = 30;
16997   verifyFormat("float    ii              = 1;\n"
16998                "unsigned j               = 2;\n"
16999                "int someVerylongVariable = 1;\n"
17000                "AnotherLongType  ll = 123456;\n"
17001                "VeryVeryLongType k  = 2;\n"
17002                "int              myvar = 1;",
17003                Alignment);
17004   Alignment.ColumnLimit = 80;
17005   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17006 
17007   verifyFormat(
17008       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17009       "          typename LongType, typename B>\n"
17010       "auto foo() {}\n",
17011       Alignment);
17012   verifyFormat("float a, b = 1;\n"
17013                "int   c = 2;\n"
17014                "int   dd = 3;\n",
17015                Alignment);
17016   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17017                "float b[1][] = {{3.f}};\n",
17018                Alignment);
17019   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17020   verifyFormat("float a, b = 1;\n"
17021                "int   c  = 2;\n"
17022                "int   dd = 3;\n",
17023                Alignment);
17024   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17025                "float b[1][] = {{3.f}};\n",
17026                Alignment);
17027   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17028 
17029   Alignment.ColumnLimit = 30;
17030   Alignment.BinPackParameters = false;
17031   verifyFormat("void foo(float     a,\n"
17032                "         float     b,\n"
17033                "         int       c,\n"
17034                "         uint32_t *d) {\n"
17035                "  int   *e = 0;\n"
17036                "  float  f = 0;\n"
17037                "  double g = 0;\n"
17038                "}\n"
17039                "void bar(ino_t     a,\n"
17040                "         int       b,\n"
17041                "         uint32_t *c,\n"
17042                "         bool      d) {}\n",
17043                Alignment);
17044   Alignment.BinPackParameters = true;
17045   Alignment.ColumnLimit = 80;
17046 
17047   // Bug 33507
17048   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17049   verifyFormat(
17050       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
17051       "  static const Version verVs2017;\n"
17052       "  return true;\n"
17053       "});\n",
17054       Alignment);
17055   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17056 
17057   // See llvm.org/PR35641
17058   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17059   verifyFormat("int func() { //\n"
17060                "  int      b;\n"
17061                "  unsigned c;\n"
17062                "}",
17063                Alignment);
17064 
17065   // See PR37175
17066   FormatStyle Style = getMozillaStyle();
17067   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17068   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
17069             "foo(int a);",
17070             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
17071 
17072   Alignment.PointerAlignment = FormatStyle::PAS_Left;
17073   verifyFormat("unsigned int*       a;\n"
17074                "int*                b;\n"
17075                "unsigned int Const* c;\n"
17076                "unsigned int const* d;\n"
17077                "unsigned int Const& e;\n"
17078                "unsigned int const& f;",
17079                Alignment);
17080   verifyFormat("Const unsigned int* c;\n"
17081                "const unsigned int* d;\n"
17082                "Const unsigned int& e;\n"
17083                "const unsigned int& f;\n"
17084                "const unsigned      g;\n"
17085                "Const unsigned      h;",
17086                Alignment);
17087 
17088   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17089   verifyFormat("unsigned int *       a;\n"
17090                "int *                b;\n"
17091                "unsigned int Const * c;\n"
17092                "unsigned int const * d;\n"
17093                "unsigned int Const & e;\n"
17094                "unsigned int const & f;",
17095                Alignment);
17096   verifyFormat("Const unsigned int * c;\n"
17097                "const unsigned int * d;\n"
17098                "Const unsigned int & e;\n"
17099                "const unsigned int & f;\n"
17100                "const unsigned       g;\n"
17101                "Const unsigned       h;",
17102                Alignment);
17103 }
17104 
17105 TEST_F(FormatTest, AlignWithLineBreaks) {
17106   auto Style = getLLVMStyleWithColumns(120);
17107 
17108   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
17109   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
17110   verifyFormat("void foo() {\n"
17111                "  int myVar = 5;\n"
17112                "  double x = 3.14;\n"
17113                "  auto str = \"Hello \"\n"
17114                "             \"World\";\n"
17115                "  auto s = \"Hello \"\n"
17116                "           \"Again\";\n"
17117                "}",
17118                Style);
17119 
17120   // clang-format off
17121   verifyFormat("void foo() {\n"
17122                "  const int capacityBefore = Entries.capacity();\n"
17123                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17124                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17125                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17126                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17127                "}",
17128                Style);
17129   // clang-format on
17130 
17131   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17132   verifyFormat("void foo() {\n"
17133                "  int myVar = 5;\n"
17134                "  double x  = 3.14;\n"
17135                "  auto str  = \"Hello \"\n"
17136                "              \"World\";\n"
17137                "  auto s    = \"Hello \"\n"
17138                "              \"Again\";\n"
17139                "}",
17140                Style);
17141 
17142   // clang-format off
17143   verifyFormat("void foo() {\n"
17144                "  const int capacityBefore = Entries.capacity();\n"
17145                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17146                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17147                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17148                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17149                "}",
17150                Style);
17151   // clang-format on
17152 
17153   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17154   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17155   verifyFormat("void foo() {\n"
17156                "  int    myVar = 5;\n"
17157                "  double x = 3.14;\n"
17158                "  auto   str = \"Hello \"\n"
17159                "               \"World\";\n"
17160                "  auto   s = \"Hello \"\n"
17161                "             \"Again\";\n"
17162                "}",
17163                Style);
17164 
17165   // clang-format off
17166   verifyFormat("void foo() {\n"
17167                "  const int  capacityBefore = Entries.capacity();\n"
17168                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17169                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17170                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17171                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17172                "}",
17173                Style);
17174   // clang-format on
17175 
17176   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17177   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17178 
17179   verifyFormat("void foo() {\n"
17180                "  int    myVar = 5;\n"
17181                "  double x     = 3.14;\n"
17182                "  auto   str   = \"Hello \"\n"
17183                "                 \"World\";\n"
17184                "  auto   s     = \"Hello \"\n"
17185                "                 \"Again\";\n"
17186                "}",
17187                Style);
17188 
17189   // clang-format off
17190   verifyFormat("void foo() {\n"
17191                "  const int  capacityBefore = Entries.capacity();\n"
17192                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17193                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17194                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17195                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17196                "}",
17197                Style);
17198   // clang-format on
17199 
17200   Style = getLLVMStyleWithColumns(120);
17201   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17202   Style.ContinuationIndentWidth = 4;
17203   Style.IndentWidth = 4;
17204 
17205   // clang-format off
17206   verifyFormat("void SomeFunc() {\n"
17207                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17208                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17209                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17210                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17211                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17212                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17213                "}",
17214                Style);
17215   // clang-format on
17216 
17217   Style.BinPackArguments = false;
17218 
17219   // clang-format off
17220   verifyFormat("void SomeFunc() {\n"
17221                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
17222                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17223                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
17224                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17225                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
17226                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17227                "}",
17228                Style);
17229   // clang-format on
17230 }
17231 
17232 TEST_F(FormatTest, AlignWithInitializerPeriods) {
17233   auto Style = getLLVMStyleWithColumns(60);
17234 
17235   verifyFormat("void foo1(void) {\n"
17236                "  BYTE p[1] = 1;\n"
17237                "  A B = {.one_foooooooooooooooo = 2,\n"
17238                "         .two_fooooooooooooo = 3,\n"
17239                "         .three_fooooooooooooo = 4};\n"
17240                "  BYTE payload = 2;\n"
17241                "}",
17242                Style);
17243 
17244   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17245   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
17246   verifyFormat("void foo2(void) {\n"
17247                "  BYTE p[1]    = 1;\n"
17248                "  A B          = {.one_foooooooooooooooo = 2,\n"
17249                "                  .two_fooooooooooooo    = 3,\n"
17250                "                  .three_fooooooooooooo  = 4};\n"
17251                "  BYTE payload = 2;\n"
17252                "}",
17253                Style);
17254 
17255   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17256   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17257   verifyFormat("void foo3(void) {\n"
17258                "  BYTE p[1] = 1;\n"
17259                "  A    B = {.one_foooooooooooooooo = 2,\n"
17260                "            .two_fooooooooooooo = 3,\n"
17261                "            .three_fooooooooooooo = 4};\n"
17262                "  BYTE payload = 2;\n"
17263                "}",
17264                Style);
17265 
17266   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17267   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17268   verifyFormat("void foo4(void) {\n"
17269                "  BYTE p[1]    = 1;\n"
17270                "  A    B       = {.one_foooooooooooooooo = 2,\n"
17271                "                  .two_fooooooooooooo    = 3,\n"
17272                "                  .three_fooooooooooooo  = 4};\n"
17273                "  BYTE payload = 2;\n"
17274                "}",
17275                Style);
17276 }
17277 
17278 TEST_F(FormatTest, LinuxBraceBreaking) {
17279   FormatStyle LinuxBraceStyle = getLLVMStyle();
17280   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
17281   verifyFormat("namespace a\n"
17282                "{\n"
17283                "class A\n"
17284                "{\n"
17285                "  void f()\n"
17286                "  {\n"
17287                "    if (true) {\n"
17288                "      a();\n"
17289                "      b();\n"
17290                "    } else {\n"
17291                "      a();\n"
17292                "    }\n"
17293                "  }\n"
17294                "  void g() { return; }\n"
17295                "};\n"
17296                "struct B {\n"
17297                "  int x;\n"
17298                "};\n"
17299                "} // namespace a\n",
17300                LinuxBraceStyle);
17301   verifyFormat("enum X {\n"
17302                "  Y = 0,\n"
17303                "}\n",
17304                LinuxBraceStyle);
17305   verifyFormat("struct S {\n"
17306                "  int Type;\n"
17307                "  union {\n"
17308                "    int x;\n"
17309                "    double y;\n"
17310                "  } Value;\n"
17311                "  class C\n"
17312                "  {\n"
17313                "    MyFavoriteType Value;\n"
17314                "  } Class;\n"
17315                "}\n",
17316                LinuxBraceStyle);
17317 }
17318 
17319 TEST_F(FormatTest, MozillaBraceBreaking) {
17320   FormatStyle MozillaBraceStyle = getLLVMStyle();
17321   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
17322   MozillaBraceStyle.FixNamespaceComments = false;
17323   verifyFormat("namespace a {\n"
17324                "class A\n"
17325                "{\n"
17326                "  void f()\n"
17327                "  {\n"
17328                "    if (true) {\n"
17329                "      a();\n"
17330                "      b();\n"
17331                "    }\n"
17332                "  }\n"
17333                "  void g() { return; }\n"
17334                "};\n"
17335                "enum E\n"
17336                "{\n"
17337                "  A,\n"
17338                "  // foo\n"
17339                "  B,\n"
17340                "  C\n"
17341                "};\n"
17342                "struct B\n"
17343                "{\n"
17344                "  int x;\n"
17345                "};\n"
17346                "}\n",
17347                MozillaBraceStyle);
17348   verifyFormat("struct S\n"
17349                "{\n"
17350                "  int Type;\n"
17351                "  union\n"
17352                "  {\n"
17353                "    int x;\n"
17354                "    double y;\n"
17355                "  } Value;\n"
17356                "  class C\n"
17357                "  {\n"
17358                "    MyFavoriteType Value;\n"
17359                "  } Class;\n"
17360                "}\n",
17361                MozillaBraceStyle);
17362 }
17363 
17364 TEST_F(FormatTest, StroustrupBraceBreaking) {
17365   FormatStyle StroustrupBraceStyle = getLLVMStyle();
17366   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
17367   verifyFormat("namespace a {\n"
17368                "class A {\n"
17369                "  void f()\n"
17370                "  {\n"
17371                "    if (true) {\n"
17372                "      a();\n"
17373                "      b();\n"
17374                "    }\n"
17375                "  }\n"
17376                "  void g() { return; }\n"
17377                "};\n"
17378                "struct B {\n"
17379                "  int x;\n"
17380                "};\n"
17381                "} // namespace a\n",
17382                StroustrupBraceStyle);
17383 
17384   verifyFormat("void foo()\n"
17385                "{\n"
17386                "  if (a) {\n"
17387                "    a();\n"
17388                "  }\n"
17389                "  else {\n"
17390                "    b();\n"
17391                "  }\n"
17392                "}\n",
17393                StroustrupBraceStyle);
17394 
17395   verifyFormat("#ifdef _DEBUG\n"
17396                "int foo(int i = 0)\n"
17397                "#else\n"
17398                "int foo(int i = 5)\n"
17399                "#endif\n"
17400                "{\n"
17401                "  return i;\n"
17402                "}",
17403                StroustrupBraceStyle);
17404 
17405   verifyFormat("void foo() {}\n"
17406                "void bar()\n"
17407                "#ifdef _DEBUG\n"
17408                "{\n"
17409                "  foo();\n"
17410                "}\n"
17411                "#else\n"
17412                "{\n"
17413                "}\n"
17414                "#endif",
17415                StroustrupBraceStyle);
17416 
17417   verifyFormat("void foobar() { int i = 5; }\n"
17418                "#ifdef _DEBUG\n"
17419                "void bar() {}\n"
17420                "#else\n"
17421                "void bar() { foobar(); }\n"
17422                "#endif",
17423                StroustrupBraceStyle);
17424 }
17425 
17426 TEST_F(FormatTest, AllmanBraceBreaking) {
17427   FormatStyle AllmanBraceStyle = getLLVMStyle();
17428   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
17429 
17430   EXPECT_EQ("namespace a\n"
17431             "{\n"
17432             "void f();\n"
17433             "void g();\n"
17434             "} // namespace a\n",
17435             format("namespace a\n"
17436                    "{\n"
17437                    "void f();\n"
17438                    "void g();\n"
17439                    "}\n",
17440                    AllmanBraceStyle));
17441 
17442   verifyFormat("namespace a\n"
17443                "{\n"
17444                "class A\n"
17445                "{\n"
17446                "  void f()\n"
17447                "  {\n"
17448                "    if (true)\n"
17449                "    {\n"
17450                "      a();\n"
17451                "      b();\n"
17452                "    }\n"
17453                "  }\n"
17454                "  void g() { return; }\n"
17455                "};\n"
17456                "struct B\n"
17457                "{\n"
17458                "  int x;\n"
17459                "};\n"
17460                "union C\n"
17461                "{\n"
17462                "};\n"
17463                "} // namespace a",
17464                AllmanBraceStyle);
17465 
17466   verifyFormat("void f()\n"
17467                "{\n"
17468                "  if (true)\n"
17469                "  {\n"
17470                "    a();\n"
17471                "  }\n"
17472                "  else if (false)\n"
17473                "  {\n"
17474                "    b();\n"
17475                "  }\n"
17476                "  else\n"
17477                "  {\n"
17478                "    c();\n"
17479                "  }\n"
17480                "}\n",
17481                AllmanBraceStyle);
17482 
17483   verifyFormat("void f()\n"
17484                "{\n"
17485                "  for (int i = 0; i < 10; ++i)\n"
17486                "  {\n"
17487                "    a();\n"
17488                "  }\n"
17489                "  while (false)\n"
17490                "  {\n"
17491                "    b();\n"
17492                "  }\n"
17493                "  do\n"
17494                "  {\n"
17495                "    c();\n"
17496                "  } while (false)\n"
17497                "}\n",
17498                AllmanBraceStyle);
17499 
17500   verifyFormat("void f(int a)\n"
17501                "{\n"
17502                "  switch (a)\n"
17503                "  {\n"
17504                "  case 0:\n"
17505                "    break;\n"
17506                "  case 1:\n"
17507                "  {\n"
17508                "    break;\n"
17509                "  }\n"
17510                "  case 2:\n"
17511                "  {\n"
17512                "  }\n"
17513                "  break;\n"
17514                "  default:\n"
17515                "    break;\n"
17516                "  }\n"
17517                "}\n",
17518                AllmanBraceStyle);
17519 
17520   verifyFormat("enum X\n"
17521                "{\n"
17522                "  Y = 0,\n"
17523                "}\n",
17524                AllmanBraceStyle);
17525   verifyFormat("enum X\n"
17526                "{\n"
17527                "  Y = 0\n"
17528                "}\n",
17529                AllmanBraceStyle);
17530 
17531   verifyFormat("@interface BSApplicationController ()\n"
17532                "{\n"
17533                "@private\n"
17534                "  id _extraIvar;\n"
17535                "}\n"
17536                "@end\n",
17537                AllmanBraceStyle);
17538 
17539   verifyFormat("#ifdef _DEBUG\n"
17540                "int foo(int i = 0)\n"
17541                "#else\n"
17542                "int foo(int i = 5)\n"
17543                "#endif\n"
17544                "{\n"
17545                "  return i;\n"
17546                "}",
17547                AllmanBraceStyle);
17548 
17549   verifyFormat("void foo() {}\n"
17550                "void bar()\n"
17551                "#ifdef _DEBUG\n"
17552                "{\n"
17553                "  foo();\n"
17554                "}\n"
17555                "#else\n"
17556                "{\n"
17557                "}\n"
17558                "#endif",
17559                AllmanBraceStyle);
17560 
17561   verifyFormat("void foobar() { int i = 5; }\n"
17562                "#ifdef _DEBUG\n"
17563                "void bar() {}\n"
17564                "#else\n"
17565                "void bar() { foobar(); }\n"
17566                "#endif",
17567                AllmanBraceStyle);
17568 
17569   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
17570             FormatStyle::SLS_All);
17571 
17572   verifyFormat("[](int i) { return i + 2; };\n"
17573                "[](int i, int j)\n"
17574                "{\n"
17575                "  auto x = i + j;\n"
17576                "  auto y = i * j;\n"
17577                "  return x ^ y;\n"
17578                "};\n"
17579                "void foo()\n"
17580                "{\n"
17581                "  auto shortLambda = [](int i) { return i + 2; };\n"
17582                "  auto longLambda = [](int i, int j)\n"
17583                "  {\n"
17584                "    auto x = i + j;\n"
17585                "    auto y = i * j;\n"
17586                "    return x ^ y;\n"
17587                "  };\n"
17588                "}",
17589                AllmanBraceStyle);
17590 
17591   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17592 
17593   verifyFormat("[](int i)\n"
17594                "{\n"
17595                "  return i + 2;\n"
17596                "};\n"
17597                "[](int i, int j)\n"
17598                "{\n"
17599                "  auto x = i + j;\n"
17600                "  auto y = i * j;\n"
17601                "  return x ^ y;\n"
17602                "};\n"
17603                "void foo()\n"
17604                "{\n"
17605                "  auto shortLambda = [](int i)\n"
17606                "  {\n"
17607                "    return i + 2;\n"
17608                "  };\n"
17609                "  auto longLambda = [](int i, int j)\n"
17610                "  {\n"
17611                "    auto x = i + j;\n"
17612                "    auto y = i * j;\n"
17613                "    return x ^ y;\n"
17614                "  };\n"
17615                "}",
17616                AllmanBraceStyle);
17617 
17618   // Reset
17619   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
17620 
17621   // This shouldn't affect ObjC blocks..
17622   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
17623                "  // ...\n"
17624                "  int i;\n"
17625                "}];",
17626                AllmanBraceStyle);
17627   verifyFormat("void (^block)(void) = ^{\n"
17628                "  // ...\n"
17629                "  int i;\n"
17630                "};",
17631                AllmanBraceStyle);
17632   // .. or dict literals.
17633   verifyFormat("void f()\n"
17634                "{\n"
17635                "  // ...\n"
17636                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
17637                "}",
17638                AllmanBraceStyle);
17639   verifyFormat("void f()\n"
17640                "{\n"
17641                "  // ...\n"
17642                "  [object someMethod:@{a : @\"b\"}];\n"
17643                "}",
17644                AllmanBraceStyle);
17645   verifyFormat("int f()\n"
17646                "{ // comment\n"
17647                "  return 42;\n"
17648                "}",
17649                AllmanBraceStyle);
17650 
17651   AllmanBraceStyle.ColumnLimit = 19;
17652   verifyFormat("void f() { int i; }", AllmanBraceStyle);
17653   AllmanBraceStyle.ColumnLimit = 18;
17654   verifyFormat("void f()\n"
17655                "{\n"
17656                "  int i;\n"
17657                "}",
17658                AllmanBraceStyle);
17659   AllmanBraceStyle.ColumnLimit = 80;
17660 
17661   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
17662   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
17663       FormatStyle::SIS_WithoutElse;
17664   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
17665   verifyFormat("void f(bool b)\n"
17666                "{\n"
17667                "  if (b)\n"
17668                "  {\n"
17669                "    return;\n"
17670                "  }\n"
17671                "}\n",
17672                BreakBeforeBraceShortIfs);
17673   verifyFormat("void f(bool b)\n"
17674                "{\n"
17675                "  if constexpr (b)\n"
17676                "  {\n"
17677                "    return;\n"
17678                "  }\n"
17679                "}\n",
17680                BreakBeforeBraceShortIfs);
17681   verifyFormat("void f(bool b)\n"
17682                "{\n"
17683                "  if CONSTEXPR (b)\n"
17684                "  {\n"
17685                "    return;\n"
17686                "  }\n"
17687                "}\n",
17688                BreakBeforeBraceShortIfs);
17689   verifyFormat("void f(bool b)\n"
17690                "{\n"
17691                "  if (b) return;\n"
17692                "}\n",
17693                BreakBeforeBraceShortIfs);
17694   verifyFormat("void f(bool b)\n"
17695                "{\n"
17696                "  if constexpr (b) return;\n"
17697                "}\n",
17698                BreakBeforeBraceShortIfs);
17699   verifyFormat("void f(bool b)\n"
17700                "{\n"
17701                "  if CONSTEXPR (b) return;\n"
17702                "}\n",
17703                BreakBeforeBraceShortIfs);
17704   verifyFormat("void f(bool b)\n"
17705                "{\n"
17706                "  while (b)\n"
17707                "  {\n"
17708                "    return;\n"
17709                "  }\n"
17710                "}\n",
17711                BreakBeforeBraceShortIfs);
17712 }
17713 
17714 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
17715   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
17716   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
17717 
17718   // Make a few changes to the style for testing purposes
17719   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
17720       FormatStyle::SFS_Empty;
17721   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17722 
17723   // FIXME: this test case can't decide whether there should be a blank line
17724   // after the ~D() line or not. It adds one if one doesn't exist in the test
17725   // and it removes the line if one exists.
17726   /*
17727   verifyFormat("class A;\n"
17728                "namespace B\n"
17729                "  {\n"
17730                "class C;\n"
17731                "// Comment\n"
17732                "class D\n"
17733                "  {\n"
17734                "public:\n"
17735                "  D();\n"
17736                "  ~D() {}\n"
17737                "private:\n"
17738                "  enum E\n"
17739                "    {\n"
17740                "    F\n"
17741                "    }\n"
17742                "  };\n"
17743                "  } // namespace B\n",
17744                WhitesmithsBraceStyle);
17745   */
17746 
17747   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
17748   verifyFormat("namespace a\n"
17749                "  {\n"
17750                "class A\n"
17751                "  {\n"
17752                "  void f()\n"
17753                "    {\n"
17754                "    if (true)\n"
17755                "      {\n"
17756                "      a();\n"
17757                "      b();\n"
17758                "      }\n"
17759                "    }\n"
17760                "  void g()\n"
17761                "    {\n"
17762                "    return;\n"
17763                "    }\n"
17764                "  };\n"
17765                "struct B\n"
17766                "  {\n"
17767                "  int x;\n"
17768                "  };\n"
17769                "  } // namespace a",
17770                WhitesmithsBraceStyle);
17771 
17772   verifyFormat("namespace a\n"
17773                "  {\n"
17774                "namespace b\n"
17775                "  {\n"
17776                "class A\n"
17777                "  {\n"
17778                "  void f()\n"
17779                "    {\n"
17780                "    if (true)\n"
17781                "      {\n"
17782                "      a();\n"
17783                "      b();\n"
17784                "      }\n"
17785                "    }\n"
17786                "  void g()\n"
17787                "    {\n"
17788                "    return;\n"
17789                "    }\n"
17790                "  };\n"
17791                "struct B\n"
17792                "  {\n"
17793                "  int x;\n"
17794                "  };\n"
17795                "  } // namespace b\n"
17796                "  } // namespace a",
17797                WhitesmithsBraceStyle);
17798 
17799   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
17800   verifyFormat("namespace a\n"
17801                "  {\n"
17802                "namespace b\n"
17803                "  {\n"
17804                "  class A\n"
17805                "    {\n"
17806                "    void f()\n"
17807                "      {\n"
17808                "      if (true)\n"
17809                "        {\n"
17810                "        a();\n"
17811                "        b();\n"
17812                "        }\n"
17813                "      }\n"
17814                "    void g()\n"
17815                "      {\n"
17816                "      return;\n"
17817                "      }\n"
17818                "    };\n"
17819                "  struct B\n"
17820                "    {\n"
17821                "    int x;\n"
17822                "    };\n"
17823                "  } // namespace b\n"
17824                "  } // namespace a",
17825                WhitesmithsBraceStyle);
17826 
17827   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
17828   verifyFormat("namespace a\n"
17829                "  {\n"
17830                "  namespace b\n"
17831                "    {\n"
17832                "    class A\n"
17833                "      {\n"
17834                "      void f()\n"
17835                "        {\n"
17836                "        if (true)\n"
17837                "          {\n"
17838                "          a();\n"
17839                "          b();\n"
17840                "          }\n"
17841                "        }\n"
17842                "      void g()\n"
17843                "        {\n"
17844                "        return;\n"
17845                "        }\n"
17846                "      };\n"
17847                "    struct B\n"
17848                "      {\n"
17849                "      int x;\n"
17850                "      };\n"
17851                "    } // namespace b\n"
17852                "  }   // namespace a",
17853                WhitesmithsBraceStyle);
17854 
17855   verifyFormat("void f()\n"
17856                "  {\n"
17857                "  if (true)\n"
17858                "    {\n"
17859                "    a();\n"
17860                "    }\n"
17861                "  else if (false)\n"
17862                "    {\n"
17863                "    b();\n"
17864                "    }\n"
17865                "  else\n"
17866                "    {\n"
17867                "    c();\n"
17868                "    }\n"
17869                "  }\n",
17870                WhitesmithsBraceStyle);
17871 
17872   verifyFormat("void f()\n"
17873                "  {\n"
17874                "  for (int i = 0; i < 10; ++i)\n"
17875                "    {\n"
17876                "    a();\n"
17877                "    }\n"
17878                "  while (false)\n"
17879                "    {\n"
17880                "    b();\n"
17881                "    }\n"
17882                "  do\n"
17883                "    {\n"
17884                "    c();\n"
17885                "    } while (false)\n"
17886                "  }\n",
17887                WhitesmithsBraceStyle);
17888 
17889   WhitesmithsBraceStyle.IndentCaseLabels = true;
17890   verifyFormat("void switchTest1(int a)\n"
17891                "  {\n"
17892                "  switch (a)\n"
17893                "    {\n"
17894                "    case 2:\n"
17895                "      {\n"
17896                "      }\n"
17897                "      break;\n"
17898                "    }\n"
17899                "  }\n",
17900                WhitesmithsBraceStyle);
17901 
17902   verifyFormat("void switchTest2(int a)\n"
17903                "  {\n"
17904                "  switch (a)\n"
17905                "    {\n"
17906                "    case 0:\n"
17907                "      break;\n"
17908                "    case 1:\n"
17909                "      {\n"
17910                "      break;\n"
17911                "      }\n"
17912                "    case 2:\n"
17913                "      {\n"
17914                "      }\n"
17915                "      break;\n"
17916                "    default:\n"
17917                "      break;\n"
17918                "    }\n"
17919                "  }\n",
17920                WhitesmithsBraceStyle);
17921 
17922   verifyFormat("void switchTest3(int a)\n"
17923                "  {\n"
17924                "  switch (a)\n"
17925                "    {\n"
17926                "    case 0:\n"
17927                "      {\n"
17928                "      foo(x);\n"
17929                "      }\n"
17930                "      break;\n"
17931                "    default:\n"
17932                "      {\n"
17933                "      foo(1);\n"
17934                "      }\n"
17935                "      break;\n"
17936                "    }\n"
17937                "  }\n",
17938                WhitesmithsBraceStyle);
17939 
17940   WhitesmithsBraceStyle.IndentCaseLabels = false;
17941 
17942   verifyFormat("void switchTest4(int a)\n"
17943                "  {\n"
17944                "  switch (a)\n"
17945                "    {\n"
17946                "  case 2:\n"
17947                "    {\n"
17948                "    }\n"
17949                "    break;\n"
17950                "    }\n"
17951                "  }\n",
17952                WhitesmithsBraceStyle);
17953 
17954   verifyFormat("void switchTest5(int a)\n"
17955                "  {\n"
17956                "  switch (a)\n"
17957                "    {\n"
17958                "  case 0:\n"
17959                "    break;\n"
17960                "  case 1:\n"
17961                "    {\n"
17962                "    foo();\n"
17963                "    break;\n"
17964                "    }\n"
17965                "  case 2:\n"
17966                "    {\n"
17967                "    }\n"
17968                "    break;\n"
17969                "  default:\n"
17970                "    break;\n"
17971                "    }\n"
17972                "  }\n",
17973                WhitesmithsBraceStyle);
17974 
17975   verifyFormat("void switchTest6(int a)\n"
17976                "  {\n"
17977                "  switch (a)\n"
17978                "    {\n"
17979                "  case 0:\n"
17980                "    {\n"
17981                "    foo(x);\n"
17982                "    }\n"
17983                "    break;\n"
17984                "  default:\n"
17985                "    {\n"
17986                "    foo(1);\n"
17987                "    }\n"
17988                "    break;\n"
17989                "    }\n"
17990                "  }\n",
17991                WhitesmithsBraceStyle);
17992 
17993   verifyFormat("enum X\n"
17994                "  {\n"
17995                "  Y = 0, // testing\n"
17996                "  }\n",
17997                WhitesmithsBraceStyle);
17998 
17999   verifyFormat("enum X\n"
18000                "  {\n"
18001                "  Y = 0\n"
18002                "  }\n",
18003                WhitesmithsBraceStyle);
18004   verifyFormat("enum X\n"
18005                "  {\n"
18006                "  Y = 0,\n"
18007                "  Z = 1\n"
18008                "  };\n",
18009                WhitesmithsBraceStyle);
18010 
18011   verifyFormat("@interface BSApplicationController ()\n"
18012                "  {\n"
18013                "@private\n"
18014                "  id _extraIvar;\n"
18015                "  }\n"
18016                "@end\n",
18017                WhitesmithsBraceStyle);
18018 
18019   verifyFormat("#ifdef _DEBUG\n"
18020                "int foo(int i = 0)\n"
18021                "#else\n"
18022                "int foo(int i = 5)\n"
18023                "#endif\n"
18024                "  {\n"
18025                "  return i;\n"
18026                "  }",
18027                WhitesmithsBraceStyle);
18028 
18029   verifyFormat("void foo() {}\n"
18030                "void bar()\n"
18031                "#ifdef _DEBUG\n"
18032                "  {\n"
18033                "  foo();\n"
18034                "  }\n"
18035                "#else\n"
18036                "  {\n"
18037                "  }\n"
18038                "#endif",
18039                WhitesmithsBraceStyle);
18040 
18041   verifyFormat("void foobar()\n"
18042                "  {\n"
18043                "  int i = 5;\n"
18044                "  }\n"
18045                "#ifdef _DEBUG\n"
18046                "void bar()\n"
18047                "  {\n"
18048                "  }\n"
18049                "#else\n"
18050                "void bar()\n"
18051                "  {\n"
18052                "  foobar();\n"
18053                "  }\n"
18054                "#endif",
18055                WhitesmithsBraceStyle);
18056 
18057   // This shouldn't affect ObjC blocks..
18058   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18059                "  // ...\n"
18060                "  int i;\n"
18061                "}];",
18062                WhitesmithsBraceStyle);
18063   verifyFormat("void (^block)(void) = ^{\n"
18064                "  // ...\n"
18065                "  int i;\n"
18066                "};",
18067                WhitesmithsBraceStyle);
18068   // .. or dict literals.
18069   verifyFormat("void f()\n"
18070                "  {\n"
18071                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18072                "  }",
18073                WhitesmithsBraceStyle);
18074 
18075   verifyFormat("int f()\n"
18076                "  { // comment\n"
18077                "  return 42;\n"
18078                "  }",
18079                WhitesmithsBraceStyle);
18080 
18081   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
18082   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18083       FormatStyle::SIS_OnlyFirstIf;
18084   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18085   verifyFormat("void f(bool b)\n"
18086                "  {\n"
18087                "  if (b)\n"
18088                "    {\n"
18089                "    return;\n"
18090                "    }\n"
18091                "  }\n",
18092                BreakBeforeBraceShortIfs);
18093   verifyFormat("void f(bool b)\n"
18094                "  {\n"
18095                "  if (b) return;\n"
18096                "  }\n",
18097                BreakBeforeBraceShortIfs);
18098   verifyFormat("void f(bool b)\n"
18099                "  {\n"
18100                "  while (b)\n"
18101                "    {\n"
18102                "    return;\n"
18103                "    }\n"
18104                "  }\n",
18105                BreakBeforeBraceShortIfs);
18106 }
18107 
18108 TEST_F(FormatTest, GNUBraceBreaking) {
18109   FormatStyle GNUBraceStyle = getLLVMStyle();
18110   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
18111   verifyFormat("namespace a\n"
18112                "{\n"
18113                "class A\n"
18114                "{\n"
18115                "  void f()\n"
18116                "  {\n"
18117                "    int a;\n"
18118                "    {\n"
18119                "      int b;\n"
18120                "    }\n"
18121                "    if (true)\n"
18122                "      {\n"
18123                "        a();\n"
18124                "        b();\n"
18125                "      }\n"
18126                "  }\n"
18127                "  void g() { return; }\n"
18128                "}\n"
18129                "} // namespace a",
18130                GNUBraceStyle);
18131 
18132   verifyFormat("void f()\n"
18133                "{\n"
18134                "  if (true)\n"
18135                "    {\n"
18136                "      a();\n"
18137                "    }\n"
18138                "  else if (false)\n"
18139                "    {\n"
18140                "      b();\n"
18141                "    }\n"
18142                "  else\n"
18143                "    {\n"
18144                "      c();\n"
18145                "    }\n"
18146                "}\n",
18147                GNUBraceStyle);
18148 
18149   verifyFormat("void f()\n"
18150                "{\n"
18151                "  for (int i = 0; i < 10; ++i)\n"
18152                "    {\n"
18153                "      a();\n"
18154                "    }\n"
18155                "  while (false)\n"
18156                "    {\n"
18157                "      b();\n"
18158                "    }\n"
18159                "  do\n"
18160                "    {\n"
18161                "      c();\n"
18162                "    }\n"
18163                "  while (false);\n"
18164                "}\n",
18165                GNUBraceStyle);
18166 
18167   verifyFormat("void f(int a)\n"
18168                "{\n"
18169                "  switch (a)\n"
18170                "    {\n"
18171                "    case 0:\n"
18172                "      break;\n"
18173                "    case 1:\n"
18174                "      {\n"
18175                "        break;\n"
18176                "      }\n"
18177                "    case 2:\n"
18178                "      {\n"
18179                "      }\n"
18180                "      break;\n"
18181                "    default:\n"
18182                "      break;\n"
18183                "    }\n"
18184                "}\n",
18185                GNUBraceStyle);
18186 
18187   verifyFormat("enum X\n"
18188                "{\n"
18189                "  Y = 0,\n"
18190                "}\n",
18191                GNUBraceStyle);
18192 
18193   verifyFormat("@interface BSApplicationController ()\n"
18194                "{\n"
18195                "@private\n"
18196                "  id _extraIvar;\n"
18197                "}\n"
18198                "@end\n",
18199                GNUBraceStyle);
18200 
18201   verifyFormat("#ifdef _DEBUG\n"
18202                "int foo(int i = 0)\n"
18203                "#else\n"
18204                "int foo(int i = 5)\n"
18205                "#endif\n"
18206                "{\n"
18207                "  return i;\n"
18208                "}",
18209                GNUBraceStyle);
18210 
18211   verifyFormat("void foo() {}\n"
18212                "void bar()\n"
18213                "#ifdef _DEBUG\n"
18214                "{\n"
18215                "  foo();\n"
18216                "}\n"
18217                "#else\n"
18218                "{\n"
18219                "}\n"
18220                "#endif",
18221                GNUBraceStyle);
18222 
18223   verifyFormat("void foobar() { int i = 5; }\n"
18224                "#ifdef _DEBUG\n"
18225                "void bar() {}\n"
18226                "#else\n"
18227                "void bar() { foobar(); }\n"
18228                "#endif",
18229                GNUBraceStyle);
18230 }
18231 
18232 TEST_F(FormatTest, WebKitBraceBreaking) {
18233   FormatStyle WebKitBraceStyle = getLLVMStyle();
18234   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
18235   WebKitBraceStyle.FixNamespaceComments = false;
18236   verifyFormat("namespace a {\n"
18237                "class A {\n"
18238                "  void f()\n"
18239                "  {\n"
18240                "    if (true) {\n"
18241                "      a();\n"
18242                "      b();\n"
18243                "    }\n"
18244                "  }\n"
18245                "  void g() { return; }\n"
18246                "};\n"
18247                "enum E {\n"
18248                "  A,\n"
18249                "  // foo\n"
18250                "  B,\n"
18251                "  C\n"
18252                "};\n"
18253                "struct B {\n"
18254                "  int x;\n"
18255                "};\n"
18256                "}\n",
18257                WebKitBraceStyle);
18258   verifyFormat("struct S {\n"
18259                "  int Type;\n"
18260                "  union {\n"
18261                "    int x;\n"
18262                "    double y;\n"
18263                "  } Value;\n"
18264                "  class C {\n"
18265                "    MyFavoriteType Value;\n"
18266                "  } Class;\n"
18267                "};\n",
18268                WebKitBraceStyle);
18269 }
18270 
18271 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
18272   verifyFormat("void f() {\n"
18273                "  try {\n"
18274                "  } catch (const Exception &e) {\n"
18275                "  }\n"
18276                "}\n",
18277                getLLVMStyle());
18278 }
18279 
18280 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
18281   auto Style = getLLVMStyle();
18282   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18283   Style.AlignConsecutiveAssignments =
18284       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18285   Style.AlignConsecutiveDeclarations =
18286       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18287   verifyFormat("struct test demo[] = {\n"
18288                "    {56,    23, \"hello\"},\n"
18289                "    {-1, 93463, \"world\"},\n"
18290                "    { 7,     5,    \"!!\"}\n"
18291                "};\n",
18292                Style);
18293 
18294   verifyFormat("struct test demo[] = {\n"
18295                "    {56,    23, \"hello\"}, // first line\n"
18296                "    {-1, 93463, \"world\"}, // second line\n"
18297                "    { 7,     5,    \"!!\"}  // third line\n"
18298                "};\n",
18299                Style);
18300 
18301   verifyFormat("struct test demo[4] = {\n"
18302                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18303                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18304                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18305                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18306                "};\n",
18307                Style);
18308 
18309   verifyFormat("struct test demo[3] = {\n"
18310                "    {56,    23, \"hello\"},\n"
18311                "    {-1, 93463, \"world\"},\n"
18312                "    { 7,     5,    \"!!\"}\n"
18313                "};\n",
18314                Style);
18315 
18316   verifyFormat("struct test demo[3] = {\n"
18317                "    {int{56},    23, \"hello\"},\n"
18318                "    {int{-1}, 93463, \"world\"},\n"
18319                "    { int{7},     5,    \"!!\"}\n"
18320                "};\n",
18321                Style);
18322 
18323   verifyFormat("struct test demo[] = {\n"
18324                "    {56,    23, \"hello\"},\n"
18325                "    {-1, 93463, \"world\"},\n"
18326                "    { 7,     5,    \"!!\"},\n"
18327                "};\n",
18328                Style);
18329 
18330   verifyFormat("test demo[] = {\n"
18331                "    {56,    23, \"hello\"},\n"
18332                "    {-1, 93463, \"world\"},\n"
18333                "    { 7,     5,    \"!!\"},\n"
18334                "};\n",
18335                Style);
18336 
18337   verifyFormat("demo = std::array<struct test, 3>{\n"
18338                "    test{56,    23, \"hello\"},\n"
18339                "    test{-1, 93463, \"world\"},\n"
18340                "    test{ 7,     5,    \"!!\"},\n"
18341                "};\n",
18342                Style);
18343 
18344   verifyFormat("test demo[] = {\n"
18345                "    {56,    23, \"hello\"},\n"
18346                "#if X\n"
18347                "    {-1, 93463, \"world\"},\n"
18348                "#endif\n"
18349                "    { 7,     5,    \"!!\"}\n"
18350                "};\n",
18351                Style);
18352 
18353   verifyFormat(
18354       "test demo[] = {\n"
18355       "    { 7,    23,\n"
18356       "     \"hello world i am a very long line that really, in any\"\n"
18357       "     \"just world, ought to be split over multiple lines\"},\n"
18358       "    {-1, 93463,                                  \"world\"},\n"
18359       "    {56,     5,                                     \"!!\"}\n"
18360       "};\n",
18361       Style);
18362 
18363   verifyFormat("return GradForUnaryCwise(g, {\n"
18364                "                                {{\"sign\"}, \"Sign\",  "
18365                "  {\"x\", \"dy\"}},\n"
18366                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
18367                ", \"sign\"}},\n"
18368                "});\n",
18369                Style);
18370 
18371   Style.ColumnLimit = 0;
18372   EXPECT_EQ(
18373       "test demo[] = {\n"
18374       "    {56,    23, \"hello world i am a very long line that really, "
18375       "in any just world, ought to be split over multiple lines\"},\n"
18376       "    {-1, 93463,                                                  "
18377       "                                                 \"world\"},\n"
18378       "    { 7,     5,                                                  "
18379       "                                                    \"!!\"},\n"
18380       "};",
18381       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18382              "that really, in any just world, ought to be split over multiple "
18383              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18384              Style));
18385 
18386   Style.ColumnLimit = 80;
18387   verifyFormat("test demo[] = {\n"
18388                "    {56,    23, /* a comment */ \"hello\"},\n"
18389                "    {-1, 93463,                 \"world\"},\n"
18390                "    { 7,     5,                    \"!!\"}\n"
18391                "};\n",
18392                Style);
18393 
18394   verifyFormat("test demo[] = {\n"
18395                "    {56,    23,                    \"hello\"},\n"
18396                "    {-1, 93463, \"world\" /* comment here */},\n"
18397                "    { 7,     5,                       \"!!\"}\n"
18398                "};\n",
18399                Style);
18400 
18401   verifyFormat("test demo[] = {\n"
18402                "    {56, /* a comment */ 23, \"hello\"},\n"
18403                "    {-1,              93463, \"world\"},\n"
18404                "    { 7,                  5,    \"!!\"}\n"
18405                "};\n",
18406                Style);
18407 
18408   Style.ColumnLimit = 20;
18409   EXPECT_EQ(
18410       "demo = std::array<\n"
18411       "    struct test, 3>{\n"
18412       "    test{\n"
18413       "         56,    23,\n"
18414       "         \"hello \"\n"
18415       "         \"world i \"\n"
18416       "         \"am a very \"\n"
18417       "         \"long line \"\n"
18418       "         \"that \"\n"
18419       "         \"really, \"\n"
18420       "         \"in any \"\n"
18421       "         \"just \"\n"
18422       "         \"world, \"\n"
18423       "         \"ought to \"\n"
18424       "         \"be split \"\n"
18425       "         \"over \"\n"
18426       "         \"multiple \"\n"
18427       "         \"lines\"},\n"
18428       "    test{-1, 93463,\n"
18429       "         \"world\"},\n"
18430       "    test{ 7,     5,\n"
18431       "         \"!!\"   },\n"
18432       "};",
18433       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18434              "i am a very long line that really, in any just world, ought "
18435              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18436              "test{7, 5, \"!!\"},};",
18437              Style));
18438   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18439   Style = getLLVMStyleWithColumns(50);
18440   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18441   verifyFormat("static A x = {\n"
18442                "    {{init1, init2, init3, init4},\n"
18443                "     {init1, init2, init3, init4}}\n"
18444                "};",
18445                Style);
18446   Style.ColumnLimit = 100;
18447   EXPECT_EQ(
18448       "test demo[] = {\n"
18449       "    {56,    23,\n"
18450       "     \"hello world i am a very long line that really, in any just world"
18451       ", ought to be split over \"\n"
18452       "     \"multiple lines\"  },\n"
18453       "    {-1, 93463, \"world\"},\n"
18454       "    { 7,     5,    \"!!\"},\n"
18455       "};",
18456       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18457              "that really, in any just world, ought to be split over multiple "
18458              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18459              Style));
18460 
18461   Style = getLLVMStyleWithColumns(50);
18462   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18463   Style.AlignConsecutiveAssignments =
18464       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18465   Style.AlignConsecutiveDeclarations =
18466       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18467   verifyFormat("struct test demo[] = {\n"
18468                "    {56,    23, \"hello\"},\n"
18469                "    {-1, 93463, \"world\"},\n"
18470                "    { 7,     5,    \"!!\"}\n"
18471                "};\n"
18472                "static A x = {\n"
18473                "    {{init1, init2, init3, init4},\n"
18474                "     {init1, init2, init3, init4}}\n"
18475                "};",
18476                Style);
18477   Style.ColumnLimit = 100;
18478   Style.AlignConsecutiveAssignments =
18479       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18480   Style.AlignConsecutiveDeclarations =
18481       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18482   verifyFormat("struct test demo[] = {\n"
18483                "    {56,    23, \"hello\"},\n"
18484                "    {-1, 93463, \"world\"},\n"
18485                "    { 7,     5,    \"!!\"}\n"
18486                "};\n"
18487                "struct test demo[4] = {\n"
18488                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18489                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18490                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18491                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18492                "};\n",
18493                Style);
18494   EXPECT_EQ(
18495       "test demo[] = {\n"
18496       "    {56,\n"
18497       "     \"hello world i am a very long line that really, in any just world"
18498       ", ought to be split over \"\n"
18499       "     \"multiple lines\",    23},\n"
18500       "    {-1,      \"world\", 93463},\n"
18501       "    { 7,         \"!!\",     5},\n"
18502       "};",
18503       format("test demo[] = {{56, \"hello world i am a very long line "
18504              "that really, in any just world, ought to be split over multiple "
18505              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
18506              Style));
18507 }
18508 
18509 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
18510   auto Style = getLLVMStyle();
18511   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18512   /* FIXME: This case gets misformatted.
18513   verifyFormat("auto foo = Items{\n"
18514                "    Section{0, bar(), },\n"
18515                "    Section{1, boo()  }\n"
18516                "};\n",
18517                Style);
18518   */
18519   verifyFormat("auto foo = Items{\n"
18520                "    Section{\n"
18521                "            0, bar(),\n"
18522                "            }\n"
18523                "};\n",
18524                Style);
18525   verifyFormat("struct test demo[] = {\n"
18526                "    {56, 23,    \"hello\"},\n"
18527                "    {-1, 93463, \"world\"},\n"
18528                "    {7,  5,     \"!!\"   }\n"
18529                "};\n",
18530                Style);
18531   verifyFormat("struct test demo[] = {\n"
18532                "    {56, 23,    \"hello\"}, // first line\n"
18533                "    {-1, 93463, \"world\"}, // second line\n"
18534                "    {7,  5,     \"!!\"   }  // third line\n"
18535                "};\n",
18536                Style);
18537   verifyFormat("struct test demo[4] = {\n"
18538                "    {56,  23,    21, \"oh\"      }, // first line\n"
18539                "    {-1,  93463, 22, \"my\"      }, // second line\n"
18540                "    {7,   5,     1,  \"goodness\"}  // third line\n"
18541                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
18542                "};\n",
18543                Style);
18544   verifyFormat("struct test demo[3] = {\n"
18545                "    {56, 23,    \"hello\"},\n"
18546                "    {-1, 93463, \"world\"},\n"
18547                "    {7,  5,     \"!!\"   }\n"
18548                "};\n",
18549                Style);
18550 
18551   verifyFormat("struct test demo[3] = {\n"
18552                "    {int{56}, 23,    \"hello\"},\n"
18553                "    {int{-1}, 93463, \"world\"},\n"
18554                "    {int{7},  5,     \"!!\"   }\n"
18555                "};\n",
18556                Style);
18557   verifyFormat("struct test demo[] = {\n"
18558                "    {56, 23,    \"hello\"},\n"
18559                "    {-1, 93463, \"world\"},\n"
18560                "    {7,  5,     \"!!\"   },\n"
18561                "};\n",
18562                Style);
18563   verifyFormat("test demo[] = {\n"
18564                "    {56, 23,    \"hello\"},\n"
18565                "    {-1, 93463, \"world\"},\n"
18566                "    {7,  5,     \"!!\"   },\n"
18567                "};\n",
18568                Style);
18569   verifyFormat("demo = std::array<struct test, 3>{\n"
18570                "    test{56, 23,    \"hello\"},\n"
18571                "    test{-1, 93463, \"world\"},\n"
18572                "    test{7,  5,     \"!!\"   },\n"
18573                "};\n",
18574                Style);
18575   verifyFormat("test demo[] = {\n"
18576                "    {56, 23,    \"hello\"},\n"
18577                "#if X\n"
18578                "    {-1, 93463, \"world\"},\n"
18579                "#endif\n"
18580                "    {7,  5,     \"!!\"   }\n"
18581                "};\n",
18582                Style);
18583   verifyFormat(
18584       "test demo[] = {\n"
18585       "    {7,  23,\n"
18586       "     \"hello world i am a very long line that really, in any\"\n"
18587       "     \"just world, ought to be split over multiple lines\"},\n"
18588       "    {-1, 93463, \"world\"                                 },\n"
18589       "    {56, 5,     \"!!\"                                    }\n"
18590       "};\n",
18591       Style);
18592 
18593   verifyFormat("return GradForUnaryCwise(g, {\n"
18594                "                                {{\"sign\"}, \"Sign\", {\"x\", "
18595                "\"dy\"}   },\n"
18596                "                                {{\"dx\"},   \"Mul\",  "
18597                "{\"dy\", \"sign\"}},\n"
18598                "});\n",
18599                Style);
18600 
18601   Style.ColumnLimit = 0;
18602   EXPECT_EQ(
18603       "test demo[] = {\n"
18604       "    {56, 23,    \"hello world i am a very long line that really, in any "
18605       "just world, ought to be split over multiple lines\"},\n"
18606       "    {-1, 93463, \"world\"                                               "
18607       "                                                   },\n"
18608       "    {7,  5,     \"!!\"                                                  "
18609       "                                                   },\n"
18610       "};",
18611       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18612              "that really, in any just world, ought to be split over multiple "
18613              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18614              Style));
18615 
18616   Style.ColumnLimit = 80;
18617   verifyFormat("test demo[] = {\n"
18618                "    {56, 23,    /* a comment */ \"hello\"},\n"
18619                "    {-1, 93463, \"world\"                },\n"
18620                "    {7,  5,     \"!!\"                   }\n"
18621                "};\n",
18622                Style);
18623 
18624   verifyFormat("test demo[] = {\n"
18625                "    {56, 23,    \"hello\"                   },\n"
18626                "    {-1, 93463, \"world\" /* comment here */},\n"
18627                "    {7,  5,     \"!!\"                      }\n"
18628                "};\n",
18629                Style);
18630 
18631   verifyFormat("test demo[] = {\n"
18632                "    {56, /* a comment */ 23, \"hello\"},\n"
18633                "    {-1, 93463,              \"world\"},\n"
18634                "    {7,  5,                  \"!!\"   }\n"
18635                "};\n",
18636                Style);
18637 
18638   Style.ColumnLimit = 20;
18639   EXPECT_EQ(
18640       "demo = std::array<\n"
18641       "    struct test, 3>{\n"
18642       "    test{\n"
18643       "         56, 23,\n"
18644       "         \"hello \"\n"
18645       "         \"world i \"\n"
18646       "         \"am a very \"\n"
18647       "         \"long line \"\n"
18648       "         \"that \"\n"
18649       "         \"really, \"\n"
18650       "         \"in any \"\n"
18651       "         \"just \"\n"
18652       "         \"world, \"\n"
18653       "         \"ought to \"\n"
18654       "         \"be split \"\n"
18655       "         \"over \"\n"
18656       "         \"multiple \"\n"
18657       "         \"lines\"},\n"
18658       "    test{-1, 93463,\n"
18659       "         \"world\"},\n"
18660       "    test{7,  5,\n"
18661       "         \"!!\"   },\n"
18662       "};",
18663       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18664              "i am a very long line that really, in any just world, ought "
18665              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18666              "test{7, 5, \"!!\"},};",
18667              Style));
18668 
18669   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18670   Style = getLLVMStyleWithColumns(50);
18671   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18672   verifyFormat("static A x = {\n"
18673                "    {{init1, init2, init3, init4},\n"
18674                "     {init1, init2, init3, init4}}\n"
18675                "};",
18676                Style);
18677   Style.ColumnLimit = 100;
18678   EXPECT_EQ(
18679       "test demo[] = {\n"
18680       "    {56, 23,\n"
18681       "     \"hello world i am a very long line that really, in any just world"
18682       ", ought to be split over \"\n"
18683       "     \"multiple lines\"  },\n"
18684       "    {-1, 93463, \"world\"},\n"
18685       "    {7,  5,     \"!!\"   },\n"
18686       "};",
18687       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18688              "that really, in any just world, ought to be split over multiple "
18689              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18690              Style));
18691 }
18692 
18693 TEST_F(FormatTest, UnderstandsPragmas) {
18694   verifyFormat("#pragma omp reduction(| : var)");
18695   verifyFormat("#pragma omp reduction(+ : var)");
18696 
18697   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
18698             "(including parentheses).",
18699             format("#pragma    mark   Any non-hyphenated or hyphenated string "
18700                    "(including parentheses)."));
18701 }
18702 
18703 TEST_F(FormatTest, UnderstandPragmaOption) {
18704   verifyFormat("#pragma option -C -A");
18705 
18706   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
18707 }
18708 
18709 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
18710   FormatStyle Style = getLLVMStyleWithColumns(20);
18711 
18712   // See PR41213
18713   EXPECT_EQ("/*\n"
18714             " *\t9012345\n"
18715             " * /8901\n"
18716             " */",
18717             format("/*\n"
18718                    " *\t9012345 /8901\n"
18719                    " */",
18720                    Style));
18721   EXPECT_EQ("/*\n"
18722             " *345678\n"
18723             " *\t/8901\n"
18724             " */",
18725             format("/*\n"
18726                    " *345678\t/8901\n"
18727                    " */",
18728                    Style));
18729 
18730   verifyFormat("int a; // the\n"
18731                "       // comment",
18732                Style);
18733   EXPECT_EQ("int a; /* first line\n"
18734             "        * second\n"
18735             "        * line third\n"
18736             "        * line\n"
18737             "        */",
18738             format("int a; /* first line\n"
18739                    "        * second\n"
18740                    "        * line third\n"
18741                    "        * line\n"
18742                    "        */",
18743                    Style));
18744   EXPECT_EQ("int a; // first line\n"
18745             "       // second\n"
18746             "       // line third\n"
18747             "       // line",
18748             format("int a; // first line\n"
18749                    "       // second line\n"
18750                    "       // third line",
18751                    Style));
18752 
18753   Style.PenaltyExcessCharacter = 90;
18754   verifyFormat("int a; // the comment", Style);
18755   EXPECT_EQ("int a; // the comment\n"
18756             "       // aaa",
18757             format("int a; // the comment aaa", Style));
18758   EXPECT_EQ("int a; /* first line\n"
18759             "        * second line\n"
18760             "        * third line\n"
18761             "        */",
18762             format("int a; /* first line\n"
18763                    "        * second line\n"
18764                    "        * third line\n"
18765                    "        */",
18766                    Style));
18767   EXPECT_EQ("int a; // first line\n"
18768             "       // second line\n"
18769             "       // third line",
18770             format("int a; // first line\n"
18771                    "       // second line\n"
18772                    "       // third line",
18773                    Style));
18774   // FIXME: Investigate why this is not getting the same layout as the test
18775   // above.
18776   EXPECT_EQ("int a; /* first line\n"
18777             "        * second line\n"
18778             "        * third line\n"
18779             "        */",
18780             format("int a; /* first line second line third line"
18781                    "\n*/",
18782                    Style));
18783 
18784   EXPECT_EQ("// foo bar baz bazfoo\n"
18785             "// foo bar foo bar\n",
18786             format("// foo bar baz bazfoo\n"
18787                    "// foo bar foo           bar\n",
18788                    Style));
18789   EXPECT_EQ("// foo bar baz bazfoo\n"
18790             "// foo bar foo bar\n",
18791             format("// foo bar baz      bazfoo\n"
18792                    "// foo            bar foo bar\n",
18793                    Style));
18794 
18795   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
18796   // next one.
18797   EXPECT_EQ("// foo bar baz bazfoo\n"
18798             "// bar foo bar\n",
18799             format("// foo bar baz      bazfoo bar\n"
18800                    "// foo            bar\n",
18801                    Style));
18802 
18803   EXPECT_EQ("// foo bar baz bazfoo\n"
18804             "// foo bar baz bazfoo\n"
18805             "// bar foo bar\n",
18806             format("// foo bar baz      bazfoo\n"
18807                    "// foo bar baz      bazfoo bar\n"
18808                    "// foo bar\n",
18809                    Style));
18810 
18811   EXPECT_EQ("// foo bar baz bazfoo\n"
18812             "// foo bar baz bazfoo\n"
18813             "// bar foo bar\n",
18814             format("// foo bar baz      bazfoo\n"
18815                    "// foo bar baz      bazfoo bar\n"
18816                    "// foo           bar\n",
18817                    Style));
18818 
18819   // Make sure we do not keep protruding characters if strict mode reflow is
18820   // cheaper than keeping protruding characters.
18821   Style.ColumnLimit = 21;
18822   EXPECT_EQ(
18823       "// foo foo foo foo\n"
18824       "// foo foo foo foo\n"
18825       "// foo foo foo foo\n",
18826       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
18827 
18828   EXPECT_EQ("int a = /* long block\n"
18829             "           comment */\n"
18830             "    42;",
18831             format("int a = /* long block comment */ 42;", Style));
18832 }
18833 
18834 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
18835   FormatStyle Style = getLLVMStyle();
18836   Style.ColumnLimit = 8;
18837   Style.PenaltyExcessCharacter = 15;
18838   verifyFormat("int foo(\n"
18839                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
18840                Style);
18841   Style.PenaltyBreakOpenParenthesis = 200;
18842   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
18843             format("int foo(\n"
18844                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
18845                    Style));
18846 }
18847 
18848 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
18849   FormatStyle Style = getLLVMStyle();
18850   Style.ColumnLimit = 5;
18851   Style.PenaltyExcessCharacter = 150;
18852   verifyFormat("foo((\n"
18853                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
18854 
18855                Style);
18856   Style.PenaltyBreakOpenParenthesis = 100000;
18857   EXPECT_EQ("foo((int)\n"
18858             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
18859             format("foo((\n"
18860                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
18861                    Style));
18862 }
18863 
18864 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
18865   FormatStyle Style = getLLVMStyle();
18866   Style.ColumnLimit = 4;
18867   Style.PenaltyExcessCharacter = 100;
18868   verifyFormat("for (\n"
18869                "    int iiiiiiiiiiiiiiiii =\n"
18870                "        0;\n"
18871                "    iiiiiiiiiiiiiiiii <\n"
18872                "    2;\n"
18873                "    iiiiiiiiiiiiiiiii++) {\n"
18874                "}",
18875 
18876                Style);
18877   Style.PenaltyBreakOpenParenthesis = 1250;
18878   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
18879             "         0;\n"
18880             "     iiiiiiiiiiiiiiiii <\n"
18881             "     2;\n"
18882             "     iiiiiiiiiiiiiiiii++) {\n"
18883             "}",
18884             format("for (\n"
18885                    "    int iiiiiiiiiiiiiiiii =\n"
18886                    "        0;\n"
18887                    "    iiiiiiiiiiiiiiiii <\n"
18888                    "    2;\n"
18889                    "    iiiiiiiiiiiiiiiii++) {\n"
18890                    "}",
18891                    Style));
18892 }
18893 
18894 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
18895   for (size_t i = 1; i < Styles.size(); ++i)                                   \
18896   EXPECT_EQ(Styles[0], Styles[i])                                              \
18897       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
18898 
18899 TEST_F(FormatTest, GetsPredefinedStyleByName) {
18900   SmallVector<FormatStyle, 3> Styles;
18901   Styles.resize(3);
18902 
18903   Styles[0] = getLLVMStyle();
18904   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
18905   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
18906   EXPECT_ALL_STYLES_EQUAL(Styles);
18907 
18908   Styles[0] = getGoogleStyle();
18909   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
18910   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
18911   EXPECT_ALL_STYLES_EQUAL(Styles);
18912 
18913   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18914   EXPECT_TRUE(
18915       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
18916   EXPECT_TRUE(
18917       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
18918   EXPECT_ALL_STYLES_EQUAL(Styles);
18919 
18920   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
18921   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
18922   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
18923   EXPECT_ALL_STYLES_EQUAL(Styles);
18924 
18925   Styles[0] = getMozillaStyle();
18926   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
18927   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
18928   EXPECT_ALL_STYLES_EQUAL(Styles);
18929 
18930   Styles[0] = getWebKitStyle();
18931   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
18932   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
18933   EXPECT_ALL_STYLES_EQUAL(Styles);
18934 
18935   Styles[0] = getGNUStyle();
18936   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
18937   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
18938   EXPECT_ALL_STYLES_EQUAL(Styles);
18939 
18940   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
18941 }
18942 
18943 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
18944   SmallVector<FormatStyle, 8> Styles;
18945   Styles.resize(2);
18946 
18947   Styles[0] = getGoogleStyle();
18948   Styles[1] = getLLVMStyle();
18949   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18950   EXPECT_ALL_STYLES_EQUAL(Styles);
18951 
18952   Styles.resize(5);
18953   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18954   Styles[1] = getLLVMStyle();
18955   Styles[1].Language = FormatStyle::LK_JavaScript;
18956   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18957 
18958   Styles[2] = getLLVMStyle();
18959   Styles[2].Language = FormatStyle::LK_JavaScript;
18960   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
18961                                   "BasedOnStyle: Google",
18962                                   &Styles[2])
18963                    .value());
18964 
18965   Styles[3] = getLLVMStyle();
18966   Styles[3].Language = FormatStyle::LK_JavaScript;
18967   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
18968                                   "Language: JavaScript",
18969                                   &Styles[3])
18970                    .value());
18971 
18972   Styles[4] = getLLVMStyle();
18973   Styles[4].Language = FormatStyle::LK_JavaScript;
18974   EXPECT_EQ(0, parseConfiguration("---\n"
18975                                   "BasedOnStyle: LLVM\n"
18976                                   "IndentWidth: 123\n"
18977                                   "---\n"
18978                                   "BasedOnStyle: Google\n"
18979                                   "Language: JavaScript",
18980                                   &Styles[4])
18981                    .value());
18982   EXPECT_ALL_STYLES_EQUAL(Styles);
18983 }
18984 
18985 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
18986   Style.FIELD = false;                                                         \
18987   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
18988   EXPECT_TRUE(Style.FIELD);                                                    \
18989   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
18990   EXPECT_FALSE(Style.FIELD);
18991 
18992 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
18993 
18994 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
18995   Style.STRUCT.FIELD = false;                                                  \
18996   EXPECT_EQ(0,                                                                 \
18997             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
18998                 .value());                                                     \
18999   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
19000   EXPECT_EQ(0,                                                                 \
19001             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
19002                 .value());                                                     \
19003   EXPECT_FALSE(Style.STRUCT.FIELD);
19004 
19005 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
19006   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
19007 
19008 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
19009   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
19010   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
19011   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
19012 
19013 TEST_F(FormatTest, ParsesConfigurationBools) {
19014   FormatStyle Style = {};
19015   Style.Language = FormatStyle::LK_Cpp;
19016   CHECK_PARSE_BOOL(AlignTrailingComments);
19017   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
19018   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
19019   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
19020   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
19021   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
19022   CHECK_PARSE_BOOL(BinPackArguments);
19023   CHECK_PARSE_BOOL(BinPackParameters);
19024   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
19025   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
19026   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
19027   CHECK_PARSE_BOOL(BreakStringLiterals);
19028   CHECK_PARSE_BOOL(CompactNamespaces);
19029   CHECK_PARSE_BOOL(DeriveLineEnding);
19030   CHECK_PARSE_BOOL(DerivePointerAlignment);
19031   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
19032   CHECK_PARSE_BOOL(DisableFormat);
19033   CHECK_PARSE_BOOL(IndentAccessModifiers);
19034   CHECK_PARSE_BOOL(IndentCaseLabels);
19035   CHECK_PARSE_BOOL(IndentCaseBlocks);
19036   CHECK_PARSE_BOOL(IndentGotoLabels);
19037   CHECK_PARSE_BOOL(IndentRequires);
19038   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
19039   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
19040   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
19041   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
19042   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
19043   CHECK_PARSE_BOOL(ReflowComments);
19044   CHECK_PARSE_BOOL(RemoveBracesLLVM);
19045   CHECK_PARSE_BOOL(SortUsingDeclarations);
19046   CHECK_PARSE_BOOL(SpacesInParentheses);
19047   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
19048   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
19049   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
19050   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
19051   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
19052   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
19053   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
19054   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
19055   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
19056   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
19057   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
19058   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
19059   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
19060   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
19061   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
19062   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
19063   CHECK_PARSE_BOOL(UseCRLF);
19064 
19065   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
19066   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
19067   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
19068   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
19069   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
19070   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
19071   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
19072   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
19073   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
19074   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
19075   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
19076   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
19077   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
19078   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
19079   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
19080   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
19081   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
19082   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
19083   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
19084   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19085                           AfterFunctionDeclarationName);
19086   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19087                           AfterFunctionDefinitionName);
19088   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
19089   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
19090   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
19091 }
19092 
19093 #undef CHECK_PARSE_BOOL
19094 
19095 TEST_F(FormatTest, ParsesConfiguration) {
19096   FormatStyle Style = {};
19097   Style.Language = FormatStyle::LK_Cpp;
19098   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
19099   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
19100               ConstructorInitializerIndentWidth, 1234u);
19101   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
19102   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
19103   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
19104   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
19105   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
19106               PenaltyBreakBeforeFirstCallParameter, 1234u);
19107   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
19108               PenaltyBreakTemplateDeclaration, 1234u);
19109   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
19110               1234u);
19111   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
19112   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
19113               PenaltyReturnTypeOnItsOwnLine, 1234u);
19114   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
19115               SpacesBeforeTrailingComments, 1234u);
19116   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
19117   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
19118   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
19119 
19120   Style.QualifierAlignment = FormatStyle::QAS_Right;
19121   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
19122               FormatStyle::QAS_Leave);
19123   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
19124               FormatStyle::QAS_Right);
19125   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
19126               FormatStyle::QAS_Left);
19127   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
19128               FormatStyle::QAS_Custom);
19129 
19130   Style.QualifierOrder.clear();
19131   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
19132               std::vector<std::string>({"const", "volatile", "type"}));
19133   Style.QualifierOrder.clear();
19134   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
19135               std::vector<std::string>({"const", "type"}));
19136   Style.QualifierOrder.clear();
19137   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
19138               std::vector<std::string>({"volatile", "type"}));
19139 
19140   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
19141   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
19142               FormatStyle::ACS_None);
19143   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
19144               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
19145   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
19146               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
19147   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
19148               AlignConsecutiveAssignments,
19149               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19150   // For backwards compability, false / true should still parse
19151   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
19152               FormatStyle::ACS_None);
19153   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
19154               FormatStyle::ACS_Consecutive);
19155 
19156   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
19157   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
19158               FormatStyle::ACS_None);
19159   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
19160               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
19161   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
19162               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
19163   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
19164               AlignConsecutiveBitFields,
19165               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19166   // For backwards compability, false / true should still parse
19167   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
19168               FormatStyle::ACS_None);
19169   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
19170               FormatStyle::ACS_Consecutive);
19171 
19172   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
19173   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
19174               FormatStyle::ACS_None);
19175   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
19176               FormatStyle::ACS_Consecutive);
19177   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
19178               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
19179   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
19180               AlignConsecutiveMacros,
19181               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19182   // For backwards compability, false / true should still parse
19183   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
19184               FormatStyle::ACS_None);
19185   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
19186               FormatStyle::ACS_Consecutive);
19187 
19188   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
19189   CHECK_PARSE("AlignConsecutiveDeclarations: None",
19190               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
19191   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
19192               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
19193   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
19194               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
19195   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
19196               AlignConsecutiveDeclarations,
19197               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19198   // For backwards compability, false / true should still parse
19199   CHECK_PARSE("AlignConsecutiveDeclarations: false",
19200               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
19201   CHECK_PARSE("AlignConsecutiveDeclarations: true",
19202               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
19203 
19204   Style.PointerAlignment = FormatStyle::PAS_Middle;
19205   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
19206               FormatStyle::PAS_Left);
19207   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
19208               FormatStyle::PAS_Right);
19209   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
19210               FormatStyle::PAS_Middle);
19211   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
19212   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
19213               FormatStyle::RAS_Pointer);
19214   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
19215               FormatStyle::RAS_Left);
19216   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
19217               FormatStyle::RAS_Right);
19218   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
19219               FormatStyle::RAS_Middle);
19220   // For backward compatibility:
19221   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
19222               FormatStyle::PAS_Left);
19223   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
19224               FormatStyle::PAS_Right);
19225   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
19226               FormatStyle::PAS_Middle);
19227 
19228   Style.Standard = FormatStyle::LS_Auto;
19229   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
19230   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
19231   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
19232   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
19233   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
19234   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
19235   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
19236   // Legacy aliases:
19237   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
19238   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
19239   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
19240   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
19241 
19242   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
19243   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
19244               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
19245   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
19246               FormatStyle::BOS_None);
19247   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
19248               FormatStyle::BOS_All);
19249   // For backward compatibility:
19250   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
19251               FormatStyle::BOS_None);
19252   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
19253               FormatStyle::BOS_All);
19254 
19255   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
19256   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
19257               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
19258   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
19259               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
19260   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
19261               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
19262   // For backward compatibility:
19263   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
19264               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
19265 
19266   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
19267   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
19268               FormatStyle::BILS_AfterComma);
19269   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
19270               FormatStyle::BILS_BeforeComma);
19271   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
19272               FormatStyle::BILS_AfterColon);
19273   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
19274               FormatStyle::BILS_BeforeColon);
19275   // For backward compatibility:
19276   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
19277               FormatStyle::BILS_BeforeComma);
19278 
19279   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19280   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
19281               FormatStyle::PCIS_Never);
19282   CHECK_PARSE("PackConstructorInitializers: BinPack",
19283               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19284   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
19285               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19286   CHECK_PARSE("PackConstructorInitializers: NextLine",
19287               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19288   // For backward compatibility:
19289   CHECK_PARSE("BasedOnStyle: Google\n"
19290               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19291               "AllowAllConstructorInitializersOnNextLine: false",
19292               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19293   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
19294   CHECK_PARSE("BasedOnStyle: Google\n"
19295               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
19296               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19297   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19298               "AllowAllConstructorInitializersOnNextLine: true",
19299               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19300   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19301   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19302               "AllowAllConstructorInitializersOnNextLine: false",
19303               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19304 
19305   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
19306   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
19307               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
19308   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
19309               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
19310   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
19311               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
19312   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
19313               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
19314 
19315   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19316   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
19317               FormatStyle::BAS_Align);
19318   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
19319               FormatStyle::BAS_DontAlign);
19320   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
19321               FormatStyle::BAS_AlwaysBreak);
19322   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
19323               FormatStyle::BAS_BlockIndent);
19324   // For backward compatibility:
19325   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
19326               FormatStyle::BAS_DontAlign);
19327   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
19328               FormatStyle::BAS_Align);
19329 
19330   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
19331   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
19332               FormatStyle::ENAS_DontAlign);
19333   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
19334               FormatStyle::ENAS_Left);
19335   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
19336               FormatStyle::ENAS_Right);
19337   // For backward compatibility:
19338   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
19339               FormatStyle::ENAS_Left);
19340   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
19341               FormatStyle::ENAS_Right);
19342 
19343   Style.AlignOperands = FormatStyle::OAS_Align;
19344   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
19345               FormatStyle::OAS_DontAlign);
19346   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
19347   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
19348               FormatStyle::OAS_AlignAfterOperator);
19349   // For backward compatibility:
19350   CHECK_PARSE("AlignOperands: false", AlignOperands,
19351               FormatStyle::OAS_DontAlign);
19352   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
19353 
19354   Style.UseTab = FormatStyle::UT_ForIndentation;
19355   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
19356   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
19357   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
19358   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
19359               FormatStyle::UT_ForContinuationAndIndentation);
19360   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
19361               FormatStyle::UT_AlignWithSpaces);
19362   // For backward compatibility:
19363   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
19364   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
19365 
19366   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
19367   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
19368               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19369   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
19370               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
19371   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
19372               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19373   // For backward compatibility:
19374   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
19375               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19376   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
19377               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19378 
19379   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
19380   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
19381               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19382   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
19383               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
19384   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
19385               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
19386   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
19387               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19388   // For backward compatibility:
19389   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
19390               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19391   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
19392               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19393 
19394   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
19395   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
19396               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
19397   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
19398               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
19399   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
19400               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
19401   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
19402               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
19403 
19404   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
19405   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
19406               FormatStyle::SBPO_Never);
19407   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
19408               FormatStyle::SBPO_Always);
19409   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
19410               FormatStyle::SBPO_ControlStatements);
19411   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
19412               SpaceBeforeParens,
19413               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19414   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
19415               FormatStyle::SBPO_NonEmptyParentheses);
19416   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
19417               FormatStyle::SBPO_Custom);
19418   // For backward compatibility:
19419   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
19420               FormatStyle::SBPO_Never);
19421   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
19422               FormatStyle::SBPO_ControlStatements);
19423   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
19424               SpaceBeforeParens,
19425               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19426 
19427   Style.ColumnLimit = 123;
19428   FormatStyle BaseStyle = getLLVMStyle();
19429   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
19430   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
19431 
19432   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
19433   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
19434               FormatStyle::BS_Attach);
19435   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
19436               FormatStyle::BS_Linux);
19437   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
19438               FormatStyle::BS_Mozilla);
19439   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
19440               FormatStyle::BS_Stroustrup);
19441   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
19442               FormatStyle::BS_Allman);
19443   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
19444               FormatStyle::BS_Whitesmiths);
19445   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
19446   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
19447               FormatStyle::BS_WebKit);
19448   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
19449               FormatStyle::BS_Custom);
19450 
19451   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
19452   CHECK_PARSE("BraceWrapping:\n"
19453               "  AfterControlStatement: MultiLine",
19454               BraceWrapping.AfterControlStatement,
19455               FormatStyle::BWACS_MultiLine);
19456   CHECK_PARSE("BraceWrapping:\n"
19457               "  AfterControlStatement: Always",
19458               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19459   CHECK_PARSE("BraceWrapping:\n"
19460               "  AfterControlStatement: Never",
19461               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19462   // For backward compatibility:
19463   CHECK_PARSE("BraceWrapping:\n"
19464               "  AfterControlStatement: true",
19465               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19466   CHECK_PARSE("BraceWrapping:\n"
19467               "  AfterControlStatement: false",
19468               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19469 
19470   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
19471   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
19472               FormatStyle::RTBS_None);
19473   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
19474               FormatStyle::RTBS_All);
19475   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
19476               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
19477   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
19478               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
19479   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
19480               AlwaysBreakAfterReturnType,
19481               FormatStyle::RTBS_TopLevelDefinitions);
19482 
19483   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
19484   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
19485               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
19486   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
19487               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19488   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
19489               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19490   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
19491               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19492   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
19493               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19494 
19495   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
19496   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
19497               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
19498   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
19499               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
19500   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
19501               AlwaysBreakAfterDefinitionReturnType,
19502               FormatStyle::DRTBS_TopLevel);
19503 
19504   Style.NamespaceIndentation = FormatStyle::NI_All;
19505   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
19506               FormatStyle::NI_None);
19507   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
19508               FormatStyle::NI_Inner);
19509   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
19510               FormatStyle::NI_All);
19511 
19512   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
19513   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
19514               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19515   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
19516               AllowShortIfStatementsOnASingleLine,
19517               FormatStyle::SIS_WithoutElse);
19518   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
19519               AllowShortIfStatementsOnASingleLine,
19520               FormatStyle::SIS_OnlyFirstIf);
19521   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
19522               AllowShortIfStatementsOnASingleLine,
19523               FormatStyle::SIS_AllIfsAndElse);
19524   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
19525               AllowShortIfStatementsOnASingleLine,
19526               FormatStyle::SIS_OnlyFirstIf);
19527   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
19528               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19529   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
19530               AllowShortIfStatementsOnASingleLine,
19531               FormatStyle::SIS_WithoutElse);
19532 
19533   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
19534   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
19535               FormatStyle::IEBS_AfterExternBlock);
19536   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
19537               FormatStyle::IEBS_Indent);
19538   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
19539               FormatStyle::IEBS_NoIndent);
19540   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
19541               FormatStyle::IEBS_Indent);
19542   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
19543               FormatStyle::IEBS_NoIndent);
19544 
19545   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
19546   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
19547               FormatStyle::BFCS_Both);
19548   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
19549               FormatStyle::BFCS_None);
19550   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
19551               FormatStyle::BFCS_Before);
19552   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
19553               FormatStyle::BFCS_After);
19554 
19555   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
19556   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
19557               FormatStyle::SJSIO_After);
19558   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
19559               FormatStyle::SJSIO_Before);
19560 
19561   // FIXME: This is required because parsing a configuration simply overwrites
19562   // the first N elements of the list instead of resetting it.
19563   Style.ForEachMacros.clear();
19564   std::vector<std::string> BoostForeach;
19565   BoostForeach.push_back("BOOST_FOREACH");
19566   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
19567   std::vector<std::string> BoostAndQForeach;
19568   BoostAndQForeach.push_back("BOOST_FOREACH");
19569   BoostAndQForeach.push_back("Q_FOREACH");
19570   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
19571               BoostAndQForeach);
19572 
19573   Style.IfMacros.clear();
19574   std::vector<std::string> CustomIfs;
19575   CustomIfs.push_back("MYIF");
19576   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
19577 
19578   Style.AttributeMacros.clear();
19579   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
19580               std::vector<std::string>{"__capability"});
19581   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
19582               std::vector<std::string>({"attr1", "attr2"}));
19583 
19584   Style.StatementAttributeLikeMacros.clear();
19585   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
19586               StatementAttributeLikeMacros,
19587               std::vector<std::string>({"emit", "Q_EMIT"}));
19588 
19589   Style.StatementMacros.clear();
19590   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
19591               std::vector<std::string>{"QUNUSED"});
19592   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
19593               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
19594 
19595   Style.NamespaceMacros.clear();
19596   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
19597               std::vector<std::string>{"TESTSUITE"});
19598   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
19599               std::vector<std::string>({"TESTSUITE", "SUITE"}));
19600 
19601   Style.WhitespaceSensitiveMacros.clear();
19602   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
19603               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
19604   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
19605               WhitespaceSensitiveMacros,
19606               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
19607   Style.WhitespaceSensitiveMacros.clear();
19608   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
19609               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
19610   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
19611               WhitespaceSensitiveMacros,
19612               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
19613 
19614   Style.IncludeStyle.IncludeCategories.clear();
19615   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
19616       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
19617   CHECK_PARSE("IncludeCategories:\n"
19618               "  - Regex: abc/.*\n"
19619               "    Priority: 2\n"
19620               "  - Regex: .*\n"
19621               "    Priority: 1\n"
19622               "    CaseSensitive: true\n",
19623               IncludeStyle.IncludeCategories, ExpectedCategories);
19624   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
19625               "abc$");
19626   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
19627               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
19628 
19629   Style.SortIncludes = FormatStyle::SI_Never;
19630   CHECK_PARSE("SortIncludes: true", SortIncludes,
19631               FormatStyle::SI_CaseSensitive);
19632   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
19633   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
19634               FormatStyle::SI_CaseInsensitive);
19635   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
19636               FormatStyle::SI_CaseSensitive);
19637   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
19638 
19639   Style.RawStringFormats.clear();
19640   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
19641       {
19642           FormatStyle::LK_TextProto,
19643           {"pb", "proto"},
19644           {"PARSE_TEXT_PROTO"},
19645           /*CanonicalDelimiter=*/"",
19646           "llvm",
19647       },
19648       {
19649           FormatStyle::LK_Cpp,
19650           {"cc", "cpp"},
19651           {"C_CODEBLOCK", "CPPEVAL"},
19652           /*CanonicalDelimiter=*/"cc",
19653           /*BasedOnStyle=*/"",
19654       },
19655   };
19656 
19657   CHECK_PARSE("RawStringFormats:\n"
19658               "  - Language: TextProto\n"
19659               "    Delimiters:\n"
19660               "      - 'pb'\n"
19661               "      - 'proto'\n"
19662               "    EnclosingFunctions:\n"
19663               "      - 'PARSE_TEXT_PROTO'\n"
19664               "    BasedOnStyle: llvm\n"
19665               "  - Language: Cpp\n"
19666               "    Delimiters:\n"
19667               "      - 'cc'\n"
19668               "      - 'cpp'\n"
19669               "    EnclosingFunctions:\n"
19670               "      - 'C_CODEBLOCK'\n"
19671               "      - 'CPPEVAL'\n"
19672               "    CanonicalDelimiter: 'cc'",
19673               RawStringFormats, ExpectedRawStringFormats);
19674 
19675   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19676               "  Minimum: 0\n"
19677               "  Maximum: 0",
19678               SpacesInLineCommentPrefix.Minimum, 0u);
19679   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
19680   Style.SpacesInLineCommentPrefix.Minimum = 1;
19681   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19682               "  Minimum: 2",
19683               SpacesInLineCommentPrefix.Minimum, 0u);
19684   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19685               "  Maximum: -1",
19686               SpacesInLineCommentPrefix.Maximum, -1u);
19687   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19688               "  Minimum: 2",
19689               SpacesInLineCommentPrefix.Minimum, 2u);
19690   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19691               "  Maximum: 1",
19692               SpacesInLineCommentPrefix.Maximum, 1u);
19693   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
19694 
19695   Style.SpacesInAngles = FormatStyle::SIAS_Always;
19696   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
19697   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
19698               FormatStyle::SIAS_Always);
19699   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
19700   // For backward compatibility:
19701   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
19702   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
19703 }
19704 
19705 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
19706   FormatStyle Style = {};
19707   Style.Language = FormatStyle::LK_Cpp;
19708   CHECK_PARSE("Language: Cpp\n"
19709               "IndentWidth: 12",
19710               IndentWidth, 12u);
19711   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
19712                                "IndentWidth: 34",
19713                                &Style),
19714             ParseError::Unsuitable);
19715   FormatStyle BinPackedTCS = {};
19716   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
19717   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
19718                                "InsertTrailingCommas: Wrapped",
19719                                &BinPackedTCS),
19720             ParseError::BinPackTrailingCommaConflict);
19721   EXPECT_EQ(12u, Style.IndentWidth);
19722   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
19723   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19724 
19725   Style.Language = FormatStyle::LK_JavaScript;
19726   CHECK_PARSE("Language: JavaScript\n"
19727               "IndentWidth: 12",
19728               IndentWidth, 12u);
19729   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
19730   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
19731                                "IndentWidth: 34",
19732                                &Style),
19733             ParseError::Unsuitable);
19734   EXPECT_EQ(23u, Style.IndentWidth);
19735   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
19736   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19737 
19738   CHECK_PARSE("BasedOnStyle: LLVM\n"
19739               "IndentWidth: 67",
19740               IndentWidth, 67u);
19741 
19742   CHECK_PARSE("---\n"
19743               "Language: JavaScript\n"
19744               "IndentWidth: 12\n"
19745               "---\n"
19746               "Language: Cpp\n"
19747               "IndentWidth: 34\n"
19748               "...\n",
19749               IndentWidth, 12u);
19750 
19751   Style.Language = FormatStyle::LK_Cpp;
19752   CHECK_PARSE("---\n"
19753               "Language: JavaScript\n"
19754               "IndentWidth: 12\n"
19755               "---\n"
19756               "Language: Cpp\n"
19757               "IndentWidth: 34\n"
19758               "...\n",
19759               IndentWidth, 34u);
19760   CHECK_PARSE("---\n"
19761               "IndentWidth: 78\n"
19762               "---\n"
19763               "Language: JavaScript\n"
19764               "IndentWidth: 56\n"
19765               "...\n",
19766               IndentWidth, 78u);
19767 
19768   Style.ColumnLimit = 123;
19769   Style.IndentWidth = 234;
19770   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
19771   Style.TabWidth = 345;
19772   EXPECT_FALSE(parseConfiguration("---\n"
19773                                   "IndentWidth: 456\n"
19774                                   "BreakBeforeBraces: Allman\n"
19775                                   "---\n"
19776                                   "Language: JavaScript\n"
19777                                   "IndentWidth: 111\n"
19778                                   "TabWidth: 111\n"
19779                                   "---\n"
19780                                   "Language: Cpp\n"
19781                                   "BreakBeforeBraces: Stroustrup\n"
19782                                   "TabWidth: 789\n"
19783                                   "...\n",
19784                                   &Style));
19785   EXPECT_EQ(123u, Style.ColumnLimit);
19786   EXPECT_EQ(456u, Style.IndentWidth);
19787   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
19788   EXPECT_EQ(789u, Style.TabWidth);
19789 
19790   EXPECT_EQ(parseConfiguration("---\n"
19791                                "Language: JavaScript\n"
19792                                "IndentWidth: 56\n"
19793                                "---\n"
19794                                "IndentWidth: 78\n"
19795                                "...\n",
19796                                &Style),
19797             ParseError::Error);
19798   EXPECT_EQ(parseConfiguration("---\n"
19799                                "Language: JavaScript\n"
19800                                "IndentWidth: 56\n"
19801                                "---\n"
19802                                "Language: JavaScript\n"
19803                                "IndentWidth: 78\n"
19804                                "...\n",
19805                                &Style),
19806             ParseError::Error);
19807 
19808   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19809 }
19810 
19811 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
19812   FormatStyle Style = {};
19813   Style.Language = FormatStyle::LK_JavaScript;
19814   Style.BreakBeforeTernaryOperators = true;
19815   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
19816   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19817 
19818   Style.BreakBeforeTernaryOperators = true;
19819   EXPECT_EQ(0, parseConfiguration("---\n"
19820                                   "BasedOnStyle: Google\n"
19821                                   "---\n"
19822                                   "Language: JavaScript\n"
19823                                   "IndentWidth: 76\n"
19824                                   "...\n",
19825                                   &Style)
19826                    .value());
19827   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19828   EXPECT_EQ(76u, Style.IndentWidth);
19829   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19830 }
19831 
19832 TEST_F(FormatTest, ConfigurationRoundTripTest) {
19833   FormatStyle Style = getLLVMStyle();
19834   std::string YAML = configurationAsText(Style);
19835   FormatStyle ParsedStyle = {};
19836   ParsedStyle.Language = FormatStyle::LK_Cpp;
19837   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
19838   EXPECT_EQ(Style, ParsedStyle);
19839 }
19840 
19841 TEST_F(FormatTest, WorksFor8bitEncodings) {
19842   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
19843             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
19844             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
19845             "\"\xef\xee\xf0\xf3...\"",
19846             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
19847                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
19848                    "\xef\xee\xf0\xf3...\"",
19849                    getLLVMStyleWithColumns(12)));
19850 }
19851 
19852 TEST_F(FormatTest, HandlesUTF8BOM) {
19853   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
19854   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
19855             format("\xef\xbb\xbf#include <iostream>"));
19856   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
19857             format("\xef\xbb\xbf\n#include <iostream>"));
19858 }
19859 
19860 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
19861 #if !defined(_MSC_VER)
19862 
19863 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
19864   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
19865                getLLVMStyleWithColumns(35));
19866   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
19867                getLLVMStyleWithColumns(31));
19868   verifyFormat("// Однажды в студёную зимнюю пору...",
19869                getLLVMStyleWithColumns(36));
19870   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
19871   verifyFormat("/* Однажды в студёную зимнюю пору... */",
19872                getLLVMStyleWithColumns(39));
19873   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
19874                getLLVMStyleWithColumns(35));
19875 }
19876 
19877 TEST_F(FormatTest, SplitsUTF8Strings) {
19878   // Non-printable characters' width is currently considered to be the length in
19879   // bytes in UTF8. The characters can be displayed in very different manner
19880   // (zero-width, single width with a substitution glyph, expanded to their code
19881   // (e.g. "<8d>"), so there's no single correct way to handle them.
19882   EXPECT_EQ("\"aaaaÄ\"\n"
19883             "\"\xc2\x8d\";",
19884             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19885   EXPECT_EQ("\"aaaaaaaÄ\"\n"
19886             "\"\xc2\x8d\";",
19887             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19888   EXPECT_EQ("\"Однажды, в \"\n"
19889             "\"студёную \"\n"
19890             "\"зимнюю \"\n"
19891             "\"пору,\"",
19892             format("\"Однажды, в студёную зимнюю пору,\"",
19893                    getLLVMStyleWithColumns(13)));
19894   EXPECT_EQ(
19895       "\"一 二 三 \"\n"
19896       "\"四 五六 \"\n"
19897       "\"七 八 九 \"\n"
19898       "\"十\"",
19899       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
19900   EXPECT_EQ("\"一\t\"\n"
19901             "\"二 \t\"\n"
19902             "\"三 四 \"\n"
19903             "\"五\t\"\n"
19904             "\"六 \t\"\n"
19905             "\"七 \"\n"
19906             "\"八九十\tqq\"",
19907             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
19908                    getLLVMStyleWithColumns(11)));
19909 
19910   // UTF8 character in an escape sequence.
19911   EXPECT_EQ("\"aaaaaa\"\n"
19912             "\"\\\xC2\x8D\"",
19913             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
19914 }
19915 
19916 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
19917   EXPECT_EQ("const char *sssss =\n"
19918             "    \"一二三四五六七八\\\n"
19919             " 九 十\";",
19920             format("const char *sssss = \"一二三四五六七八\\\n"
19921                    " 九 十\";",
19922                    getLLVMStyleWithColumns(30)));
19923 }
19924 
19925 TEST_F(FormatTest, SplitsUTF8LineComments) {
19926   EXPECT_EQ("// aaaaÄ\xc2\x8d",
19927             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
19928   EXPECT_EQ("// Я из лесу\n"
19929             "// вышел; был\n"
19930             "// сильный\n"
19931             "// мороз.",
19932             format("// Я из лесу вышел; был сильный мороз.",
19933                    getLLVMStyleWithColumns(13)));
19934   EXPECT_EQ("// 一二三\n"
19935             "// 四五六七\n"
19936             "// 八  九\n"
19937             "// 十",
19938             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
19939 }
19940 
19941 TEST_F(FormatTest, SplitsUTF8BlockComments) {
19942   EXPECT_EQ("/* Гляжу,\n"
19943             " * поднимается\n"
19944             " * медленно в\n"
19945             " * гору\n"
19946             " * Лошадка,\n"
19947             " * везущая\n"
19948             " * хворосту\n"
19949             " * воз. */",
19950             format("/* Гляжу, поднимается медленно в гору\n"
19951                    " * Лошадка, везущая хворосту воз. */",
19952                    getLLVMStyleWithColumns(13)));
19953   EXPECT_EQ(
19954       "/* 一二三\n"
19955       " * 四五六七\n"
19956       " * 八  九\n"
19957       " * 十  */",
19958       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
19959   EXPECT_EQ("/* �������� ��������\n"
19960             " * ��������\n"
19961             " * ������-�� */",
19962             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
19963 }
19964 
19965 #endif // _MSC_VER
19966 
19967 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
19968   FormatStyle Style = getLLVMStyle();
19969 
19970   Style.ConstructorInitializerIndentWidth = 4;
19971   verifyFormat(
19972       "SomeClass::Constructor()\n"
19973       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19974       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19975       Style);
19976 
19977   Style.ConstructorInitializerIndentWidth = 2;
19978   verifyFormat(
19979       "SomeClass::Constructor()\n"
19980       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19981       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19982       Style);
19983 
19984   Style.ConstructorInitializerIndentWidth = 0;
19985   verifyFormat(
19986       "SomeClass::Constructor()\n"
19987       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19988       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19989       Style);
19990   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19991   verifyFormat(
19992       "SomeLongTemplateVariableName<\n"
19993       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
19994       Style);
19995   verifyFormat("bool smaller = 1 < "
19996                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
19997                "                       "
19998                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
19999                Style);
20000 
20001   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
20002   verifyFormat("SomeClass::Constructor() :\n"
20003                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
20004                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
20005                Style);
20006 }
20007 
20008 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
20009   FormatStyle Style = getLLVMStyle();
20010   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20011   Style.ConstructorInitializerIndentWidth = 4;
20012   verifyFormat("SomeClass::Constructor()\n"
20013                "    : a(a)\n"
20014                "    , b(b)\n"
20015                "    , c(c) {}",
20016                Style);
20017   verifyFormat("SomeClass::Constructor()\n"
20018                "    : a(a) {}",
20019                Style);
20020 
20021   Style.ColumnLimit = 0;
20022   verifyFormat("SomeClass::Constructor()\n"
20023                "    : a(a) {}",
20024                Style);
20025   verifyFormat("SomeClass::Constructor() noexcept\n"
20026                "    : a(a) {}",
20027                Style);
20028   verifyFormat("SomeClass::Constructor()\n"
20029                "    : a(a)\n"
20030                "    , b(b)\n"
20031                "    , c(c) {}",
20032                Style);
20033   verifyFormat("SomeClass::Constructor()\n"
20034                "    : a(a) {\n"
20035                "  foo();\n"
20036                "  bar();\n"
20037                "}",
20038                Style);
20039 
20040   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
20041   verifyFormat("SomeClass::Constructor()\n"
20042                "    : a(a)\n"
20043                "    , b(b)\n"
20044                "    , c(c) {\n}",
20045                Style);
20046   verifyFormat("SomeClass::Constructor()\n"
20047                "    : a(a) {\n}",
20048                Style);
20049 
20050   Style.ColumnLimit = 80;
20051   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
20052   Style.ConstructorInitializerIndentWidth = 2;
20053   verifyFormat("SomeClass::Constructor()\n"
20054                "  : a(a)\n"
20055                "  , b(b)\n"
20056                "  , c(c) {}",
20057                Style);
20058 
20059   Style.ConstructorInitializerIndentWidth = 0;
20060   verifyFormat("SomeClass::Constructor()\n"
20061                ": a(a)\n"
20062                ", b(b)\n"
20063                ", c(c) {}",
20064                Style);
20065 
20066   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20067   Style.ConstructorInitializerIndentWidth = 4;
20068   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
20069   verifyFormat(
20070       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
20071       Style);
20072   verifyFormat(
20073       "SomeClass::Constructor()\n"
20074       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
20075       Style);
20076   Style.ConstructorInitializerIndentWidth = 4;
20077   Style.ColumnLimit = 60;
20078   verifyFormat("SomeClass::Constructor()\n"
20079                "    : aaaaaaaa(aaaaaaaa)\n"
20080                "    , aaaaaaaa(aaaaaaaa)\n"
20081                "    , aaaaaaaa(aaaaaaaa) {}",
20082                Style);
20083 }
20084 
20085 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
20086   FormatStyle Style = getLLVMStyle();
20087   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20088   Style.ConstructorInitializerIndentWidth = 4;
20089   verifyFormat("SomeClass::Constructor()\n"
20090                "    : a{a}\n"
20091                "    , b{b} {}",
20092                Style);
20093   verifyFormat("SomeClass::Constructor()\n"
20094                "    : a{a}\n"
20095                "#if CONDITION\n"
20096                "    , b{b}\n"
20097                "#endif\n"
20098                "{\n}",
20099                Style);
20100   Style.ConstructorInitializerIndentWidth = 2;
20101   verifyFormat("SomeClass::Constructor()\n"
20102                "#if CONDITION\n"
20103                "  : a{a}\n"
20104                "#endif\n"
20105                "  , b{b}\n"
20106                "  , c{c} {\n}",
20107                Style);
20108   Style.ConstructorInitializerIndentWidth = 0;
20109   verifyFormat("SomeClass::Constructor()\n"
20110                ": a{a}\n"
20111                "#ifdef CONDITION\n"
20112                ", b{b}\n"
20113                "#else\n"
20114                ", c{c}\n"
20115                "#endif\n"
20116                ", d{d} {\n}",
20117                Style);
20118   Style.ConstructorInitializerIndentWidth = 4;
20119   verifyFormat("SomeClass::Constructor()\n"
20120                "    : a{a}\n"
20121                "#if WINDOWS\n"
20122                "#if DEBUG\n"
20123                "    , b{0}\n"
20124                "#else\n"
20125                "    , b{1}\n"
20126                "#endif\n"
20127                "#else\n"
20128                "#if DEBUG\n"
20129                "    , b{2}\n"
20130                "#else\n"
20131                "    , b{3}\n"
20132                "#endif\n"
20133                "#endif\n"
20134                "{\n}",
20135                Style);
20136   verifyFormat("SomeClass::Constructor()\n"
20137                "    : a{a}\n"
20138                "#if WINDOWS\n"
20139                "    , b{0}\n"
20140                "#if DEBUG\n"
20141                "    , c{0}\n"
20142                "#else\n"
20143                "    , c{1}\n"
20144                "#endif\n"
20145                "#else\n"
20146                "#if DEBUG\n"
20147                "    , c{2}\n"
20148                "#else\n"
20149                "    , c{3}\n"
20150                "#endif\n"
20151                "    , b{1}\n"
20152                "#endif\n"
20153                "{\n}",
20154                Style);
20155 }
20156 
20157 TEST_F(FormatTest, Destructors) {
20158   verifyFormat("void F(int &i) { i.~int(); }");
20159   verifyFormat("void F(int &i) { i->~int(); }");
20160 }
20161 
20162 TEST_F(FormatTest, FormatsWithWebKitStyle) {
20163   FormatStyle Style = getWebKitStyle();
20164 
20165   // Don't indent in outer namespaces.
20166   verifyFormat("namespace outer {\n"
20167                "int i;\n"
20168                "namespace inner {\n"
20169                "    int i;\n"
20170                "} // namespace inner\n"
20171                "} // namespace outer\n"
20172                "namespace other_outer {\n"
20173                "int i;\n"
20174                "}",
20175                Style);
20176 
20177   // Don't indent case labels.
20178   verifyFormat("switch (variable) {\n"
20179                "case 1:\n"
20180                "case 2:\n"
20181                "    doSomething();\n"
20182                "    break;\n"
20183                "default:\n"
20184                "    ++variable;\n"
20185                "}",
20186                Style);
20187 
20188   // Wrap before binary operators.
20189   EXPECT_EQ("void f()\n"
20190             "{\n"
20191             "    if (aaaaaaaaaaaaaaaa\n"
20192             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
20193             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20194             "        return;\n"
20195             "}",
20196             format("void f() {\n"
20197                    "if (aaaaaaaaaaaaaaaa\n"
20198                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
20199                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20200                    "return;\n"
20201                    "}",
20202                    Style));
20203 
20204   // Allow functions on a single line.
20205   verifyFormat("void f() { return; }", Style);
20206 
20207   // Allow empty blocks on a single line and insert a space in empty blocks.
20208   EXPECT_EQ("void f() { }", format("void f() {}", Style));
20209   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
20210   // However, don't merge non-empty short loops.
20211   EXPECT_EQ("while (true) {\n"
20212             "    continue;\n"
20213             "}",
20214             format("while (true) { continue; }", Style));
20215 
20216   // Constructor initializers are formatted one per line with the "," on the
20217   // new line.
20218   verifyFormat("Constructor()\n"
20219                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
20220                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
20221                "          aaaaaaaaaaaaaa)\n"
20222                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
20223                "{\n"
20224                "}",
20225                Style);
20226   verifyFormat("SomeClass::Constructor()\n"
20227                "    : a(a)\n"
20228                "{\n"
20229                "}",
20230                Style);
20231   EXPECT_EQ("SomeClass::Constructor()\n"
20232             "    : a(a)\n"
20233             "{\n"
20234             "}",
20235             format("SomeClass::Constructor():a(a){}", Style));
20236   verifyFormat("SomeClass::Constructor()\n"
20237                "    : a(a)\n"
20238                "    , b(b)\n"
20239                "    , c(c)\n"
20240                "{\n"
20241                "}",
20242                Style);
20243   verifyFormat("SomeClass::Constructor()\n"
20244                "    : a(a)\n"
20245                "{\n"
20246                "    foo();\n"
20247                "    bar();\n"
20248                "}",
20249                Style);
20250 
20251   // Access specifiers should be aligned left.
20252   verifyFormat("class C {\n"
20253                "public:\n"
20254                "    int i;\n"
20255                "};",
20256                Style);
20257 
20258   // Do not align comments.
20259   verifyFormat("int a; // Do not\n"
20260                "double b; // align comments.",
20261                Style);
20262 
20263   // Do not align operands.
20264   EXPECT_EQ("ASSERT(aaaa\n"
20265             "    || bbbb);",
20266             format("ASSERT ( aaaa\n||bbbb);", Style));
20267 
20268   // Accept input's line breaks.
20269   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
20270             "    || bbbbbbbbbbbbbbb) {\n"
20271             "    i++;\n"
20272             "}",
20273             format("if (aaaaaaaaaaaaaaa\n"
20274                    "|| bbbbbbbbbbbbbbb) { i++; }",
20275                    Style));
20276   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
20277             "    i++;\n"
20278             "}",
20279             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
20280 
20281   // Don't automatically break all macro definitions (llvm.org/PR17842).
20282   verifyFormat("#define aNumber 10", Style);
20283   // However, generally keep the line breaks that the user authored.
20284   EXPECT_EQ("#define aNumber \\\n"
20285             "    10",
20286             format("#define aNumber \\\n"
20287                    " 10",
20288                    Style));
20289 
20290   // Keep empty and one-element array literals on a single line.
20291   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
20292             "                                  copyItems:YES];",
20293             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
20294                    "copyItems:YES];",
20295                    Style));
20296   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
20297             "                                  copyItems:YES];",
20298             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
20299                    "             copyItems:YES];",
20300                    Style));
20301   // FIXME: This does not seem right, there should be more indentation before
20302   // the array literal's entries. Nested blocks have the same problem.
20303   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20304             "    @\"a\",\n"
20305             "    @\"a\"\n"
20306             "]\n"
20307             "                                  copyItems:YES];",
20308             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20309                    "     @\"a\",\n"
20310                    "     @\"a\"\n"
20311                    "     ]\n"
20312                    "       copyItems:YES];",
20313                    Style));
20314   EXPECT_EQ(
20315       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20316       "                                  copyItems:YES];",
20317       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20318              "   copyItems:YES];",
20319              Style));
20320 
20321   verifyFormat("[self.a b:c c:d];", Style);
20322   EXPECT_EQ("[self.a b:c\n"
20323             "        c:d];",
20324             format("[self.a b:c\n"
20325                    "c:d];",
20326                    Style));
20327 }
20328 
20329 TEST_F(FormatTest, FormatsLambdas) {
20330   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
20331   verifyFormat(
20332       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
20333   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
20334   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
20335   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
20336   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
20337   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
20338   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
20339   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
20340   verifyFormat("int x = f(*+[] {});");
20341   verifyFormat("void f() {\n"
20342                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
20343                "}\n");
20344   verifyFormat("void f() {\n"
20345                "  other(x.begin(), //\n"
20346                "        x.end(),   //\n"
20347                "        [&](int, int) { return 1; });\n"
20348                "}\n");
20349   verifyFormat("void f() {\n"
20350                "  other.other.other.other.other(\n"
20351                "      x.begin(), x.end(),\n"
20352                "      [something, rather](int, int, int, int, int, int, int) { "
20353                "return 1; });\n"
20354                "}\n");
20355   verifyFormat(
20356       "void f() {\n"
20357       "  other.other.other.other.other(\n"
20358       "      x.begin(), x.end(),\n"
20359       "      [something, rather](int, int, int, int, int, int, int) {\n"
20360       "        //\n"
20361       "      });\n"
20362       "}\n");
20363   verifyFormat("SomeFunction([]() { // A cool function...\n"
20364                "  return 43;\n"
20365                "});");
20366   EXPECT_EQ("SomeFunction([]() {\n"
20367             "#define A a\n"
20368             "  return 43;\n"
20369             "});",
20370             format("SomeFunction([](){\n"
20371                    "#define A a\n"
20372                    "return 43;\n"
20373                    "});"));
20374   verifyFormat("void f() {\n"
20375                "  SomeFunction([](decltype(x), A *a) {});\n"
20376                "  SomeFunction([](typeof(x), A *a) {});\n"
20377                "  SomeFunction([](_Atomic(x), A *a) {});\n"
20378                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
20379                "}");
20380   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20381                "    [](const aaaaaaaaaa &a) { return a; });");
20382   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
20383                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
20384                "});");
20385   verifyFormat("Constructor()\n"
20386                "    : Field([] { // comment\n"
20387                "        int i;\n"
20388                "      }) {}");
20389   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
20390                "  return some_parameter.size();\n"
20391                "};");
20392   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
20393                "    [](const string &s) { return s; };");
20394   verifyFormat("int i = aaaaaa ? 1 //\n"
20395                "               : [] {\n"
20396                "                   return 2; //\n"
20397                "                 }();");
20398   verifyFormat("llvm::errs() << \"number of twos is \"\n"
20399                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
20400                "                  return x == 2; // force break\n"
20401                "                });");
20402   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20403                "    [=](int iiiiiiiiiiii) {\n"
20404                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
20405                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
20406                "    });",
20407                getLLVMStyleWithColumns(60));
20408 
20409   verifyFormat("SomeFunction({[&] {\n"
20410                "                // comment\n"
20411                "              },\n"
20412                "              [&] {\n"
20413                "                // comment\n"
20414                "              }});");
20415   verifyFormat("SomeFunction({[&] {\n"
20416                "  // comment\n"
20417                "}});");
20418   verifyFormat(
20419       "virtual aaaaaaaaaaaaaaaa(\n"
20420       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
20421       "    aaaaa aaaaaaaaa);");
20422 
20423   // Lambdas with return types.
20424   verifyFormat("int c = []() -> int { return 2; }();\n");
20425   verifyFormat("int c = []() -> int * { return 2; }();\n");
20426   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
20427   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
20428   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
20429   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
20430   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
20431   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
20432   verifyFormat("[a, a]() -> a<1> {};");
20433   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
20434   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
20435   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
20436   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
20437   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
20438   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
20439   verifyFormat("[]() -> foo<!5> { return {}; };");
20440   verifyFormat("[]() -> foo<~5> { return {}; };");
20441   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
20442   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
20443   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
20444   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
20445   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
20446   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
20447   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
20448   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
20449   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
20450   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
20451   verifyFormat("namespace bar {\n"
20452                "// broken:\n"
20453                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
20454                "} // namespace bar");
20455   verifyFormat("namespace bar {\n"
20456                "// broken:\n"
20457                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
20458                "} // namespace bar");
20459   verifyFormat("namespace bar {\n"
20460                "// broken:\n"
20461                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
20462                "} // namespace bar");
20463   verifyFormat("namespace bar {\n"
20464                "// broken:\n"
20465                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
20466                "} // namespace bar");
20467   verifyFormat("namespace bar {\n"
20468                "// broken:\n"
20469                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
20470                "} // namespace bar");
20471   verifyFormat("namespace bar {\n"
20472                "// broken:\n"
20473                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
20474                "} // namespace bar");
20475   verifyFormat("namespace bar {\n"
20476                "// broken:\n"
20477                "auto foo{[]() -> foo<!5> { return {}; }};\n"
20478                "} // namespace bar");
20479   verifyFormat("namespace bar {\n"
20480                "// broken:\n"
20481                "auto foo{[]() -> foo<~5> { return {}; }};\n"
20482                "} // namespace bar");
20483   verifyFormat("namespace bar {\n"
20484                "// broken:\n"
20485                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
20486                "} // namespace bar");
20487   verifyFormat("namespace bar {\n"
20488                "// broken:\n"
20489                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
20490                "} // namespace bar");
20491   verifyFormat("namespace bar {\n"
20492                "// broken:\n"
20493                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
20494                "} // namespace bar");
20495   verifyFormat("namespace bar {\n"
20496                "// broken:\n"
20497                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
20498                "} // namespace bar");
20499   verifyFormat("namespace bar {\n"
20500                "// broken:\n"
20501                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
20502                "} // namespace bar");
20503   verifyFormat("namespace bar {\n"
20504                "// broken:\n"
20505                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
20506                "} // namespace bar");
20507   verifyFormat("namespace bar {\n"
20508                "// broken:\n"
20509                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
20510                "} // namespace bar");
20511   verifyFormat("namespace bar {\n"
20512                "// broken:\n"
20513                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
20514                "} // namespace bar");
20515   verifyFormat("namespace bar {\n"
20516                "// broken:\n"
20517                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
20518                "} // namespace bar");
20519   verifyFormat("namespace bar {\n"
20520                "// broken:\n"
20521                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
20522                "} // namespace bar");
20523   verifyFormat("[]() -> a<1> {};");
20524   verifyFormat("[]() -> a<1> { ; };");
20525   verifyFormat("[]() -> a<1> { ; }();");
20526   verifyFormat("[a, a]() -> a<true> {};");
20527   verifyFormat("[]() -> a<true> {};");
20528   verifyFormat("[]() -> a<true> { ; };");
20529   verifyFormat("[]() -> a<true> { ; }();");
20530   verifyFormat("[a, a]() -> a<false> {};");
20531   verifyFormat("[]() -> a<false> {};");
20532   verifyFormat("[]() -> a<false> { ; };");
20533   verifyFormat("[]() -> a<false> { ; }();");
20534   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
20535   verifyFormat("namespace bar {\n"
20536                "auto foo{[]() -> foo<false> { ; }};\n"
20537                "} // namespace bar");
20538   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
20539                "                   int j) -> int {\n"
20540                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
20541                "};");
20542   verifyFormat(
20543       "aaaaaaaaaaaaaaaaaaaaaa(\n"
20544       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
20545       "      return aaaaaaaaaaaaaaaaa;\n"
20546       "    });",
20547       getLLVMStyleWithColumns(70));
20548   verifyFormat("[]() //\n"
20549                "    -> int {\n"
20550                "  return 1; //\n"
20551                "};");
20552   verifyFormat("[]() -> Void<T...> {};");
20553   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
20554   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
20555   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
20556   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
20557   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
20558   verifyFormat("return int{[x = x]() { return x; }()};");
20559 
20560   // Lambdas with explicit template argument lists.
20561   verifyFormat(
20562       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
20563   verifyFormat("auto L = []<class T>(T) {\n"
20564                "  {\n"
20565                "    f();\n"
20566                "    g();\n"
20567                "  }\n"
20568                "};\n");
20569   verifyFormat("auto L = []<class... T>(T...) {\n"
20570                "  {\n"
20571                "    f();\n"
20572                "    g();\n"
20573                "  }\n"
20574                "};\n");
20575   verifyFormat("auto L = []<typename... T>(T...) {\n"
20576                "  {\n"
20577                "    f();\n"
20578                "    g();\n"
20579                "  }\n"
20580                "};\n");
20581   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
20582                "  {\n"
20583                "    f();\n"
20584                "    g();\n"
20585                "  }\n"
20586                "};\n");
20587   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
20588                "  {\n"
20589                "    f();\n"
20590                "    g();\n"
20591                "  }\n"
20592                "};\n");
20593 
20594   // Multiple lambdas in the same parentheses change indentation rules. These
20595   // lambdas are forced to start on new lines.
20596   verifyFormat("SomeFunction(\n"
20597                "    []() {\n"
20598                "      //\n"
20599                "    },\n"
20600                "    []() {\n"
20601                "      //\n"
20602                "    });");
20603 
20604   // A lambda passed as arg0 is always pushed to the next line.
20605   verifyFormat("SomeFunction(\n"
20606                "    [this] {\n"
20607                "      //\n"
20608                "    },\n"
20609                "    1);\n");
20610 
20611   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
20612   // the arg0 case above.
20613   auto Style = getGoogleStyle();
20614   Style.BinPackArguments = false;
20615   verifyFormat("SomeFunction(\n"
20616                "    a,\n"
20617                "    [this] {\n"
20618                "      //\n"
20619                "    },\n"
20620                "    b);\n",
20621                Style);
20622   verifyFormat("SomeFunction(\n"
20623                "    a,\n"
20624                "    [this] {\n"
20625                "      //\n"
20626                "    },\n"
20627                "    b);\n");
20628 
20629   // A lambda with a very long line forces arg0 to be pushed out irrespective of
20630   // the BinPackArguments value (as long as the code is wide enough).
20631   verifyFormat(
20632       "something->SomeFunction(\n"
20633       "    a,\n"
20634       "    [this] {\n"
20635       "      "
20636       "D0000000000000000000000000000000000000000000000000000000000001();\n"
20637       "    },\n"
20638       "    b);\n");
20639 
20640   // A multi-line lambda is pulled up as long as the introducer fits on the
20641   // previous line and there are no further args.
20642   verifyFormat("function(1, [this, that] {\n"
20643                "  //\n"
20644                "});\n");
20645   verifyFormat("function([this, that] {\n"
20646                "  //\n"
20647                "});\n");
20648   // FIXME: this format is not ideal and we should consider forcing the first
20649   // arg onto its own line.
20650   verifyFormat("function(a, b, c, //\n"
20651                "         d, [this, that] {\n"
20652                "           //\n"
20653                "         });\n");
20654 
20655   // Multiple lambdas are treated correctly even when there is a short arg0.
20656   verifyFormat("SomeFunction(\n"
20657                "    1,\n"
20658                "    [this] {\n"
20659                "      //\n"
20660                "    },\n"
20661                "    [this] {\n"
20662                "      //\n"
20663                "    },\n"
20664                "    1);\n");
20665 
20666   // More complex introducers.
20667   verifyFormat("return [i, args...] {};");
20668 
20669   // Not lambdas.
20670   verifyFormat("constexpr char hello[]{\"hello\"};");
20671   verifyFormat("double &operator[](int i) { return 0; }\n"
20672                "int i;");
20673   verifyFormat("std::unique_ptr<int[]> foo() {}");
20674   verifyFormat("int i = a[a][a]->f();");
20675   verifyFormat("int i = (*b)[a]->f();");
20676 
20677   // Other corner cases.
20678   verifyFormat("void f() {\n"
20679                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
20680                "  );\n"
20681                "}");
20682 
20683   // Lambdas created through weird macros.
20684   verifyFormat("void f() {\n"
20685                "  MACRO((const AA &a) { return 1; });\n"
20686                "  MACRO((AA &a) { return 1; });\n"
20687                "}");
20688 
20689   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
20690                "      doo_dah();\n"
20691                "      doo_dah();\n"
20692                "    })) {\n"
20693                "}");
20694   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
20695                "                doo_dah();\n"
20696                "                doo_dah();\n"
20697                "              })) {\n"
20698                "}");
20699   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
20700                "                doo_dah();\n"
20701                "                doo_dah();\n"
20702                "              })) {\n"
20703                "}");
20704   verifyFormat("auto lambda = []() {\n"
20705                "  int a = 2\n"
20706                "#if A\n"
20707                "          + 2\n"
20708                "#endif\n"
20709                "      ;\n"
20710                "};");
20711 
20712   // Lambdas with complex multiline introducers.
20713   verifyFormat(
20714       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20715       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
20716       "        -> ::std::unordered_set<\n"
20717       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
20718       "      //\n"
20719       "    });");
20720 
20721   FormatStyle DoNotMerge = getLLVMStyle();
20722   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
20723   verifyFormat("auto c = []() {\n"
20724                "  return b;\n"
20725                "};",
20726                "auto c = []() { return b; };", DoNotMerge);
20727   verifyFormat("auto c = []() {\n"
20728                "};",
20729                " auto c = []() {};", DoNotMerge);
20730 
20731   FormatStyle MergeEmptyOnly = getLLVMStyle();
20732   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
20733   verifyFormat("auto c = []() {\n"
20734                "  return b;\n"
20735                "};",
20736                "auto c = []() {\n"
20737                "  return b;\n"
20738                " };",
20739                MergeEmptyOnly);
20740   verifyFormat("auto c = []() {};",
20741                "auto c = []() {\n"
20742                "};",
20743                MergeEmptyOnly);
20744 
20745   FormatStyle MergeInline = getLLVMStyle();
20746   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
20747   verifyFormat("auto c = []() {\n"
20748                "  return b;\n"
20749                "};",
20750                "auto c = []() { return b; };", MergeInline);
20751   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
20752                MergeInline);
20753   verifyFormat("function([]() { return b; }, a)",
20754                "function([]() { return b; }, a)", MergeInline);
20755   verifyFormat("function(a, []() { return b; })",
20756                "function(a, []() { return b; })", MergeInline);
20757 
20758   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
20759   // AllowShortLambdasOnASingleLine
20760   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
20761   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
20762   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
20763   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20764       FormatStyle::ShortLambdaStyle::SLS_None;
20765   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
20766                "    []()\n"
20767                "    {\n"
20768                "      return 17;\n"
20769                "    });",
20770                LLVMWithBeforeLambdaBody);
20771   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
20772                "    []()\n"
20773                "    {\n"
20774                "    });",
20775                LLVMWithBeforeLambdaBody);
20776   verifyFormat("auto fct_SLS_None = []()\n"
20777                "{\n"
20778                "  return 17;\n"
20779                "};",
20780                LLVMWithBeforeLambdaBody);
20781   verifyFormat("TwoNestedLambdas_SLS_None(\n"
20782                "    []()\n"
20783                "    {\n"
20784                "      return Call(\n"
20785                "          []()\n"
20786                "          {\n"
20787                "            return 17;\n"
20788                "          });\n"
20789                "    });",
20790                LLVMWithBeforeLambdaBody);
20791   verifyFormat("void Fct() {\n"
20792                "  return {[]()\n"
20793                "          {\n"
20794                "            return 17;\n"
20795                "          }};\n"
20796                "}",
20797                LLVMWithBeforeLambdaBody);
20798 
20799   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20800       FormatStyle::ShortLambdaStyle::SLS_Empty;
20801   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
20802                "    []()\n"
20803                "    {\n"
20804                "      return 17;\n"
20805                "    });",
20806                LLVMWithBeforeLambdaBody);
20807   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
20808                LLVMWithBeforeLambdaBody);
20809   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
20810                "ongFunctionName_SLS_Empty(\n"
20811                "    []() {});",
20812                LLVMWithBeforeLambdaBody);
20813   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
20814                "                                []()\n"
20815                "                                {\n"
20816                "                                  return 17;\n"
20817                "                                });",
20818                LLVMWithBeforeLambdaBody);
20819   verifyFormat("auto fct_SLS_Empty = []()\n"
20820                "{\n"
20821                "  return 17;\n"
20822                "};",
20823                LLVMWithBeforeLambdaBody);
20824   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
20825                "    []()\n"
20826                "    {\n"
20827                "      return Call([]() {});\n"
20828                "    });",
20829                LLVMWithBeforeLambdaBody);
20830   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
20831                "                           []()\n"
20832                "                           {\n"
20833                "                             return Call([]() {});\n"
20834                "                           });",
20835                LLVMWithBeforeLambdaBody);
20836   verifyFormat(
20837       "FctWithLongLineInLambda_SLS_Empty(\n"
20838       "    []()\n"
20839       "    {\n"
20840       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20841       "                               AndShouldNotBeConsiderAsInline,\n"
20842       "                               LambdaBodyMustBeBreak);\n"
20843       "    });",
20844       LLVMWithBeforeLambdaBody);
20845 
20846   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20847       FormatStyle::ShortLambdaStyle::SLS_Inline;
20848   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
20849                LLVMWithBeforeLambdaBody);
20850   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
20851                LLVMWithBeforeLambdaBody);
20852   verifyFormat("auto fct_SLS_Inline = []()\n"
20853                "{\n"
20854                "  return 17;\n"
20855                "};",
20856                LLVMWithBeforeLambdaBody);
20857   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
20858                "17; }); });",
20859                LLVMWithBeforeLambdaBody);
20860   verifyFormat(
20861       "FctWithLongLineInLambda_SLS_Inline(\n"
20862       "    []()\n"
20863       "    {\n"
20864       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20865       "                               AndShouldNotBeConsiderAsInline,\n"
20866       "                               LambdaBodyMustBeBreak);\n"
20867       "    });",
20868       LLVMWithBeforeLambdaBody);
20869   verifyFormat("FctWithMultipleParams_SLS_Inline("
20870                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20871                "                                 []() { return 17; });",
20872                LLVMWithBeforeLambdaBody);
20873   verifyFormat(
20874       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
20875       LLVMWithBeforeLambdaBody);
20876 
20877   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20878       FormatStyle::ShortLambdaStyle::SLS_All;
20879   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
20880                LLVMWithBeforeLambdaBody);
20881   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
20882                LLVMWithBeforeLambdaBody);
20883   verifyFormat("auto fct_SLS_All = []() { return 17; };",
20884                LLVMWithBeforeLambdaBody);
20885   verifyFormat("FctWithOneParam_SLS_All(\n"
20886                "    []()\n"
20887                "    {\n"
20888                "      // A cool function...\n"
20889                "      return 43;\n"
20890                "    });",
20891                LLVMWithBeforeLambdaBody);
20892   verifyFormat("FctWithMultipleParams_SLS_All("
20893                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20894                "                              []() { return 17; });",
20895                LLVMWithBeforeLambdaBody);
20896   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
20897                LLVMWithBeforeLambdaBody);
20898   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
20899                LLVMWithBeforeLambdaBody);
20900   verifyFormat(
20901       "FctWithLongLineInLambda_SLS_All(\n"
20902       "    []()\n"
20903       "    {\n"
20904       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20905       "                               AndShouldNotBeConsiderAsInline,\n"
20906       "                               LambdaBodyMustBeBreak);\n"
20907       "    });",
20908       LLVMWithBeforeLambdaBody);
20909   verifyFormat(
20910       "auto fct_SLS_All = []()\n"
20911       "{\n"
20912       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20913       "                           AndShouldNotBeConsiderAsInline,\n"
20914       "                           LambdaBodyMustBeBreak);\n"
20915       "};",
20916       LLVMWithBeforeLambdaBody);
20917   LLVMWithBeforeLambdaBody.BinPackParameters = false;
20918   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
20919                LLVMWithBeforeLambdaBody);
20920   verifyFormat(
20921       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
20922       "                                FirstParam,\n"
20923       "                                SecondParam,\n"
20924       "                                ThirdParam,\n"
20925       "                                FourthParam);",
20926       LLVMWithBeforeLambdaBody);
20927   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20928                "    []() { return "
20929                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
20930                "    FirstParam,\n"
20931                "    SecondParam,\n"
20932                "    ThirdParam,\n"
20933                "    FourthParam);",
20934                LLVMWithBeforeLambdaBody);
20935   verifyFormat(
20936       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
20937       "                                SecondParam,\n"
20938       "                                ThirdParam,\n"
20939       "                                FourthParam,\n"
20940       "                                []() { return SomeValueNotSoLong; });",
20941       LLVMWithBeforeLambdaBody);
20942   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20943                "    []()\n"
20944                "    {\n"
20945                "      return "
20946                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
20947                "eConsiderAsInline;\n"
20948                "    });",
20949                LLVMWithBeforeLambdaBody);
20950   verifyFormat(
20951       "FctWithLongLineInLambda_SLS_All(\n"
20952       "    []()\n"
20953       "    {\n"
20954       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20955       "                               AndShouldNotBeConsiderAsInline,\n"
20956       "                               LambdaBodyMustBeBreak);\n"
20957       "    });",
20958       LLVMWithBeforeLambdaBody);
20959   verifyFormat("FctWithTwoParams_SLS_All(\n"
20960                "    []()\n"
20961                "    {\n"
20962                "      // A cool function...\n"
20963                "      return 43;\n"
20964                "    },\n"
20965                "    87);",
20966                LLVMWithBeforeLambdaBody);
20967   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
20968                LLVMWithBeforeLambdaBody);
20969   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
20970                LLVMWithBeforeLambdaBody);
20971   verifyFormat(
20972       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
20973       LLVMWithBeforeLambdaBody);
20974   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
20975                "}); }, x);",
20976                LLVMWithBeforeLambdaBody);
20977   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20978                "    []()\n"
20979                "    {\n"
20980                "      // A cool function...\n"
20981                "      return Call([]() { return 17; });\n"
20982                "    });",
20983                LLVMWithBeforeLambdaBody);
20984   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20985                "    []()\n"
20986                "    {\n"
20987                "      return Call(\n"
20988                "          []()\n"
20989                "          {\n"
20990                "            // A cool function...\n"
20991                "            return 17;\n"
20992                "          });\n"
20993                "    });",
20994                LLVMWithBeforeLambdaBody);
20995 
20996   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20997       FormatStyle::ShortLambdaStyle::SLS_None;
20998 
20999   verifyFormat("auto select = [this]() -> const Library::Object *\n"
21000                "{\n"
21001                "  return MyAssignment::SelectFromList(this);\n"
21002                "};\n",
21003                LLVMWithBeforeLambdaBody);
21004 
21005   verifyFormat("auto select = [this]() -> const Library::Object &\n"
21006                "{\n"
21007                "  return MyAssignment::SelectFromList(this);\n"
21008                "};\n",
21009                LLVMWithBeforeLambdaBody);
21010 
21011   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
21012                "{\n"
21013                "  return MyAssignment::SelectFromList(this);\n"
21014                "};\n",
21015                LLVMWithBeforeLambdaBody);
21016 
21017   verifyFormat("namespace test {\n"
21018                "class Test {\n"
21019                "public:\n"
21020                "  Test() = default;\n"
21021                "};\n"
21022                "} // namespace test",
21023                LLVMWithBeforeLambdaBody);
21024 
21025   // Lambdas with different indentation styles.
21026   Style = getLLVMStyleWithColumns(100);
21027   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21028             "  return promise.then(\n"
21029             "      [this, &someVariable, someObject = "
21030             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21031             "        return someObject.startAsyncAction().then(\n"
21032             "            [this, &someVariable](AsyncActionResult result) "
21033             "mutable { result.processMore(); });\n"
21034             "      });\n"
21035             "}\n",
21036             format("SomeResult doSomething(SomeObject promise) {\n"
21037                    "  return promise.then([this, &someVariable, someObject = "
21038                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21039                    "    return someObject.startAsyncAction().then([this, "
21040                    "&someVariable](AsyncActionResult result) mutable {\n"
21041                    "      result.processMore();\n"
21042                    "    });\n"
21043                    "  });\n"
21044                    "}\n",
21045                    Style));
21046   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21047   verifyFormat("test() {\n"
21048                "  ([]() -> {\n"
21049                "    int b = 32;\n"
21050                "    return 3;\n"
21051                "  }).foo();\n"
21052                "}",
21053                Style);
21054   verifyFormat("test() {\n"
21055                "  []() -> {\n"
21056                "    int b = 32;\n"
21057                "    return 3;\n"
21058                "  }\n"
21059                "}",
21060                Style);
21061   verifyFormat("std::sort(v.begin(), v.end(),\n"
21062                "          [](const auto &someLongArgumentName, const auto "
21063                "&someOtherLongArgumentName) {\n"
21064                "  return someLongArgumentName.someMemberVariable < "
21065                "someOtherLongArgumentName.someMemberVariable;\n"
21066                "});",
21067                Style);
21068   verifyFormat("test() {\n"
21069                "  (\n"
21070                "      []() -> {\n"
21071                "        int b = 32;\n"
21072                "        return 3;\n"
21073                "      },\n"
21074                "      foo, bar)\n"
21075                "      .foo();\n"
21076                "}",
21077                Style);
21078   verifyFormat("test() {\n"
21079                "  ([]() -> {\n"
21080                "    int b = 32;\n"
21081                "    return 3;\n"
21082                "  })\n"
21083                "      .foo()\n"
21084                "      .bar();\n"
21085                "}",
21086                Style);
21087   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21088             "  return promise.then(\n"
21089             "      [this, &someVariable, someObject = "
21090             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21091             "    return someObject.startAsyncAction().then(\n"
21092             "        [this, &someVariable](AsyncActionResult result) mutable { "
21093             "result.processMore(); });\n"
21094             "  });\n"
21095             "}\n",
21096             format("SomeResult doSomething(SomeObject promise) {\n"
21097                    "  return promise.then([this, &someVariable, someObject = "
21098                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21099                    "    return someObject.startAsyncAction().then([this, "
21100                    "&someVariable](AsyncActionResult result) mutable {\n"
21101                    "      result.processMore();\n"
21102                    "    });\n"
21103                    "  });\n"
21104                    "}\n",
21105                    Style));
21106   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21107             "  return promise.then([this, &someVariable] {\n"
21108             "    return someObject.startAsyncAction().then(\n"
21109             "        [this, &someVariable](AsyncActionResult result) mutable { "
21110             "result.processMore(); });\n"
21111             "  });\n"
21112             "}\n",
21113             format("SomeResult doSomething(SomeObject promise) {\n"
21114                    "  return promise.then([this, &someVariable] {\n"
21115                    "    return someObject.startAsyncAction().then([this, "
21116                    "&someVariable](AsyncActionResult result) mutable {\n"
21117                    "      result.processMore();\n"
21118                    "    });\n"
21119                    "  });\n"
21120                    "}\n",
21121                    Style));
21122   Style = getGoogleStyle();
21123   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21124   EXPECT_EQ("#define A                                       \\\n"
21125             "  [] {                                          \\\n"
21126             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
21127             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
21128             "      }",
21129             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
21130                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
21131                    Style));
21132   // TODO: The current formatting has a minor issue that's not worth fixing
21133   // right now whereby the closing brace is indented relative to the signature
21134   // instead of being aligned. This only happens with macros.
21135 }
21136 
21137 TEST_F(FormatTest, LambdaWithLineComments) {
21138   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21139   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21140   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21141   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21142       FormatStyle::ShortLambdaStyle::SLS_All;
21143 
21144   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
21145   verifyFormat("auto k = []() // comment\n"
21146                "{ return; }",
21147                LLVMWithBeforeLambdaBody);
21148   verifyFormat("auto k = []() /* comment */ { return; }",
21149                LLVMWithBeforeLambdaBody);
21150   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
21151                LLVMWithBeforeLambdaBody);
21152   verifyFormat("auto k = []() // X\n"
21153                "{ return; }",
21154                LLVMWithBeforeLambdaBody);
21155   verifyFormat(
21156       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
21157       "{ return; }",
21158       LLVMWithBeforeLambdaBody);
21159 }
21160 
21161 TEST_F(FormatTest, EmptyLinesInLambdas) {
21162   verifyFormat("auto lambda = []() {\n"
21163                "  x(); //\n"
21164                "};",
21165                "auto lambda = []() {\n"
21166                "\n"
21167                "  x(); //\n"
21168                "\n"
21169                "};");
21170 }
21171 
21172 TEST_F(FormatTest, FormatsBlocks) {
21173   FormatStyle ShortBlocks = getLLVMStyle();
21174   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21175   verifyFormat("int (^Block)(int, int);", ShortBlocks);
21176   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
21177   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
21178   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
21179   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
21180   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
21181 
21182   verifyFormat("foo(^{ bar(); });", ShortBlocks);
21183   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
21184   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
21185 
21186   verifyFormat("[operation setCompletionBlock:^{\n"
21187                "  [self onOperationDone];\n"
21188                "}];");
21189   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
21190                "  [self onOperationDone];\n"
21191                "}]};");
21192   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
21193                "  f();\n"
21194                "}];");
21195   verifyFormat("int a = [operation block:^int(int *i) {\n"
21196                "  return 1;\n"
21197                "}];");
21198   verifyFormat("[myObject doSomethingWith:arg1\n"
21199                "                      aaa:^int(int *a) {\n"
21200                "                        return 1;\n"
21201                "                      }\n"
21202                "                      bbb:f(a * bbbbbbbb)];");
21203 
21204   verifyFormat("[operation setCompletionBlock:^{\n"
21205                "  [self.delegate newDataAvailable];\n"
21206                "}];",
21207                getLLVMStyleWithColumns(60));
21208   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
21209                "  NSString *path = [self sessionFilePath];\n"
21210                "  if (path) {\n"
21211                "    // ...\n"
21212                "  }\n"
21213                "});");
21214   verifyFormat("[[SessionService sharedService]\n"
21215                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21216                "      if (window) {\n"
21217                "        [self windowDidLoad:window];\n"
21218                "      } else {\n"
21219                "        [self errorLoadingWindow];\n"
21220                "      }\n"
21221                "    }];");
21222   verifyFormat("void (^largeBlock)(void) = ^{\n"
21223                "  // ...\n"
21224                "};\n",
21225                getLLVMStyleWithColumns(40));
21226   verifyFormat("[[SessionService sharedService]\n"
21227                "    loadWindowWithCompletionBlock: //\n"
21228                "        ^(SessionWindow *window) {\n"
21229                "          if (window) {\n"
21230                "            [self windowDidLoad:window];\n"
21231                "          } else {\n"
21232                "            [self errorLoadingWindow];\n"
21233                "          }\n"
21234                "        }];",
21235                getLLVMStyleWithColumns(60));
21236   verifyFormat("[myObject doSomethingWith:arg1\n"
21237                "    firstBlock:^(Foo *a) {\n"
21238                "      // ...\n"
21239                "      int i;\n"
21240                "    }\n"
21241                "    secondBlock:^(Bar *b) {\n"
21242                "      // ...\n"
21243                "      int i;\n"
21244                "    }\n"
21245                "    thirdBlock:^Foo(Bar *b) {\n"
21246                "      // ...\n"
21247                "      int i;\n"
21248                "    }];");
21249   verifyFormat("[myObject doSomethingWith:arg1\n"
21250                "               firstBlock:-1\n"
21251                "              secondBlock:^(Bar *b) {\n"
21252                "                // ...\n"
21253                "                int i;\n"
21254                "              }];");
21255 
21256   verifyFormat("f(^{\n"
21257                "  @autoreleasepool {\n"
21258                "    if (a) {\n"
21259                "      g();\n"
21260                "    }\n"
21261                "  }\n"
21262                "});");
21263   verifyFormat("Block b = ^int *(A *a, B *b) {}");
21264   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
21265                "};");
21266 
21267   FormatStyle FourIndent = getLLVMStyle();
21268   FourIndent.ObjCBlockIndentWidth = 4;
21269   verifyFormat("[operation setCompletionBlock:^{\n"
21270                "    [self onOperationDone];\n"
21271                "}];",
21272                FourIndent);
21273 }
21274 
21275 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
21276   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
21277 
21278   verifyFormat("[[SessionService sharedService] "
21279                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21280                "  if (window) {\n"
21281                "    [self windowDidLoad:window];\n"
21282                "  } else {\n"
21283                "    [self errorLoadingWindow];\n"
21284                "  }\n"
21285                "}];",
21286                ZeroColumn);
21287   EXPECT_EQ("[[SessionService sharedService]\n"
21288             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21289             "      if (window) {\n"
21290             "        [self windowDidLoad:window];\n"
21291             "      } else {\n"
21292             "        [self errorLoadingWindow];\n"
21293             "      }\n"
21294             "    }];",
21295             format("[[SessionService sharedService]\n"
21296                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21297                    "                if (window) {\n"
21298                    "    [self windowDidLoad:window];\n"
21299                    "  } else {\n"
21300                    "    [self errorLoadingWindow];\n"
21301                    "  }\n"
21302                    "}];",
21303                    ZeroColumn));
21304   verifyFormat("[myObject doSomethingWith:arg1\n"
21305                "    firstBlock:^(Foo *a) {\n"
21306                "      // ...\n"
21307                "      int i;\n"
21308                "    }\n"
21309                "    secondBlock:^(Bar *b) {\n"
21310                "      // ...\n"
21311                "      int i;\n"
21312                "    }\n"
21313                "    thirdBlock:^Foo(Bar *b) {\n"
21314                "      // ...\n"
21315                "      int i;\n"
21316                "    }];",
21317                ZeroColumn);
21318   verifyFormat("f(^{\n"
21319                "  @autoreleasepool {\n"
21320                "    if (a) {\n"
21321                "      g();\n"
21322                "    }\n"
21323                "  }\n"
21324                "});",
21325                ZeroColumn);
21326   verifyFormat("void (^largeBlock)(void) = ^{\n"
21327                "  // ...\n"
21328                "};",
21329                ZeroColumn);
21330 
21331   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21332   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
21333             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21334   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
21335   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
21336             "  int i;\n"
21337             "};",
21338             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21339 }
21340 
21341 TEST_F(FormatTest, SupportsCRLF) {
21342   EXPECT_EQ("int a;\r\n"
21343             "int b;\r\n"
21344             "int c;\r\n",
21345             format("int a;\r\n"
21346                    "  int b;\r\n"
21347                    "    int c;\r\n",
21348                    getLLVMStyle()));
21349   EXPECT_EQ("int a;\r\n"
21350             "int b;\r\n"
21351             "int c;\r\n",
21352             format("int a;\r\n"
21353                    "  int b;\n"
21354                    "    int c;\r\n",
21355                    getLLVMStyle()));
21356   EXPECT_EQ("int a;\n"
21357             "int b;\n"
21358             "int c;\n",
21359             format("int a;\r\n"
21360                    "  int b;\n"
21361                    "    int c;\n",
21362                    getLLVMStyle()));
21363   EXPECT_EQ("\"aaaaaaa \"\r\n"
21364             "\"bbbbbbb\";\r\n",
21365             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
21366   EXPECT_EQ("#define A \\\r\n"
21367             "  b;      \\\r\n"
21368             "  c;      \\\r\n"
21369             "  d;\r\n",
21370             format("#define A \\\r\n"
21371                    "  b; \\\r\n"
21372                    "  c; d; \r\n",
21373                    getGoogleStyle()));
21374 
21375   EXPECT_EQ("/*\r\n"
21376             "multi line block comments\r\n"
21377             "should not introduce\r\n"
21378             "an extra carriage return\r\n"
21379             "*/\r\n",
21380             format("/*\r\n"
21381                    "multi line block comments\r\n"
21382                    "should not introduce\r\n"
21383                    "an extra carriage return\r\n"
21384                    "*/\r\n"));
21385   EXPECT_EQ("/*\r\n"
21386             "\r\n"
21387             "*/",
21388             format("/*\r\n"
21389                    "    \r\r\r\n"
21390                    "*/"));
21391 
21392   FormatStyle style = getLLVMStyle();
21393 
21394   style.DeriveLineEnding = true;
21395   style.UseCRLF = false;
21396   EXPECT_EQ("union FooBarBazQux {\n"
21397             "  int foo;\n"
21398             "  int bar;\n"
21399             "  int baz;\n"
21400             "};",
21401             format("union FooBarBazQux {\r\n"
21402                    "  int foo;\n"
21403                    "  int bar;\r\n"
21404                    "  int baz;\n"
21405                    "};",
21406                    style));
21407   style.UseCRLF = true;
21408   EXPECT_EQ("union FooBarBazQux {\r\n"
21409             "  int foo;\r\n"
21410             "  int bar;\r\n"
21411             "  int baz;\r\n"
21412             "};",
21413             format("union FooBarBazQux {\r\n"
21414                    "  int foo;\n"
21415                    "  int bar;\r\n"
21416                    "  int baz;\n"
21417                    "};",
21418                    style));
21419 
21420   style.DeriveLineEnding = false;
21421   style.UseCRLF = false;
21422   EXPECT_EQ("union FooBarBazQux {\n"
21423             "  int foo;\n"
21424             "  int bar;\n"
21425             "  int baz;\n"
21426             "  int qux;\n"
21427             "};",
21428             format("union FooBarBazQux {\r\n"
21429                    "  int foo;\n"
21430                    "  int bar;\r\n"
21431                    "  int baz;\n"
21432                    "  int qux;\r\n"
21433                    "};",
21434                    style));
21435   style.UseCRLF = true;
21436   EXPECT_EQ("union FooBarBazQux {\r\n"
21437             "  int foo;\r\n"
21438             "  int bar;\r\n"
21439             "  int baz;\r\n"
21440             "  int qux;\r\n"
21441             "};",
21442             format("union FooBarBazQux {\r\n"
21443                    "  int foo;\n"
21444                    "  int bar;\r\n"
21445                    "  int baz;\n"
21446                    "  int qux;\n"
21447                    "};",
21448                    style));
21449 
21450   style.DeriveLineEnding = true;
21451   style.UseCRLF = false;
21452   EXPECT_EQ("union FooBarBazQux {\r\n"
21453             "  int foo;\r\n"
21454             "  int bar;\r\n"
21455             "  int baz;\r\n"
21456             "  int qux;\r\n"
21457             "};",
21458             format("union FooBarBazQux {\r\n"
21459                    "  int foo;\n"
21460                    "  int bar;\r\n"
21461                    "  int baz;\n"
21462                    "  int qux;\r\n"
21463                    "};",
21464                    style));
21465   style.UseCRLF = true;
21466   EXPECT_EQ("union FooBarBazQux {\n"
21467             "  int foo;\n"
21468             "  int bar;\n"
21469             "  int baz;\n"
21470             "  int qux;\n"
21471             "};",
21472             format("union FooBarBazQux {\r\n"
21473                    "  int foo;\n"
21474                    "  int bar;\r\n"
21475                    "  int baz;\n"
21476                    "  int qux;\n"
21477                    "};",
21478                    style));
21479 }
21480 
21481 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
21482   verifyFormat("MY_CLASS(C) {\n"
21483                "  int i;\n"
21484                "  int j;\n"
21485                "};");
21486 }
21487 
21488 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
21489   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
21490   TwoIndent.ContinuationIndentWidth = 2;
21491 
21492   EXPECT_EQ("int i =\n"
21493             "  longFunction(\n"
21494             "    arg);",
21495             format("int i = longFunction(arg);", TwoIndent));
21496 
21497   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
21498   SixIndent.ContinuationIndentWidth = 6;
21499 
21500   EXPECT_EQ("int i =\n"
21501             "      longFunction(\n"
21502             "            arg);",
21503             format("int i = longFunction(arg);", SixIndent));
21504 }
21505 
21506 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
21507   FormatStyle Style = getLLVMStyle();
21508   verifyFormat("int Foo::getter(\n"
21509                "    //\n"
21510                ") const {\n"
21511                "  return foo;\n"
21512                "}",
21513                Style);
21514   verifyFormat("void Foo::setter(\n"
21515                "    //\n"
21516                ") {\n"
21517                "  foo = 1;\n"
21518                "}",
21519                Style);
21520 }
21521 
21522 TEST_F(FormatTest, SpacesInAngles) {
21523   FormatStyle Spaces = getLLVMStyle();
21524   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21525 
21526   verifyFormat("vector< ::std::string > x1;", Spaces);
21527   verifyFormat("Foo< int, Bar > x2;", Spaces);
21528   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
21529 
21530   verifyFormat("static_cast< int >(arg);", Spaces);
21531   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
21532   verifyFormat("f< int, float >();", Spaces);
21533   verifyFormat("template <> g() {}", Spaces);
21534   verifyFormat("template < std::vector< int > > f() {}", Spaces);
21535   verifyFormat("std::function< void(int, int) > fct;", Spaces);
21536   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
21537                Spaces);
21538 
21539   Spaces.Standard = FormatStyle::LS_Cpp03;
21540   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21541   verifyFormat("A< A< int > >();", Spaces);
21542 
21543   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
21544   verifyFormat("A<A<int> >();", Spaces);
21545 
21546   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
21547   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
21548                Spaces);
21549   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
21550                Spaces);
21551 
21552   verifyFormat("A<A<int> >();", Spaces);
21553   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
21554   verifyFormat("A< A< int > >();", Spaces);
21555 
21556   Spaces.Standard = FormatStyle::LS_Cpp11;
21557   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21558   verifyFormat("A< A< int > >();", Spaces);
21559 
21560   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
21561   verifyFormat("vector<::std::string> x4;", Spaces);
21562   verifyFormat("vector<int> x5;", Spaces);
21563   verifyFormat("Foo<int, Bar> x6;", Spaces);
21564   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
21565 
21566   verifyFormat("A<A<int>>();", Spaces);
21567 
21568   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
21569   verifyFormat("vector<::std::string> x4;", Spaces);
21570   verifyFormat("vector< ::std::string > x4;", Spaces);
21571   verifyFormat("vector<int> x5;", Spaces);
21572   verifyFormat("vector< int > x5;", Spaces);
21573   verifyFormat("Foo<int, Bar> x6;", Spaces);
21574   verifyFormat("Foo< int, Bar > x6;", Spaces);
21575   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
21576   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
21577 
21578   verifyFormat("A<A<int>>();", Spaces);
21579   verifyFormat("A< A< int > >();", Spaces);
21580   verifyFormat("A<A<int > >();", Spaces);
21581   verifyFormat("A< A< int>>();", Spaces);
21582 
21583   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21584   verifyFormat("// clang-format off\n"
21585                "foo<<<1, 1>>>();\n"
21586                "// clang-format on\n",
21587                Spaces);
21588   verifyFormat("// clang-format off\n"
21589                "foo< < <1, 1> > >();\n"
21590                "// clang-format on\n",
21591                Spaces);
21592 }
21593 
21594 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
21595   FormatStyle Style = getLLVMStyle();
21596   Style.SpaceAfterTemplateKeyword = false;
21597   verifyFormat("template<int> void foo();", Style);
21598 }
21599 
21600 TEST_F(FormatTest, TripleAngleBrackets) {
21601   verifyFormat("f<<<1, 1>>>();");
21602   verifyFormat("f<<<1, 1, 1, s>>>();");
21603   verifyFormat("f<<<a, b, c, d>>>();");
21604   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
21605   verifyFormat("f<param><<<1, 1>>>();");
21606   verifyFormat("f<1><<<1, 1>>>();");
21607   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
21608   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21609                "aaaaaaaaaaa<<<\n    1, 1>>>();");
21610   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
21611                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
21612 }
21613 
21614 TEST_F(FormatTest, MergeLessLessAtEnd) {
21615   verifyFormat("<<");
21616   EXPECT_EQ("< < <", format("\\\n<<<"));
21617   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21618                "aaallvm::outs() <<");
21619   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21620                "aaaallvm::outs()\n    <<");
21621 }
21622 
21623 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
21624   std::string code = "#if A\n"
21625                      "#if B\n"
21626                      "a.\n"
21627                      "#endif\n"
21628                      "    a = 1;\n"
21629                      "#else\n"
21630                      "#endif\n"
21631                      "#if C\n"
21632                      "#else\n"
21633                      "#endif\n";
21634   EXPECT_EQ(code, format(code));
21635 }
21636 
21637 TEST_F(FormatTest, HandleConflictMarkers) {
21638   // Git/SVN conflict markers.
21639   EXPECT_EQ("int a;\n"
21640             "void f() {\n"
21641             "  callme(some(parameter1,\n"
21642             "<<<<<<< text by the vcs\n"
21643             "              parameter2),\n"
21644             "||||||| text by the vcs\n"
21645             "              parameter2),\n"
21646             "         parameter3,\n"
21647             "======= text by the vcs\n"
21648             "              parameter2, parameter3),\n"
21649             ">>>>>>> text by the vcs\n"
21650             "         otherparameter);\n",
21651             format("int a;\n"
21652                    "void f() {\n"
21653                    "  callme(some(parameter1,\n"
21654                    "<<<<<<< text by the vcs\n"
21655                    "  parameter2),\n"
21656                    "||||||| text by the vcs\n"
21657                    "  parameter2),\n"
21658                    "  parameter3,\n"
21659                    "======= text by the vcs\n"
21660                    "  parameter2,\n"
21661                    "  parameter3),\n"
21662                    ">>>>>>> text by the vcs\n"
21663                    "  otherparameter);\n"));
21664 
21665   // Perforce markers.
21666   EXPECT_EQ("void f() {\n"
21667             "  function(\n"
21668             ">>>> text by the vcs\n"
21669             "      parameter,\n"
21670             "==== text by the vcs\n"
21671             "      parameter,\n"
21672             "==== text by the vcs\n"
21673             "      parameter,\n"
21674             "<<<< text by the vcs\n"
21675             "      parameter);\n",
21676             format("void f() {\n"
21677                    "  function(\n"
21678                    ">>>> text by the vcs\n"
21679                    "  parameter,\n"
21680                    "==== text by the vcs\n"
21681                    "  parameter,\n"
21682                    "==== text by the vcs\n"
21683                    "  parameter,\n"
21684                    "<<<< text by the vcs\n"
21685                    "  parameter);\n"));
21686 
21687   EXPECT_EQ("<<<<<<<\n"
21688             "|||||||\n"
21689             "=======\n"
21690             ">>>>>>>",
21691             format("<<<<<<<\n"
21692                    "|||||||\n"
21693                    "=======\n"
21694                    ">>>>>>>"));
21695 
21696   EXPECT_EQ("<<<<<<<\n"
21697             "|||||||\n"
21698             "int i;\n"
21699             "=======\n"
21700             ">>>>>>>",
21701             format("<<<<<<<\n"
21702                    "|||||||\n"
21703                    "int i;\n"
21704                    "=======\n"
21705                    ">>>>>>>"));
21706 
21707   // FIXME: Handle parsing of macros around conflict markers correctly:
21708   EXPECT_EQ("#define Macro \\\n"
21709             "<<<<<<<\n"
21710             "Something \\\n"
21711             "|||||||\n"
21712             "Else \\\n"
21713             "=======\n"
21714             "Other \\\n"
21715             ">>>>>>>\n"
21716             "    End int i;\n",
21717             format("#define Macro \\\n"
21718                    "<<<<<<<\n"
21719                    "  Something \\\n"
21720                    "|||||||\n"
21721                    "  Else \\\n"
21722                    "=======\n"
21723                    "  Other \\\n"
21724                    ">>>>>>>\n"
21725                    "  End\n"
21726                    "int i;\n"));
21727 
21728   verifyFormat(R"(====
21729 #ifdef A
21730 a
21731 #else
21732 b
21733 #endif
21734 )");
21735 }
21736 
21737 TEST_F(FormatTest, DisableRegions) {
21738   EXPECT_EQ("int i;\n"
21739             "// clang-format off\n"
21740             "  int j;\n"
21741             "// clang-format on\n"
21742             "int k;",
21743             format(" int  i;\n"
21744                    "   // clang-format off\n"
21745                    "  int j;\n"
21746                    " // clang-format on\n"
21747                    "   int   k;"));
21748   EXPECT_EQ("int i;\n"
21749             "/* clang-format off */\n"
21750             "  int j;\n"
21751             "/* clang-format on */\n"
21752             "int k;",
21753             format(" int  i;\n"
21754                    "   /* clang-format off */\n"
21755                    "  int j;\n"
21756                    " /* clang-format on */\n"
21757                    "   int   k;"));
21758 
21759   // Don't reflow comments within disabled regions.
21760   EXPECT_EQ("// clang-format off\n"
21761             "// long long long long long long line\n"
21762             "/* clang-format on */\n"
21763             "/* long long long\n"
21764             " * long long long\n"
21765             " * line */\n"
21766             "int i;\n"
21767             "/* clang-format off */\n"
21768             "/* long long long long long long line */\n",
21769             format("// clang-format off\n"
21770                    "// long long long long long long line\n"
21771                    "/* clang-format on */\n"
21772                    "/* long long long long long long line */\n"
21773                    "int i;\n"
21774                    "/* clang-format off */\n"
21775                    "/* long long long long long long line */\n",
21776                    getLLVMStyleWithColumns(20)));
21777 }
21778 
21779 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
21780   format("? ) =");
21781   verifyNoCrash("#define a\\\n /**/}");
21782 }
21783 
21784 TEST_F(FormatTest, FormatsTableGenCode) {
21785   FormatStyle Style = getLLVMStyle();
21786   Style.Language = FormatStyle::LK_TableGen;
21787   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
21788 }
21789 
21790 TEST_F(FormatTest, ArrayOfTemplates) {
21791   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
21792             format("auto a = new unique_ptr<int > [ 10];"));
21793 
21794   FormatStyle Spaces = getLLVMStyle();
21795   Spaces.SpacesInSquareBrackets = true;
21796   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
21797             format("auto a = new unique_ptr<int > [10];", Spaces));
21798 }
21799 
21800 TEST_F(FormatTest, ArrayAsTemplateType) {
21801   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
21802             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
21803 
21804   FormatStyle Spaces = getLLVMStyle();
21805   Spaces.SpacesInSquareBrackets = true;
21806   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
21807             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
21808 }
21809 
21810 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
21811 
21812 TEST(FormatStyle, GetStyleWithEmptyFileName) {
21813   llvm::vfs::InMemoryFileSystem FS;
21814   auto Style1 = getStyle("file", "", "Google", "", &FS);
21815   ASSERT_TRUE((bool)Style1);
21816   ASSERT_EQ(*Style1, getGoogleStyle());
21817 }
21818 
21819 TEST(FormatStyle, GetStyleOfFile) {
21820   llvm::vfs::InMemoryFileSystem FS;
21821   // Test 1: format file in the same directory.
21822   ASSERT_TRUE(
21823       FS.addFile("/a/.clang-format", 0,
21824                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
21825   ASSERT_TRUE(
21826       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21827   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
21828   ASSERT_TRUE((bool)Style1);
21829   ASSERT_EQ(*Style1, getLLVMStyle());
21830 
21831   // Test 2.1: fallback to default.
21832   ASSERT_TRUE(
21833       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21834   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
21835   ASSERT_TRUE((bool)Style2);
21836   ASSERT_EQ(*Style2, getMozillaStyle());
21837 
21838   // Test 2.2: no format on 'none' fallback style.
21839   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21840   ASSERT_TRUE((bool)Style2);
21841   ASSERT_EQ(*Style2, getNoStyle());
21842 
21843   // Test 2.3: format if config is found with no based style while fallback is
21844   // 'none'.
21845   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
21846                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
21847   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21848   ASSERT_TRUE((bool)Style2);
21849   ASSERT_EQ(*Style2, getLLVMStyle());
21850 
21851   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
21852   Style2 = getStyle("{}", "a.h", "none", "", &FS);
21853   ASSERT_TRUE((bool)Style2);
21854   ASSERT_EQ(*Style2, getLLVMStyle());
21855 
21856   // Test 3: format file in parent directory.
21857   ASSERT_TRUE(
21858       FS.addFile("/c/.clang-format", 0,
21859                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21860   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
21861                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21862   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21863   ASSERT_TRUE((bool)Style3);
21864   ASSERT_EQ(*Style3, getGoogleStyle());
21865 
21866   // Test 4: error on invalid fallback style
21867   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
21868   ASSERT_FALSE((bool)Style4);
21869   llvm::consumeError(Style4.takeError());
21870 
21871   // Test 5: error on invalid yaml on command line
21872   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
21873   ASSERT_FALSE((bool)Style5);
21874   llvm::consumeError(Style5.takeError());
21875 
21876   // Test 6: error on invalid style
21877   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
21878   ASSERT_FALSE((bool)Style6);
21879   llvm::consumeError(Style6.takeError());
21880 
21881   // Test 7: found config file, error on parsing it
21882   ASSERT_TRUE(
21883       FS.addFile("/d/.clang-format", 0,
21884                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
21885                                                   "InvalidKey: InvalidValue")));
21886   ASSERT_TRUE(
21887       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21888   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
21889   ASSERT_FALSE((bool)Style7a);
21890   llvm::consumeError(Style7a.takeError());
21891 
21892   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
21893   ASSERT_TRUE((bool)Style7b);
21894 
21895   // Test 8: inferred per-language defaults apply.
21896   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
21897   ASSERT_TRUE((bool)StyleTd);
21898   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
21899 
21900   // Test 9.1.1: overwriting a file style, when no parent file exists with no
21901   // fallback style.
21902   ASSERT_TRUE(FS.addFile(
21903       "/e/sub/.clang-format", 0,
21904       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
21905                                        "ColumnLimit: 20")));
21906   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
21907                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21908   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21909   ASSERT_TRUE(static_cast<bool>(Style9));
21910   ASSERT_EQ(*Style9, [] {
21911     auto Style = getNoStyle();
21912     Style.ColumnLimit = 20;
21913     return Style;
21914   }());
21915 
21916   // Test 9.1.2: propagate more than one level with no parent file.
21917   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
21918                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21919   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
21920                          llvm::MemoryBuffer::getMemBuffer(
21921                              "BasedOnStyle: InheritParentConfig\n"
21922                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
21923   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
21924 
21925   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
21926   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
21927   ASSERT_TRUE(static_cast<bool>(Style9));
21928   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
21929     auto Style = getNoStyle();
21930     Style.ColumnLimit = 20;
21931     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
21932     return Style;
21933   }());
21934 
21935   // Test 9.2: with LLVM fallback style
21936   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
21937   ASSERT_TRUE(static_cast<bool>(Style9));
21938   ASSERT_EQ(*Style9, [] {
21939     auto Style = getLLVMStyle();
21940     Style.ColumnLimit = 20;
21941     return Style;
21942   }());
21943 
21944   // Test 9.3: with a parent file
21945   ASSERT_TRUE(
21946       FS.addFile("/e/.clang-format", 0,
21947                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
21948                                                   "UseTab: Always")));
21949   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21950   ASSERT_TRUE(static_cast<bool>(Style9));
21951   ASSERT_EQ(*Style9, [] {
21952     auto Style = getGoogleStyle();
21953     Style.ColumnLimit = 20;
21954     Style.UseTab = FormatStyle::UT_Always;
21955     return Style;
21956   }());
21957 
21958   // Test 9.4: propagate more than one level with a parent file.
21959   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
21960     auto Style = getGoogleStyle();
21961     Style.ColumnLimit = 20;
21962     Style.UseTab = FormatStyle::UT_Always;
21963     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
21964     return Style;
21965   }();
21966 
21967   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
21968   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
21969   ASSERT_TRUE(static_cast<bool>(Style9));
21970   ASSERT_EQ(*Style9, SubSubStyle);
21971 
21972   // Test 9.5: use InheritParentConfig as style name
21973   Style9 =
21974       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
21975   ASSERT_TRUE(static_cast<bool>(Style9));
21976   ASSERT_EQ(*Style9, SubSubStyle);
21977 
21978   // Test 9.6: use command line style with inheritance
21979   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
21980                     "none", "", &FS);
21981   ASSERT_TRUE(static_cast<bool>(Style9));
21982   ASSERT_EQ(*Style9, SubSubStyle);
21983 
21984   // Test 9.7: use command line style with inheritance and own config
21985   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
21986                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
21987                     "/e/sub/code.cpp", "none", "", &FS);
21988   ASSERT_TRUE(static_cast<bool>(Style9));
21989   ASSERT_EQ(*Style9, SubSubStyle);
21990 
21991   // Test 9.8: use inheritance from a file without BasedOnStyle
21992   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
21993                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
21994   ASSERT_TRUE(
21995       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
21996                  llvm::MemoryBuffer::getMemBuffer(
21997                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
21998   // Make sure we do not use the fallback style
21999   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
22000   ASSERT_TRUE(static_cast<bool>(Style9));
22001   ASSERT_EQ(*Style9, [] {
22002     auto Style = getLLVMStyle();
22003     Style.ColumnLimit = 123;
22004     return Style;
22005   }());
22006 
22007   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
22008   ASSERT_TRUE(static_cast<bool>(Style9));
22009   ASSERT_EQ(*Style9, [] {
22010     auto Style = getLLVMStyle();
22011     Style.ColumnLimit = 123;
22012     Style.IndentWidth = 7;
22013     return Style;
22014   }());
22015 
22016   // Test 9.9: use inheritance from a specific config file.
22017   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
22018                     "none", "", &FS);
22019   ASSERT_TRUE(static_cast<bool>(Style9));
22020   ASSERT_EQ(*Style9, SubSubStyle);
22021 }
22022 
22023 TEST(FormatStyle, GetStyleOfSpecificFile) {
22024   llvm::vfs::InMemoryFileSystem FS;
22025   // Specify absolute path to a format file in a parent directory.
22026   ASSERT_TRUE(
22027       FS.addFile("/e/.clang-format", 0,
22028                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22029   ASSERT_TRUE(
22030       FS.addFile("/e/explicit.clang-format", 0,
22031                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22032   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
22033                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22034   auto Style = getStyle("file:/e/explicit.clang-format",
22035                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22036   ASSERT_TRUE(static_cast<bool>(Style));
22037   ASSERT_EQ(*Style, getGoogleStyle());
22038 
22039   // Specify relative path to a format file.
22040   ASSERT_TRUE(
22041       FS.addFile("../../e/explicit.clang-format", 0,
22042                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22043   Style = getStyle("file:../../e/explicit.clang-format",
22044                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22045   ASSERT_TRUE(static_cast<bool>(Style));
22046   ASSERT_EQ(*Style, getGoogleStyle());
22047 
22048   // Specify path to a format file that does not exist.
22049   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
22050                    "LLVM", "", &FS);
22051   ASSERT_FALSE(static_cast<bool>(Style));
22052   llvm::consumeError(Style.takeError());
22053 
22054   // Specify path to a file on the filesystem.
22055   SmallString<128> FormatFilePath;
22056   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
22057       "FormatFileTest", "tpl", FormatFilePath);
22058   EXPECT_FALSE((bool)ECF);
22059   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
22060   EXPECT_FALSE((bool)ECF);
22061   FormatFileTest << "BasedOnStyle: Google\n";
22062   FormatFileTest.close();
22063 
22064   SmallString<128> TestFilePath;
22065   std::error_code ECT =
22066       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
22067   EXPECT_FALSE((bool)ECT);
22068   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
22069   CodeFileTest << "int i;\n";
22070   CodeFileTest.close();
22071 
22072   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
22073   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
22074 
22075   llvm::sys::fs::remove(FormatFilePath.c_str());
22076   llvm::sys::fs::remove(TestFilePath.c_str());
22077   ASSERT_TRUE(static_cast<bool>(Style));
22078   ASSERT_EQ(*Style, getGoogleStyle());
22079 }
22080 
22081 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
22082   // Column limit is 20.
22083   std::string Code = "Type *a =\n"
22084                      "    new Type();\n"
22085                      "g(iiiii, 0, jjjjj,\n"
22086                      "  0, kkkkk, 0, mm);\n"
22087                      "int  bad     = format   ;";
22088   std::string Expected = "auto a = new Type();\n"
22089                          "g(iiiii, nullptr,\n"
22090                          "  jjjjj, nullptr,\n"
22091                          "  kkkkk, nullptr,\n"
22092                          "  mm);\n"
22093                          "int  bad     = format   ;";
22094   FileID ID = Context.createInMemoryFile("format.cpp", Code);
22095   tooling::Replacements Replaces = toReplacements(
22096       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
22097                             "auto "),
22098        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
22099                             "nullptr"),
22100        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
22101                             "nullptr"),
22102        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
22103                             "nullptr")});
22104 
22105   FormatStyle Style = getLLVMStyle();
22106   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
22107   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22108   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22109       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22110   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22111   EXPECT_TRUE(static_cast<bool>(Result));
22112   EXPECT_EQ(Expected, *Result);
22113 }
22114 
22115 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
22116   std::string Code = "#include \"a.h\"\n"
22117                      "#include \"c.h\"\n"
22118                      "\n"
22119                      "int main() {\n"
22120                      "  return 0;\n"
22121                      "}";
22122   std::string Expected = "#include \"a.h\"\n"
22123                          "#include \"b.h\"\n"
22124                          "#include \"c.h\"\n"
22125                          "\n"
22126                          "int main() {\n"
22127                          "  return 0;\n"
22128                          "}";
22129   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
22130   tooling::Replacements Replaces = toReplacements(
22131       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
22132                             "#include \"b.h\"\n")});
22133 
22134   FormatStyle Style = getLLVMStyle();
22135   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
22136   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22137   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22138       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22139   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22140   EXPECT_TRUE(static_cast<bool>(Result));
22141   EXPECT_EQ(Expected, *Result);
22142 }
22143 
22144 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
22145   EXPECT_EQ("using std::cin;\n"
22146             "using std::cout;",
22147             format("using std::cout;\n"
22148                    "using std::cin;",
22149                    getGoogleStyle()));
22150 }
22151 
22152 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
22153   FormatStyle Style = getLLVMStyle();
22154   Style.Standard = FormatStyle::LS_Cpp03;
22155   // cpp03 recognize this string as identifier u8 and literal character 'a'
22156   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
22157 }
22158 
22159 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
22160   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
22161   // all modes, including C++11, C++14 and C++17
22162   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
22163 }
22164 
22165 TEST_F(FormatTest, DoNotFormatLikelyXml) {
22166   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
22167   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
22168 }
22169 
22170 TEST_F(FormatTest, StructuredBindings) {
22171   // Structured bindings is a C++17 feature.
22172   // all modes, including C++11, C++14 and C++17
22173   verifyFormat("auto [a, b] = f();");
22174   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
22175   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
22176   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
22177   EXPECT_EQ("auto const volatile [a, b] = f();",
22178             format("auto  const   volatile[a, b] = f();"));
22179   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
22180   EXPECT_EQ("auto &[a, b, c] = f();",
22181             format("auto   &[  a  ,  b,c   ] = f();"));
22182   EXPECT_EQ("auto &&[a, b, c] = f();",
22183             format("auto   &&[  a  ,  b,c   ] = f();"));
22184   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
22185   EXPECT_EQ("auto const volatile &&[a, b] = f();",
22186             format("auto  const  volatile  &&[a, b] = f();"));
22187   EXPECT_EQ("auto const &&[a, b] = f();",
22188             format("auto  const   &&  [a, b] = f();"));
22189   EXPECT_EQ("const auto &[a, b] = f();",
22190             format("const  auto  &  [a, b] = f();"));
22191   EXPECT_EQ("const auto volatile &&[a, b] = f();",
22192             format("const  auto   volatile  &&[a, b] = f();"));
22193   EXPECT_EQ("volatile const auto &&[a, b] = f();",
22194             format("volatile  const  auto   &&[a, b] = f();"));
22195   EXPECT_EQ("const auto &&[a, b] = f();",
22196             format("const  auto  &&  [a, b] = f();"));
22197 
22198   // Make sure we don't mistake structured bindings for lambdas.
22199   FormatStyle PointerMiddle = getLLVMStyle();
22200   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
22201   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
22202   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
22203   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
22204   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
22205   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
22206   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
22207   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
22208   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
22209   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
22210   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
22211   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
22212   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
22213 
22214   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
22215             format("for (const auto   &&   [a, b] : some_range) {\n}"));
22216   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
22217             format("for (const auto   &   [a, b] : some_range) {\n}"));
22218   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
22219             format("for (const auto[a, b] : some_range) {\n}"));
22220   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
22221   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
22222   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
22223   EXPECT_EQ("auto const &[x, y](expr);",
22224             format("auto  const  &  [x,y]  (expr);"));
22225   EXPECT_EQ("auto const &&[x, y](expr);",
22226             format("auto  const  &&  [x,y]  (expr);"));
22227   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
22228   EXPECT_EQ("auto const &[x, y]{expr};",
22229             format("auto  const  &  [x,y]  {expr};"));
22230   EXPECT_EQ("auto const &&[x, y]{expr};",
22231             format("auto  const  &&  [x,y]  {expr};"));
22232 
22233   FormatStyle Spaces = getLLVMStyle();
22234   Spaces.SpacesInSquareBrackets = true;
22235   verifyFormat("auto [ a, b ] = f();", Spaces);
22236   verifyFormat("auto &&[ a, b ] = f();", Spaces);
22237   verifyFormat("auto &[ a, b ] = f();", Spaces);
22238   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
22239   verifyFormat("auto const &[ a, b ] = f();", Spaces);
22240 }
22241 
22242 TEST_F(FormatTest, FileAndCode) {
22243   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
22244   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
22245   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
22246   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
22247   EXPECT_EQ(FormatStyle::LK_ObjC,
22248             guessLanguage("foo.h", "@interface Foo\n@end\n"));
22249   EXPECT_EQ(
22250       FormatStyle::LK_ObjC,
22251       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
22252   EXPECT_EQ(FormatStyle::LK_ObjC,
22253             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
22254   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
22255   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
22256   EXPECT_EQ(FormatStyle::LK_ObjC,
22257             guessLanguage("foo", "@interface Foo\n@end\n"));
22258   EXPECT_EQ(FormatStyle::LK_ObjC,
22259             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
22260   EXPECT_EQ(
22261       FormatStyle::LK_ObjC,
22262       guessLanguage("foo.h",
22263                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
22264   EXPECT_EQ(
22265       FormatStyle::LK_Cpp,
22266       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
22267 }
22268 
22269 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
22270   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
22271   EXPECT_EQ(FormatStyle::LK_ObjC,
22272             guessLanguage("foo.h", "array[[calculator getIndex]];"));
22273   EXPECT_EQ(FormatStyle::LK_Cpp,
22274             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
22275   EXPECT_EQ(
22276       FormatStyle::LK_Cpp,
22277       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
22278   EXPECT_EQ(FormatStyle::LK_ObjC,
22279             guessLanguage("foo.h", "[[noreturn foo] bar];"));
22280   EXPECT_EQ(FormatStyle::LK_Cpp,
22281             guessLanguage("foo.h", "[[clang::fallthrough]];"));
22282   EXPECT_EQ(FormatStyle::LK_ObjC,
22283             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
22284   EXPECT_EQ(FormatStyle::LK_Cpp,
22285             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
22286   EXPECT_EQ(FormatStyle::LK_Cpp,
22287             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
22288   EXPECT_EQ(FormatStyle::LK_ObjC,
22289             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
22290   EXPECT_EQ(FormatStyle::LK_Cpp,
22291             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
22292   EXPECT_EQ(
22293       FormatStyle::LK_Cpp,
22294       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
22295   EXPECT_EQ(
22296       FormatStyle::LK_Cpp,
22297       guessLanguage("foo.h",
22298                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
22299   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
22300 }
22301 
22302 TEST_F(FormatTest, GuessLanguageWithCaret) {
22303   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
22304   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
22305   EXPECT_EQ(FormatStyle::LK_ObjC,
22306             guessLanguage("foo.h", "int(^)(char, float);"));
22307   EXPECT_EQ(FormatStyle::LK_ObjC,
22308             guessLanguage("foo.h", "int(^foo)(char, float);"));
22309   EXPECT_EQ(FormatStyle::LK_ObjC,
22310             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
22311   EXPECT_EQ(FormatStyle::LK_ObjC,
22312             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
22313   EXPECT_EQ(
22314       FormatStyle::LK_ObjC,
22315       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
22316 }
22317 
22318 TEST_F(FormatTest, GuessLanguageWithPragmas) {
22319   EXPECT_EQ(FormatStyle::LK_Cpp,
22320             guessLanguage("foo.h", "__pragma(warning(disable:))"));
22321   EXPECT_EQ(FormatStyle::LK_Cpp,
22322             guessLanguage("foo.h", "#pragma(warning(disable:))"));
22323   EXPECT_EQ(FormatStyle::LK_Cpp,
22324             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
22325 }
22326 
22327 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
22328   // ASM symbolic names are identifiers that must be surrounded by [] without
22329   // space in between:
22330   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
22331 
22332   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
22333   verifyFormat(R"(//
22334 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
22335 )");
22336 
22337   // A list of several ASM symbolic names.
22338   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
22339 
22340   // ASM symbolic names in inline ASM with inputs and outputs.
22341   verifyFormat(R"(//
22342 asm("cmoveq %1, %2, %[result]"
22343     : [result] "=r"(result)
22344     : "r"(test), "r"(new), "[result]"(old));
22345 )");
22346 
22347   // ASM symbolic names in inline ASM with no outputs.
22348   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
22349 }
22350 
22351 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
22352   EXPECT_EQ(FormatStyle::LK_Cpp,
22353             guessLanguage("foo.h", "void f() {\n"
22354                                    "  asm (\"mov %[e], %[d]\"\n"
22355                                    "     : [d] \"=rm\" (d)\n"
22356                                    "       [e] \"rm\" (*e));\n"
22357                                    "}"));
22358   EXPECT_EQ(FormatStyle::LK_Cpp,
22359             guessLanguage("foo.h", "void f() {\n"
22360                                    "  _asm (\"mov %[e], %[d]\"\n"
22361                                    "     : [d] \"=rm\" (d)\n"
22362                                    "       [e] \"rm\" (*e));\n"
22363                                    "}"));
22364   EXPECT_EQ(FormatStyle::LK_Cpp,
22365             guessLanguage("foo.h", "void f() {\n"
22366                                    "  __asm (\"mov %[e], %[d]\"\n"
22367                                    "     : [d] \"=rm\" (d)\n"
22368                                    "       [e] \"rm\" (*e));\n"
22369                                    "}"));
22370   EXPECT_EQ(FormatStyle::LK_Cpp,
22371             guessLanguage("foo.h", "void f() {\n"
22372                                    "  __asm__ (\"mov %[e], %[d]\"\n"
22373                                    "     : [d] \"=rm\" (d)\n"
22374                                    "       [e] \"rm\" (*e));\n"
22375                                    "}"));
22376   EXPECT_EQ(FormatStyle::LK_Cpp,
22377             guessLanguage("foo.h", "void f() {\n"
22378                                    "  asm (\"mov %[e], %[d]\"\n"
22379                                    "     : [d] \"=rm\" (d),\n"
22380                                    "       [e] \"rm\" (*e));\n"
22381                                    "}"));
22382   EXPECT_EQ(FormatStyle::LK_Cpp,
22383             guessLanguage("foo.h", "void f() {\n"
22384                                    "  asm volatile (\"mov %[e], %[d]\"\n"
22385                                    "     : [d] \"=rm\" (d)\n"
22386                                    "       [e] \"rm\" (*e));\n"
22387                                    "}"));
22388 }
22389 
22390 TEST_F(FormatTest, GuessLanguageWithChildLines) {
22391   EXPECT_EQ(FormatStyle::LK_Cpp,
22392             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
22393   EXPECT_EQ(FormatStyle::LK_ObjC,
22394             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
22395   EXPECT_EQ(
22396       FormatStyle::LK_Cpp,
22397       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
22398   EXPECT_EQ(
22399       FormatStyle::LK_ObjC,
22400       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
22401 }
22402 
22403 TEST_F(FormatTest, TypenameMacros) {
22404   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
22405 
22406   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
22407   FormatStyle Google = getGoogleStyleWithColumns(0);
22408   Google.TypenameMacros = TypenameMacros;
22409   verifyFormat("struct foo {\n"
22410                "  int bar;\n"
22411                "  TAILQ_ENTRY(a) bleh;\n"
22412                "};",
22413                Google);
22414 
22415   FormatStyle Macros = getLLVMStyle();
22416   Macros.TypenameMacros = TypenameMacros;
22417 
22418   verifyFormat("STACK_OF(int) a;", Macros);
22419   verifyFormat("STACK_OF(int) *a;", Macros);
22420   verifyFormat("STACK_OF(int const *) *a;", Macros);
22421   verifyFormat("STACK_OF(int *const) *a;", Macros);
22422   verifyFormat("STACK_OF(int, string) a;", Macros);
22423   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
22424   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
22425   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
22426   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
22427   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
22428   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
22429 
22430   Macros.PointerAlignment = FormatStyle::PAS_Left;
22431   verifyFormat("STACK_OF(int)* a;", Macros);
22432   verifyFormat("STACK_OF(int*)* a;", Macros);
22433   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
22434   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
22435   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
22436 }
22437 
22438 TEST_F(FormatTest, AtomicQualifier) {
22439   // Check that we treate _Atomic as a type and not a function call
22440   FormatStyle Google = getGoogleStyleWithColumns(0);
22441   verifyFormat("struct foo {\n"
22442                "  int a1;\n"
22443                "  _Atomic(a) a2;\n"
22444                "  _Atomic(_Atomic(int) *const) a3;\n"
22445                "};",
22446                Google);
22447   verifyFormat("_Atomic(uint64_t) a;");
22448   verifyFormat("_Atomic(uint64_t) *a;");
22449   verifyFormat("_Atomic(uint64_t const *) *a;");
22450   verifyFormat("_Atomic(uint64_t *const) *a;");
22451   verifyFormat("_Atomic(const uint64_t *) *a;");
22452   verifyFormat("_Atomic(uint64_t) a;");
22453   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
22454   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
22455   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
22456   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
22457 
22458   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
22459   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
22460   FormatStyle Style = getLLVMStyle();
22461   Style.PointerAlignment = FormatStyle::PAS_Left;
22462   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
22463   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
22464   verifyFormat("_Atomic(int)* a;", Style);
22465   verifyFormat("_Atomic(int*)* a;", Style);
22466   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
22467 
22468   Style.SpacesInCStyleCastParentheses = true;
22469   Style.SpacesInParentheses = false;
22470   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
22471   Style.SpacesInCStyleCastParentheses = false;
22472   Style.SpacesInParentheses = true;
22473   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
22474   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
22475 }
22476 
22477 TEST_F(FormatTest, AmbersandInLamda) {
22478   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
22479   FormatStyle AlignStyle = getLLVMStyle();
22480   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
22481   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22482   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
22483   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22484 }
22485 
22486 TEST_F(FormatTest, SpacesInConditionalStatement) {
22487   FormatStyle Spaces = getLLVMStyle();
22488   Spaces.IfMacros.clear();
22489   Spaces.IfMacros.push_back("MYIF");
22490   Spaces.SpacesInConditionalStatement = true;
22491   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
22492   verifyFormat("if ( !a )\n  return;", Spaces);
22493   verifyFormat("if ( a )\n  return;", Spaces);
22494   verifyFormat("if constexpr ( a )\n  return;", Spaces);
22495   verifyFormat("MYIF ( a )\n  return;", Spaces);
22496   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
22497   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
22498   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
22499   verifyFormat("while ( a )\n  return;", Spaces);
22500   verifyFormat("while ( (a && b) )\n  return;", Spaces);
22501   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
22502   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
22503   // Check that space on the left of "::" is inserted as expected at beginning
22504   // of condition.
22505   verifyFormat("while ( ::func() )\n  return;", Spaces);
22506 
22507   // Check impact of ControlStatementsExceptControlMacros is honored.
22508   Spaces.SpaceBeforeParens =
22509       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
22510   verifyFormat("MYIF( a )\n  return;", Spaces);
22511   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
22512   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
22513 }
22514 
22515 TEST_F(FormatTest, AlternativeOperators) {
22516   // Test case for ensuring alternate operators are not
22517   // combined with their right most neighbour.
22518   verifyFormat("int a and b;");
22519   verifyFormat("int a and_eq b;");
22520   verifyFormat("int a bitand b;");
22521   verifyFormat("int a bitor b;");
22522   verifyFormat("int a compl b;");
22523   verifyFormat("int a not b;");
22524   verifyFormat("int a not_eq b;");
22525   verifyFormat("int a or b;");
22526   verifyFormat("int a xor b;");
22527   verifyFormat("int a xor_eq b;");
22528   verifyFormat("return this not_eq bitand other;");
22529   verifyFormat("bool operator not_eq(const X bitand other)");
22530 
22531   verifyFormat("int a and 5;");
22532   verifyFormat("int a and_eq 5;");
22533   verifyFormat("int a bitand 5;");
22534   verifyFormat("int a bitor 5;");
22535   verifyFormat("int a compl 5;");
22536   verifyFormat("int a not 5;");
22537   verifyFormat("int a not_eq 5;");
22538   verifyFormat("int a or 5;");
22539   verifyFormat("int a xor 5;");
22540   verifyFormat("int a xor_eq 5;");
22541 
22542   verifyFormat("int a compl(5);");
22543   verifyFormat("int a not(5);");
22544 
22545   /* FIXME handle alternate tokens
22546    * https://en.cppreference.com/w/cpp/language/operator_alternative
22547   // alternative tokens
22548   verifyFormat("compl foo();");     //  ~foo();
22549   verifyFormat("foo() <%%>;");      // foo();
22550   verifyFormat("void foo() <%%>;"); // void foo(){}
22551   verifyFormat("int a <:1:>;");     // int a[1];[
22552   verifyFormat("%:define ABC abc"); // #define ABC abc
22553   verifyFormat("%:%:");             // ##
22554   */
22555 }
22556 
22557 TEST_F(FormatTest, STLWhileNotDefineChed) {
22558   verifyFormat("#if defined(while)\n"
22559                "#define while EMIT WARNING C4005\n"
22560                "#endif // while");
22561 }
22562 
22563 TEST_F(FormatTest, OperatorSpacing) {
22564   FormatStyle Style = getLLVMStyle();
22565   Style.PointerAlignment = FormatStyle::PAS_Right;
22566   verifyFormat("Foo::operator*();", Style);
22567   verifyFormat("Foo::operator void *();", Style);
22568   verifyFormat("Foo::operator void **();", Style);
22569   verifyFormat("Foo::operator void *&();", Style);
22570   verifyFormat("Foo::operator void *&&();", Style);
22571   verifyFormat("Foo::operator void const *();", Style);
22572   verifyFormat("Foo::operator void const **();", Style);
22573   verifyFormat("Foo::operator void const *&();", Style);
22574   verifyFormat("Foo::operator void const *&&();", Style);
22575   verifyFormat("Foo::operator()(void *);", Style);
22576   verifyFormat("Foo::operator*(void *);", Style);
22577   verifyFormat("Foo::operator*();", Style);
22578   verifyFormat("Foo::operator**();", Style);
22579   verifyFormat("Foo::operator&();", Style);
22580   verifyFormat("Foo::operator<int> *();", Style);
22581   verifyFormat("Foo::operator<Foo> *();", Style);
22582   verifyFormat("Foo::operator<int> **();", Style);
22583   verifyFormat("Foo::operator<Foo> **();", Style);
22584   verifyFormat("Foo::operator<int> &();", Style);
22585   verifyFormat("Foo::operator<Foo> &();", Style);
22586   verifyFormat("Foo::operator<int> &&();", Style);
22587   verifyFormat("Foo::operator<Foo> &&();", Style);
22588   verifyFormat("Foo::operator<int> *&();", Style);
22589   verifyFormat("Foo::operator<Foo> *&();", Style);
22590   verifyFormat("Foo::operator<int> *&&();", Style);
22591   verifyFormat("Foo::operator<Foo> *&&();", Style);
22592   verifyFormat("operator*(int (*)(), class Foo);", Style);
22593 
22594   verifyFormat("Foo::operator&();", Style);
22595   verifyFormat("Foo::operator void &();", Style);
22596   verifyFormat("Foo::operator void const &();", Style);
22597   verifyFormat("Foo::operator()(void &);", Style);
22598   verifyFormat("Foo::operator&(void &);", Style);
22599   verifyFormat("Foo::operator&();", Style);
22600   verifyFormat("operator&(int (&)(), class Foo);", Style);
22601   verifyFormat("operator&&(int (&)(), class Foo);", Style);
22602 
22603   verifyFormat("Foo::operator&&();", Style);
22604   verifyFormat("Foo::operator**();", Style);
22605   verifyFormat("Foo::operator void &&();", Style);
22606   verifyFormat("Foo::operator void const &&();", Style);
22607   verifyFormat("Foo::operator()(void &&);", Style);
22608   verifyFormat("Foo::operator&&(void &&);", Style);
22609   verifyFormat("Foo::operator&&();", Style);
22610   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22611   verifyFormat("operator const nsTArrayRight<E> &()", Style);
22612   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
22613                Style);
22614   verifyFormat("operator void **()", Style);
22615   verifyFormat("operator const FooRight<Object> &()", Style);
22616   verifyFormat("operator const FooRight<Object> *()", Style);
22617   verifyFormat("operator const FooRight<Object> **()", Style);
22618   verifyFormat("operator const FooRight<Object> *&()", Style);
22619   verifyFormat("operator const FooRight<Object> *&&()", Style);
22620 
22621   Style.PointerAlignment = FormatStyle::PAS_Left;
22622   verifyFormat("Foo::operator*();", Style);
22623   verifyFormat("Foo::operator**();", Style);
22624   verifyFormat("Foo::operator void*();", Style);
22625   verifyFormat("Foo::operator void**();", Style);
22626   verifyFormat("Foo::operator void*&();", Style);
22627   verifyFormat("Foo::operator void*&&();", Style);
22628   verifyFormat("Foo::operator void const*();", Style);
22629   verifyFormat("Foo::operator void const**();", Style);
22630   verifyFormat("Foo::operator void const*&();", Style);
22631   verifyFormat("Foo::operator void const*&&();", Style);
22632   verifyFormat("Foo::operator/*comment*/ void*();", Style);
22633   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
22634   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
22635   verifyFormat("Foo::operator()(void*);", Style);
22636   verifyFormat("Foo::operator*(void*);", Style);
22637   verifyFormat("Foo::operator*();", Style);
22638   verifyFormat("Foo::operator<int>*();", Style);
22639   verifyFormat("Foo::operator<Foo>*();", Style);
22640   verifyFormat("Foo::operator<int>**();", Style);
22641   verifyFormat("Foo::operator<Foo>**();", Style);
22642   verifyFormat("Foo::operator<Foo>*&();", Style);
22643   verifyFormat("Foo::operator<int>&();", Style);
22644   verifyFormat("Foo::operator<Foo>&();", Style);
22645   verifyFormat("Foo::operator<int>&&();", Style);
22646   verifyFormat("Foo::operator<Foo>&&();", Style);
22647   verifyFormat("Foo::operator<int>*&();", Style);
22648   verifyFormat("Foo::operator<Foo>*&();", Style);
22649   verifyFormat("operator*(int (*)(), class Foo);", Style);
22650 
22651   verifyFormat("Foo::operator&();", Style);
22652   verifyFormat("Foo::operator void&();", Style);
22653   verifyFormat("Foo::operator void const&();", Style);
22654   verifyFormat("Foo::operator/*comment*/ void&();", Style);
22655   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
22656   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
22657   verifyFormat("Foo::operator()(void&);", Style);
22658   verifyFormat("Foo::operator&(void&);", Style);
22659   verifyFormat("Foo::operator&();", Style);
22660   verifyFormat("operator&(int (&)(), class Foo);", Style);
22661   verifyFormat("operator&(int (&&)(), class Foo);", Style);
22662   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22663 
22664   verifyFormat("Foo::operator&&();", Style);
22665   verifyFormat("Foo::operator void&&();", Style);
22666   verifyFormat("Foo::operator void const&&();", Style);
22667   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
22668   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
22669   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
22670   verifyFormat("Foo::operator()(void&&);", Style);
22671   verifyFormat("Foo::operator&&(void&&);", Style);
22672   verifyFormat("Foo::operator&&();", Style);
22673   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22674   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
22675   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
22676                Style);
22677   verifyFormat("operator void**()", Style);
22678   verifyFormat("operator const FooLeft<Object>&()", Style);
22679   verifyFormat("operator const FooLeft<Object>*()", Style);
22680   verifyFormat("operator const FooLeft<Object>**()", Style);
22681   verifyFormat("operator const FooLeft<Object>*&()", Style);
22682   verifyFormat("operator const FooLeft<Object>*&&()", Style);
22683 
22684   // PR45107
22685   verifyFormat("operator Vector<String>&();", Style);
22686   verifyFormat("operator const Vector<String>&();", Style);
22687   verifyFormat("operator foo::Bar*();", Style);
22688   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
22689   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
22690                Style);
22691 
22692   Style.PointerAlignment = FormatStyle::PAS_Middle;
22693   verifyFormat("Foo::operator*();", Style);
22694   verifyFormat("Foo::operator void *();", Style);
22695   verifyFormat("Foo::operator()(void *);", Style);
22696   verifyFormat("Foo::operator*(void *);", Style);
22697   verifyFormat("Foo::operator*();", Style);
22698   verifyFormat("operator*(int (*)(), class Foo);", Style);
22699 
22700   verifyFormat("Foo::operator&();", Style);
22701   verifyFormat("Foo::operator void &();", Style);
22702   verifyFormat("Foo::operator void const &();", Style);
22703   verifyFormat("Foo::operator()(void &);", Style);
22704   verifyFormat("Foo::operator&(void &);", Style);
22705   verifyFormat("Foo::operator&();", Style);
22706   verifyFormat("operator&(int (&)(), class Foo);", Style);
22707 
22708   verifyFormat("Foo::operator&&();", Style);
22709   verifyFormat("Foo::operator void &&();", Style);
22710   verifyFormat("Foo::operator void const &&();", Style);
22711   verifyFormat("Foo::operator()(void &&);", Style);
22712   verifyFormat("Foo::operator&&(void &&);", Style);
22713   verifyFormat("Foo::operator&&();", Style);
22714   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22715 }
22716 
22717 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
22718   FormatStyle Style = getLLVMStyle();
22719   // PR46157
22720   verifyFormat("foo(operator+, -42);", Style);
22721   verifyFormat("foo(operator++, -42);", Style);
22722   verifyFormat("foo(operator--, -42);", Style);
22723   verifyFormat("foo(-42, operator--);", Style);
22724   verifyFormat("foo(-42, operator, );", Style);
22725   verifyFormat("foo(operator, , -42);", Style);
22726 }
22727 
22728 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
22729   FormatStyle Style = getLLVMStyle();
22730   Style.WhitespaceSensitiveMacros.push_back("FOO");
22731 
22732   // Don't use the helpers here, since 'mess up' will change the whitespace
22733   // and these are all whitespace sensitive by definition
22734   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
22735             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
22736   EXPECT_EQ(
22737       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
22738       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
22739   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
22740             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
22741   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
22742             "       Still=Intentional);",
22743             format("FOO(String-ized&Messy+But,: :\n"
22744                    "       Still=Intentional);",
22745                    Style));
22746   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
22747   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
22748             "       Still=Intentional);",
22749             format("FOO(String-ized=&Messy+But,: :\n"
22750                    "       Still=Intentional);",
22751                    Style));
22752 
22753   Style.ColumnLimit = 21;
22754   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
22755             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
22756 }
22757 
22758 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
22759   // These tests are not in NamespaceFixer because that doesn't
22760   // test its interaction with line wrapping
22761   FormatStyle Style = getLLVMStyleWithColumns(80);
22762   verifyFormat("namespace {\n"
22763                "int i;\n"
22764                "int j;\n"
22765                "} // namespace",
22766                Style);
22767 
22768   verifyFormat("namespace AAA {\n"
22769                "int i;\n"
22770                "int j;\n"
22771                "} // namespace AAA",
22772                Style);
22773 
22774   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
22775             "int i;\n"
22776             "int j;\n"
22777             "} // namespace Averyveryveryverylongnamespace",
22778             format("namespace Averyveryveryverylongnamespace {\n"
22779                    "int i;\n"
22780                    "int j;\n"
22781                    "}",
22782                    Style));
22783 
22784   EXPECT_EQ(
22785       "namespace "
22786       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
22787       "    went::mad::now {\n"
22788       "int i;\n"
22789       "int j;\n"
22790       "} // namespace\n"
22791       "  // "
22792       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
22793       "went::mad::now",
22794       format("namespace "
22795              "would::it::save::you::a::lot::of::time::if_::i::"
22796              "just::gave::up::and_::went::mad::now {\n"
22797              "int i;\n"
22798              "int j;\n"
22799              "}",
22800              Style));
22801 
22802   // This used to duplicate the comment again and again on subsequent runs
22803   EXPECT_EQ(
22804       "namespace "
22805       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
22806       "    went::mad::now {\n"
22807       "int i;\n"
22808       "int j;\n"
22809       "} // namespace\n"
22810       "  // "
22811       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
22812       "went::mad::now",
22813       format("namespace "
22814              "would::it::save::you::a::lot::of::time::if_::i::"
22815              "just::gave::up::and_::went::mad::now {\n"
22816              "int i;\n"
22817              "int j;\n"
22818              "} // namespace\n"
22819              "  // "
22820              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
22821              "and_::went::mad::now",
22822              Style));
22823 }
22824 
22825 TEST_F(FormatTest, LikelyUnlikely) {
22826   FormatStyle Style = getLLVMStyle();
22827 
22828   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22829                "  return 29;\n"
22830                "}",
22831                Style);
22832 
22833   verifyFormat("if (argc > 5) [[likely]] {\n"
22834                "  return 29;\n"
22835                "}",
22836                Style);
22837 
22838   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22839                "  return 29;\n"
22840                "} else [[likely]] {\n"
22841                "  return 42;\n"
22842                "}\n",
22843                Style);
22844 
22845   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22846                "  return 29;\n"
22847                "} else if (argc > 10) [[likely]] {\n"
22848                "  return 99;\n"
22849                "} else {\n"
22850                "  return 42;\n"
22851                "}\n",
22852                Style);
22853 
22854   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
22855                "  return 29;\n"
22856                "}",
22857                Style);
22858 
22859   verifyFormat("if (argc > 5) [[unlikely]]\n"
22860                "  return 29;\n",
22861                Style);
22862   verifyFormat("if (argc > 5) [[likely]]\n"
22863                "  return 29;\n",
22864                Style);
22865 
22866   Style.AttributeMacros.push_back("UNLIKELY");
22867   Style.AttributeMacros.push_back("LIKELY");
22868   verifyFormat("if (argc > 5) UNLIKELY\n"
22869                "  return 29;\n",
22870                Style);
22871 
22872   verifyFormat("if (argc > 5) UNLIKELY {\n"
22873                "  return 29;\n"
22874                "}",
22875                Style);
22876   verifyFormat("if (argc > 5) UNLIKELY {\n"
22877                "  return 29;\n"
22878                "} else [[likely]] {\n"
22879                "  return 42;\n"
22880                "}\n",
22881                Style);
22882   verifyFormat("if (argc > 5) UNLIKELY {\n"
22883                "  return 29;\n"
22884                "} else LIKELY {\n"
22885                "  return 42;\n"
22886                "}\n",
22887                Style);
22888   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22889                "  return 29;\n"
22890                "} else LIKELY {\n"
22891                "  return 42;\n"
22892                "}\n",
22893                Style);
22894 }
22895 
22896 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
22897   verifyFormat("Constructor()\n"
22898                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
22899                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
22900                "aaaaaaaaaaaaaaaaaat))");
22901   verifyFormat("Constructor()\n"
22902                "    : aaaaaaaaaaaaa(aaaaaa), "
22903                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
22904 
22905   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
22906   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
22907   verifyFormat("Constructor()\n"
22908                "    : aaaaaa(aaaaaa),\n"
22909                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
22910                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
22911                StyleWithWhitespacePenalty);
22912   verifyFormat("Constructor()\n"
22913                "    : aaaaaaaaaaaaa(aaaaaa), "
22914                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
22915                StyleWithWhitespacePenalty);
22916 }
22917 
22918 TEST_F(FormatTest, LLVMDefaultStyle) {
22919   FormatStyle Style = getLLVMStyle();
22920   verifyFormat("extern \"C\" {\n"
22921                "int foo();\n"
22922                "}",
22923                Style);
22924 }
22925 TEST_F(FormatTest, GNUDefaultStyle) {
22926   FormatStyle Style = getGNUStyle();
22927   verifyFormat("extern \"C\"\n"
22928                "{\n"
22929                "  int foo ();\n"
22930                "}",
22931                Style);
22932 }
22933 TEST_F(FormatTest, MozillaDefaultStyle) {
22934   FormatStyle Style = getMozillaStyle();
22935   verifyFormat("extern \"C\"\n"
22936                "{\n"
22937                "  int foo();\n"
22938                "}",
22939                Style);
22940 }
22941 TEST_F(FormatTest, GoogleDefaultStyle) {
22942   FormatStyle Style = getGoogleStyle();
22943   verifyFormat("extern \"C\" {\n"
22944                "int foo();\n"
22945                "}",
22946                Style);
22947 }
22948 TEST_F(FormatTest, ChromiumDefaultStyle) {
22949   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
22950   verifyFormat("extern \"C\" {\n"
22951                "int foo();\n"
22952                "}",
22953                Style);
22954 }
22955 TEST_F(FormatTest, MicrosoftDefaultStyle) {
22956   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
22957   verifyFormat("extern \"C\"\n"
22958                "{\n"
22959                "    int foo();\n"
22960                "}",
22961                Style);
22962 }
22963 TEST_F(FormatTest, WebKitDefaultStyle) {
22964   FormatStyle Style = getWebKitStyle();
22965   verifyFormat("extern \"C\" {\n"
22966                "int foo();\n"
22967                "}",
22968                Style);
22969 }
22970 
22971 TEST_F(FormatTest, ConceptsAndRequires) {
22972   FormatStyle Style = getLLVMStyle();
22973   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
22974 
22975   verifyFormat("template <typename T>\n"
22976                "concept Hashable = requires(T a) {\n"
22977                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22978                "};",
22979                Style);
22980   verifyFormat("template <typename T>\n"
22981                "concept EqualityComparable = requires(T a, T b) {\n"
22982                "  { a == b } -> bool;\n"
22983                "};",
22984                Style);
22985   verifyFormat("template <typename T>\n"
22986                "concept EqualityComparable = requires(T a, T b) {\n"
22987                "  { a == b } -> bool;\n"
22988                "  { a != b } -> bool;\n"
22989                "};",
22990                Style);
22991   verifyFormat("template <typename T>\n"
22992                "concept EqualityComparable = requires(T a, T b) {\n"
22993                "  { a == b } -> bool;\n"
22994                "  { a != b } -> bool;\n"
22995                "};",
22996                Style);
22997 
22998   verifyFormat("template <typename It>\n"
22999                "requires Iterator<It>\n"
23000                "void sort(It begin, It end) {\n"
23001                "  //....\n"
23002                "}",
23003                Style);
23004 
23005   verifyFormat("template <typename T>\n"
23006                "concept Large = sizeof(T) > 10;",
23007                Style);
23008 
23009   verifyFormat("template <typename T, typename U>\n"
23010                "concept FooableWith = requires(T t, U u) {\n"
23011                "  typename T::foo_type;\n"
23012                "  { t.foo(u) } -> typename T::foo_type;\n"
23013                "  t++;\n"
23014                "};\n"
23015                "void doFoo(FooableWith<int> auto t) {\n"
23016                "  t.foo(3);\n"
23017                "}",
23018                Style);
23019   verifyFormat("template <typename T>\n"
23020                "concept Context = sizeof(T) == 1;",
23021                Style);
23022   verifyFormat("template <typename T>\n"
23023                "concept Context = is_specialization_of_v<context, T>;",
23024                Style);
23025   verifyFormat("template <typename T>\n"
23026                "concept Node = std::is_object_v<T>;",
23027                Style);
23028   verifyFormat("template <typename T>\n"
23029                "concept Tree = true;",
23030                Style);
23031 
23032   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
23033                "  //...\n"
23034                "}",
23035                Style);
23036 
23037   verifyFormat(
23038       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
23039       "  //...\n"
23040       "}",
23041       Style);
23042 
23043   verifyFormat(
23044       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
23045       "  //...\n"
23046       "}",
23047       Style);
23048 
23049   verifyFormat("template <typename T>\n"
23050                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
23051                "Concept2<I> {\n"
23052                "  //...\n"
23053                "}",
23054                Style);
23055 
23056   verifyFormat("template <typename T>\n"
23057                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
23058                "Concept2<I> {\n"
23059                "  //...\n"
23060                "}",
23061                Style);
23062 
23063   verifyFormat(
23064       "template <typename T>\n"
23065       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
23066       "  //...\n"
23067       "}",
23068       Style);
23069 
23070   verifyFormat(
23071       "template <typename T>\n"
23072       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
23073       "  //...\n"
23074       "}",
23075       Style);
23076 
23077   verifyFormat("template <typename It>\n"
23078                "requires Foo<It>() && Bar<It> {\n"
23079                "  //....\n"
23080                "}",
23081                Style);
23082 
23083   verifyFormat("template <typename It>\n"
23084                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
23085                "  //....\n"
23086                "}",
23087                Style);
23088 
23089   verifyFormat("template <typename It>\n"
23090                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
23091                "  //....\n"
23092                "}",
23093                Style);
23094 
23095   verifyFormat(
23096       "template <typename It>\n"
23097       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
23098       "  //....\n"
23099       "}",
23100       Style);
23101 
23102   Style.IndentRequires = true;
23103   verifyFormat("template <typename It>\n"
23104                "  requires Iterator<It>\n"
23105                "void sort(It begin, It end) {\n"
23106                "  //....\n"
23107                "}",
23108                Style);
23109   verifyFormat("template <std::size index_>\n"
23110                "  requires(index_ < sizeof...(Children_))\n"
23111                "Tree auto &child() {\n"
23112                "  // ...\n"
23113                "}",
23114                Style);
23115 
23116   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
23117   verifyFormat("template <typename T>\n"
23118                "concept Hashable = requires (T a) {\n"
23119                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
23120                "};",
23121                Style);
23122 
23123   verifyFormat("template <class T = void>\n"
23124                "  requires EqualityComparable<T> || Same<T, void>\n"
23125                "struct equal_to;",
23126                Style);
23127 
23128   verifyFormat("template <class T>\n"
23129                "  requires requires {\n"
23130                "    T{};\n"
23131                "    T (int);\n"
23132                "  }\n",
23133                Style);
23134 
23135   Style.ColumnLimit = 78;
23136   verifyFormat("template <typename T>\n"
23137                "concept Context = Traits<typename T::traits_type> and\n"
23138                "    Interface<typename T::interface_type> and\n"
23139                "    Request<typename T::request_type> and\n"
23140                "    Response<typename T::response_type> and\n"
23141                "    ContextExtension<typename T::extension_type> and\n"
23142                "    ::std::is_copy_constructable<T> and "
23143                "::std::is_move_constructable<T> and\n"
23144                "    requires (T c) {\n"
23145                "  { c.response; } -> Response;\n"
23146                "} and requires (T c) {\n"
23147                "  { c.request; } -> Request;\n"
23148                "}\n",
23149                Style);
23150 
23151   verifyFormat("template <typename T>\n"
23152                "concept Context = Traits<typename T::traits_type> or\n"
23153                "    Interface<typename T::interface_type> or\n"
23154                "    Request<typename T::request_type> or\n"
23155                "    Response<typename T::response_type> or\n"
23156                "    ContextExtension<typename T::extension_type> or\n"
23157                "    ::std::is_copy_constructable<T> or "
23158                "::std::is_move_constructable<T> or\n"
23159                "    requires (T c) {\n"
23160                "  { c.response; } -> Response;\n"
23161                "} or requires (T c) {\n"
23162                "  { c.request; } -> Request;\n"
23163                "}\n",
23164                Style);
23165 
23166   verifyFormat("template <typename T>\n"
23167                "concept Context = Traits<typename T::traits_type> &&\n"
23168                "    Interface<typename T::interface_type> &&\n"
23169                "    Request<typename T::request_type> &&\n"
23170                "    Response<typename T::response_type> &&\n"
23171                "    ContextExtension<typename T::extension_type> &&\n"
23172                "    ::std::is_copy_constructable<T> && "
23173                "::std::is_move_constructable<T> &&\n"
23174                "    requires (T c) {\n"
23175                "  { c.response; } -> Response;\n"
23176                "} && requires (T c) {\n"
23177                "  { c.request; } -> Request;\n"
23178                "}\n",
23179                Style);
23180 
23181   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
23182                "Constraint2<T>;");
23183 
23184   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
23185   Style.BraceWrapping.AfterFunction = true;
23186   Style.BraceWrapping.AfterClass = true;
23187   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
23188   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
23189   verifyFormat("void Foo () requires (std::copyable<T>)\n"
23190                "{\n"
23191                "  return\n"
23192                "}\n",
23193                Style);
23194 
23195   verifyFormat("void Foo () requires std::copyable<T>\n"
23196                "{\n"
23197                "  return\n"
23198                "}\n",
23199                Style);
23200 
23201   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
23202                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
23203                "struct constant;",
23204                Style);
23205 
23206   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
23207                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
23208                "struct constant;",
23209                Style);
23210 
23211   verifyFormat("template <class T>\n"
23212                "class plane_with_very_very_very_long_name\n"
23213                "{\n"
23214                "  constexpr plane_with_very_very_very_long_name () requires "
23215                "std::copyable<T>\n"
23216                "      : plane_with_very_very_very_long_name (1)\n"
23217                "  {\n"
23218                "  }\n"
23219                "}\n",
23220                Style);
23221 
23222   verifyFormat("template <class T>\n"
23223                "class plane_with_long_name\n"
23224                "{\n"
23225                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
23226                "      : plane_with_long_name (1)\n"
23227                "  {\n"
23228                "  }\n"
23229                "}\n",
23230                Style);
23231 
23232   Style.BreakBeforeConceptDeclarations = false;
23233   verifyFormat("template <typename T> concept Tree = true;", Style);
23234 
23235   Style.IndentRequires = false;
23236   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
23237                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
23238                "struct constant;",
23239                Style);
23240 }
23241 
23242 TEST_F(FormatTest, StatementAttributeLikeMacros) {
23243   FormatStyle Style = getLLVMStyle();
23244   StringRef Source = "void Foo::slot() {\n"
23245                      "  unsigned char MyChar = 'x';\n"
23246                      "  emit signal(MyChar);\n"
23247                      "  Q_EMIT signal(MyChar);\n"
23248                      "}";
23249 
23250   EXPECT_EQ(Source, format(Source, Style));
23251 
23252   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
23253   EXPECT_EQ("void Foo::slot() {\n"
23254             "  unsigned char MyChar = 'x';\n"
23255             "  emit          signal(MyChar);\n"
23256             "  Q_EMIT signal(MyChar);\n"
23257             "}",
23258             format(Source, Style));
23259 
23260   Style.StatementAttributeLikeMacros.push_back("emit");
23261   EXPECT_EQ(Source, format(Source, Style));
23262 
23263   Style.StatementAttributeLikeMacros = {};
23264   EXPECT_EQ("void Foo::slot() {\n"
23265             "  unsigned char MyChar = 'x';\n"
23266             "  emit          signal(MyChar);\n"
23267             "  Q_EMIT        signal(MyChar);\n"
23268             "}",
23269             format(Source, Style));
23270 }
23271 
23272 TEST_F(FormatTest, IndentAccessModifiers) {
23273   FormatStyle Style = getLLVMStyle();
23274   Style.IndentAccessModifiers = true;
23275   // Members are *two* levels below the record;
23276   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
23277   verifyFormat("class C {\n"
23278                "    int i;\n"
23279                "};\n",
23280                Style);
23281   verifyFormat("union C {\n"
23282                "    int i;\n"
23283                "    unsigned u;\n"
23284                "};\n",
23285                Style);
23286   // Access modifiers should be indented one level below the record.
23287   verifyFormat("class C {\n"
23288                "  public:\n"
23289                "    int i;\n"
23290                "};\n",
23291                Style);
23292   verifyFormat("struct S {\n"
23293                "  private:\n"
23294                "    class C {\n"
23295                "        int j;\n"
23296                "\n"
23297                "      public:\n"
23298                "        C();\n"
23299                "    };\n"
23300                "\n"
23301                "  public:\n"
23302                "    int i;\n"
23303                "};\n",
23304                Style);
23305   // Enumerations are not records and should be unaffected.
23306   Style.AllowShortEnumsOnASingleLine = false;
23307   verifyFormat("enum class E {\n"
23308                "  A,\n"
23309                "  B\n"
23310                "};\n",
23311                Style);
23312   // Test with a different indentation width;
23313   // also proves that the result is Style.AccessModifierOffset agnostic.
23314   Style.IndentWidth = 3;
23315   verifyFormat("class C {\n"
23316                "   public:\n"
23317                "      int i;\n"
23318                "};\n",
23319                Style);
23320 }
23321 
23322 TEST_F(FormatTest, LimitlessStringsAndComments) {
23323   auto Style = getLLVMStyleWithColumns(0);
23324   constexpr StringRef Code =
23325       "/**\n"
23326       " * This is a multiline comment with quite some long lines, at least for "
23327       "the LLVM Style.\n"
23328       " * We will redo this with strings and line comments. Just to  check if "
23329       "everything is working.\n"
23330       " */\n"
23331       "bool foo() {\n"
23332       "  /* Single line multi line comment. */\n"
23333       "  const std::string String = \"This is a multiline string with quite "
23334       "some long lines, at least for the LLVM Style.\"\n"
23335       "                             \"We already did it with multi line "
23336       "comments, and we will do it with line comments. Just to check if "
23337       "everything is working.\";\n"
23338       "  // This is a line comment (block) with quite some long lines, at "
23339       "least for the LLVM Style.\n"
23340       "  // We already did this with multi line comments and strings. Just to "
23341       "check if everything is working.\n"
23342       "  const std::string SmallString = \"Hello World\";\n"
23343       "  // Small line comment\n"
23344       "  return String.size() > SmallString.size();\n"
23345       "}";
23346   EXPECT_EQ(Code, format(Code, Style));
23347 }
23348 
23349 TEST_F(FormatTest, FormatDecayCopy) {
23350   // error cases from unit tests
23351   verifyFormat("foo(auto())");
23352   verifyFormat("foo(auto{})");
23353   verifyFormat("foo(auto({}))");
23354   verifyFormat("foo(auto{{}})");
23355 
23356   verifyFormat("foo(auto(1))");
23357   verifyFormat("foo(auto{1})");
23358   verifyFormat("foo(new auto(1))");
23359   verifyFormat("foo(new auto{1})");
23360   verifyFormat("decltype(auto(1)) x;");
23361   verifyFormat("decltype(auto{1}) x;");
23362   verifyFormat("auto(x);");
23363   verifyFormat("auto{x};");
23364   verifyFormat("new auto{x};");
23365   verifyFormat("auto{x} = y;");
23366   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
23367                                 // the user's own fault
23368   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
23369                                          // clearly the user's own fault
23370   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
23371 }
23372 
23373 TEST_F(FormatTest, Cpp20ModulesSupport) {
23374   FormatStyle Style = getLLVMStyle();
23375   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
23376   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
23377 
23378   verifyFormat("export import foo;", Style);
23379   verifyFormat("export import foo:bar;", Style);
23380   verifyFormat("export import foo.bar;", Style);
23381   verifyFormat("export import foo.bar:baz;", Style);
23382   verifyFormat("export import :bar;", Style);
23383   verifyFormat("export module foo:bar;", Style);
23384   verifyFormat("export module foo;", Style);
23385   verifyFormat("export module foo.bar;", Style);
23386   verifyFormat("export module foo.bar:baz;", Style);
23387   verifyFormat("export import <string_view>;", Style);
23388 
23389   verifyFormat("export type_name var;", Style);
23390   verifyFormat("template <class T> export using A = B<T>;", Style);
23391   verifyFormat("export using A = B;", Style);
23392   verifyFormat("export int func() {\n"
23393                "  foo();\n"
23394                "}",
23395                Style);
23396   verifyFormat("export struct {\n"
23397                "  int foo;\n"
23398                "};",
23399                Style);
23400   verifyFormat("export {\n"
23401                "  int foo;\n"
23402                "};",
23403                Style);
23404   verifyFormat("export export char const *hello() { return \"hello\"; }");
23405 
23406   verifyFormat("import bar;", Style);
23407   verifyFormat("import foo.bar;", Style);
23408   verifyFormat("import foo:bar;", Style);
23409   verifyFormat("import :bar;", Style);
23410   verifyFormat("import <ctime>;", Style);
23411   verifyFormat("import \"header\";", Style);
23412 
23413   verifyFormat("module foo;", Style);
23414   verifyFormat("module foo:bar;", Style);
23415   verifyFormat("module foo.bar;", Style);
23416   verifyFormat("module;", Style);
23417 
23418   verifyFormat("export namespace hi {\n"
23419                "const char *sayhi();\n"
23420                "}",
23421                Style);
23422 
23423   verifyFormat("module :private;", Style);
23424   verifyFormat("import <foo/bar.h>;", Style);
23425   verifyFormat("import foo...bar;", Style);
23426   verifyFormat("import ..........;", Style);
23427   verifyFormat("module foo:private;", Style);
23428   verifyFormat("import a", Style);
23429   verifyFormat("module a", Style);
23430   verifyFormat("export import a", Style);
23431   verifyFormat("export module a", Style);
23432 
23433   verifyFormat("import", Style);
23434   verifyFormat("module", Style);
23435   verifyFormat("export", Style);
23436 }
23437 
23438 TEST_F(FormatTest, CoroutineForCoawait) {
23439   FormatStyle Style = getLLVMStyle();
23440   verifyFormat("for co_await (auto x : range())\n  ;");
23441   verifyFormat("for (auto i : arr) {\n"
23442                "}",
23443                Style);
23444   verifyFormat("for co_await (auto i : arr) {\n"
23445                "}",
23446                Style);
23447   verifyFormat("for co_await (auto i : foo(T{})) {\n"
23448                "}",
23449                Style);
23450 }
23451 
23452 TEST_F(FormatTest, CoroutineCoAwait) {
23453   verifyFormat("int x = co_await foo();");
23454   verifyFormat("int x = (co_await foo());");
23455   verifyFormat("co_await (42);");
23456   verifyFormat("void operator co_await(int);");
23457   verifyFormat("void operator co_await(a);");
23458   verifyFormat("co_await a;");
23459   verifyFormat("co_await missing_await_resume{};");
23460   verifyFormat("co_await a; // comment");
23461   verifyFormat("void test0() { co_await a; }");
23462   verifyFormat("co_await co_await co_await foo();");
23463   verifyFormat("co_await foo().bar();");
23464   verifyFormat("co_await [this]() -> Task { co_return x; }");
23465   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
23466                "foo(); }(x, y);");
23467 
23468   FormatStyle Style = getLLVMStyleWithColumns(40);
23469   verifyFormat("co_await [this](int a, int b) -> Task {\n"
23470                "  co_return co_await foo();\n"
23471                "}(x, y);",
23472                Style);
23473   verifyFormat("co_await;");
23474 }
23475 
23476 TEST_F(FormatTest, CoroutineCoYield) {
23477   verifyFormat("int x = co_yield foo();");
23478   verifyFormat("int x = (co_yield foo());");
23479   verifyFormat("co_yield (42);");
23480   verifyFormat("co_yield {42};");
23481   verifyFormat("co_yield 42;");
23482   verifyFormat("co_yield n++;");
23483   verifyFormat("co_yield ++n;");
23484   verifyFormat("co_yield;");
23485 }
23486 
23487 TEST_F(FormatTest, CoroutineCoReturn) {
23488   verifyFormat("co_return (42);");
23489   verifyFormat("co_return;");
23490   verifyFormat("co_return {};");
23491   verifyFormat("co_return x;");
23492   verifyFormat("co_return co_await foo();");
23493   verifyFormat("co_return co_yield foo();");
23494 }
23495 
23496 TEST_F(FormatTest, EmptyShortBlock) {
23497   auto Style = getLLVMStyle();
23498   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
23499 
23500   verifyFormat("try {\n"
23501                "  doA();\n"
23502                "} catch (Exception &e) {\n"
23503                "  e.printStackTrace();\n"
23504                "}\n",
23505                Style);
23506 
23507   verifyFormat("try {\n"
23508                "  doA();\n"
23509                "} catch (Exception &e) {}\n",
23510                Style);
23511 }
23512 
23513 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
23514   auto Style = getLLVMStyle();
23515 
23516   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
23517   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
23518   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
23519   verifyFormat("struct Y<[] { return 0; }> {};", Style);
23520 
23521   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
23522 }
23523 
23524 TEST_F(FormatTest, RemoveBraces) {
23525   FormatStyle Style = getLLVMStyle();
23526   Style.RemoveBracesLLVM = true;
23527 
23528   // The following eight test cases are fully-braced versions of the examples at
23529   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
23530   // statement-bodies-of-if-else-loop-statements".
23531 
23532   // 1. Omit the braces, since the body is simple and clearly associated with
23533   // the if.
23534   verifyFormat("if (isa<FunctionDecl>(D))\n"
23535                "  handleFunctionDecl(D);\n"
23536                "else if (isa<VarDecl>(D))\n"
23537                "  handleVarDecl(D);",
23538                "if (isa<FunctionDecl>(D)) {\n"
23539                "  handleFunctionDecl(D);\n"
23540                "} else if (isa<VarDecl>(D)) {\n"
23541                "  handleVarDecl(D);\n"
23542                "}",
23543                Style);
23544 
23545   // 2. Here we document the condition itself and not the body.
23546   verifyFormat("if (isa<VarDecl>(D)) {\n"
23547                "  // It is necessary that we explain the situation with this\n"
23548                "  // surprisingly long comment, so it would be unclear\n"
23549                "  // without the braces whether the following statement is in\n"
23550                "  // the scope of the `if`.\n"
23551                "  // Because the condition is documented, we can't really\n"
23552                "  // hoist this comment that applies to the body above the\n"
23553                "  // if.\n"
23554                "  handleOtherDecl(D);\n"
23555                "}",
23556                Style);
23557 
23558   // 3. Use braces on the outer `if` to avoid a potential dangling else
23559   // situation.
23560   verifyFormat("if (isa<VarDecl>(D)) {\n"
23561                "  for (auto *A : D.attrs())\n"
23562                "    if (shouldProcessAttr(A))\n"
23563                "      handleAttr(A);\n"
23564                "}",
23565                "if (isa<VarDecl>(D)) {\n"
23566                "  for (auto *A : D.attrs()) {\n"
23567                "    if (shouldProcessAttr(A)) {\n"
23568                "      handleAttr(A);\n"
23569                "    }\n"
23570                "  }\n"
23571                "}",
23572                Style);
23573 
23574   // 4. Use braces for the `if` block to keep it uniform with the else block.
23575   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
23576                "  handleFunctionDecl(D);\n"
23577                "} else {\n"
23578                "  // In this else case, it is necessary that we explain the\n"
23579                "  // situation with this surprisingly long comment, so it\n"
23580                "  // would be unclear without the braces whether the\n"
23581                "  // following statement is in the scope of the `if`.\n"
23582                "  handleOtherDecl(D);\n"
23583                "}",
23584                Style);
23585 
23586   // 5. This should also omit braces.  The `for` loop contains only a single
23587   // statement, so it shouldn't have braces.  The `if` also only contains a
23588   // single simple statement (the for loop), so it also should omit braces.
23589   verifyFormat("if (isa<FunctionDecl>(D))\n"
23590                "  for (auto *A : D.attrs())\n"
23591                "    handleAttr(A);",
23592                "if (isa<FunctionDecl>(D)) {\n"
23593                "  for (auto *A : D.attrs()) {\n"
23594                "    handleAttr(A);\n"
23595                "  }\n"
23596                "}",
23597                Style);
23598 
23599   // 6. Use braces for the outer `if` since the nested `for` is braced.
23600   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
23601                "  for (auto *A : D.attrs()) {\n"
23602                "    // In this for loop body, it is necessary that we explain\n"
23603                "    // the situation with this surprisingly long comment,\n"
23604                "    // forcing braces on the `for` block.\n"
23605                "    handleAttr(A);\n"
23606                "  }\n"
23607                "}",
23608                Style);
23609 
23610   // 7. Use braces on the outer block because there are more than two levels of
23611   // nesting.
23612   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
23613                "  for (auto *A : D.attrs())\n"
23614                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
23615                "      handleAttrOnDecl(D, A, i);\n"
23616                "}",
23617                "if (isa<FunctionDecl>(D)) {\n"
23618                "  for (auto *A : D.attrs()) {\n"
23619                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
23620                "      handleAttrOnDecl(D, A, i);\n"
23621                "    }\n"
23622                "  }\n"
23623                "}",
23624                Style);
23625 
23626   // 8. Use braces on the outer block because of a nested `if`, otherwise the
23627   // compiler would warn: `add explicit braces to avoid dangling else`
23628   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
23629                "  if (shouldProcess(D))\n"
23630                "    handleVarDecl(D);\n"
23631                "  else\n"
23632                "    markAsIgnored(D);\n"
23633                "}",
23634                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
23635                "  if (shouldProcess(D)) {\n"
23636                "    handleVarDecl(D);\n"
23637                "  } else {\n"
23638                "    markAsIgnored(D);\n"
23639                "  }\n"
23640                "}",
23641                Style);
23642 
23643   verifyFormat("if (a)\n"
23644                "  b; // comment\n"
23645                "else if (c)\n"
23646                "  d; /* comment */\n"
23647                "else\n"
23648                "  e;",
23649                "if (a) {\n"
23650                "  b; // comment\n"
23651                "} else if (c) {\n"
23652                "  d; /* comment */\n"
23653                "} else {\n"
23654                "  e;\n"
23655                "}",
23656                Style);
23657 
23658   verifyFormat("if (a) {\n"
23659                "  b;\n"
23660                "  c;\n"
23661                "} else if (d) {\n"
23662                "  e;\n"
23663                "}",
23664                Style);
23665 
23666   verifyFormat("if (a) {\n"
23667                "#undef NDEBUG\n"
23668                "  b;\n"
23669                "} else {\n"
23670                "  c;\n"
23671                "}",
23672                Style);
23673 
23674   verifyFormat("if (a) {\n"
23675                "  // comment\n"
23676                "} else if (b) {\n"
23677                "  c;\n"
23678                "}",
23679                Style);
23680 
23681   verifyFormat("if (a) {\n"
23682                "  b;\n"
23683                "} else {\n"
23684                "  { c; }\n"
23685                "}",
23686                Style);
23687 
23688   verifyFormat("if (a) {\n"
23689                "  if (b) // comment\n"
23690                "    c;\n"
23691                "} else if (d) {\n"
23692                "  e;\n"
23693                "}",
23694                "if (a) {\n"
23695                "  if (b) { // comment\n"
23696                "    c;\n"
23697                "  }\n"
23698                "} else if (d) {\n"
23699                "  e;\n"
23700                "}",
23701                Style);
23702 
23703   verifyFormat("if (a) {\n"
23704                "  if (b) {\n"
23705                "    c;\n"
23706                "    // comment\n"
23707                "  } else if (d) {\n"
23708                "    e;\n"
23709                "  }\n"
23710                "}",
23711                Style);
23712 
23713   verifyFormat("if (a) {\n"
23714                "  if (b)\n"
23715                "    c;\n"
23716                "}",
23717                "if (a) {\n"
23718                "  if (b) {\n"
23719                "    c;\n"
23720                "  }\n"
23721                "}",
23722                Style);
23723 
23724   verifyFormat("if (a)\n"
23725                "  if (b)\n"
23726                "    c;\n"
23727                "  else\n"
23728                "    d;\n"
23729                "else\n"
23730                "  e;",
23731                "if (a) {\n"
23732                "  if (b) {\n"
23733                "    c;\n"
23734                "  } else {\n"
23735                "    d;\n"
23736                "  }\n"
23737                "} else {\n"
23738                "  e;\n"
23739                "}",
23740                Style);
23741 
23742   verifyFormat("if (a) {\n"
23743                "  // comment\n"
23744                "  if (b)\n"
23745                "    c;\n"
23746                "  else if (d)\n"
23747                "    e;\n"
23748                "} else {\n"
23749                "  g;\n"
23750                "}",
23751                "if (a) {\n"
23752                "  // comment\n"
23753                "  if (b) {\n"
23754                "    c;\n"
23755                "  } else if (d) {\n"
23756                "    e;\n"
23757                "  }\n"
23758                "} else {\n"
23759                "  g;\n"
23760                "}",
23761                Style);
23762 
23763   verifyFormat("if (a)\n"
23764                "  b;\n"
23765                "else if (c)\n"
23766                "  d;\n"
23767                "else\n"
23768                "  e;",
23769                "if (a) {\n"
23770                "  b;\n"
23771                "} else {\n"
23772                "  if (c) {\n"
23773                "    d;\n"
23774                "  } else {\n"
23775                "    e;\n"
23776                "  }\n"
23777                "}",
23778                Style);
23779 
23780   verifyFormat("if (a) {\n"
23781                "  if (b)\n"
23782                "    c;\n"
23783                "  else if (d)\n"
23784                "    e;\n"
23785                "} else {\n"
23786                "  g;\n"
23787                "}",
23788                "if (a) {\n"
23789                "  if (b)\n"
23790                "    c;\n"
23791                "  else {\n"
23792                "    if (d)\n"
23793                "      e;\n"
23794                "  }\n"
23795                "} else {\n"
23796                "  g;\n"
23797                "}",
23798                Style);
23799 
23800   verifyFormat("if (a)\n"
23801                "  b;\n"
23802                "else if (c)\n"
23803                "  while (d)\n"
23804                "    e;\n"
23805                "// comment",
23806                "if (a)\n"
23807                "{\n"
23808                "  b;\n"
23809                "} else if (c) {\n"
23810                "  while (d) {\n"
23811                "    e;\n"
23812                "  }\n"
23813                "}\n"
23814                "// comment",
23815                Style);
23816 
23817   verifyFormat("if (a) {\n"
23818                "  b;\n"
23819                "} else if (c) {\n"
23820                "  d;\n"
23821                "} else {\n"
23822                "  e;\n"
23823                "  g;\n"
23824                "}",
23825                Style);
23826 
23827   verifyFormat("if (a) {\n"
23828                "  b;\n"
23829                "} else if (c) {\n"
23830                "  d;\n"
23831                "} else {\n"
23832                "  e;\n"
23833                "} // comment",
23834                Style);
23835 
23836   verifyFormat("int abs = [](int i) {\n"
23837                "  if (i >= 0)\n"
23838                "    return i;\n"
23839                "  return -i;\n"
23840                "};",
23841                "int abs = [](int i) {\n"
23842                "  if (i >= 0) {\n"
23843                "    return i;\n"
23844                "  }\n"
23845                "  return -i;\n"
23846                "};",
23847                Style);
23848 
23849   Style.ColumnLimit = 20;
23850 
23851   verifyFormat("if (a) {\n"
23852                "  b = c + // 1 -\n"
23853                "      d;\n"
23854                "}",
23855                Style);
23856 
23857   verifyFormat("if (a) {\n"
23858                "  b = c >= 0 ? d\n"
23859                "             : e;\n"
23860                "}",
23861                "if (a) {\n"
23862                "  b = c >= 0 ? d : e;\n"
23863                "}",
23864                Style);
23865 
23866   verifyFormat("if (a)\n"
23867                "  b = c > 0 ? d : e;",
23868                "if (a) {\n"
23869                "  b = c > 0 ? d : e;\n"
23870                "}",
23871                Style);
23872 
23873   Style.ColumnLimit = 0;
23874 
23875   verifyFormat("if (a)\n"
23876                "  b234567890223456789032345678904234567890 = "
23877                "c234567890223456789032345678904234567890;",
23878                "if (a) {\n"
23879                "  b234567890223456789032345678904234567890 = "
23880                "c234567890223456789032345678904234567890;\n"
23881                "}",
23882                Style);
23883 }
23884 
23885 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
23886   auto Style = getLLVMStyle();
23887 
23888   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
23889                     "void functionDecl(int a, int b, int c);";
23890 
23891   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
23892                      "paramF, paramG, paramH, paramI);\n"
23893                      "void functionDecl(int argumentA, int argumentB, int "
23894                      "argumentC, int argumentD, int argumentE);";
23895 
23896   verifyFormat(Short, Style);
23897 
23898   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
23899                       "paramF, paramG, paramH,\n"
23900                       "             paramI);\n"
23901                       "void functionDecl(int argumentA, int argumentB, int "
23902                       "argumentC, int argumentD,\n"
23903                       "                  int argumentE);";
23904 
23905   verifyFormat(NoBreak, Medium, Style);
23906   verifyFormat(NoBreak,
23907                "functionCall(\n"
23908                "    paramA,\n"
23909                "    paramB,\n"
23910                "    paramC,\n"
23911                "    paramD,\n"
23912                "    paramE,\n"
23913                "    paramF,\n"
23914                "    paramG,\n"
23915                "    paramH,\n"
23916                "    paramI\n"
23917                ");\n"
23918                "void functionDecl(\n"
23919                "    int argumentA,\n"
23920                "    int argumentB,\n"
23921                "    int argumentC,\n"
23922                "    int argumentD,\n"
23923                "    int argumentE\n"
23924                ");",
23925                Style);
23926 
23927   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
23928                "                  nestedLongFunctionCall(argument1, "
23929                "argument2, argument3,\n"
23930                "                                         argument4, "
23931                "argument5));",
23932                Style);
23933 
23934   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
23935 
23936   verifyFormat(Short, Style);
23937   verifyFormat(
23938       "functionCall(\n"
23939       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
23940       "paramI\n"
23941       ");\n"
23942       "void functionDecl(\n"
23943       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
23944       "argumentE\n"
23945       ");",
23946       Medium, Style);
23947 
23948   Style.AllowAllArgumentsOnNextLine = false;
23949   Style.AllowAllParametersOfDeclarationOnNextLine = false;
23950 
23951   verifyFormat(Short, Style);
23952   verifyFormat(
23953       "functionCall(\n"
23954       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
23955       "paramI\n"
23956       ");\n"
23957       "void functionDecl(\n"
23958       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
23959       "argumentE\n"
23960       ");",
23961       Medium, Style);
23962 
23963   Style.BinPackArguments = false;
23964   Style.BinPackParameters = false;
23965 
23966   verifyFormat(Short, Style);
23967 
23968   verifyFormat("functionCall(\n"
23969                "    paramA,\n"
23970                "    paramB,\n"
23971                "    paramC,\n"
23972                "    paramD,\n"
23973                "    paramE,\n"
23974                "    paramF,\n"
23975                "    paramG,\n"
23976                "    paramH,\n"
23977                "    paramI\n"
23978                ");\n"
23979                "void functionDecl(\n"
23980                "    int argumentA,\n"
23981                "    int argumentB,\n"
23982                "    int argumentC,\n"
23983                "    int argumentD,\n"
23984                "    int argumentE\n"
23985                ");",
23986                Medium, Style);
23987 
23988   verifyFormat("outerFunctionCall(\n"
23989                "    nestedFunctionCall(argument1),\n"
23990                "    nestedLongFunctionCall(\n"
23991                "        argument1,\n"
23992                "        argument2,\n"
23993                "        argument3,\n"
23994                "        argument4,\n"
23995                "        argument5\n"
23996                "    )\n"
23997                ");",
23998                Style);
23999 
24000   verifyFormat("int a = (int)b;", Style);
24001   verifyFormat("int a = (int)b;",
24002                "int a = (\n"
24003                "    int\n"
24004                ") b;",
24005                Style);
24006 
24007   verifyFormat("return (true);", Style);
24008   verifyFormat("return (true);",
24009                "return (\n"
24010                "    true\n"
24011                ");",
24012                Style);
24013 
24014   verifyFormat("void foo();", Style);
24015   verifyFormat("void foo();",
24016                "void foo(\n"
24017                ");",
24018                Style);
24019 
24020   verifyFormat("void foo() {}", Style);
24021   verifyFormat("void foo() {}",
24022                "void foo(\n"
24023                ") {\n"
24024                "}",
24025                Style);
24026 
24027   verifyFormat("auto string = std::string();", Style);
24028   verifyFormat("auto string = std::string();",
24029                "auto string = std::string(\n"
24030                ");",
24031                Style);
24032 
24033   verifyFormat("void (*functionPointer)() = nullptr;", Style);
24034   verifyFormat("void (*functionPointer)() = nullptr;",
24035                "void (\n"
24036                "    *functionPointer\n"
24037                ")\n"
24038                "(\n"
24039                ") = nullptr;",
24040                Style);
24041 }
24042 
24043 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
24044   auto Style = getLLVMStyle();
24045 
24046   verifyFormat("if (foo()) {\n"
24047                "  return;\n"
24048                "}",
24049                Style);
24050 
24051   verifyFormat("if (quitelongarg !=\n"
24052                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
24053                "comment\n"
24054                "  return;\n"
24055                "}",
24056                Style);
24057 
24058   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
24059 
24060   verifyFormat("if (foo()) {\n"
24061                "  return;\n"
24062                "}",
24063                Style);
24064 
24065   verifyFormat("if (quitelongarg !=\n"
24066                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
24067                "comment\n"
24068                "  return;\n"
24069                "}",
24070                Style);
24071 }
24072 
24073 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
24074   auto Style = getLLVMStyle();
24075 
24076   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
24077                "  doSomething();\n"
24078                "}",
24079                Style);
24080 
24081   verifyFormat("for (int myReallyLongCountVariable = 0; "
24082                "myReallyLongCountVariable < count;\n"
24083                "     myReallyLongCountVariable++) {\n"
24084                "  doSomething();\n"
24085                "}",
24086                Style);
24087 
24088   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
24089 
24090   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
24091                "  doSomething();\n"
24092                "}",
24093                Style);
24094 
24095   verifyFormat("for (int myReallyLongCountVariable = 0; "
24096                "myReallyLongCountVariable < count;\n"
24097                "     myReallyLongCountVariable++) {\n"
24098                "  doSomething();\n"
24099                "}",
24100                Style);
24101 }
24102 
24103 } // namespace
24104 } // namespace format
24105 } // namespace clang
24106