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 consteval {\n}");
587   verifyFormat("if !consteval {\n}");
588   verifyFormat("if not consteval {\n}");
589   verifyFormat("if consteval {\n} else {\n}");
590   verifyFormat("if !consteval {\n} else {\n}");
591   verifyFormat("if consteval {\n"
592                "  f();\n"
593                "}");
594   verifyFormat("if !consteval {\n"
595                "  f();\n"
596                "}");
597   verifyFormat("if consteval {\n"
598                "  f();\n"
599                "} else {\n"
600                "  g();\n"
601                "}");
602   verifyFormat("if CONSTEVAL {\n"
603                "  f();\n"
604                "}");
605   verifyFormat("if !CONSTEVAL {\n"
606                "  f();\n"
607                "}");
608 
609   verifyFormat("if (a)\n"
610                "  g();");
611   verifyFormat("if (a) {\n"
612                "  g()\n"
613                "};");
614   verifyFormat("if (a)\n"
615                "  g();\n"
616                "else\n"
617                "  g();");
618   verifyFormat("if (a) {\n"
619                "  g();\n"
620                "} else\n"
621                "  g();");
622   verifyFormat("if (a)\n"
623                "  g();\n"
624                "else {\n"
625                "  g();\n"
626                "}");
627   verifyFormat("if (a) {\n"
628                "  g();\n"
629                "} else {\n"
630                "  g();\n"
631                "}");
632   verifyFormat("if (a)\n"
633                "  g();\n"
634                "else if (b)\n"
635                "  g();\n"
636                "else\n"
637                "  g();");
638   verifyFormat("if (a) {\n"
639                "  g();\n"
640                "} else if (b)\n"
641                "  g();\n"
642                "else\n"
643                "  g();");
644   verifyFormat("if (a)\n"
645                "  g();\n"
646                "else if (b) {\n"
647                "  g();\n"
648                "} else\n"
649                "  g();");
650   verifyFormat("if (a)\n"
651                "  g();\n"
652                "else if (b)\n"
653                "  g();\n"
654                "else {\n"
655                "  g();\n"
656                "}");
657   verifyFormat("if (a)\n"
658                "  g();\n"
659                "else if (b) {\n"
660                "  g();\n"
661                "} else {\n"
662                "  g();\n"
663                "}");
664   verifyFormat("if (a) {\n"
665                "  g();\n"
666                "} else if (b) {\n"
667                "  g();\n"
668                "} else {\n"
669                "  g();\n"
670                "}");
671 
672   FormatStyle AllowsMergedIf = getLLVMStyle();
673   AllowsMergedIf.IfMacros.push_back("MYIF");
674   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
675   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
676       FormatStyle::SIS_WithoutElse;
677   verifyFormat("if (a)\n"
678                "  // comment\n"
679                "  f();",
680                AllowsMergedIf);
681   verifyFormat("{\n"
682                "  if (a)\n"
683                "  label:\n"
684                "    f();\n"
685                "}",
686                AllowsMergedIf);
687   verifyFormat("#define A \\\n"
688                "  if (a)  \\\n"
689                "  label:  \\\n"
690                "    f()",
691                AllowsMergedIf);
692   verifyFormat("if (a)\n"
693                "  ;",
694                AllowsMergedIf);
695   verifyFormat("if (a)\n"
696                "  if (b) return;",
697                AllowsMergedIf);
698 
699   verifyFormat("if (a) // Can't merge this\n"
700                "  f();\n",
701                AllowsMergedIf);
702   verifyFormat("if (a) /* still don't merge */\n"
703                "  f();",
704                AllowsMergedIf);
705   verifyFormat("if (a) { // Never merge this\n"
706                "  f();\n"
707                "}",
708                AllowsMergedIf);
709   verifyFormat("if (a) { /* Never merge this */\n"
710                "  f();\n"
711                "}",
712                AllowsMergedIf);
713   verifyFormat("MYIF (a)\n"
714                "  // comment\n"
715                "  f();",
716                AllowsMergedIf);
717   verifyFormat("{\n"
718                "  MYIF (a)\n"
719                "  label:\n"
720                "    f();\n"
721                "}",
722                AllowsMergedIf);
723   verifyFormat("#define A  \\\n"
724                "  MYIF (a) \\\n"
725                "  label:   \\\n"
726                "    f()",
727                AllowsMergedIf);
728   verifyFormat("MYIF (a)\n"
729                "  ;",
730                AllowsMergedIf);
731   verifyFormat("MYIF (a)\n"
732                "  MYIF (b) return;",
733                AllowsMergedIf);
734 
735   verifyFormat("MYIF (a) // Can't merge this\n"
736                "  f();\n",
737                AllowsMergedIf);
738   verifyFormat("MYIF (a) /* still don't merge */\n"
739                "  f();",
740                AllowsMergedIf);
741   verifyFormat("MYIF (a) { // Never merge this\n"
742                "  f();\n"
743                "}",
744                AllowsMergedIf);
745   verifyFormat("MYIF (a) { /* Never merge this */\n"
746                "  f();\n"
747                "}",
748                AllowsMergedIf);
749 
750   AllowsMergedIf.ColumnLimit = 14;
751   // Where line-lengths matter, a 2-letter synonym that maintains line length.
752   // Not IF to avoid any confusion that IF is somehow special.
753   AllowsMergedIf.IfMacros.push_back("FI");
754   verifyFormat("if (a) return;", AllowsMergedIf);
755   verifyFormat("if (aaaaaaaaa)\n"
756                "  return;",
757                AllowsMergedIf);
758   verifyFormat("FI (a) return;", AllowsMergedIf);
759   verifyFormat("FI (aaaaaaaaa)\n"
760                "  return;",
761                AllowsMergedIf);
762 
763   AllowsMergedIf.ColumnLimit = 13;
764   verifyFormat("if (a)\n  return;", AllowsMergedIf);
765   verifyFormat("FI (a)\n  return;", AllowsMergedIf);
766 
767   FormatStyle AllowsMergedIfElse = getLLVMStyle();
768   AllowsMergedIfElse.IfMacros.push_back("MYIF");
769   AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine =
770       FormatStyle::SIS_AllIfsAndElse;
771   verifyFormat("if (a)\n"
772                "  // comment\n"
773                "  f();\n"
774                "else\n"
775                "  // comment\n"
776                "  f();",
777                AllowsMergedIfElse);
778   verifyFormat("{\n"
779                "  if (a)\n"
780                "  label:\n"
781                "    f();\n"
782                "  else\n"
783                "  label:\n"
784                "    f();\n"
785                "}",
786                AllowsMergedIfElse);
787   verifyFormat("if (a)\n"
788                "  ;\n"
789                "else\n"
790                "  ;",
791                AllowsMergedIfElse);
792   verifyFormat("if (a) {\n"
793                "} else {\n"
794                "}",
795                AllowsMergedIfElse);
796   verifyFormat("if (a) return;\n"
797                "else if (b) return;\n"
798                "else return;",
799                AllowsMergedIfElse);
800   verifyFormat("if (a) {\n"
801                "} else return;",
802                AllowsMergedIfElse);
803   verifyFormat("if (a) {\n"
804                "} else if (b) return;\n"
805                "else return;",
806                AllowsMergedIfElse);
807   verifyFormat("if (a) return;\n"
808                "else if (b) {\n"
809                "} else return;",
810                AllowsMergedIfElse);
811   verifyFormat("if (a)\n"
812                "  if (b) return;\n"
813                "  else return;",
814                AllowsMergedIfElse);
815   verifyFormat("if constexpr (a)\n"
816                "  if constexpr (b) return;\n"
817                "  else if constexpr (c) return;\n"
818                "  else return;",
819                AllowsMergedIfElse);
820   verifyFormat("MYIF (a)\n"
821                "  // comment\n"
822                "  f();\n"
823                "else\n"
824                "  // comment\n"
825                "  f();",
826                AllowsMergedIfElse);
827   verifyFormat("{\n"
828                "  MYIF (a)\n"
829                "  label:\n"
830                "    f();\n"
831                "  else\n"
832                "  label:\n"
833                "    f();\n"
834                "}",
835                AllowsMergedIfElse);
836   verifyFormat("MYIF (a)\n"
837                "  ;\n"
838                "else\n"
839                "  ;",
840                AllowsMergedIfElse);
841   verifyFormat("MYIF (a) {\n"
842                "} else {\n"
843                "}",
844                AllowsMergedIfElse);
845   verifyFormat("MYIF (a) return;\n"
846                "else MYIF (b) return;\n"
847                "else return;",
848                AllowsMergedIfElse);
849   verifyFormat("MYIF (a) {\n"
850                "} else return;",
851                AllowsMergedIfElse);
852   verifyFormat("MYIF (a) {\n"
853                "} else MYIF (b) return;\n"
854                "else return;",
855                AllowsMergedIfElse);
856   verifyFormat("MYIF (a) return;\n"
857                "else MYIF (b) {\n"
858                "} else return;",
859                AllowsMergedIfElse);
860   verifyFormat("MYIF (a)\n"
861                "  MYIF (b) return;\n"
862                "  else return;",
863                AllowsMergedIfElse);
864   verifyFormat("MYIF constexpr (a)\n"
865                "  MYIF constexpr (b) return;\n"
866                "  else MYIF constexpr (c) return;\n"
867                "  else return;",
868                AllowsMergedIfElse);
869 }
870 
871 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
872   FormatStyle AllowsMergedIf = getLLVMStyle();
873   AllowsMergedIf.IfMacros.push_back("MYIF");
874   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
875   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
876       FormatStyle::SIS_WithoutElse;
877   verifyFormat("if (a)\n"
878                "  f();\n"
879                "else {\n"
880                "  g();\n"
881                "}",
882                AllowsMergedIf);
883   verifyFormat("if (a)\n"
884                "  f();\n"
885                "else\n"
886                "  g();\n",
887                AllowsMergedIf);
888 
889   verifyFormat("if (a) g();", AllowsMergedIf);
890   verifyFormat("if (a) {\n"
891                "  g()\n"
892                "};",
893                AllowsMergedIf);
894   verifyFormat("if (a)\n"
895                "  g();\n"
896                "else\n"
897                "  g();",
898                AllowsMergedIf);
899   verifyFormat("if (a) {\n"
900                "  g();\n"
901                "} else\n"
902                "  g();",
903                AllowsMergedIf);
904   verifyFormat("if (a)\n"
905                "  g();\n"
906                "else {\n"
907                "  g();\n"
908                "}",
909                AllowsMergedIf);
910   verifyFormat("if (a) {\n"
911                "  g();\n"
912                "} else {\n"
913                "  g();\n"
914                "}",
915                AllowsMergedIf);
916   verifyFormat("if (a)\n"
917                "  g();\n"
918                "else if (b)\n"
919                "  g();\n"
920                "else\n"
921                "  g();",
922                AllowsMergedIf);
923   verifyFormat("if (a) {\n"
924                "  g();\n"
925                "} else if (b)\n"
926                "  g();\n"
927                "else\n"
928                "  g();",
929                AllowsMergedIf);
930   verifyFormat("if (a)\n"
931                "  g();\n"
932                "else if (b) {\n"
933                "  g();\n"
934                "} else\n"
935                "  g();",
936                AllowsMergedIf);
937   verifyFormat("if (a)\n"
938                "  g();\n"
939                "else if (b)\n"
940                "  g();\n"
941                "else {\n"
942                "  g();\n"
943                "}",
944                AllowsMergedIf);
945   verifyFormat("if (a)\n"
946                "  g();\n"
947                "else if (b) {\n"
948                "  g();\n"
949                "} else {\n"
950                "  g();\n"
951                "}",
952                AllowsMergedIf);
953   verifyFormat("if (a) {\n"
954                "  g();\n"
955                "} else if (b) {\n"
956                "  g();\n"
957                "} else {\n"
958                "  g();\n"
959                "}",
960                AllowsMergedIf);
961   verifyFormat("MYIF (a)\n"
962                "  f();\n"
963                "else {\n"
964                "  g();\n"
965                "}",
966                AllowsMergedIf);
967   verifyFormat("MYIF (a)\n"
968                "  f();\n"
969                "else\n"
970                "  g();\n",
971                AllowsMergedIf);
972 
973   verifyFormat("MYIF (a) g();", AllowsMergedIf);
974   verifyFormat("MYIF (a) {\n"
975                "  g()\n"
976                "};",
977                AllowsMergedIf);
978   verifyFormat("MYIF (a)\n"
979                "  g();\n"
980                "else\n"
981                "  g();",
982                AllowsMergedIf);
983   verifyFormat("MYIF (a) {\n"
984                "  g();\n"
985                "} else\n"
986                "  g();",
987                AllowsMergedIf);
988   verifyFormat("MYIF (a)\n"
989                "  g();\n"
990                "else {\n"
991                "  g();\n"
992                "}",
993                AllowsMergedIf);
994   verifyFormat("MYIF (a) {\n"
995                "  g();\n"
996                "} else {\n"
997                "  g();\n"
998                "}",
999                AllowsMergedIf);
1000   verifyFormat("MYIF (a)\n"
1001                "  g();\n"
1002                "else MYIF (b)\n"
1003                "  g();\n"
1004                "else\n"
1005                "  g();",
1006                AllowsMergedIf);
1007   verifyFormat("MYIF (a)\n"
1008                "  g();\n"
1009                "else if (b)\n"
1010                "  g();\n"
1011                "else\n"
1012                "  g();",
1013                AllowsMergedIf);
1014   verifyFormat("MYIF (a) {\n"
1015                "  g();\n"
1016                "} else MYIF (b)\n"
1017                "  g();\n"
1018                "else\n"
1019                "  g();",
1020                AllowsMergedIf);
1021   verifyFormat("MYIF (a) {\n"
1022                "  g();\n"
1023                "} else if (b)\n"
1024                "  g();\n"
1025                "else\n"
1026                "  g();",
1027                AllowsMergedIf);
1028   verifyFormat("MYIF (a)\n"
1029                "  g();\n"
1030                "else MYIF (b) {\n"
1031                "  g();\n"
1032                "} else\n"
1033                "  g();",
1034                AllowsMergedIf);
1035   verifyFormat("MYIF (a)\n"
1036                "  g();\n"
1037                "else if (b) {\n"
1038                "  g();\n"
1039                "} else\n"
1040                "  g();",
1041                AllowsMergedIf);
1042   verifyFormat("MYIF (a)\n"
1043                "  g();\n"
1044                "else MYIF (b)\n"
1045                "  g();\n"
1046                "else {\n"
1047                "  g();\n"
1048                "}",
1049                AllowsMergedIf);
1050   verifyFormat("MYIF (a)\n"
1051                "  g();\n"
1052                "else if (b)\n"
1053                "  g();\n"
1054                "else {\n"
1055                "  g();\n"
1056                "}",
1057                AllowsMergedIf);
1058   verifyFormat("MYIF (a)\n"
1059                "  g();\n"
1060                "else MYIF (b) {\n"
1061                "  g();\n"
1062                "} else {\n"
1063                "  g();\n"
1064                "}",
1065                AllowsMergedIf);
1066   verifyFormat("MYIF (a)\n"
1067                "  g();\n"
1068                "else if (b) {\n"
1069                "  g();\n"
1070                "} else {\n"
1071                "  g();\n"
1072                "}",
1073                AllowsMergedIf);
1074   verifyFormat("MYIF (a) {\n"
1075                "  g();\n"
1076                "} else MYIF (b) {\n"
1077                "  g();\n"
1078                "} else {\n"
1079                "  g();\n"
1080                "}",
1081                AllowsMergedIf);
1082   verifyFormat("MYIF (a) {\n"
1083                "  g();\n"
1084                "} else if (b) {\n"
1085                "  g();\n"
1086                "} else {\n"
1087                "  g();\n"
1088                "}",
1089                AllowsMergedIf);
1090 
1091   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1092       FormatStyle::SIS_OnlyFirstIf;
1093 
1094   verifyFormat("if (a) f();\n"
1095                "else {\n"
1096                "  g();\n"
1097                "}",
1098                AllowsMergedIf);
1099   verifyFormat("if (a) f();\n"
1100                "else {\n"
1101                "  if (a) f();\n"
1102                "  else {\n"
1103                "    g();\n"
1104                "  }\n"
1105                "  g();\n"
1106                "}",
1107                AllowsMergedIf);
1108 
1109   verifyFormat("if (a) g();", AllowsMergedIf);
1110   verifyFormat("if (a) {\n"
1111                "  g()\n"
1112                "};",
1113                AllowsMergedIf);
1114   verifyFormat("if (a) g();\n"
1115                "else\n"
1116                "  g();",
1117                AllowsMergedIf);
1118   verifyFormat("if (a) {\n"
1119                "  g();\n"
1120                "} else\n"
1121                "  g();",
1122                AllowsMergedIf);
1123   verifyFormat("if (a) g();\n"
1124                "else {\n"
1125                "  g();\n"
1126                "}",
1127                AllowsMergedIf);
1128   verifyFormat("if (a) {\n"
1129                "  g();\n"
1130                "} else {\n"
1131                "  g();\n"
1132                "}",
1133                AllowsMergedIf);
1134   verifyFormat("if (a) g();\n"
1135                "else if (b)\n"
1136                "  g();\n"
1137                "else\n"
1138                "  g();",
1139                AllowsMergedIf);
1140   verifyFormat("if (a) {\n"
1141                "  g();\n"
1142                "} else if (b)\n"
1143                "  g();\n"
1144                "else\n"
1145                "  g();",
1146                AllowsMergedIf);
1147   verifyFormat("if (a) g();\n"
1148                "else if (b) {\n"
1149                "  g();\n"
1150                "} else\n"
1151                "  g();",
1152                AllowsMergedIf);
1153   verifyFormat("if (a) g();\n"
1154                "else if (b)\n"
1155                "  g();\n"
1156                "else {\n"
1157                "  g();\n"
1158                "}",
1159                AllowsMergedIf);
1160   verifyFormat("if (a) g();\n"
1161                "else if (b) {\n"
1162                "  g();\n"
1163                "} else {\n"
1164                "  g();\n"
1165                "}",
1166                AllowsMergedIf);
1167   verifyFormat("if (a) {\n"
1168                "  g();\n"
1169                "} else if (b) {\n"
1170                "  g();\n"
1171                "} else {\n"
1172                "  g();\n"
1173                "}",
1174                AllowsMergedIf);
1175   verifyFormat("MYIF (a) f();\n"
1176                "else {\n"
1177                "  g();\n"
1178                "}",
1179                AllowsMergedIf);
1180   verifyFormat("MYIF (a) f();\n"
1181                "else {\n"
1182                "  if (a) f();\n"
1183                "  else {\n"
1184                "    g();\n"
1185                "  }\n"
1186                "  g();\n"
1187                "}",
1188                AllowsMergedIf);
1189 
1190   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1191   verifyFormat("MYIF (a) {\n"
1192                "  g()\n"
1193                "};",
1194                AllowsMergedIf);
1195   verifyFormat("MYIF (a) g();\n"
1196                "else\n"
1197                "  g();",
1198                AllowsMergedIf);
1199   verifyFormat("MYIF (a) {\n"
1200                "  g();\n"
1201                "} else\n"
1202                "  g();",
1203                AllowsMergedIf);
1204   verifyFormat("MYIF (a) g();\n"
1205                "else {\n"
1206                "  g();\n"
1207                "}",
1208                AllowsMergedIf);
1209   verifyFormat("MYIF (a) {\n"
1210                "  g();\n"
1211                "} else {\n"
1212                "  g();\n"
1213                "}",
1214                AllowsMergedIf);
1215   verifyFormat("MYIF (a) g();\n"
1216                "else MYIF (b)\n"
1217                "  g();\n"
1218                "else\n"
1219                "  g();",
1220                AllowsMergedIf);
1221   verifyFormat("MYIF (a) g();\n"
1222                "else if (b)\n"
1223                "  g();\n"
1224                "else\n"
1225                "  g();",
1226                AllowsMergedIf);
1227   verifyFormat("MYIF (a) {\n"
1228                "  g();\n"
1229                "} else MYIF (b)\n"
1230                "  g();\n"
1231                "else\n"
1232                "  g();",
1233                AllowsMergedIf);
1234   verifyFormat("MYIF (a) {\n"
1235                "  g();\n"
1236                "} else if (b)\n"
1237                "  g();\n"
1238                "else\n"
1239                "  g();",
1240                AllowsMergedIf);
1241   verifyFormat("MYIF (a) g();\n"
1242                "else MYIF (b) {\n"
1243                "  g();\n"
1244                "} else\n"
1245                "  g();",
1246                AllowsMergedIf);
1247   verifyFormat("MYIF (a) g();\n"
1248                "else if (b) {\n"
1249                "  g();\n"
1250                "} else\n"
1251                "  g();",
1252                AllowsMergedIf);
1253   verifyFormat("MYIF (a) g();\n"
1254                "else MYIF (b)\n"
1255                "  g();\n"
1256                "else {\n"
1257                "  g();\n"
1258                "}",
1259                AllowsMergedIf);
1260   verifyFormat("MYIF (a) g();\n"
1261                "else if (b)\n"
1262                "  g();\n"
1263                "else {\n"
1264                "  g();\n"
1265                "}",
1266                AllowsMergedIf);
1267   verifyFormat("MYIF (a) g();\n"
1268                "else MYIF (b) {\n"
1269                "  g();\n"
1270                "} else {\n"
1271                "  g();\n"
1272                "}",
1273                AllowsMergedIf);
1274   verifyFormat("MYIF (a) g();\n"
1275                "else if (b) {\n"
1276                "  g();\n"
1277                "} else {\n"
1278                "  g();\n"
1279                "}",
1280                AllowsMergedIf);
1281   verifyFormat("MYIF (a) {\n"
1282                "  g();\n"
1283                "} else MYIF (b) {\n"
1284                "  g();\n"
1285                "} else {\n"
1286                "  g();\n"
1287                "}",
1288                AllowsMergedIf);
1289   verifyFormat("MYIF (a) {\n"
1290                "  g();\n"
1291                "} else if (b) {\n"
1292                "  g();\n"
1293                "} else {\n"
1294                "  g();\n"
1295                "}",
1296                AllowsMergedIf);
1297 
1298   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1299       FormatStyle::SIS_AllIfsAndElse;
1300 
1301   verifyFormat("if (a) f();\n"
1302                "else {\n"
1303                "  g();\n"
1304                "}",
1305                AllowsMergedIf);
1306   verifyFormat("if (a) f();\n"
1307                "else {\n"
1308                "  if (a) f();\n"
1309                "  else {\n"
1310                "    g();\n"
1311                "  }\n"
1312                "  g();\n"
1313                "}",
1314                AllowsMergedIf);
1315 
1316   verifyFormat("if (a) g();", AllowsMergedIf);
1317   verifyFormat("if (a) {\n"
1318                "  g()\n"
1319                "};",
1320                AllowsMergedIf);
1321   verifyFormat("if (a) g();\n"
1322                "else g();",
1323                AllowsMergedIf);
1324   verifyFormat("if (a) {\n"
1325                "  g();\n"
1326                "} else g();",
1327                AllowsMergedIf);
1328   verifyFormat("if (a) g();\n"
1329                "else {\n"
1330                "  g();\n"
1331                "}",
1332                AllowsMergedIf);
1333   verifyFormat("if (a) {\n"
1334                "  g();\n"
1335                "} else {\n"
1336                "  g();\n"
1337                "}",
1338                AllowsMergedIf);
1339   verifyFormat("if (a) g();\n"
1340                "else if (b) g();\n"
1341                "else g();",
1342                AllowsMergedIf);
1343   verifyFormat("if (a) {\n"
1344                "  g();\n"
1345                "} else if (b) g();\n"
1346                "else g();",
1347                AllowsMergedIf);
1348   verifyFormat("if (a) g();\n"
1349                "else if (b) {\n"
1350                "  g();\n"
1351                "} else g();",
1352                AllowsMergedIf);
1353   verifyFormat("if (a) g();\n"
1354                "else if (b) g();\n"
1355                "else {\n"
1356                "  g();\n"
1357                "}",
1358                AllowsMergedIf);
1359   verifyFormat("if (a) g();\n"
1360                "else if (b) {\n"
1361                "  g();\n"
1362                "} else {\n"
1363                "  g();\n"
1364                "}",
1365                AllowsMergedIf);
1366   verifyFormat("if (a) {\n"
1367                "  g();\n"
1368                "} else if (b) {\n"
1369                "  g();\n"
1370                "} else {\n"
1371                "  g();\n"
1372                "}",
1373                AllowsMergedIf);
1374   verifyFormat("MYIF (a) f();\n"
1375                "else {\n"
1376                "  g();\n"
1377                "}",
1378                AllowsMergedIf);
1379   verifyFormat("MYIF (a) f();\n"
1380                "else {\n"
1381                "  if (a) f();\n"
1382                "  else {\n"
1383                "    g();\n"
1384                "  }\n"
1385                "  g();\n"
1386                "}",
1387                AllowsMergedIf);
1388 
1389   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1390   verifyFormat("MYIF (a) {\n"
1391                "  g()\n"
1392                "};",
1393                AllowsMergedIf);
1394   verifyFormat("MYIF (a) g();\n"
1395                "else g();",
1396                AllowsMergedIf);
1397   verifyFormat("MYIF (a) {\n"
1398                "  g();\n"
1399                "} else g();",
1400                AllowsMergedIf);
1401   verifyFormat("MYIF (a) g();\n"
1402                "else {\n"
1403                "  g();\n"
1404                "}",
1405                AllowsMergedIf);
1406   verifyFormat("MYIF (a) {\n"
1407                "  g();\n"
1408                "} else {\n"
1409                "  g();\n"
1410                "}",
1411                AllowsMergedIf);
1412   verifyFormat("MYIF (a) g();\n"
1413                "else MYIF (b) g();\n"
1414                "else g();",
1415                AllowsMergedIf);
1416   verifyFormat("MYIF (a) g();\n"
1417                "else if (b) g();\n"
1418                "else g();",
1419                AllowsMergedIf);
1420   verifyFormat("MYIF (a) {\n"
1421                "  g();\n"
1422                "} else MYIF (b) g();\n"
1423                "else g();",
1424                AllowsMergedIf);
1425   verifyFormat("MYIF (a) {\n"
1426                "  g();\n"
1427                "} else if (b) g();\n"
1428                "else g();",
1429                AllowsMergedIf);
1430   verifyFormat("MYIF (a) g();\n"
1431                "else MYIF (b) {\n"
1432                "  g();\n"
1433                "} else g();",
1434                AllowsMergedIf);
1435   verifyFormat("MYIF (a) g();\n"
1436                "else if (b) {\n"
1437                "  g();\n"
1438                "} else g();",
1439                AllowsMergedIf);
1440   verifyFormat("MYIF (a) g();\n"
1441                "else MYIF (b) g();\n"
1442                "else {\n"
1443                "  g();\n"
1444                "}",
1445                AllowsMergedIf);
1446   verifyFormat("MYIF (a) g();\n"
1447                "else if (b) g();\n"
1448                "else {\n"
1449                "  g();\n"
1450                "}",
1451                AllowsMergedIf);
1452   verifyFormat("MYIF (a) g();\n"
1453                "else MYIF (b) {\n"
1454                "  g();\n"
1455                "} else {\n"
1456                "  g();\n"
1457                "}",
1458                AllowsMergedIf);
1459   verifyFormat("MYIF (a) g();\n"
1460                "else if (b) {\n"
1461                "  g();\n"
1462                "} else {\n"
1463                "  g();\n"
1464                "}",
1465                AllowsMergedIf);
1466   verifyFormat("MYIF (a) {\n"
1467                "  g();\n"
1468                "} else MYIF (b) {\n"
1469                "  g();\n"
1470                "} else {\n"
1471                "  g();\n"
1472                "}",
1473                AllowsMergedIf);
1474   verifyFormat("MYIF (a) {\n"
1475                "  g();\n"
1476                "} else if (b) {\n"
1477                "  g();\n"
1478                "} else {\n"
1479                "  g();\n"
1480                "}",
1481                AllowsMergedIf);
1482 }
1483 
1484 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
1485   FormatStyle AllowsMergedLoops = getLLVMStyle();
1486   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
1487   verifyFormat("while (true) continue;", AllowsMergedLoops);
1488   verifyFormat("for (;;) continue;", AllowsMergedLoops);
1489   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
1490   verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
1491   verifyFormat("while (true)\n"
1492                "  ;",
1493                AllowsMergedLoops);
1494   verifyFormat("for (;;)\n"
1495                "  ;",
1496                AllowsMergedLoops);
1497   verifyFormat("for (;;)\n"
1498                "  for (;;) continue;",
1499                AllowsMergedLoops);
1500   verifyFormat("for (;;)\n"
1501                "  while (true) continue;",
1502                AllowsMergedLoops);
1503   verifyFormat("while (true)\n"
1504                "  for (;;) continue;",
1505                AllowsMergedLoops);
1506   verifyFormat("BOOST_FOREACH (int &v, vec)\n"
1507                "  for (;;) continue;",
1508                AllowsMergedLoops);
1509   verifyFormat("for (;;)\n"
1510                "  BOOST_FOREACH (int &v, vec) continue;",
1511                AllowsMergedLoops);
1512   verifyFormat("for (;;) // Can't merge this\n"
1513                "  continue;",
1514                AllowsMergedLoops);
1515   verifyFormat("for (;;) /* still don't merge */\n"
1516                "  continue;",
1517                AllowsMergedLoops);
1518   verifyFormat("do a++;\n"
1519                "while (true);",
1520                AllowsMergedLoops);
1521   verifyFormat("do /* Don't merge */\n"
1522                "  a++;\n"
1523                "while (true);",
1524                AllowsMergedLoops);
1525   verifyFormat("do // Don't merge\n"
1526                "  a++;\n"
1527                "while (true);",
1528                AllowsMergedLoops);
1529   verifyFormat("do\n"
1530                "  // Don't merge\n"
1531                "  a++;\n"
1532                "while (true);",
1533                AllowsMergedLoops);
1534   // Without braces labels are interpreted differently.
1535   verifyFormat("{\n"
1536                "  do\n"
1537                "  label:\n"
1538                "    a++;\n"
1539                "  while (true);\n"
1540                "}",
1541                AllowsMergedLoops);
1542 }
1543 
1544 TEST_F(FormatTest, FormatShortBracedStatements) {
1545   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
1546   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false);
1547   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine,
1548             FormatStyle::SIS_Never);
1549   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false);
1550   EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false);
1551   verifyFormat("for (;;) {\n"
1552                "  f();\n"
1553                "}");
1554   verifyFormat("/*comment*/ for (;;) {\n"
1555                "  f();\n"
1556                "}");
1557   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1558                "  f();\n"
1559                "}");
1560   verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n"
1561                "  f();\n"
1562                "}");
1563   verifyFormat("while (true) {\n"
1564                "  f();\n"
1565                "}");
1566   verifyFormat("/*comment*/ while (true) {\n"
1567                "  f();\n"
1568                "}");
1569   verifyFormat("if (true) {\n"
1570                "  f();\n"
1571                "}");
1572   verifyFormat("/*comment*/ if (true) {\n"
1573                "  f();\n"
1574                "}");
1575 
1576   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1577       FormatStyle::SBS_Empty;
1578   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1579       FormatStyle::SIS_WithoutElse;
1580   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1581   verifyFormat("if (i) break;", AllowSimpleBracedStatements);
1582   verifyFormat("if (i > 0) {\n"
1583                "  return i;\n"
1584                "}",
1585                AllowSimpleBracedStatements);
1586 
1587   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
1588   // Where line-lengths matter, a 2-letter synonym that maintains line length.
1589   // Not IF to avoid any confusion that IF is somehow special.
1590   AllowSimpleBracedStatements.IfMacros.push_back("FI");
1591   AllowSimpleBracedStatements.ColumnLimit = 40;
1592   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1593       FormatStyle::SBS_Always;
1594   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1595   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1596   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1597   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1598 
1599   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1600   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1601   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1602   verifyFormat("if consteval {}", AllowSimpleBracedStatements);
1603   verifyFormat("if !consteval {}", AllowSimpleBracedStatements);
1604   verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements);
1605   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1606   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1607   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1608   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1609   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1610   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1611   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1612   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1613   verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements);
1614   verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements);
1615   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1616   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1617   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1618   verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements);
1619   verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements);
1620   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1621   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1622   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1623                AllowSimpleBracedStatements);
1624   verifyFormat("if (true) {\n"
1625                "  ffffffffffffffffffffffff();\n"
1626                "}",
1627                AllowSimpleBracedStatements);
1628   verifyFormat("if (true) {\n"
1629                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1630                "}",
1631                AllowSimpleBracedStatements);
1632   verifyFormat("if (true) { //\n"
1633                "  f();\n"
1634                "}",
1635                AllowSimpleBracedStatements);
1636   verifyFormat("if (true) {\n"
1637                "  f();\n"
1638                "  f();\n"
1639                "}",
1640                AllowSimpleBracedStatements);
1641   verifyFormat("if (true) {\n"
1642                "  f();\n"
1643                "} else {\n"
1644                "  f();\n"
1645                "}",
1646                AllowSimpleBracedStatements);
1647   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1648                AllowSimpleBracedStatements);
1649   verifyFormat("MYIF (true) {\n"
1650                "  ffffffffffffffffffffffff();\n"
1651                "}",
1652                AllowSimpleBracedStatements);
1653   verifyFormat("MYIF (true) {\n"
1654                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1655                "}",
1656                AllowSimpleBracedStatements);
1657   verifyFormat("MYIF (true) { //\n"
1658                "  f();\n"
1659                "}",
1660                AllowSimpleBracedStatements);
1661   verifyFormat("MYIF (true) {\n"
1662                "  f();\n"
1663                "  f();\n"
1664                "}",
1665                AllowSimpleBracedStatements);
1666   verifyFormat("MYIF (true) {\n"
1667                "  f();\n"
1668                "} else {\n"
1669                "  f();\n"
1670                "}",
1671                AllowSimpleBracedStatements);
1672 
1673   verifyFormat("struct A2 {\n"
1674                "  int X;\n"
1675                "};",
1676                AllowSimpleBracedStatements);
1677   verifyFormat("typedef struct A2 {\n"
1678                "  int X;\n"
1679                "} A2_t;",
1680                AllowSimpleBracedStatements);
1681   verifyFormat("template <int> struct A2 {\n"
1682                "  struct B {};\n"
1683                "};",
1684                AllowSimpleBracedStatements);
1685 
1686   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1687       FormatStyle::SIS_Never;
1688   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1689   verifyFormat("if (true) {\n"
1690                "  f();\n"
1691                "}",
1692                AllowSimpleBracedStatements);
1693   verifyFormat("if (true) {\n"
1694                "  f();\n"
1695                "} else {\n"
1696                "  f();\n"
1697                "}",
1698                AllowSimpleBracedStatements);
1699   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1700   verifyFormat("MYIF (true) {\n"
1701                "  f();\n"
1702                "}",
1703                AllowSimpleBracedStatements);
1704   verifyFormat("MYIF (true) {\n"
1705                "  f();\n"
1706                "} else {\n"
1707                "  f();\n"
1708                "}",
1709                AllowSimpleBracedStatements);
1710 
1711   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1712   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1713   verifyFormat("while (true) {\n"
1714                "  f();\n"
1715                "}",
1716                AllowSimpleBracedStatements);
1717   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1718   verifyFormat("for (;;) {\n"
1719                "  f();\n"
1720                "}",
1721                AllowSimpleBracedStatements);
1722   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1723   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1724                "  f();\n"
1725                "}",
1726                AllowSimpleBracedStatements);
1727 
1728   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1729       FormatStyle::SIS_WithoutElse;
1730   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1731   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1732       FormatStyle::BWACS_Always;
1733 
1734   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1735   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1736   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1737   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1738   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1739   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1740   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1741   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1742   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1743   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1744   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1745   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1746   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1747   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1748   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1749   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1750   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1751                AllowSimpleBracedStatements);
1752   verifyFormat("if (true)\n"
1753                "{\n"
1754                "  ffffffffffffffffffffffff();\n"
1755                "}",
1756                AllowSimpleBracedStatements);
1757   verifyFormat("if (true)\n"
1758                "{\n"
1759                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1760                "}",
1761                AllowSimpleBracedStatements);
1762   verifyFormat("if (true)\n"
1763                "{ //\n"
1764                "  f();\n"
1765                "}",
1766                AllowSimpleBracedStatements);
1767   verifyFormat("if (true)\n"
1768                "{\n"
1769                "  f();\n"
1770                "  f();\n"
1771                "}",
1772                AllowSimpleBracedStatements);
1773   verifyFormat("if (true)\n"
1774                "{\n"
1775                "  f();\n"
1776                "} else\n"
1777                "{\n"
1778                "  f();\n"
1779                "}",
1780                AllowSimpleBracedStatements);
1781   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1782                AllowSimpleBracedStatements);
1783   verifyFormat("MYIF (true)\n"
1784                "{\n"
1785                "  ffffffffffffffffffffffff();\n"
1786                "}",
1787                AllowSimpleBracedStatements);
1788   verifyFormat("MYIF (true)\n"
1789                "{\n"
1790                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1791                "}",
1792                AllowSimpleBracedStatements);
1793   verifyFormat("MYIF (true)\n"
1794                "{ //\n"
1795                "  f();\n"
1796                "}",
1797                AllowSimpleBracedStatements);
1798   verifyFormat("MYIF (true)\n"
1799                "{\n"
1800                "  f();\n"
1801                "  f();\n"
1802                "}",
1803                AllowSimpleBracedStatements);
1804   verifyFormat("MYIF (true)\n"
1805                "{\n"
1806                "  f();\n"
1807                "} else\n"
1808                "{\n"
1809                "  f();\n"
1810                "}",
1811                AllowSimpleBracedStatements);
1812 
1813   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1814       FormatStyle::SIS_Never;
1815   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1816   verifyFormat("if (true)\n"
1817                "{\n"
1818                "  f();\n"
1819                "}",
1820                AllowSimpleBracedStatements);
1821   verifyFormat("if (true)\n"
1822                "{\n"
1823                "  f();\n"
1824                "} else\n"
1825                "{\n"
1826                "  f();\n"
1827                "}",
1828                AllowSimpleBracedStatements);
1829   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1830   verifyFormat("MYIF (true)\n"
1831                "{\n"
1832                "  f();\n"
1833                "}",
1834                AllowSimpleBracedStatements);
1835   verifyFormat("MYIF (true)\n"
1836                "{\n"
1837                "  f();\n"
1838                "} else\n"
1839                "{\n"
1840                "  f();\n"
1841                "}",
1842                AllowSimpleBracedStatements);
1843 
1844   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1845   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1846   verifyFormat("while (true)\n"
1847                "{\n"
1848                "  f();\n"
1849                "}",
1850                AllowSimpleBracedStatements);
1851   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1852   verifyFormat("for (;;)\n"
1853                "{\n"
1854                "  f();\n"
1855                "}",
1856                AllowSimpleBracedStatements);
1857   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1858   verifyFormat("BOOST_FOREACH (int v, vec)\n"
1859                "{\n"
1860                "  f();\n"
1861                "}",
1862                AllowSimpleBracedStatements);
1863 }
1864 
1865 TEST_F(FormatTest, UnderstandsMacros) {
1866   verifyFormat("#define A (parentheses)");
1867   verifyFormat("/* comment */ #define A (parentheses)");
1868   verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
1869   // Even the partial code should never be merged.
1870   EXPECT_EQ("/* comment */ #define A (parentheses)\n"
1871             "#",
1872             format("/* comment */ #define A (parentheses)\n"
1873                    "#"));
1874   verifyFormat("/* comment */ #define A (parentheses)\n"
1875                "#\n");
1876   verifyFormat("/* comment */ #define A (parentheses)\n"
1877                "#define B (parentheses)");
1878   verifyFormat("#define true ((int)1)");
1879   verifyFormat("#define and(x)");
1880   verifyFormat("#define if(x) x");
1881   verifyFormat("#define return(x) (x)");
1882   verifyFormat("#define while(x) for (; x;)");
1883   verifyFormat("#define xor(x) (^(x))");
1884   verifyFormat("#define __except(x)");
1885   verifyFormat("#define __try(x)");
1886 
1887   // https://llvm.org/PR54348.
1888   verifyFormat(
1889       "#define A"
1890       "                                                                      "
1891       "\\\n"
1892       "  class & {}");
1893 
1894   FormatStyle Style = getLLVMStyle();
1895   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1896   Style.BraceWrapping.AfterFunction = true;
1897   // Test that a macro definition never gets merged with the following
1898   // definition.
1899   // FIXME: The AAA macro definition probably should not be split into 3 lines.
1900   verifyFormat("#define AAA                                                    "
1901                "                \\\n"
1902                "  N                                                            "
1903                "                \\\n"
1904                "  {\n"
1905                "#define BBB }\n",
1906                Style);
1907   // verifyFormat("#define AAA N { //\n", Style);
1908 
1909   verifyFormat("MACRO(return)");
1910   verifyFormat("MACRO(co_await)");
1911   verifyFormat("MACRO(co_return)");
1912   verifyFormat("MACRO(co_yield)");
1913   verifyFormat("MACRO(return, something)");
1914   verifyFormat("MACRO(co_return, something)");
1915   verifyFormat("MACRO(something##something)");
1916   verifyFormat("MACRO(return##something)");
1917   verifyFormat("MACRO(co_return##something)");
1918 }
1919 
1920 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1921   FormatStyle Style = getLLVMStyleWithColumns(60);
1922   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1923   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1924   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1925   EXPECT_EQ("#define A                                                  \\\n"
1926             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1927             "  {                                                        \\\n"
1928             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1929             "  }\n"
1930             "X;",
1931             format("#define A \\\n"
1932                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1933                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1934                    "   }\n"
1935                    "X;",
1936                    Style));
1937 }
1938 
1939 TEST_F(FormatTest, ParseIfElse) {
1940   verifyFormat("if (true)\n"
1941                "  if (true)\n"
1942                "    if (true)\n"
1943                "      f();\n"
1944                "    else\n"
1945                "      g();\n"
1946                "  else\n"
1947                "    h();\n"
1948                "else\n"
1949                "  i();");
1950   verifyFormat("if (true)\n"
1951                "  if (true)\n"
1952                "    if (true) {\n"
1953                "      if (true)\n"
1954                "        f();\n"
1955                "    } else {\n"
1956                "      g();\n"
1957                "    }\n"
1958                "  else\n"
1959                "    h();\n"
1960                "else {\n"
1961                "  i();\n"
1962                "}");
1963   verifyFormat("if (true)\n"
1964                "  if constexpr (true)\n"
1965                "    if (true) {\n"
1966                "      if constexpr (true)\n"
1967                "        f();\n"
1968                "    } else {\n"
1969                "      g();\n"
1970                "    }\n"
1971                "  else\n"
1972                "    h();\n"
1973                "else {\n"
1974                "  i();\n"
1975                "}");
1976   verifyFormat("if (true)\n"
1977                "  if CONSTEXPR (true)\n"
1978                "    if (true) {\n"
1979                "      if CONSTEXPR (true)\n"
1980                "        f();\n"
1981                "    } else {\n"
1982                "      g();\n"
1983                "    }\n"
1984                "  else\n"
1985                "    h();\n"
1986                "else {\n"
1987                "  i();\n"
1988                "}");
1989   verifyFormat("void f() {\n"
1990                "  if (a) {\n"
1991                "  } else {\n"
1992                "  }\n"
1993                "}");
1994 }
1995 
1996 TEST_F(FormatTest, ElseIf) {
1997   verifyFormat("if (a) {\n} else if (b) {\n}");
1998   verifyFormat("if (a)\n"
1999                "  f();\n"
2000                "else if (b)\n"
2001                "  g();\n"
2002                "else\n"
2003                "  h();");
2004   verifyFormat("if (a)\n"
2005                "  f();\n"
2006                "else // comment\n"
2007                "  if (b) {\n"
2008                "    g();\n"
2009                "    h();\n"
2010                "  }");
2011   verifyFormat("if constexpr (a)\n"
2012                "  f();\n"
2013                "else if constexpr (b)\n"
2014                "  g();\n"
2015                "else\n"
2016                "  h();");
2017   verifyFormat("if CONSTEXPR (a)\n"
2018                "  f();\n"
2019                "else if CONSTEXPR (b)\n"
2020                "  g();\n"
2021                "else\n"
2022                "  h();");
2023   verifyFormat("if (a) {\n"
2024                "  f();\n"
2025                "}\n"
2026                "// or else ..\n"
2027                "else {\n"
2028                "  g()\n"
2029                "}");
2030 
2031   verifyFormat("if (a) {\n"
2032                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2033                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2034                "}");
2035   verifyFormat("if (a) {\n"
2036                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2037                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2038                "}");
2039   verifyFormat("if (a) {\n"
2040                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2041                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2042                "}");
2043   verifyFormat("if (a) {\n"
2044                "} else if (\n"
2045                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2046                "}",
2047                getLLVMStyleWithColumns(62));
2048   verifyFormat("if (a) {\n"
2049                "} else if constexpr (\n"
2050                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2051                "}",
2052                getLLVMStyleWithColumns(62));
2053   verifyFormat("if (a) {\n"
2054                "} else if CONSTEXPR (\n"
2055                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2056                "}",
2057                getLLVMStyleWithColumns(62));
2058 }
2059 
2060 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
2061   FormatStyle Style = getLLVMStyle();
2062   EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
2063   EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer);
2064   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
2065   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
2066   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
2067   verifyFormat("int *f1(int &a) const &;", Style);
2068   verifyFormat("int *f1(int &a) const & = 0;", Style);
2069   verifyFormat("int *a = f1();", Style);
2070   verifyFormat("int &b = f2();", Style);
2071   verifyFormat("int &&c = f3();", Style);
2072   verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
2073   verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2074   verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", 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 auto &c : {1, 2, 3})", Style);
2077   verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2078   verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
2079   verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
2080   verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
2081   verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
2082   verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
2083   verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
2084   verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
2085   verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
2086   verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
2087   verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
2088   verifyFormat(
2089       "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n"
2090       "                     res2 = [](int &a) { return 0000000000000; };",
2091       Style);
2092 
2093   Style.AlignConsecutiveDeclarations.Enabled = true;
2094   verifyFormat("Const unsigned int *c;\n"
2095                "const unsigned int *d;\n"
2096                "Const unsigned int &e;\n"
2097                "const unsigned int &f;\n"
2098                "const unsigned    &&g;\n"
2099                "Const unsigned      h;",
2100                Style);
2101 
2102   Style.PointerAlignment = FormatStyle::PAS_Left;
2103   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
2104   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
2105   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
2106   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
2107   verifyFormat("int* f1(int& a) const& = 0;", Style);
2108   verifyFormat("int* a = f1();", Style);
2109   verifyFormat("int& b = f2();", Style);
2110   verifyFormat("int&& c = f3();", Style);
2111   verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2112   verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2113   verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2114   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2115   verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2116   verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2117   verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2118   verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2119   verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
2120   verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
2121   verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
2122   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2123   verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
2124   verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
2125   verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
2126   verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
2127   verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
2128   verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
2129   verifyFormat(
2130       "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n"
2131       "                    res2 = [](int& a) { return 0000000000000; };",
2132       Style);
2133 
2134   Style.AlignConsecutiveDeclarations.Enabled = true;
2135   verifyFormat("Const unsigned int* c;\n"
2136                "const unsigned int* d;\n"
2137                "Const unsigned int& e;\n"
2138                "const unsigned int& f;\n"
2139                "const unsigned&&    g;\n"
2140                "Const unsigned      h;",
2141                Style);
2142 
2143   Style.PointerAlignment = FormatStyle::PAS_Right;
2144   Style.ReferenceAlignment = FormatStyle::RAS_Left;
2145   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
2146   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
2147   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
2148   verifyFormat("int *a = f1();", Style);
2149   verifyFormat("int& b = f2();", Style);
2150   verifyFormat("int&& c = f3();", Style);
2151   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2152   verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2153   verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
2154 
2155   Style.AlignConsecutiveDeclarations.Enabled = true;
2156   verifyFormat("Const unsigned int *c;\n"
2157                "const unsigned int *d;\n"
2158                "Const unsigned int& e;\n"
2159                "const unsigned int& f;\n"
2160                "const unsigned      g;\n"
2161                "Const unsigned      h;",
2162                Style);
2163 
2164   Style.PointerAlignment = FormatStyle::PAS_Left;
2165   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
2166   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
2167   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
2168   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
2169   verifyFormat("int* a = f1();", Style);
2170   verifyFormat("int & b = f2();", Style);
2171   verifyFormat("int && c = f3();", Style);
2172   verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
2173   verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
2174   verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
2175   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2176   verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
2177   verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
2178   verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
2179   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2180   verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
2181   verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
2182   verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
2183   verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
2184   verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
2185   verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
2186   verifyFormat(
2187       "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n"
2188       "                     res2 = [](int & a) { return 0000000000000; };",
2189       Style);
2190 
2191   Style.AlignConsecutiveDeclarations.Enabled = true;
2192   verifyFormat("Const unsigned int*  c;\n"
2193                "const unsigned int*  d;\n"
2194                "Const unsigned int & e;\n"
2195                "const unsigned int & f;\n"
2196                "const unsigned &&    g;\n"
2197                "Const unsigned       h;",
2198                Style);
2199 
2200   Style.PointerAlignment = FormatStyle::PAS_Middle;
2201   Style.ReferenceAlignment = FormatStyle::RAS_Right;
2202   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
2203   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
2204   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
2205   verifyFormat("int * a = f1();", Style);
2206   verifyFormat("int &b = f2();", Style);
2207   verifyFormat("int &&c = f3();", Style);
2208   verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2209   verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2210   verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
2211 
2212   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2213   // specifically handled
2214   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2215 }
2216 
2217 TEST_F(FormatTest, FormatsForLoop) {
2218   verifyFormat(
2219       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2220       "     ++VeryVeryLongLoopVariable)\n"
2221       "  ;");
2222   verifyFormat("for (;;)\n"
2223                "  f();");
2224   verifyFormat("for (;;) {\n}");
2225   verifyFormat("for (;;) {\n"
2226                "  f();\n"
2227                "}");
2228   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2229 
2230   verifyFormat(
2231       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2232       "                                          E = UnwrappedLines.end();\n"
2233       "     I != E; ++I) {\n}");
2234 
2235   verifyFormat(
2236       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2237       "     ++IIIII) {\n}");
2238   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2239                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2240                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2241   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2242                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2243                "         E = FD->getDeclsInPrototypeScope().end();\n"
2244                "     I != E; ++I) {\n}");
2245   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2246                "         I = Container.begin(),\n"
2247                "         E = Container.end();\n"
2248                "     I != E; ++I) {\n}",
2249                getLLVMStyleWithColumns(76));
2250 
2251   verifyFormat(
2252       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2253       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2254       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2255       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2256       "     ++aaaaaaaaaaa) {\n}");
2257   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2258                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2259                "     ++i) {\n}");
2260   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2261                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2262                "}");
2263   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2264                "         aaaaaaaaaa);\n"
2265                "     iter; ++iter) {\n"
2266                "}");
2267   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2268                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2269                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2270                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2271 
2272   // These should not be formatted as Objective-C for-in loops.
2273   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2274   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2275   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2276   verifyFormat(
2277       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2278 
2279   FormatStyle NoBinPacking = getLLVMStyle();
2280   NoBinPacking.BinPackParameters = false;
2281   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2282                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2283                "                                           aaaaaaaaaaaaaaaa,\n"
2284                "                                           aaaaaaaaaaaaaaaa,\n"
2285                "                                           aaaaaaaaaaaaaaaa);\n"
2286                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2287                "}",
2288                NoBinPacking);
2289   verifyFormat(
2290       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2291       "                                          E = UnwrappedLines.end();\n"
2292       "     I != E;\n"
2293       "     ++I) {\n}",
2294       NoBinPacking);
2295 
2296   FormatStyle AlignLeft = getLLVMStyle();
2297   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2298   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2299 }
2300 
2301 TEST_F(FormatTest, RangeBasedForLoops) {
2302   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2303                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2304   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2305                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2306   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2307                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2308   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2309                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2310 }
2311 
2312 TEST_F(FormatTest, ForEachLoops) {
2313   FormatStyle Style = getLLVMStyle();
2314   EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2315   EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
2316   verifyFormat("void f() {\n"
2317                "  for (;;) {\n"
2318                "  }\n"
2319                "  foreach (Item *item, itemlist) {\n"
2320                "  }\n"
2321                "  Q_FOREACH (Item *item, itemlist) {\n"
2322                "  }\n"
2323                "  BOOST_FOREACH (Item *item, itemlist) {\n"
2324                "  }\n"
2325                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2326                "}",
2327                Style);
2328   verifyFormat("void f() {\n"
2329                "  for (;;)\n"
2330                "    int j = 1;\n"
2331                "  Q_FOREACH (int v, vec)\n"
2332                "    v *= 2;\n"
2333                "  for (;;) {\n"
2334                "    int j = 1;\n"
2335                "  }\n"
2336                "  Q_FOREACH (int v, vec) {\n"
2337                "    v *= 2;\n"
2338                "  }\n"
2339                "}",
2340                Style);
2341 
2342   FormatStyle ShortBlocks = getLLVMStyle();
2343   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2344   EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
2345   verifyFormat("void f() {\n"
2346                "  for (;;)\n"
2347                "    int j = 1;\n"
2348                "  Q_FOREACH (int &v, vec)\n"
2349                "    v *= 2;\n"
2350                "  for (;;) {\n"
2351                "    int j = 1;\n"
2352                "  }\n"
2353                "  Q_FOREACH (int &v, vec) {\n"
2354                "    int j = 1;\n"
2355                "  }\n"
2356                "}",
2357                ShortBlocks);
2358 
2359   FormatStyle ShortLoops = getLLVMStyle();
2360   ShortLoops.AllowShortLoopsOnASingleLine = true;
2361   EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2362   verifyFormat("void f() {\n"
2363                "  for (;;) int j = 1;\n"
2364                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2365                "  for (;;) {\n"
2366                "    int j = 1;\n"
2367                "  }\n"
2368                "  Q_FOREACH (int &v, vec) {\n"
2369                "    int j = 1;\n"
2370                "  }\n"
2371                "}",
2372                ShortLoops);
2373 
2374   FormatStyle ShortBlocksAndLoops = getLLVMStyle();
2375   ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2376   ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true;
2377   verifyFormat("void f() {\n"
2378                "  for (;;) int j = 1;\n"
2379                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2380                "  for (;;) { int j = 1; }\n"
2381                "  Q_FOREACH (int &v, vec) { int j = 1; }\n"
2382                "}",
2383                ShortBlocksAndLoops);
2384 
2385   Style.SpaceBeforeParens =
2386       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2387   verifyFormat("void f() {\n"
2388                "  for (;;) {\n"
2389                "  }\n"
2390                "  foreach(Item *item, itemlist) {\n"
2391                "  }\n"
2392                "  Q_FOREACH(Item *item, itemlist) {\n"
2393                "  }\n"
2394                "  BOOST_FOREACH(Item *item, itemlist) {\n"
2395                "  }\n"
2396                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2397                "}",
2398                Style);
2399 
2400   // As function-like macros.
2401   verifyFormat("#define foreach(x, y)\n"
2402                "#define Q_FOREACH(x, y)\n"
2403                "#define BOOST_FOREACH(x, y)\n"
2404                "#define UNKNOWN_FOREACH(x, y)\n");
2405 
2406   // Not as function-like macros.
2407   verifyFormat("#define foreach (x, y)\n"
2408                "#define Q_FOREACH (x, y)\n"
2409                "#define BOOST_FOREACH (x, y)\n"
2410                "#define UNKNOWN_FOREACH (x, y)\n");
2411 
2412   // handle microsoft non standard extension
2413   verifyFormat("for each (char c in x->MyStringProperty)");
2414 }
2415 
2416 TEST_F(FormatTest, FormatsWhileLoop) {
2417   verifyFormat("while (true) {\n}");
2418   verifyFormat("while (true)\n"
2419                "  f();");
2420   verifyFormat("while () {\n}");
2421   verifyFormat("while () {\n"
2422                "  f();\n"
2423                "}");
2424 }
2425 
2426 TEST_F(FormatTest, FormatsDoWhile) {
2427   verifyFormat("do {\n"
2428                "  do_something();\n"
2429                "} while (something());");
2430   verifyFormat("do\n"
2431                "  do_something();\n"
2432                "while (something());");
2433 }
2434 
2435 TEST_F(FormatTest, FormatsSwitchStatement) {
2436   verifyFormat("switch (x) {\n"
2437                "case 1:\n"
2438                "  f();\n"
2439                "  break;\n"
2440                "case kFoo:\n"
2441                "case ns::kBar:\n"
2442                "case kBaz:\n"
2443                "  break;\n"
2444                "default:\n"
2445                "  g();\n"
2446                "  break;\n"
2447                "}");
2448   verifyFormat("switch (x) {\n"
2449                "case 1: {\n"
2450                "  f();\n"
2451                "  break;\n"
2452                "}\n"
2453                "case 2: {\n"
2454                "  break;\n"
2455                "}\n"
2456                "}");
2457   verifyFormat("switch (x) {\n"
2458                "case 1: {\n"
2459                "  f();\n"
2460                "  {\n"
2461                "    g();\n"
2462                "    h();\n"
2463                "  }\n"
2464                "  break;\n"
2465                "}\n"
2466                "}");
2467   verifyFormat("switch (x) {\n"
2468                "case 1: {\n"
2469                "  f();\n"
2470                "  if (foo) {\n"
2471                "    g();\n"
2472                "    h();\n"
2473                "  }\n"
2474                "  break;\n"
2475                "}\n"
2476                "}");
2477   verifyFormat("switch (x) {\n"
2478                "case 1: {\n"
2479                "  f();\n"
2480                "  g();\n"
2481                "} break;\n"
2482                "}");
2483   verifyFormat("switch (test)\n"
2484                "  ;");
2485   verifyFormat("switch (x) {\n"
2486                "default: {\n"
2487                "  // Do nothing.\n"
2488                "}\n"
2489                "}");
2490   verifyFormat("switch (x) {\n"
2491                "// comment\n"
2492                "// if 1, do f()\n"
2493                "case 1:\n"
2494                "  f();\n"
2495                "}");
2496   verifyFormat("switch (x) {\n"
2497                "case 1:\n"
2498                "  // Do amazing stuff\n"
2499                "  {\n"
2500                "    f();\n"
2501                "    g();\n"
2502                "  }\n"
2503                "  break;\n"
2504                "}");
2505   verifyFormat("#define A          \\\n"
2506                "  switch (x) {     \\\n"
2507                "  case a:          \\\n"
2508                "    foo = b;       \\\n"
2509                "  }",
2510                getLLVMStyleWithColumns(20));
2511   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2512                "  case OP_name:                        \\\n"
2513                "    return operations::Operation##name\n",
2514                getLLVMStyleWithColumns(40));
2515   verifyFormat("switch (x) {\n"
2516                "case 1:;\n"
2517                "default:;\n"
2518                "  int i;\n"
2519                "}");
2520 
2521   verifyGoogleFormat("switch (x) {\n"
2522                      "  case 1:\n"
2523                      "    f();\n"
2524                      "    break;\n"
2525                      "  case kFoo:\n"
2526                      "  case ns::kBar:\n"
2527                      "  case kBaz:\n"
2528                      "    break;\n"
2529                      "  default:\n"
2530                      "    g();\n"
2531                      "    break;\n"
2532                      "}");
2533   verifyGoogleFormat("switch (x) {\n"
2534                      "  case 1: {\n"
2535                      "    f();\n"
2536                      "    break;\n"
2537                      "  }\n"
2538                      "}");
2539   verifyGoogleFormat("switch (test)\n"
2540                      "  ;");
2541 
2542   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2543                      "  case OP_name:              \\\n"
2544                      "    return operations::Operation##name\n");
2545   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2546                      "  // Get the correction operation class.\n"
2547                      "  switch (OpCode) {\n"
2548                      "    CASE(Add);\n"
2549                      "    CASE(Subtract);\n"
2550                      "    default:\n"
2551                      "      return operations::Unknown;\n"
2552                      "  }\n"
2553                      "#undef OPERATION_CASE\n"
2554                      "}");
2555   verifyFormat("DEBUG({\n"
2556                "  switch (x) {\n"
2557                "  case A:\n"
2558                "    f();\n"
2559                "    break;\n"
2560                "    // fallthrough\n"
2561                "  case B:\n"
2562                "    g();\n"
2563                "    break;\n"
2564                "  }\n"
2565                "});");
2566   EXPECT_EQ("DEBUG({\n"
2567             "  switch (x) {\n"
2568             "  case A:\n"
2569             "    f();\n"
2570             "    break;\n"
2571             "  // On B:\n"
2572             "  case B:\n"
2573             "    g();\n"
2574             "    break;\n"
2575             "  }\n"
2576             "});",
2577             format("DEBUG({\n"
2578                    "  switch (x) {\n"
2579                    "  case A:\n"
2580                    "    f();\n"
2581                    "    break;\n"
2582                    "  // On B:\n"
2583                    "  case B:\n"
2584                    "    g();\n"
2585                    "    break;\n"
2586                    "  }\n"
2587                    "});",
2588                    getLLVMStyle()));
2589   EXPECT_EQ("switch (n) {\n"
2590             "case 0: {\n"
2591             "  return false;\n"
2592             "}\n"
2593             "default: {\n"
2594             "  return true;\n"
2595             "}\n"
2596             "}",
2597             format("switch (n)\n"
2598                    "{\n"
2599                    "case 0: {\n"
2600                    "  return false;\n"
2601                    "}\n"
2602                    "default: {\n"
2603                    "  return true;\n"
2604                    "}\n"
2605                    "}",
2606                    getLLVMStyle()));
2607   verifyFormat("switch (a) {\n"
2608                "case (b):\n"
2609                "  return;\n"
2610                "}");
2611 
2612   verifyFormat("switch (a) {\n"
2613                "case some_namespace::\n"
2614                "    some_constant:\n"
2615                "  return;\n"
2616                "}",
2617                getLLVMStyleWithColumns(34));
2618 
2619   verifyFormat("switch (a) {\n"
2620                "[[likely]] case 1:\n"
2621                "  return;\n"
2622                "}");
2623   verifyFormat("switch (a) {\n"
2624                "[[likely]] [[other::likely]] case 1:\n"
2625                "  return;\n"
2626                "}");
2627   verifyFormat("switch (x) {\n"
2628                "case 1:\n"
2629                "  return;\n"
2630                "[[likely]] case 2:\n"
2631                "  return;\n"
2632                "}");
2633   verifyFormat("switch (a) {\n"
2634                "case 1:\n"
2635                "[[likely]] case 2:\n"
2636                "  return;\n"
2637                "}");
2638   FormatStyle Attributes = getLLVMStyle();
2639   Attributes.AttributeMacros.push_back("LIKELY");
2640   Attributes.AttributeMacros.push_back("OTHER_LIKELY");
2641   verifyFormat("switch (a) {\n"
2642                "LIKELY case b:\n"
2643                "  return;\n"
2644                "}",
2645                Attributes);
2646   verifyFormat("switch (a) {\n"
2647                "LIKELY OTHER_LIKELY() case b:\n"
2648                "  return;\n"
2649                "}",
2650                Attributes);
2651   verifyFormat("switch (a) {\n"
2652                "case 1:\n"
2653                "  return;\n"
2654                "LIKELY case 2:\n"
2655                "  return;\n"
2656                "}",
2657                Attributes);
2658   verifyFormat("switch (a) {\n"
2659                "case 1:\n"
2660                "LIKELY case 2:\n"
2661                "  return;\n"
2662                "}",
2663                Attributes);
2664 
2665   FormatStyle Style = getLLVMStyle();
2666   Style.IndentCaseLabels = true;
2667   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2668   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2669   Style.BraceWrapping.AfterCaseLabel = true;
2670   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2671   EXPECT_EQ("switch (n)\n"
2672             "{\n"
2673             "  case 0:\n"
2674             "  {\n"
2675             "    return false;\n"
2676             "  }\n"
2677             "  default:\n"
2678             "  {\n"
2679             "    return true;\n"
2680             "  }\n"
2681             "}",
2682             format("switch (n) {\n"
2683                    "  case 0: {\n"
2684                    "    return false;\n"
2685                    "  }\n"
2686                    "  default: {\n"
2687                    "    return true;\n"
2688                    "  }\n"
2689                    "}",
2690                    Style));
2691   Style.BraceWrapping.AfterCaseLabel = false;
2692   EXPECT_EQ("switch (n)\n"
2693             "{\n"
2694             "  case 0: {\n"
2695             "    return false;\n"
2696             "  }\n"
2697             "  default: {\n"
2698             "    return true;\n"
2699             "  }\n"
2700             "}",
2701             format("switch (n) {\n"
2702                    "  case 0:\n"
2703                    "  {\n"
2704                    "    return false;\n"
2705                    "  }\n"
2706                    "  default:\n"
2707                    "  {\n"
2708                    "    return true;\n"
2709                    "  }\n"
2710                    "}",
2711                    Style));
2712   Style.IndentCaseLabels = false;
2713   Style.IndentCaseBlocks = true;
2714   EXPECT_EQ("switch (n)\n"
2715             "{\n"
2716             "case 0:\n"
2717             "  {\n"
2718             "    return false;\n"
2719             "  }\n"
2720             "case 1:\n"
2721             "  break;\n"
2722             "default:\n"
2723             "  {\n"
2724             "    return true;\n"
2725             "  }\n"
2726             "}",
2727             format("switch (n) {\n"
2728                    "case 0: {\n"
2729                    "  return false;\n"
2730                    "}\n"
2731                    "case 1:\n"
2732                    "  break;\n"
2733                    "default: {\n"
2734                    "  return true;\n"
2735                    "}\n"
2736                    "}",
2737                    Style));
2738   Style.IndentCaseLabels = true;
2739   Style.IndentCaseBlocks = true;
2740   EXPECT_EQ("switch (n)\n"
2741             "{\n"
2742             "  case 0:\n"
2743             "    {\n"
2744             "      return false;\n"
2745             "    }\n"
2746             "  case 1:\n"
2747             "    break;\n"
2748             "  default:\n"
2749             "    {\n"
2750             "      return true;\n"
2751             "    }\n"
2752             "}",
2753             format("switch (n) {\n"
2754                    "case 0: {\n"
2755                    "  return false;\n"
2756                    "}\n"
2757                    "case 1:\n"
2758                    "  break;\n"
2759                    "default: {\n"
2760                    "  return true;\n"
2761                    "}\n"
2762                    "}",
2763                    Style));
2764 }
2765 
2766 TEST_F(FormatTest, CaseRanges) {
2767   verifyFormat("switch (x) {\n"
2768                "case 'A' ... 'Z':\n"
2769                "case 1 ... 5:\n"
2770                "case a ... b:\n"
2771                "  break;\n"
2772                "}");
2773 }
2774 
2775 TEST_F(FormatTest, ShortEnums) {
2776   FormatStyle Style = getLLVMStyle();
2777   EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine);
2778   EXPECT_FALSE(Style.BraceWrapping.AfterEnum);
2779   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2780   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2781   Style.AllowShortEnumsOnASingleLine = false;
2782   verifyFormat("enum {\n"
2783                "  A,\n"
2784                "  B,\n"
2785                "  C\n"
2786                "} ShortEnum1, ShortEnum2;",
2787                Style);
2788   verifyFormat("typedef enum {\n"
2789                "  A,\n"
2790                "  B,\n"
2791                "  C\n"
2792                "} ShortEnum1, ShortEnum2;",
2793                Style);
2794   verifyFormat("enum {\n"
2795                "  A,\n"
2796                "} ShortEnum1, ShortEnum2;",
2797                Style);
2798   verifyFormat("typedef enum {\n"
2799                "  A,\n"
2800                "} ShortEnum1, ShortEnum2;",
2801                Style);
2802   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2803   Style.BraceWrapping.AfterEnum = true;
2804   verifyFormat("enum\n"
2805                "{\n"
2806                "  A,\n"
2807                "  B,\n"
2808                "  C\n"
2809                "} ShortEnum1, ShortEnum2;",
2810                Style);
2811   verifyFormat("typedef enum\n"
2812                "{\n"
2813                "  A,\n"
2814                "  B,\n"
2815                "  C\n"
2816                "} ShortEnum1, ShortEnum2;",
2817                Style);
2818 }
2819 
2820 TEST_F(FormatTest, ShortCaseLabels) {
2821   FormatStyle Style = getLLVMStyle();
2822   Style.AllowShortCaseLabelsOnASingleLine = true;
2823   verifyFormat("switch (a) {\n"
2824                "case 1: x = 1; break;\n"
2825                "case 2: return;\n"
2826                "case 3:\n"
2827                "case 4:\n"
2828                "case 5: return;\n"
2829                "case 6: // comment\n"
2830                "  return;\n"
2831                "case 7:\n"
2832                "  // comment\n"
2833                "  return;\n"
2834                "case 8:\n"
2835                "  x = 8; // comment\n"
2836                "  break;\n"
2837                "default: y = 1; break;\n"
2838                "}",
2839                Style);
2840   verifyFormat("switch (a) {\n"
2841                "case 0: return; // comment\n"
2842                "case 1: break;  // comment\n"
2843                "case 2: return;\n"
2844                "// comment\n"
2845                "case 3: return;\n"
2846                "// comment 1\n"
2847                "// comment 2\n"
2848                "// comment 3\n"
2849                "case 4: break; /* comment */\n"
2850                "case 5:\n"
2851                "  // comment\n"
2852                "  break;\n"
2853                "case 6: /* comment */ x = 1; break;\n"
2854                "case 7: x = /* comment */ 1; break;\n"
2855                "case 8:\n"
2856                "  x = 1; /* comment */\n"
2857                "  break;\n"
2858                "case 9:\n"
2859                "  break; // comment line 1\n"
2860                "         // comment line 2\n"
2861                "}",
2862                Style);
2863   EXPECT_EQ("switch (a) {\n"
2864             "case 1:\n"
2865             "  x = 8;\n"
2866             "  // fall through\n"
2867             "case 2: x = 8;\n"
2868             "// comment\n"
2869             "case 3:\n"
2870             "  return; /* comment line 1\n"
2871             "           * comment line 2 */\n"
2872             "case 4: i = 8;\n"
2873             "// something else\n"
2874             "#if FOO\n"
2875             "case 5: break;\n"
2876             "#endif\n"
2877             "}",
2878             format("switch (a) {\n"
2879                    "case 1: x = 8;\n"
2880                    "  // fall through\n"
2881                    "case 2:\n"
2882                    "  x = 8;\n"
2883                    "// comment\n"
2884                    "case 3:\n"
2885                    "  return; /* comment line 1\n"
2886                    "           * comment line 2 */\n"
2887                    "case 4:\n"
2888                    "  i = 8;\n"
2889                    "// something else\n"
2890                    "#if FOO\n"
2891                    "case 5: break;\n"
2892                    "#endif\n"
2893                    "}",
2894                    Style));
2895   EXPECT_EQ("switch (a) {\n"
2896             "case 0:\n"
2897             "  return; // long long long long long long long long long long "
2898             "long long comment\n"
2899             "          // line\n"
2900             "}",
2901             format("switch (a) {\n"
2902                    "case 0: return; // long long long long long long long long "
2903                    "long long long long comment line\n"
2904                    "}",
2905                    Style));
2906   EXPECT_EQ("switch (a) {\n"
2907             "case 0:\n"
2908             "  return; /* long long long long long long long long long long "
2909             "long long comment\n"
2910             "             line */\n"
2911             "}",
2912             format("switch (a) {\n"
2913                    "case 0: return; /* long long long long long long long long "
2914                    "long long long long comment line */\n"
2915                    "}",
2916                    Style));
2917   verifyFormat("switch (a) {\n"
2918                "#if FOO\n"
2919                "case 0: return 0;\n"
2920                "#endif\n"
2921                "}",
2922                Style);
2923   verifyFormat("switch (a) {\n"
2924                "case 1: {\n"
2925                "}\n"
2926                "case 2: {\n"
2927                "  return;\n"
2928                "}\n"
2929                "case 3: {\n"
2930                "  x = 1;\n"
2931                "  return;\n"
2932                "}\n"
2933                "case 4:\n"
2934                "  if (x)\n"
2935                "    return;\n"
2936                "}",
2937                Style);
2938   Style.ColumnLimit = 21;
2939   verifyFormat("switch (a) {\n"
2940                "case 1: x = 1; break;\n"
2941                "case 2: return;\n"
2942                "case 3:\n"
2943                "case 4:\n"
2944                "case 5: return;\n"
2945                "default:\n"
2946                "  y = 1;\n"
2947                "  break;\n"
2948                "}",
2949                Style);
2950   Style.ColumnLimit = 80;
2951   Style.AllowShortCaseLabelsOnASingleLine = false;
2952   Style.IndentCaseLabels = true;
2953   EXPECT_EQ("switch (n) {\n"
2954             "  default /*comments*/:\n"
2955             "    return true;\n"
2956             "  case 0:\n"
2957             "    return false;\n"
2958             "}",
2959             format("switch (n) {\n"
2960                    "default/*comments*/:\n"
2961                    "  return true;\n"
2962                    "case 0:\n"
2963                    "  return false;\n"
2964                    "}",
2965                    Style));
2966   Style.AllowShortCaseLabelsOnASingleLine = true;
2967   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2968   Style.BraceWrapping.AfterCaseLabel = true;
2969   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2970   EXPECT_EQ("switch (n)\n"
2971             "{\n"
2972             "  case 0:\n"
2973             "  {\n"
2974             "    return false;\n"
2975             "  }\n"
2976             "  default:\n"
2977             "  {\n"
2978             "    return true;\n"
2979             "  }\n"
2980             "}",
2981             format("switch (n) {\n"
2982                    "  case 0: {\n"
2983                    "    return false;\n"
2984                    "  }\n"
2985                    "  default:\n"
2986                    "  {\n"
2987                    "    return true;\n"
2988                    "  }\n"
2989                    "}",
2990                    Style));
2991 }
2992 
2993 TEST_F(FormatTest, FormatsLabels) {
2994   verifyFormat("void f() {\n"
2995                "  some_code();\n"
2996                "test_label:\n"
2997                "  some_other_code();\n"
2998                "  {\n"
2999                "    some_more_code();\n"
3000                "  another_label:\n"
3001                "    some_more_code();\n"
3002                "  }\n"
3003                "}");
3004   verifyFormat("{\n"
3005                "  some_code();\n"
3006                "test_label:\n"
3007                "  some_other_code();\n"
3008                "}");
3009   verifyFormat("{\n"
3010                "  some_code();\n"
3011                "test_label:;\n"
3012                "  int i = 0;\n"
3013                "}");
3014   FormatStyle Style = getLLVMStyle();
3015   Style.IndentGotoLabels = false;
3016   verifyFormat("void f() {\n"
3017                "  some_code();\n"
3018                "test_label:\n"
3019                "  some_other_code();\n"
3020                "  {\n"
3021                "    some_more_code();\n"
3022                "another_label:\n"
3023                "    some_more_code();\n"
3024                "  }\n"
3025                "}",
3026                Style);
3027   verifyFormat("{\n"
3028                "  some_code();\n"
3029                "test_label:\n"
3030                "  some_other_code();\n"
3031                "}",
3032                Style);
3033   verifyFormat("{\n"
3034                "  some_code();\n"
3035                "test_label:;\n"
3036                "  int i = 0;\n"
3037                "}");
3038 }
3039 
3040 TEST_F(FormatTest, MultiLineControlStatements) {
3041   FormatStyle Style = getLLVMStyleWithColumns(20);
3042   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3043   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3044   // Short lines should keep opening brace on same line.
3045   EXPECT_EQ("if (foo) {\n"
3046             "  bar();\n"
3047             "}",
3048             format("if(foo){bar();}", Style));
3049   EXPECT_EQ("if (foo) {\n"
3050             "  bar();\n"
3051             "} else {\n"
3052             "  baz();\n"
3053             "}",
3054             format("if(foo){bar();}else{baz();}", Style));
3055   EXPECT_EQ("if (foo && bar) {\n"
3056             "  baz();\n"
3057             "}",
3058             format("if(foo&&bar){baz();}", Style));
3059   EXPECT_EQ("if (foo) {\n"
3060             "  bar();\n"
3061             "} else if (baz) {\n"
3062             "  quux();\n"
3063             "}",
3064             format("if(foo){bar();}else if(baz){quux();}", Style));
3065   EXPECT_EQ(
3066       "if (foo) {\n"
3067       "  bar();\n"
3068       "} else if (baz) {\n"
3069       "  quux();\n"
3070       "} else {\n"
3071       "  foobar();\n"
3072       "}",
3073       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
3074   EXPECT_EQ("for (;;) {\n"
3075             "  foo();\n"
3076             "}",
3077             format("for(;;){foo();}"));
3078   EXPECT_EQ("while (1) {\n"
3079             "  foo();\n"
3080             "}",
3081             format("while(1){foo();}", Style));
3082   EXPECT_EQ("switch (foo) {\n"
3083             "case bar:\n"
3084             "  return;\n"
3085             "}",
3086             format("switch(foo){case bar:return;}", Style));
3087   EXPECT_EQ("try {\n"
3088             "  foo();\n"
3089             "} catch (...) {\n"
3090             "  bar();\n"
3091             "}",
3092             format("try{foo();}catch(...){bar();}", Style));
3093   EXPECT_EQ("do {\n"
3094             "  foo();\n"
3095             "} while (bar &&\n"
3096             "         baz);",
3097             format("do{foo();}while(bar&&baz);", Style));
3098   // Long lines should put opening brace on new line.
3099   verifyFormat("void f() {\n"
3100                "  if (a1 && a2 &&\n"
3101                "      a3)\n"
3102                "  {\n"
3103                "    quux();\n"
3104                "  }\n"
3105                "}",
3106                "void f(){if(a1&&a2&&a3){quux();}}", Style);
3107   EXPECT_EQ("if (foo && bar &&\n"
3108             "    baz)\n"
3109             "{\n"
3110             "  quux();\n"
3111             "}",
3112             format("if(foo&&bar&&baz){quux();}", Style));
3113   EXPECT_EQ("if (foo && bar &&\n"
3114             "    baz)\n"
3115             "{\n"
3116             "  quux();\n"
3117             "}",
3118             format("if (foo && bar &&\n"
3119                    "    baz) {\n"
3120                    "  quux();\n"
3121                    "}",
3122                    Style));
3123   EXPECT_EQ("if (foo) {\n"
3124             "  bar();\n"
3125             "} else if (baz ||\n"
3126             "           quux)\n"
3127             "{\n"
3128             "  foobar();\n"
3129             "}",
3130             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
3131   EXPECT_EQ(
3132       "if (foo) {\n"
3133       "  bar();\n"
3134       "} else if (baz ||\n"
3135       "           quux)\n"
3136       "{\n"
3137       "  foobar();\n"
3138       "} else {\n"
3139       "  barbaz();\n"
3140       "}",
3141       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3142              Style));
3143   EXPECT_EQ("for (int i = 0;\n"
3144             "     i < 10; ++i)\n"
3145             "{\n"
3146             "  foo();\n"
3147             "}",
3148             format("for(int i=0;i<10;++i){foo();}", Style));
3149   EXPECT_EQ("foreach (int i,\n"
3150             "         list)\n"
3151             "{\n"
3152             "  foo();\n"
3153             "}",
3154             format("foreach(int i, list){foo();}", Style));
3155   Style.ColumnLimit =
3156       40; // to concentrate at brace wrapping, not line wrap due to column limit
3157   EXPECT_EQ("foreach (int i, list) {\n"
3158             "  foo();\n"
3159             "}",
3160             format("foreach(int i, list){foo();}", Style));
3161   Style.ColumnLimit =
3162       20; // to concentrate at brace wrapping, not line wrap due to column limit
3163   EXPECT_EQ("while (foo || bar ||\n"
3164             "       baz)\n"
3165             "{\n"
3166             "  quux();\n"
3167             "}",
3168             format("while(foo||bar||baz){quux();}", Style));
3169   EXPECT_EQ("switch (\n"
3170             "    foo = barbaz)\n"
3171             "{\n"
3172             "case quux:\n"
3173             "  return;\n"
3174             "}",
3175             format("switch(foo=barbaz){case quux:return;}", Style));
3176   EXPECT_EQ("try {\n"
3177             "  foo();\n"
3178             "} catch (\n"
3179             "    Exception &bar)\n"
3180             "{\n"
3181             "  baz();\n"
3182             "}",
3183             format("try{foo();}catch(Exception&bar){baz();}", Style));
3184   Style.ColumnLimit =
3185       40; // to concentrate at brace wrapping, not line wrap due to column limit
3186   EXPECT_EQ("try {\n"
3187             "  foo();\n"
3188             "} catch (Exception &bar) {\n"
3189             "  baz();\n"
3190             "}",
3191             format("try{foo();}catch(Exception&bar){baz();}", Style));
3192   Style.ColumnLimit =
3193       20; // to concentrate at brace wrapping, not line wrap due to column limit
3194 
3195   Style.BraceWrapping.BeforeElse = true;
3196   EXPECT_EQ(
3197       "if (foo) {\n"
3198       "  bar();\n"
3199       "}\n"
3200       "else if (baz ||\n"
3201       "         quux)\n"
3202       "{\n"
3203       "  foobar();\n"
3204       "}\n"
3205       "else {\n"
3206       "  barbaz();\n"
3207       "}",
3208       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3209              Style));
3210 
3211   Style.BraceWrapping.BeforeCatch = true;
3212   EXPECT_EQ("try {\n"
3213             "  foo();\n"
3214             "}\n"
3215             "catch (...) {\n"
3216             "  baz();\n"
3217             "}",
3218             format("try{foo();}catch(...){baz();}", Style));
3219 
3220   Style.BraceWrapping.AfterFunction = true;
3221   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3222   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
3223   Style.ColumnLimit = 80;
3224   verifyFormat("void shortfunction() { bar(); }", Style);
3225 
3226   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
3227   verifyFormat("void shortfunction()\n"
3228                "{\n"
3229                "  bar();\n"
3230                "}",
3231                Style);
3232 }
3233 
3234 TEST_F(FormatTest, BeforeWhile) {
3235   FormatStyle Style = getLLVMStyle();
3236   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3237 
3238   verifyFormat("do {\n"
3239                "  foo();\n"
3240                "} while (1);",
3241                Style);
3242   Style.BraceWrapping.BeforeWhile = true;
3243   verifyFormat("do {\n"
3244                "  foo();\n"
3245                "}\n"
3246                "while (1);",
3247                Style);
3248 }
3249 
3250 //===----------------------------------------------------------------------===//
3251 // Tests for classes, namespaces, etc.
3252 //===----------------------------------------------------------------------===//
3253 
3254 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
3255   verifyFormat("class A {};");
3256 }
3257 
3258 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
3259   verifyFormat("class A {\n"
3260                "public:\n"
3261                "public: // comment\n"
3262                "protected:\n"
3263                "private:\n"
3264                "  void f() {}\n"
3265                "};");
3266   verifyFormat("export class A {\n"
3267                "public:\n"
3268                "public: // comment\n"
3269                "protected:\n"
3270                "private:\n"
3271                "  void f() {}\n"
3272                "};");
3273   verifyGoogleFormat("class A {\n"
3274                      " public:\n"
3275                      " protected:\n"
3276                      " private:\n"
3277                      "  void f() {}\n"
3278                      "};");
3279   verifyGoogleFormat("export class A {\n"
3280                      " public:\n"
3281                      " protected:\n"
3282                      " private:\n"
3283                      "  void f() {}\n"
3284                      "};");
3285   verifyFormat("class A {\n"
3286                "public slots:\n"
3287                "  void f1() {}\n"
3288                "public Q_SLOTS:\n"
3289                "  void f2() {}\n"
3290                "protected slots:\n"
3291                "  void f3() {}\n"
3292                "protected Q_SLOTS:\n"
3293                "  void f4() {}\n"
3294                "private slots:\n"
3295                "  void f5() {}\n"
3296                "private Q_SLOTS:\n"
3297                "  void f6() {}\n"
3298                "signals:\n"
3299                "  void g1();\n"
3300                "Q_SIGNALS:\n"
3301                "  void g2();\n"
3302                "};");
3303 
3304   // Don't interpret 'signals' the wrong way.
3305   verifyFormat("signals.set();");
3306   verifyFormat("for (Signals signals : f()) {\n}");
3307   verifyFormat("{\n"
3308                "  signals.set(); // This needs indentation.\n"
3309                "}");
3310   verifyFormat("void f() {\n"
3311                "label:\n"
3312                "  signals.baz();\n"
3313                "}");
3314   verifyFormat("private[1];");
3315   verifyFormat("testArray[public] = 1;");
3316   verifyFormat("public();");
3317   verifyFormat("myFunc(public);");
3318   verifyFormat("std::vector<int> testVec = {private};");
3319   verifyFormat("private.p = 1;");
3320   verifyFormat("void function(private...){};");
3321   verifyFormat("if (private && public)\n");
3322   verifyFormat("private &= true;");
3323   verifyFormat("int x = private * public;");
3324   verifyFormat("public *= private;");
3325   verifyFormat("int x = public + private;");
3326   verifyFormat("private++;");
3327   verifyFormat("++private;");
3328   verifyFormat("public += private;");
3329   verifyFormat("public = public - private;");
3330   verifyFormat("public->foo();");
3331   verifyFormat("private--;");
3332   verifyFormat("--private;");
3333   verifyFormat("public -= 1;");
3334   verifyFormat("if (!private && !public)\n");
3335   verifyFormat("public != private;");
3336   verifyFormat("int x = public / private;");
3337   verifyFormat("public /= 2;");
3338   verifyFormat("public = public % 2;");
3339   verifyFormat("public %= 2;");
3340   verifyFormat("if (public < private)\n");
3341   verifyFormat("public << private;");
3342   verifyFormat("public <<= private;");
3343   verifyFormat("if (public > private)\n");
3344   verifyFormat("public >> private;");
3345   verifyFormat("public >>= private;");
3346   verifyFormat("public ^ private;");
3347   verifyFormat("public ^= private;");
3348   verifyFormat("public | private;");
3349   verifyFormat("public |= private;");
3350   verifyFormat("auto x = private ? 1 : 2;");
3351   verifyFormat("if (public == private)\n");
3352   verifyFormat("void foo(public, private)");
3353   verifyFormat("public::foo();");
3354 
3355   verifyFormat("class A {\n"
3356                "public:\n"
3357                "  std::unique_ptr<int *[]> b() { return nullptr; }\n"
3358                "\n"
3359                "private:\n"
3360                "  int c;\n"
3361                "};");
3362 }
3363 
3364 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3365   EXPECT_EQ("class A {\n"
3366             "public:\n"
3367             "  void f();\n"
3368             "\n"
3369             "private:\n"
3370             "  void g() {}\n"
3371             "  // test\n"
3372             "protected:\n"
3373             "  int h;\n"
3374             "};",
3375             format("class A {\n"
3376                    "public:\n"
3377                    "void f();\n"
3378                    "private:\n"
3379                    "void g() {}\n"
3380                    "// test\n"
3381                    "protected:\n"
3382                    "int h;\n"
3383                    "};"));
3384   EXPECT_EQ("class A {\n"
3385             "protected:\n"
3386             "public:\n"
3387             "  void f();\n"
3388             "};",
3389             format("class A {\n"
3390                    "protected:\n"
3391                    "\n"
3392                    "public:\n"
3393                    "\n"
3394                    "  void f();\n"
3395                    "};"));
3396 
3397   // Even ensure proper spacing inside macros.
3398   EXPECT_EQ("#define B     \\\n"
3399             "  class A {   \\\n"
3400             "   protected: \\\n"
3401             "   public:    \\\n"
3402             "    void f(); \\\n"
3403             "  };",
3404             format("#define B     \\\n"
3405                    "  class A {   \\\n"
3406                    "   protected: \\\n"
3407                    "              \\\n"
3408                    "   public:    \\\n"
3409                    "              \\\n"
3410                    "    void f(); \\\n"
3411                    "  };",
3412                    getGoogleStyle()));
3413   // But don't remove empty lines after macros ending in access specifiers.
3414   EXPECT_EQ("#define A private:\n"
3415             "\n"
3416             "int i;",
3417             format("#define A         private:\n"
3418                    "\n"
3419                    "int              i;"));
3420 }
3421 
3422 TEST_F(FormatTest, FormatsClasses) {
3423   verifyFormat("class A : public B {};");
3424   verifyFormat("class A : public ::B {};");
3425 
3426   verifyFormat(
3427       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3428       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3429   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3430                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3431                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3432   verifyFormat(
3433       "class A : public B, public C, public D, public E, public F {};");
3434   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3435                "                     public C,\n"
3436                "                     public D,\n"
3437                "                     public E,\n"
3438                "                     public F,\n"
3439                "                     public G {};");
3440 
3441   verifyFormat("class\n"
3442                "    ReallyReallyLongClassName {\n"
3443                "  int i;\n"
3444                "};",
3445                getLLVMStyleWithColumns(32));
3446   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3447                "                           aaaaaaaaaaaaaaaa> {};");
3448   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3449                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3450                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3451   verifyFormat("template <class R, class C>\n"
3452                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3453                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3454   verifyFormat("class ::A::B {};");
3455 }
3456 
3457 TEST_F(FormatTest, BreakInheritanceStyle) {
3458   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3459   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3460       FormatStyle::BILS_BeforeComma;
3461   verifyFormat("class MyClass : public X {};",
3462                StyleWithInheritanceBreakBeforeComma);
3463   verifyFormat("class MyClass\n"
3464                "    : public X\n"
3465                "    , public Y {};",
3466                StyleWithInheritanceBreakBeforeComma);
3467   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3468                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3469                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3470                StyleWithInheritanceBreakBeforeComma);
3471   verifyFormat("struct aaaaaaaaaaaaa\n"
3472                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3473                "          aaaaaaaaaaaaaaaa> {};",
3474                StyleWithInheritanceBreakBeforeComma);
3475 
3476   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3477   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3478       FormatStyle::BILS_AfterColon;
3479   verifyFormat("class MyClass : public X {};",
3480                StyleWithInheritanceBreakAfterColon);
3481   verifyFormat("class MyClass : public X, public Y {};",
3482                StyleWithInheritanceBreakAfterColon);
3483   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3484                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3485                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3486                StyleWithInheritanceBreakAfterColon);
3487   verifyFormat("struct aaaaaaaaaaaaa :\n"
3488                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3489                "        aaaaaaaaaaaaaaaa> {};",
3490                StyleWithInheritanceBreakAfterColon);
3491 
3492   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3493   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3494       FormatStyle::BILS_AfterComma;
3495   verifyFormat("class MyClass : public X {};",
3496                StyleWithInheritanceBreakAfterComma);
3497   verifyFormat("class MyClass : public X,\n"
3498                "                public Y {};",
3499                StyleWithInheritanceBreakAfterComma);
3500   verifyFormat(
3501       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3502       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3503       "{};",
3504       StyleWithInheritanceBreakAfterComma);
3505   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3506                "                           aaaaaaaaaaaaaaaa> {};",
3507                StyleWithInheritanceBreakAfterComma);
3508   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3509                "    : public OnceBreak,\n"
3510                "      public AlwaysBreak,\n"
3511                "      EvenBasesFitInOneLine {};",
3512                StyleWithInheritanceBreakAfterComma);
3513 }
3514 
3515 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) {
3516   verifyFormat("class A {\n} a, b;");
3517   verifyFormat("struct A {\n} a, b;");
3518   verifyFormat("union A {\n} a, b;");
3519 
3520   verifyFormat("constexpr class A {\n} a, b;");
3521   verifyFormat("constexpr struct A {\n} a, b;");
3522   verifyFormat("constexpr union A {\n} a, b;");
3523 
3524   verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace");
3525   verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace");
3526   verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace");
3527 
3528   verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace");
3529   verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace");
3530   verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace");
3531 
3532   verifyFormat("namespace ns {\n"
3533                "class {\n"
3534                "} a, b;\n"
3535                "} // namespace ns");
3536   verifyFormat("namespace ns {\n"
3537                "const class {\n"
3538                "} a, b;\n"
3539                "} // namespace ns");
3540   verifyFormat("namespace ns {\n"
3541                "constexpr class C {\n"
3542                "} a, b;\n"
3543                "} // namespace ns");
3544   verifyFormat("namespace ns {\n"
3545                "class { /* comment */\n"
3546                "} a, b;\n"
3547                "} // namespace ns");
3548   verifyFormat("namespace ns {\n"
3549                "const class { /* comment */\n"
3550                "} a, b;\n"
3551                "} // namespace ns");
3552 }
3553 
3554 TEST_F(FormatTest, FormatsEnum) {
3555   verifyFormat("enum {\n"
3556                "  Zero,\n"
3557                "  One = 1,\n"
3558                "  Two = One + 1,\n"
3559                "  Three = (One + Two),\n"
3560                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3561                "  Five = (One, Two, Three, Four, 5)\n"
3562                "};");
3563   verifyGoogleFormat("enum {\n"
3564                      "  Zero,\n"
3565                      "  One = 1,\n"
3566                      "  Two = One + 1,\n"
3567                      "  Three = (One + Two),\n"
3568                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3569                      "  Five = (One, Two, Three, Four, 5)\n"
3570                      "};");
3571   verifyFormat("enum Enum {};");
3572   verifyFormat("enum {};");
3573   verifyFormat("enum X E {} d;");
3574   verifyFormat("enum __attribute__((...)) E {} d;");
3575   verifyFormat("enum __declspec__((...)) E {} d;");
3576   verifyFormat("enum [[nodiscard]] E {} d;");
3577   verifyFormat("enum {\n"
3578                "  Bar = Foo<int, int>::value\n"
3579                "};",
3580                getLLVMStyleWithColumns(30));
3581 
3582   verifyFormat("enum ShortEnum { A, B, C };");
3583   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3584 
3585   EXPECT_EQ("enum KeepEmptyLines {\n"
3586             "  ONE,\n"
3587             "\n"
3588             "  TWO,\n"
3589             "\n"
3590             "  THREE\n"
3591             "}",
3592             format("enum KeepEmptyLines {\n"
3593                    "  ONE,\n"
3594                    "\n"
3595                    "  TWO,\n"
3596                    "\n"
3597                    "\n"
3598                    "  THREE\n"
3599                    "}"));
3600   verifyFormat("enum E { // comment\n"
3601                "  ONE,\n"
3602                "  TWO\n"
3603                "};\n"
3604                "int i;");
3605 
3606   FormatStyle EightIndent = getLLVMStyle();
3607   EightIndent.IndentWidth = 8;
3608   verifyFormat("enum {\n"
3609                "        VOID,\n"
3610                "        CHAR,\n"
3611                "        SHORT,\n"
3612                "        INT,\n"
3613                "        LONG,\n"
3614                "        SIGNED,\n"
3615                "        UNSIGNED,\n"
3616                "        BOOL,\n"
3617                "        FLOAT,\n"
3618                "        DOUBLE,\n"
3619                "        COMPLEX\n"
3620                "};",
3621                EightIndent);
3622 
3623   verifyFormat("enum [[nodiscard]] E {\n"
3624                "  ONE,\n"
3625                "  TWO,\n"
3626                "};");
3627   verifyFormat("enum [[nodiscard]] E {\n"
3628                "  // Comment 1\n"
3629                "  ONE,\n"
3630                "  // Comment 2\n"
3631                "  TWO,\n"
3632                "};");
3633 
3634   // Not enums.
3635   verifyFormat("enum X f() {\n"
3636                "  a();\n"
3637                "  return 42;\n"
3638                "}");
3639   verifyFormat("enum X Type::f() {\n"
3640                "  a();\n"
3641                "  return 42;\n"
3642                "}");
3643   verifyFormat("enum ::X f() {\n"
3644                "  a();\n"
3645                "  return 42;\n"
3646                "}");
3647   verifyFormat("enum ns::X f() {\n"
3648                "  a();\n"
3649                "  return 42;\n"
3650                "}");
3651 }
3652 
3653 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3654   verifyFormat("enum Type {\n"
3655                "  One = 0; // These semicolons should be commas.\n"
3656                "  Two = 1;\n"
3657                "};");
3658   verifyFormat("namespace n {\n"
3659                "enum Type {\n"
3660                "  One,\n"
3661                "  Two, // missing };\n"
3662                "  int i;\n"
3663                "}\n"
3664                "void g() {}");
3665 }
3666 
3667 TEST_F(FormatTest, FormatsEnumStruct) {
3668   verifyFormat("enum struct {\n"
3669                "  Zero,\n"
3670                "  One = 1,\n"
3671                "  Two = One + 1,\n"
3672                "  Three = (One + Two),\n"
3673                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3674                "  Five = (One, Two, Three, Four, 5)\n"
3675                "};");
3676   verifyFormat("enum struct Enum {};");
3677   verifyFormat("enum struct {};");
3678   verifyFormat("enum struct X E {} d;");
3679   verifyFormat("enum struct __attribute__((...)) E {} d;");
3680   verifyFormat("enum struct __declspec__((...)) E {} d;");
3681   verifyFormat("enum struct [[nodiscard]] E {} d;");
3682   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3683 
3684   verifyFormat("enum struct [[nodiscard]] E {\n"
3685                "  ONE,\n"
3686                "  TWO,\n"
3687                "};");
3688   verifyFormat("enum struct [[nodiscard]] E {\n"
3689                "  // Comment 1\n"
3690                "  ONE,\n"
3691                "  // Comment 2\n"
3692                "  TWO,\n"
3693                "};");
3694 }
3695 
3696 TEST_F(FormatTest, FormatsEnumClass) {
3697   verifyFormat("enum class {\n"
3698                "  Zero,\n"
3699                "  One = 1,\n"
3700                "  Two = One + 1,\n"
3701                "  Three = (One + Two),\n"
3702                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3703                "  Five = (One, Two, Three, Four, 5)\n"
3704                "};");
3705   verifyFormat("enum class Enum {};");
3706   verifyFormat("enum class {};");
3707   verifyFormat("enum class X E {} d;");
3708   verifyFormat("enum class __attribute__((...)) E {} d;");
3709   verifyFormat("enum class __declspec__((...)) E {} d;");
3710   verifyFormat("enum class [[nodiscard]] E {} d;");
3711   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3712 
3713   verifyFormat("enum class [[nodiscard]] E {\n"
3714                "  ONE,\n"
3715                "  TWO,\n"
3716                "};");
3717   verifyFormat("enum class [[nodiscard]] E {\n"
3718                "  // Comment 1\n"
3719                "  ONE,\n"
3720                "  // Comment 2\n"
3721                "  TWO,\n"
3722                "};");
3723 }
3724 
3725 TEST_F(FormatTest, FormatsEnumTypes) {
3726   verifyFormat("enum X : int {\n"
3727                "  A, // Force multiple lines.\n"
3728                "  B\n"
3729                "};");
3730   verifyFormat("enum X : int { A, B };");
3731   verifyFormat("enum X : std::uint32_t { A, B };");
3732 }
3733 
3734 TEST_F(FormatTest, FormatsTypedefEnum) {
3735   FormatStyle Style = getLLVMStyleWithColumns(40);
3736   verifyFormat("typedef enum {} EmptyEnum;");
3737   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3738   verifyFormat("typedef enum {\n"
3739                "  ZERO = 0,\n"
3740                "  ONE = 1,\n"
3741                "  TWO = 2,\n"
3742                "  THREE = 3\n"
3743                "} LongEnum;",
3744                Style);
3745   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3746   Style.BraceWrapping.AfterEnum = true;
3747   verifyFormat("typedef enum {} EmptyEnum;");
3748   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3749   verifyFormat("typedef enum\n"
3750                "{\n"
3751                "  ZERO = 0,\n"
3752                "  ONE = 1,\n"
3753                "  TWO = 2,\n"
3754                "  THREE = 3\n"
3755                "} LongEnum;",
3756                Style);
3757 }
3758 
3759 TEST_F(FormatTest, FormatsNSEnums) {
3760   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3761   verifyGoogleFormat(
3762       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3763   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3764                      "  // Information about someDecentlyLongValue.\n"
3765                      "  someDecentlyLongValue,\n"
3766                      "  // Information about anotherDecentlyLongValue.\n"
3767                      "  anotherDecentlyLongValue,\n"
3768                      "  // Information about aThirdDecentlyLongValue.\n"
3769                      "  aThirdDecentlyLongValue\n"
3770                      "};");
3771   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3772                      "  // Information about someDecentlyLongValue.\n"
3773                      "  someDecentlyLongValue,\n"
3774                      "  // Information about anotherDecentlyLongValue.\n"
3775                      "  anotherDecentlyLongValue,\n"
3776                      "  // Information about aThirdDecentlyLongValue.\n"
3777                      "  aThirdDecentlyLongValue\n"
3778                      "};");
3779   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3780                      "  a = 1,\n"
3781                      "  b = 2,\n"
3782                      "  c = 3,\n"
3783                      "};");
3784   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3785                      "  a = 1,\n"
3786                      "  b = 2,\n"
3787                      "  c = 3,\n"
3788                      "};");
3789   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3790                      "  a = 1,\n"
3791                      "  b = 2,\n"
3792                      "  c = 3,\n"
3793                      "};");
3794   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3795                      "  a = 1,\n"
3796                      "  b = 2,\n"
3797                      "  c = 3,\n"
3798                      "};");
3799 }
3800 
3801 TEST_F(FormatTest, FormatsBitfields) {
3802   verifyFormat("struct Bitfields {\n"
3803                "  unsigned sClass : 8;\n"
3804                "  unsigned ValueKind : 2;\n"
3805                "};");
3806   verifyFormat("struct A {\n"
3807                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3808                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3809                "};");
3810   verifyFormat("struct MyStruct {\n"
3811                "  uchar data;\n"
3812                "  uchar : 8;\n"
3813                "  uchar : 8;\n"
3814                "  uchar other;\n"
3815                "};");
3816   FormatStyle Style = getLLVMStyle();
3817   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3818   verifyFormat("struct Bitfields {\n"
3819                "  unsigned sClass:8;\n"
3820                "  unsigned ValueKind:2;\n"
3821                "  uchar other;\n"
3822                "};",
3823                Style);
3824   verifyFormat("struct A {\n"
3825                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3826                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3827                "};",
3828                Style);
3829   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3830   verifyFormat("struct Bitfields {\n"
3831                "  unsigned sClass :8;\n"
3832                "  unsigned ValueKind :2;\n"
3833                "  uchar other;\n"
3834                "};",
3835                Style);
3836   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3837   verifyFormat("struct Bitfields {\n"
3838                "  unsigned sClass: 8;\n"
3839                "  unsigned ValueKind: 2;\n"
3840                "  uchar other;\n"
3841                "};",
3842                Style);
3843 }
3844 
3845 TEST_F(FormatTest, FormatsNamespaces) {
3846   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3847   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3848 
3849   verifyFormat("namespace some_namespace {\n"
3850                "class A {};\n"
3851                "void f() { f(); }\n"
3852                "}",
3853                LLVMWithNoNamespaceFix);
3854   verifyFormat("#define M(x) x##x\n"
3855                "namespace M(x) {\n"
3856                "class A {};\n"
3857                "void f() { f(); }\n"
3858                "}",
3859                LLVMWithNoNamespaceFix);
3860   verifyFormat("#define M(x) x##x\n"
3861                "namespace N::inline M(x) {\n"
3862                "class A {};\n"
3863                "void f() { f(); }\n"
3864                "}",
3865                LLVMWithNoNamespaceFix);
3866   verifyFormat("#define M(x) x##x\n"
3867                "namespace M(x)::inline N {\n"
3868                "class A {};\n"
3869                "void f() { f(); }\n"
3870                "}",
3871                LLVMWithNoNamespaceFix);
3872   verifyFormat("#define M(x) x##x\n"
3873                "namespace N::M(x) {\n"
3874                "class A {};\n"
3875                "void f() { f(); }\n"
3876                "}",
3877                LLVMWithNoNamespaceFix);
3878   verifyFormat("#define M(x) x##x\n"
3879                "namespace M::N(x) {\n"
3880                "class A {};\n"
3881                "void f() { f(); }\n"
3882                "}",
3883                LLVMWithNoNamespaceFix);
3884   verifyFormat("namespace N::inline D {\n"
3885                "class A {};\n"
3886                "void f() { f(); }\n"
3887                "}",
3888                LLVMWithNoNamespaceFix);
3889   verifyFormat("namespace N::inline D::E {\n"
3890                "class A {};\n"
3891                "void f() { f(); }\n"
3892                "}",
3893                LLVMWithNoNamespaceFix);
3894   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3895                "class A {};\n"
3896                "void f() { f(); }\n"
3897                "}",
3898                LLVMWithNoNamespaceFix);
3899   verifyFormat("/* something */ namespace some_namespace {\n"
3900                "class A {};\n"
3901                "void f() { f(); }\n"
3902                "}",
3903                LLVMWithNoNamespaceFix);
3904   verifyFormat("namespace {\n"
3905                "class A {};\n"
3906                "void f() { f(); }\n"
3907                "}",
3908                LLVMWithNoNamespaceFix);
3909   verifyFormat("/* something */ namespace {\n"
3910                "class A {};\n"
3911                "void f() { f(); }\n"
3912                "}",
3913                LLVMWithNoNamespaceFix);
3914   verifyFormat("inline namespace X {\n"
3915                "class A {};\n"
3916                "void f() { f(); }\n"
3917                "}",
3918                LLVMWithNoNamespaceFix);
3919   verifyFormat("/* something */ inline namespace X {\n"
3920                "class A {};\n"
3921                "void f() { f(); }\n"
3922                "}",
3923                LLVMWithNoNamespaceFix);
3924   verifyFormat("export namespace X {\n"
3925                "class A {};\n"
3926                "void f() { f(); }\n"
3927                "}",
3928                LLVMWithNoNamespaceFix);
3929   verifyFormat("using namespace some_namespace;\n"
3930                "class A {};\n"
3931                "void f() { f(); }",
3932                LLVMWithNoNamespaceFix);
3933 
3934   // This code is more common than we thought; if we
3935   // layout this correctly the semicolon will go into
3936   // its own line, which is undesirable.
3937   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3938   verifyFormat("namespace {\n"
3939                "class A {};\n"
3940                "};",
3941                LLVMWithNoNamespaceFix);
3942 
3943   verifyFormat("namespace {\n"
3944                "int SomeVariable = 0; // comment\n"
3945                "} // namespace",
3946                LLVMWithNoNamespaceFix);
3947   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3948             "#define HEADER_GUARD\n"
3949             "namespace my_namespace {\n"
3950             "int i;\n"
3951             "} // my_namespace\n"
3952             "#endif // HEADER_GUARD",
3953             format("#ifndef HEADER_GUARD\n"
3954                    " #define HEADER_GUARD\n"
3955                    "   namespace my_namespace {\n"
3956                    "int i;\n"
3957                    "}    // my_namespace\n"
3958                    "#endif    // HEADER_GUARD",
3959                    LLVMWithNoNamespaceFix));
3960 
3961   EXPECT_EQ("namespace A::B {\n"
3962             "class C {};\n"
3963             "}",
3964             format("namespace A::B {\n"
3965                    "class C {};\n"
3966                    "}",
3967                    LLVMWithNoNamespaceFix));
3968 
3969   FormatStyle Style = getLLVMStyle();
3970   Style.NamespaceIndentation = FormatStyle::NI_All;
3971   EXPECT_EQ("namespace out {\n"
3972             "  int i;\n"
3973             "  namespace in {\n"
3974             "    int i;\n"
3975             "  } // namespace in\n"
3976             "} // namespace out",
3977             format("namespace out {\n"
3978                    "int i;\n"
3979                    "namespace in {\n"
3980                    "int i;\n"
3981                    "} // namespace in\n"
3982                    "} // namespace out",
3983                    Style));
3984 
3985   FormatStyle ShortInlineFunctions = getLLVMStyle();
3986   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3987   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3988       FormatStyle::SFS_Inline;
3989   verifyFormat("namespace {\n"
3990                "  void f() {\n"
3991                "    return;\n"
3992                "  }\n"
3993                "} // namespace\n",
3994                ShortInlineFunctions);
3995   verifyFormat("namespace { /* comment */\n"
3996                "  void f() {\n"
3997                "    return;\n"
3998                "  }\n"
3999                "} // namespace\n",
4000                ShortInlineFunctions);
4001   verifyFormat("namespace { // comment\n"
4002                "  void f() {\n"
4003                "    return;\n"
4004                "  }\n"
4005                "} // namespace\n",
4006                ShortInlineFunctions);
4007   verifyFormat("namespace {\n"
4008                "  int some_int;\n"
4009                "  void f() {\n"
4010                "    return;\n"
4011                "  }\n"
4012                "} // namespace\n",
4013                ShortInlineFunctions);
4014   verifyFormat("namespace interface {\n"
4015                "  void f() {\n"
4016                "    return;\n"
4017                "  }\n"
4018                "} // namespace interface\n",
4019                ShortInlineFunctions);
4020   verifyFormat("namespace {\n"
4021                "  class X {\n"
4022                "    void f() { return; }\n"
4023                "  };\n"
4024                "} // namespace\n",
4025                ShortInlineFunctions);
4026   verifyFormat("namespace {\n"
4027                "  class X { /* comment */\n"
4028                "    void f() { return; }\n"
4029                "  };\n"
4030                "} // namespace\n",
4031                ShortInlineFunctions);
4032   verifyFormat("namespace {\n"
4033                "  class X { // comment\n"
4034                "    void f() { return; }\n"
4035                "  };\n"
4036                "} // namespace\n",
4037                ShortInlineFunctions);
4038   verifyFormat("namespace {\n"
4039                "  struct X {\n"
4040                "    void f() { return; }\n"
4041                "  };\n"
4042                "} // namespace\n",
4043                ShortInlineFunctions);
4044   verifyFormat("namespace {\n"
4045                "  union X {\n"
4046                "    void f() { return; }\n"
4047                "  };\n"
4048                "} // namespace\n",
4049                ShortInlineFunctions);
4050   verifyFormat("extern \"C\" {\n"
4051                "void f() {\n"
4052                "  return;\n"
4053                "}\n"
4054                "} // namespace\n",
4055                ShortInlineFunctions);
4056   verifyFormat("namespace {\n"
4057                "  class X {\n"
4058                "    void f() { return; }\n"
4059                "  } x;\n"
4060                "} // namespace\n",
4061                ShortInlineFunctions);
4062   verifyFormat("namespace {\n"
4063                "  [[nodiscard]] class X {\n"
4064                "    void f() { return; }\n"
4065                "  };\n"
4066                "} // namespace\n",
4067                ShortInlineFunctions);
4068   verifyFormat("namespace {\n"
4069                "  static class X {\n"
4070                "    void f() { return; }\n"
4071                "  } x;\n"
4072                "} // namespace\n",
4073                ShortInlineFunctions);
4074   verifyFormat("namespace {\n"
4075                "  constexpr class X {\n"
4076                "    void f() { return; }\n"
4077                "  } x;\n"
4078                "} // namespace\n",
4079                ShortInlineFunctions);
4080 
4081   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
4082   verifyFormat("extern \"C\" {\n"
4083                "  void f() {\n"
4084                "    return;\n"
4085                "  }\n"
4086                "} // namespace\n",
4087                ShortInlineFunctions);
4088 
4089   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4090   EXPECT_EQ("namespace out {\n"
4091             "int i;\n"
4092             "namespace in {\n"
4093             "  int i;\n"
4094             "} // namespace in\n"
4095             "} // namespace out",
4096             format("namespace out {\n"
4097                    "int i;\n"
4098                    "namespace in {\n"
4099                    "int i;\n"
4100                    "} // namespace in\n"
4101                    "} // namespace out",
4102                    Style));
4103 
4104   Style.NamespaceIndentation = FormatStyle::NI_None;
4105   verifyFormat("template <class T>\n"
4106                "concept a_concept = X<>;\n"
4107                "namespace B {\n"
4108                "struct b_struct {};\n"
4109                "} // namespace B\n",
4110                Style);
4111   verifyFormat("template <int I>\n"
4112                "constexpr void foo()\n"
4113                "  requires(I == 42)\n"
4114                "{}\n"
4115                "namespace ns {\n"
4116                "void foo() {}\n"
4117                "} // namespace ns\n",
4118                Style);
4119 }
4120 
4121 TEST_F(FormatTest, NamespaceMacros) {
4122   FormatStyle Style = getLLVMStyle();
4123   Style.NamespaceMacros.push_back("TESTSUITE");
4124 
4125   verifyFormat("TESTSUITE(A) {\n"
4126                "int foo();\n"
4127                "} // TESTSUITE(A)",
4128                Style);
4129 
4130   verifyFormat("TESTSUITE(A, B) {\n"
4131                "int foo();\n"
4132                "} // TESTSUITE(A)",
4133                Style);
4134 
4135   // Properly indent according to NamespaceIndentation style
4136   Style.NamespaceIndentation = FormatStyle::NI_All;
4137   verifyFormat("TESTSUITE(A) {\n"
4138                "  int foo();\n"
4139                "} // TESTSUITE(A)",
4140                Style);
4141   verifyFormat("TESTSUITE(A) {\n"
4142                "  namespace B {\n"
4143                "    int foo();\n"
4144                "  } // namespace B\n"
4145                "} // TESTSUITE(A)",
4146                Style);
4147   verifyFormat("namespace A {\n"
4148                "  TESTSUITE(B) {\n"
4149                "    int foo();\n"
4150                "  } // TESTSUITE(B)\n"
4151                "} // namespace A",
4152                Style);
4153 
4154   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4155   verifyFormat("TESTSUITE(A) {\n"
4156                "TESTSUITE(B) {\n"
4157                "  int foo();\n"
4158                "} // TESTSUITE(B)\n"
4159                "} // TESTSUITE(A)",
4160                Style);
4161   verifyFormat("TESTSUITE(A) {\n"
4162                "namespace B {\n"
4163                "  int foo();\n"
4164                "} // namespace B\n"
4165                "} // TESTSUITE(A)",
4166                Style);
4167   verifyFormat("namespace A {\n"
4168                "TESTSUITE(B) {\n"
4169                "  int foo();\n"
4170                "} // TESTSUITE(B)\n"
4171                "} // namespace A",
4172                Style);
4173 
4174   // Properly merge namespace-macros blocks in CompactNamespaces mode
4175   Style.NamespaceIndentation = FormatStyle::NI_None;
4176   Style.CompactNamespaces = true;
4177   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
4178                "}} // TESTSUITE(A::B)",
4179                Style);
4180 
4181   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4182             "}} // TESTSUITE(out::in)",
4183             format("TESTSUITE(out) {\n"
4184                    "TESTSUITE(in) {\n"
4185                    "} // TESTSUITE(in)\n"
4186                    "} // TESTSUITE(out)",
4187                    Style));
4188 
4189   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4190             "}} // TESTSUITE(out::in)",
4191             format("TESTSUITE(out) {\n"
4192                    "TESTSUITE(in) {\n"
4193                    "} // TESTSUITE(in)\n"
4194                    "} // TESTSUITE(out)",
4195                    Style));
4196 
4197   // Do not merge different namespaces/macros
4198   EXPECT_EQ("namespace out {\n"
4199             "TESTSUITE(in) {\n"
4200             "} // TESTSUITE(in)\n"
4201             "} // namespace out",
4202             format("namespace out {\n"
4203                    "TESTSUITE(in) {\n"
4204                    "} // TESTSUITE(in)\n"
4205                    "} // namespace out",
4206                    Style));
4207   EXPECT_EQ("TESTSUITE(out) {\n"
4208             "namespace in {\n"
4209             "} // namespace in\n"
4210             "} // TESTSUITE(out)",
4211             format("TESTSUITE(out) {\n"
4212                    "namespace in {\n"
4213                    "} // namespace in\n"
4214                    "} // TESTSUITE(out)",
4215                    Style));
4216   Style.NamespaceMacros.push_back("FOOBAR");
4217   EXPECT_EQ("TESTSUITE(out) {\n"
4218             "FOOBAR(in) {\n"
4219             "} // FOOBAR(in)\n"
4220             "} // TESTSUITE(out)",
4221             format("TESTSUITE(out) {\n"
4222                    "FOOBAR(in) {\n"
4223                    "} // FOOBAR(in)\n"
4224                    "} // TESTSUITE(out)",
4225                    Style));
4226 }
4227 
4228 TEST_F(FormatTest, FormatsCompactNamespaces) {
4229   FormatStyle Style = getLLVMStyle();
4230   Style.CompactNamespaces = true;
4231   Style.NamespaceMacros.push_back("TESTSUITE");
4232 
4233   verifyFormat("namespace A { namespace B {\n"
4234                "}} // namespace A::B",
4235                Style);
4236 
4237   EXPECT_EQ("namespace out { namespace in {\n"
4238             "}} // namespace out::in",
4239             format("namespace out {\n"
4240                    "namespace in {\n"
4241                    "} // namespace in\n"
4242                    "} // namespace out",
4243                    Style));
4244 
4245   // Only namespaces which have both consecutive opening and end get compacted
4246   EXPECT_EQ("namespace out {\n"
4247             "namespace in1 {\n"
4248             "} // namespace in1\n"
4249             "namespace in2 {\n"
4250             "} // namespace in2\n"
4251             "} // namespace out",
4252             format("namespace out {\n"
4253                    "namespace in1 {\n"
4254                    "} // namespace in1\n"
4255                    "namespace in2 {\n"
4256                    "} // namespace in2\n"
4257                    "} // namespace out",
4258                    Style));
4259 
4260   EXPECT_EQ("namespace out {\n"
4261             "int i;\n"
4262             "namespace in {\n"
4263             "int j;\n"
4264             "} // namespace in\n"
4265             "int k;\n"
4266             "} // namespace out",
4267             format("namespace out { int i;\n"
4268                    "namespace in { int j; } // namespace in\n"
4269                    "int k; } // namespace out",
4270                    Style));
4271 
4272   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
4273             "}}} // namespace A::B::C\n",
4274             format("namespace A { namespace B {\n"
4275                    "namespace C {\n"
4276                    "}} // namespace B::C\n"
4277                    "} // namespace A\n",
4278                    Style));
4279 
4280   Style.ColumnLimit = 40;
4281   EXPECT_EQ("namespace aaaaaaaaaa {\n"
4282             "namespace bbbbbbbbbb {\n"
4283             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
4284             format("namespace aaaaaaaaaa {\n"
4285                    "namespace bbbbbbbbbb {\n"
4286                    "} // namespace bbbbbbbbbb\n"
4287                    "} // namespace aaaaaaaaaa",
4288                    Style));
4289 
4290   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
4291             "namespace cccccc {\n"
4292             "}}} // namespace aaaaaa::bbbbbb::cccccc",
4293             format("namespace aaaaaa {\n"
4294                    "namespace bbbbbb {\n"
4295                    "namespace cccccc {\n"
4296                    "} // namespace cccccc\n"
4297                    "} // namespace bbbbbb\n"
4298                    "} // namespace aaaaaa",
4299                    Style));
4300   Style.ColumnLimit = 80;
4301 
4302   // Extra semicolon after 'inner' closing brace prevents merging
4303   EXPECT_EQ("namespace out { namespace in {\n"
4304             "}; } // namespace out::in",
4305             format("namespace out {\n"
4306                    "namespace in {\n"
4307                    "}; // namespace in\n"
4308                    "} // namespace out",
4309                    Style));
4310 
4311   // Extra semicolon after 'outer' closing brace is conserved
4312   EXPECT_EQ("namespace out { namespace in {\n"
4313             "}}; // namespace out::in",
4314             format("namespace out {\n"
4315                    "namespace in {\n"
4316                    "} // namespace in\n"
4317                    "}; // namespace out",
4318                    Style));
4319 
4320   Style.NamespaceIndentation = FormatStyle::NI_All;
4321   EXPECT_EQ("namespace out { namespace in {\n"
4322             "  int i;\n"
4323             "}} // namespace out::in",
4324             format("namespace out {\n"
4325                    "namespace in {\n"
4326                    "int i;\n"
4327                    "} // namespace in\n"
4328                    "} // namespace out",
4329                    Style));
4330   EXPECT_EQ("namespace out { namespace mid {\n"
4331             "  namespace in {\n"
4332             "    int j;\n"
4333             "  } // namespace in\n"
4334             "  int k;\n"
4335             "}} // namespace out::mid",
4336             format("namespace out { namespace mid {\n"
4337                    "namespace in { int j; } // namespace in\n"
4338                    "int k; }} // namespace out::mid",
4339                    Style));
4340 
4341   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4342   EXPECT_EQ("namespace out { namespace in {\n"
4343             "  int i;\n"
4344             "}} // namespace out::in",
4345             format("namespace out {\n"
4346                    "namespace in {\n"
4347                    "int i;\n"
4348                    "} // namespace in\n"
4349                    "} // namespace out",
4350                    Style));
4351   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
4352             "  int i;\n"
4353             "}}} // namespace out::mid::in",
4354             format("namespace out {\n"
4355                    "namespace mid {\n"
4356                    "namespace in {\n"
4357                    "int i;\n"
4358                    "} // namespace in\n"
4359                    "} // namespace mid\n"
4360                    "} // namespace out",
4361                    Style));
4362 
4363   Style.CompactNamespaces = true;
4364   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
4365   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4366   Style.BraceWrapping.BeforeLambdaBody = true;
4367   verifyFormat("namespace out { namespace in {\n"
4368                "}} // namespace out::in",
4369                Style);
4370   EXPECT_EQ("namespace out { namespace in {\n"
4371             "}} // namespace out::in",
4372             format("namespace out {\n"
4373                    "namespace in {\n"
4374                    "} // namespace in\n"
4375                    "} // namespace out",
4376                    Style));
4377 }
4378 
4379 TEST_F(FormatTest, FormatsExternC) {
4380   verifyFormat("extern \"C\" {\nint a;");
4381   verifyFormat("extern \"C\" {}");
4382   verifyFormat("extern \"C\" {\n"
4383                "int foo();\n"
4384                "}");
4385   verifyFormat("extern \"C\" int foo() {}");
4386   verifyFormat("extern \"C\" int foo();");
4387   verifyFormat("extern \"C\" int foo() {\n"
4388                "  int i = 42;\n"
4389                "  return i;\n"
4390                "}");
4391 
4392   FormatStyle Style = getLLVMStyle();
4393   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4394   Style.BraceWrapping.AfterFunction = true;
4395   verifyFormat("extern \"C\" int foo() {}", Style);
4396   verifyFormat("extern \"C\" int foo();", Style);
4397   verifyFormat("extern \"C\" int foo()\n"
4398                "{\n"
4399                "  int i = 42;\n"
4400                "  return i;\n"
4401                "}",
4402                Style);
4403 
4404   Style.BraceWrapping.AfterExternBlock = true;
4405   Style.BraceWrapping.SplitEmptyRecord = false;
4406   verifyFormat("extern \"C\"\n"
4407                "{}",
4408                Style);
4409   verifyFormat("extern \"C\"\n"
4410                "{\n"
4411                "  int foo();\n"
4412                "}",
4413                Style);
4414 }
4415 
4416 TEST_F(FormatTest, IndentExternBlockStyle) {
4417   FormatStyle Style = getLLVMStyle();
4418   Style.IndentWidth = 2;
4419 
4420   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4421   verifyFormat("extern \"C\" { /*9*/\n"
4422                "}",
4423                Style);
4424   verifyFormat("extern \"C\" {\n"
4425                "  int foo10();\n"
4426                "}",
4427                Style);
4428 
4429   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4430   verifyFormat("extern \"C\" { /*11*/\n"
4431                "}",
4432                Style);
4433   verifyFormat("extern \"C\" {\n"
4434                "int foo12();\n"
4435                "}",
4436                Style);
4437 
4438   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4439   Style.BraceWrapping.AfterExternBlock = true;
4440   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4441   verifyFormat("extern \"C\"\n"
4442                "{ /*13*/\n"
4443                "}",
4444                Style);
4445   verifyFormat("extern \"C\"\n{\n"
4446                "  int foo14();\n"
4447                "}",
4448                Style);
4449 
4450   Style.BraceWrapping.AfterExternBlock = false;
4451   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4452   verifyFormat("extern \"C\" { /*15*/\n"
4453                "}",
4454                Style);
4455   verifyFormat("extern \"C\" {\n"
4456                "int foo16();\n"
4457                "}",
4458                Style);
4459 
4460   Style.BraceWrapping.AfterExternBlock = true;
4461   verifyFormat("extern \"C\"\n"
4462                "{ /*13*/\n"
4463                "}",
4464                Style);
4465   verifyFormat("extern \"C\"\n"
4466                "{\n"
4467                "int foo14();\n"
4468                "}",
4469                Style);
4470 
4471   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4472   verifyFormat("extern \"C\"\n"
4473                "{ /*13*/\n"
4474                "}",
4475                Style);
4476   verifyFormat("extern \"C\"\n"
4477                "{\n"
4478                "  int foo14();\n"
4479                "}",
4480                Style);
4481 }
4482 
4483 TEST_F(FormatTest, FormatsInlineASM) {
4484   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4485   verifyFormat("asm(\"nop\" ::: \"memory\");");
4486   verifyFormat(
4487       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4488       "    \"cpuid\\n\\t\"\n"
4489       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4490       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4491       "    : \"a\"(value));");
4492   EXPECT_EQ(
4493       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4494       "  __asm {\n"
4495       "        mov     edx,[that] // vtable in edx\n"
4496       "        mov     eax,methodIndex\n"
4497       "        call    [edx][eax*4] // stdcall\n"
4498       "  }\n"
4499       "}",
4500       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4501              "    __asm {\n"
4502              "        mov     edx,[that] // vtable in edx\n"
4503              "        mov     eax,methodIndex\n"
4504              "        call    [edx][eax*4] // stdcall\n"
4505              "    }\n"
4506              "}"));
4507   EXPECT_EQ("_asm {\n"
4508             "  xor eax, eax;\n"
4509             "  cpuid;\n"
4510             "}",
4511             format("_asm {\n"
4512                    "  xor eax, eax;\n"
4513                    "  cpuid;\n"
4514                    "}"));
4515   verifyFormat("void function() {\n"
4516                "  // comment\n"
4517                "  asm(\"\");\n"
4518                "}");
4519   EXPECT_EQ("__asm {\n"
4520             "}\n"
4521             "int i;",
4522             format("__asm   {\n"
4523                    "}\n"
4524                    "int   i;"));
4525 }
4526 
4527 TEST_F(FormatTest, FormatTryCatch) {
4528   verifyFormat("try {\n"
4529                "  throw a * b;\n"
4530                "} catch (int a) {\n"
4531                "  // Do nothing.\n"
4532                "} catch (...) {\n"
4533                "  exit(42);\n"
4534                "}");
4535 
4536   // Function-level try statements.
4537   verifyFormat("int f() try { return 4; } catch (...) {\n"
4538                "  return 5;\n"
4539                "}");
4540   verifyFormat("class A {\n"
4541                "  int a;\n"
4542                "  A() try : a(0) {\n"
4543                "  } catch (...) {\n"
4544                "    throw;\n"
4545                "  }\n"
4546                "};\n");
4547   verifyFormat("class A {\n"
4548                "  int a;\n"
4549                "  A() try : a(0), b{1} {\n"
4550                "  } catch (...) {\n"
4551                "    throw;\n"
4552                "  }\n"
4553                "};\n");
4554   verifyFormat("class A {\n"
4555                "  int a;\n"
4556                "  A() try : a(0), b{1}, c{2} {\n"
4557                "  } catch (...) {\n"
4558                "    throw;\n"
4559                "  }\n"
4560                "};\n");
4561   verifyFormat("class A {\n"
4562                "  int a;\n"
4563                "  A() try : a(0), b{1}, c{2} {\n"
4564                "    { // New scope.\n"
4565                "    }\n"
4566                "  } catch (...) {\n"
4567                "    throw;\n"
4568                "  }\n"
4569                "};\n");
4570 
4571   // Incomplete try-catch blocks.
4572   verifyIncompleteFormat("try {} catch (");
4573 }
4574 
4575 TEST_F(FormatTest, FormatTryAsAVariable) {
4576   verifyFormat("int try;");
4577   verifyFormat("int try, size;");
4578   verifyFormat("try = foo();");
4579   verifyFormat("if (try < size) {\n  return true;\n}");
4580 
4581   verifyFormat("int catch;");
4582   verifyFormat("int catch, size;");
4583   verifyFormat("catch = foo();");
4584   verifyFormat("if (catch < size) {\n  return true;\n}");
4585 
4586   FormatStyle Style = getLLVMStyle();
4587   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4588   Style.BraceWrapping.AfterFunction = true;
4589   Style.BraceWrapping.BeforeCatch = true;
4590   verifyFormat("try {\n"
4591                "  int bar = 1;\n"
4592                "}\n"
4593                "catch (...) {\n"
4594                "  int bar = 1;\n"
4595                "}",
4596                Style);
4597   verifyFormat("#if NO_EX\n"
4598                "try\n"
4599                "#endif\n"
4600                "{\n"
4601                "}\n"
4602                "#if NO_EX\n"
4603                "catch (...) {\n"
4604                "}",
4605                Style);
4606   verifyFormat("try /* abc */ {\n"
4607                "  int bar = 1;\n"
4608                "}\n"
4609                "catch (...) {\n"
4610                "  int bar = 1;\n"
4611                "}",
4612                Style);
4613   verifyFormat("try\n"
4614                "// abc\n"
4615                "{\n"
4616                "  int bar = 1;\n"
4617                "}\n"
4618                "catch (...) {\n"
4619                "  int bar = 1;\n"
4620                "}",
4621                Style);
4622 }
4623 
4624 TEST_F(FormatTest, FormatSEHTryCatch) {
4625   verifyFormat("__try {\n"
4626                "  int a = b * c;\n"
4627                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4628                "  // Do nothing.\n"
4629                "}");
4630 
4631   verifyFormat("__try {\n"
4632                "  int a = b * c;\n"
4633                "} __finally {\n"
4634                "  // Do nothing.\n"
4635                "}");
4636 
4637   verifyFormat("DEBUG({\n"
4638                "  __try {\n"
4639                "  } __finally {\n"
4640                "  }\n"
4641                "});\n");
4642 }
4643 
4644 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4645   verifyFormat("try {\n"
4646                "  f();\n"
4647                "} catch {\n"
4648                "  g();\n"
4649                "}");
4650   verifyFormat("try {\n"
4651                "  f();\n"
4652                "} catch (A a) MACRO(x) {\n"
4653                "  g();\n"
4654                "} catch (B b) MACRO(x) {\n"
4655                "  g();\n"
4656                "}");
4657 }
4658 
4659 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4660   FormatStyle Style = getLLVMStyle();
4661   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4662                           FormatStyle::BS_WebKit}) {
4663     Style.BreakBeforeBraces = BraceStyle;
4664     verifyFormat("try {\n"
4665                  "  // something\n"
4666                  "} catch (...) {\n"
4667                  "  // something\n"
4668                  "}",
4669                  Style);
4670   }
4671   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4672   verifyFormat("try {\n"
4673                "  // something\n"
4674                "}\n"
4675                "catch (...) {\n"
4676                "  // something\n"
4677                "}",
4678                Style);
4679   verifyFormat("__try {\n"
4680                "  // something\n"
4681                "}\n"
4682                "__finally {\n"
4683                "  // something\n"
4684                "}",
4685                Style);
4686   verifyFormat("@try {\n"
4687                "  // something\n"
4688                "}\n"
4689                "@finally {\n"
4690                "  // something\n"
4691                "}",
4692                Style);
4693   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4694   verifyFormat("try\n"
4695                "{\n"
4696                "  // something\n"
4697                "}\n"
4698                "catch (...)\n"
4699                "{\n"
4700                "  // something\n"
4701                "}",
4702                Style);
4703   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4704   verifyFormat("try\n"
4705                "  {\n"
4706                "  // something white\n"
4707                "  }\n"
4708                "catch (...)\n"
4709                "  {\n"
4710                "  // something white\n"
4711                "  }",
4712                Style);
4713   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4714   verifyFormat("try\n"
4715                "  {\n"
4716                "    // something\n"
4717                "  }\n"
4718                "catch (...)\n"
4719                "  {\n"
4720                "    // something\n"
4721                "  }",
4722                Style);
4723   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4724   Style.BraceWrapping.BeforeCatch = true;
4725   verifyFormat("try {\n"
4726                "  // something\n"
4727                "}\n"
4728                "catch (...) {\n"
4729                "  // something\n"
4730                "}",
4731                Style);
4732 }
4733 
4734 TEST_F(FormatTest, StaticInitializers) {
4735   verifyFormat("static SomeClass SC = {1, 'a'};");
4736 
4737   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4738                "    100000000, "
4739                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4740 
4741   // Here, everything other than the "}" would fit on a line.
4742   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4743                "    10000000000000000000000000};");
4744   EXPECT_EQ("S s = {a,\n"
4745             "\n"
4746             "       b};",
4747             format("S s = {\n"
4748                    "  a,\n"
4749                    "\n"
4750                    "  b\n"
4751                    "};"));
4752 
4753   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4754   // line. However, the formatting looks a bit off and this probably doesn't
4755   // happen often in practice.
4756   verifyFormat("static int Variable[1] = {\n"
4757                "    {1000000000000000000000000000000000000}};",
4758                getLLVMStyleWithColumns(40));
4759 }
4760 
4761 TEST_F(FormatTest, DesignatedInitializers) {
4762   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4763   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4764                "                    .bbbbbbbbbb = 2,\n"
4765                "                    .cccccccccc = 3,\n"
4766                "                    .dddddddddd = 4,\n"
4767                "                    .eeeeeeeeee = 5};");
4768   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4769                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4770                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4771                "    .ccccccccccccccccccccccccccc = 3,\n"
4772                "    .ddddddddddddddddddddddddddd = 4,\n"
4773                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4774 
4775   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4776 
4777   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4778   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4779                "                    [2] = bbbbbbbbbb,\n"
4780                "                    [3] = cccccccccc,\n"
4781                "                    [4] = dddddddddd,\n"
4782                "                    [5] = eeeeeeeeee};");
4783   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4784                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4785                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4786                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4787                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4788                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4789 }
4790 
4791 TEST_F(FormatTest, NestedStaticInitializers) {
4792   verifyFormat("static A x = {{{}}};\n");
4793   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4794                "               {init1, init2, init3, init4}}};",
4795                getLLVMStyleWithColumns(50));
4796 
4797   verifyFormat("somes Status::global_reps[3] = {\n"
4798                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4799                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4800                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4801                getLLVMStyleWithColumns(60));
4802   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4803                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4804                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4805                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4806   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4807                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4808                "rect.fTop}};");
4809 
4810   verifyFormat(
4811       "SomeArrayOfSomeType a = {\n"
4812       "    {{1, 2, 3},\n"
4813       "     {1, 2, 3},\n"
4814       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4815       "      333333333333333333333333333333},\n"
4816       "     {1, 2, 3},\n"
4817       "     {1, 2, 3}}};");
4818   verifyFormat(
4819       "SomeArrayOfSomeType a = {\n"
4820       "    {{1, 2, 3}},\n"
4821       "    {{1, 2, 3}},\n"
4822       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4823       "      333333333333333333333333333333}},\n"
4824       "    {{1, 2, 3}},\n"
4825       "    {{1, 2, 3}}};");
4826 
4827   verifyFormat("struct {\n"
4828                "  unsigned bit;\n"
4829                "  const char *const name;\n"
4830                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4831                "                 {kOsWin, \"Windows\"},\n"
4832                "                 {kOsLinux, \"Linux\"},\n"
4833                "                 {kOsCrOS, \"Chrome OS\"}};");
4834   verifyFormat("struct {\n"
4835                "  unsigned bit;\n"
4836                "  const char *const name;\n"
4837                "} kBitsToOs[] = {\n"
4838                "    {kOsMac, \"Mac\"},\n"
4839                "    {kOsWin, \"Windows\"},\n"
4840                "    {kOsLinux, \"Linux\"},\n"
4841                "    {kOsCrOS, \"Chrome OS\"},\n"
4842                "};");
4843 }
4844 
4845 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4846   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4847                "                      \\\n"
4848                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4849 }
4850 
4851 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4852   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4853                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4854 
4855   // Do break defaulted and deleted functions.
4856   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4857                "    default;",
4858                getLLVMStyleWithColumns(40));
4859   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4860                "    delete;",
4861                getLLVMStyleWithColumns(40));
4862 }
4863 
4864 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4865   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4866                getLLVMStyleWithColumns(40));
4867   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4868                getLLVMStyleWithColumns(40));
4869   EXPECT_EQ("#define Q                              \\\n"
4870             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4871             "  \"aaaaaaaa.cpp\"",
4872             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4873                    getLLVMStyleWithColumns(40)));
4874 }
4875 
4876 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4877   EXPECT_EQ("# 123 \"A string literal\"",
4878             format("   #     123    \"A string literal\""));
4879 }
4880 
4881 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4882   EXPECT_EQ("#;", format("#;"));
4883   verifyFormat("#\n;\n;\n;");
4884 }
4885 
4886 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4887   EXPECT_EQ("#line 42 \"test\"\n",
4888             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4889   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4890                                     getLLVMStyleWithColumns(12)));
4891 }
4892 
4893 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4894   EXPECT_EQ("#line 42 \"test\"",
4895             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4896   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4897 }
4898 
4899 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4900   verifyFormat("#define A \\x20");
4901   verifyFormat("#define A \\ x20");
4902   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4903   verifyFormat("#define A ''");
4904   verifyFormat("#define A ''qqq");
4905   verifyFormat("#define A `qqq");
4906   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4907   EXPECT_EQ("const char *c = STRINGIFY(\n"
4908             "\\na : b);",
4909             format("const char * c = STRINGIFY(\n"
4910                    "\\na : b);"));
4911 
4912   verifyFormat("a\r\\");
4913   verifyFormat("a\v\\");
4914   verifyFormat("a\f\\");
4915 }
4916 
4917 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4918   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4919   style.IndentWidth = 4;
4920   style.PPIndentWidth = 1;
4921 
4922   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4923   verifyFormat("#ifdef __linux__\n"
4924                "void foo() {\n"
4925                "    int x = 0;\n"
4926                "}\n"
4927                "#define FOO\n"
4928                "#endif\n"
4929                "void bar() {\n"
4930                "    int y = 0;\n"
4931                "}\n",
4932                style);
4933 
4934   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4935   verifyFormat("#ifdef __linux__\n"
4936                "void foo() {\n"
4937                "    int x = 0;\n"
4938                "}\n"
4939                "# define FOO foo\n"
4940                "#endif\n"
4941                "void bar() {\n"
4942                "    int y = 0;\n"
4943                "}\n",
4944                style);
4945 
4946   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4947   verifyFormat("#ifdef __linux__\n"
4948                "void foo() {\n"
4949                "    int x = 0;\n"
4950                "}\n"
4951                " #define FOO foo\n"
4952                "#endif\n"
4953                "void bar() {\n"
4954                "    int y = 0;\n"
4955                "}\n",
4956                style);
4957 }
4958 
4959 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4960   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4961   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4962   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4963   // FIXME: We never break before the macro name.
4964   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4965 
4966   verifyFormat("#define A A\n#define A A");
4967   verifyFormat("#define A(X) A\n#define A A");
4968 
4969   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4970   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4971 }
4972 
4973 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4974   EXPECT_EQ("// somecomment\n"
4975             "#include \"a.h\"\n"
4976             "#define A(  \\\n"
4977             "    A, B)\n"
4978             "#include \"b.h\"\n"
4979             "// somecomment\n",
4980             format("  // somecomment\n"
4981                    "  #include \"a.h\"\n"
4982                    "#define A(A,\\\n"
4983                    "    B)\n"
4984                    "    #include \"b.h\"\n"
4985                    " // somecomment\n",
4986                    getLLVMStyleWithColumns(13)));
4987 }
4988 
4989 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4990 
4991 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4992   EXPECT_EQ("#define A    \\\n"
4993             "  c;         \\\n"
4994             "  e;\n"
4995             "f;",
4996             format("#define A c; e;\n"
4997                    "f;",
4998                    getLLVMStyleWithColumns(14)));
4999 }
5000 
5001 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
5002 
5003 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
5004   EXPECT_EQ("int x,\n"
5005             "#define A\n"
5006             "    y;",
5007             format("int x,\n#define A\ny;"));
5008 }
5009 
5010 TEST_F(FormatTest, HashInMacroDefinition) {
5011   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
5012   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
5013   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
5014   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
5015   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
5016   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
5017   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
5018   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
5019   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
5020   verifyFormat("#define A  \\\n"
5021                "  {        \\\n"
5022                "    f(#c); \\\n"
5023                "  }",
5024                getLLVMStyleWithColumns(11));
5025 
5026   verifyFormat("#define A(X)         \\\n"
5027                "  void function##X()",
5028                getLLVMStyleWithColumns(22));
5029 
5030   verifyFormat("#define A(a, b, c)   \\\n"
5031                "  void a##b##c()",
5032                getLLVMStyleWithColumns(22));
5033 
5034   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
5035 }
5036 
5037 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
5038   EXPECT_EQ("#define A (x)", format("#define A (x)"));
5039   EXPECT_EQ("#define A(x)", format("#define A(x)"));
5040 
5041   FormatStyle Style = getLLVMStyle();
5042   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
5043   verifyFormat("#define true ((foo)1)", Style);
5044   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
5045   verifyFormat("#define false((foo)0)", Style);
5046 }
5047 
5048 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
5049   EXPECT_EQ("#define A b;", format("#define A \\\n"
5050                                    "          \\\n"
5051                                    "  b;",
5052                                    getLLVMStyleWithColumns(25)));
5053   EXPECT_EQ("#define A \\\n"
5054             "          \\\n"
5055             "  a;      \\\n"
5056             "  b;",
5057             format("#define A \\\n"
5058                    "          \\\n"
5059                    "  a;      \\\n"
5060                    "  b;",
5061                    getLLVMStyleWithColumns(11)));
5062   EXPECT_EQ("#define A \\\n"
5063             "  a;      \\\n"
5064             "          \\\n"
5065             "  b;",
5066             format("#define A \\\n"
5067                    "  a;      \\\n"
5068                    "          \\\n"
5069                    "  b;",
5070                    getLLVMStyleWithColumns(11)));
5071 }
5072 
5073 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
5074   verifyIncompleteFormat("#define A :");
5075   verifyFormat("#define SOMECASES  \\\n"
5076                "  case 1:          \\\n"
5077                "  case 2\n",
5078                getLLVMStyleWithColumns(20));
5079   verifyFormat("#define MACRO(a) \\\n"
5080                "  if (a)         \\\n"
5081                "    f();         \\\n"
5082                "  else           \\\n"
5083                "    g()",
5084                getLLVMStyleWithColumns(18));
5085   verifyFormat("#define A template <typename T>");
5086   verifyIncompleteFormat("#define STR(x) #x\n"
5087                          "f(STR(this_is_a_string_literal{));");
5088   verifyFormat("#pragma omp threadprivate( \\\n"
5089                "    y)), // expected-warning",
5090                getLLVMStyleWithColumns(28));
5091   verifyFormat("#d, = };");
5092   verifyFormat("#if \"a");
5093   verifyIncompleteFormat("({\n"
5094                          "#define b     \\\n"
5095                          "  }           \\\n"
5096                          "  a\n"
5097                          "a",
5098                          getLLVMStyleWithColumns(15));
5099   verifyFormat("#define A     \\\n"
5100                "  {           \\\n"
5101                "    {\n"
5102                "#define B     \\\n"
5103                "  }           \\\n"
5104                "  }",
5105                getLLVMStyleWithColumns(15));
5106   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
5107   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
5108   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
5109   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
5110 }
5111 
5112 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
5113   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
5114   EXPECT_EQ("class A : public QObject {\n"
5115             "  Q_OBJECT\n"
5116             "\n"
5117             "  A() {}\n"
5118             "};",
5119             format("class A  :  public QObject {\n"
5120                    "     Q_OBJECT\n"
5121                    "\n"
5122                    "  A() {\n}\n"
5123                    "}  ;"));
5124   EXPECT_EQ("MACRO\n"
5125             "/*static*/ int i;",
5126             format("MACRO\n"
5127                    " /*static*/ int   i;"));
5128   EXPECT_EQ("SOME_MACRO\n"
5129             "namespace {\n"
5130             "void f();\n"
5131             "} // namespace",
5132             format("SOME_MACRO\n"
5133                    "  namespace    {\n"
5134                    "void   f(  );\n"
5135                    "} // namespace"));
5136   // Only if the identifier contains at least 5 characters.
5137   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
5138   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
5139   // Only if everything is upper case.
5140   EXPECT_EQ("class A : public QObject {\n"
5141             "  Q_Object A() {}\n"
5142             "};",
5143             format("class A  :  public QObject {\n"
5144                    "     Q_Object\n"
5145                    "  A() {\n}\n"
5146                    "}  ;"));
5147 
5148   // Only if the next line can actually start an unwrapped line.
5149   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
5150             format("SOME_WEIRD_LOG_MACRO\n"
5151                    "<< SomeThing;"));
5152 
5153   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
5154                "(n, buffers))\n",
5155                getChromiumStyle(FormatStyle::LK_Cpp));
5156 
5157   // See PR41483
5158   EXPECT_EQ("/**/ FOO(a)\n"
5159             "FOO(b)",
5160             format("/**/ FOO(a)\n"
5161                    "FOO(b)"));
5162 }
5163 
5164 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
5165   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5166             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5167             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5168             "class X {};\n"
5169             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5170             "int *createScopDetectionPass() { return 0; }",
5171             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5172                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5173                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5174                    "  class X {};\n"
5175                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5176                    "  int *createScopDetectionPass() { return 0; }"));
5177   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
5178   // braces, so that inner block is indented one level more.
5179   EXPECT_EQ("int q() {\n"
5180             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5181             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5182             "  IPC_END_MESSAGE_MAP()\n"
5183             "}",
5184             format("int q() {\n"
5185                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5186                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5187                    "  IPC_END_MESSAGE_MAP()\n"
5188                    "}"));
5189 
5190   // Same inside macros.
5191   EXPECT_EQ("#define LIST(L) \\\n"
5192             "  L(A)          \\\n"
5193             "  L(B)          \\\n"
5194             "  L(C)",
5195             format("#define LIST(L) \\\n"
5196                    "  L(A) \\\n"
5197                    "  L(B) \\\n"
5198                    "  L(C)",
5199                    getGoogleStyle()));
5200 
5201   // These must not be recognized as macros.
5202   EXPECT_EQ("int q() {\n"
5203             "  f(x);\n"
5204             "  f(x) {}\n"
5205             "  f(x)->g();\n"
5206             "  f(x)->*g();\n"
5207             "  f(x).g();\n"
5208             "  f(x) = x;\n"
5209             "  f(x) += x;\n"
5210             "  f(x) -= x;\n"
5211             "  f(x) *= x;\n"
5212             "  f(x) /= x;\n"
5213             "  f(x) %= x;\n"
5214             "  f(x) &= x;\n"
5215             "  f(x) |= x;\n"
5216             "  f(x) ^= x;\n"
5217             "  f(x) >>= x;\n"
5218             "  f(x) <<= x;\n"
5219             "  f(x)[y].z();\n"
5220             "  LOG(INFO) << x;\n"
5221             "  ifstream(x) >> x;\n"
5222             "}\n",
5223             format("int q() {\n"
5224                    "  f(x)\n;\n"
5225                    "  f(x)\n {}\n"
5226                    "  f(x)\n->g();\n"
5227                    "  f(x)\n->*g();\n"
5228                    "  f(x)\n.g();\n"
5229                    "  f(x)\n = x;\n"
5230                    "  f(x)\n += x;\n"
5231                    "  f(x)\n -= x;\n"
5232                    "  f(x)\n *= x;\n"
5233                    "  f(x)\n /= x;\n"
5234                    "  f(x)\n %= x;\n"
5235                    "  f(x)\n &= x;\n"
5236                    "  f(x)\n |= x;\n"
5237                    "  f(x)\n ^= x;\n"
5238                    "  f(x)\n >>= x;\n"
5239                    "  f(x)\n <<= x;\n"
5240                    "  f(x)\n[y].z();\n"
5241                    "  LOG(INFO)\n << x;\n"
5242                    "  ifstream(x)\n >> x;\n"
5243                    "}\n"));
5244   EXPECT_EQ("int q() {\n"
5245             "  F(x)\n"
5246             "  if (1) {\n"
5247             "  }\n"
5248             "  F(x)\n"
5249             "  while (1) {\n"
5250             "  }\n"
5251             "  F(x)\n"
5252             "  G(x);\n"
5253             "  F(x)\n"
5254             "  try {\n"
5255             "    Q();\n"
5256             "  } catch (...) {\n"
5257             "  }\n"
5258             "}\n",
5259             format("int q() {\n"
5260                    "F(x)\n"
5261                    "if (1) {}\n"
5262                    "F(x)\n"
5263                    "while (1) {}\n"
5264                    "F(x)\n"
5265                    "G(x);\n"
5266                    "F(x)\n"
5267                    "try { Q(); } catch (...) {}\n"
5268                    "}\n"));
5269   EXPECT_EQ("class A {\n"
5270             "  A() : t(0) {}\n"
5271             "  A(int i) noexcept() : {}\n"
5272             "  A(X x)\n" // FIXME: function-level try blocks are broken.
5273             "  try : t(0) {\n"
5274             "  } catch (...) {\n"
5275             "  }\n"
5276             "};",
5277             format("class A {\n"
5278                    "  A()\n : t(0) {}\n"
5279                    "  A(int i)\n noexcept() : {}\n"
5280                    "  A(X x)\n"
5281                    "  try : t(0) {} catch (...) {}\n"
5282                    "};"));
5283   FormatStyle Style = getLLVMStyle();
5284   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5285   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5286   Style.BraceWrapping.AfterFunction = true;
5287   EXPECT_EQ("void f()\n"
5288             "try\n"
5289             "{\n"
5290             "}",
5291             format("void f() try {\n"
5292                    "}",
5293                    Style));
5294   EXPECT_EQ("class SomeClass {\n"
5295             "public:\n"
5296             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5297             "};",
5298             format("class SomeClass {\n"
5299                    "public:\n"
5300                    "  SomeClass()\n"
5301                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5302                    "};"));
5303   EXPECT_EQ("class SomeClass {\n"
5304             "public:\n"
5305             "  SomeClass()\n"
5306             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5307             "};",
5308             format("class SomeClass {\n"
5309                    "public:\n"
5310                    "  SomeClass()\n"
5311                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5312                    "};",
5313                    getLLVMStyleWithColumns(40)));
5314 
5315   verifyFormat("MACRO(>)");
5316 
5317   // Some macros contain an implicit semicolon.
5318   Style = getLLVMStyle();
5319   Style.StatementMacros.push_back("FOO");
5320   verifyFormat("FOO(a) int b = 0;");
5321   verifyFormat("FOO(a)\n"
5322                "int b = 0;",
5323                Style);
5324   verifyFormat("FOO(a);\n"
5325                "int b = 0;",
5326                Style);
5327   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
5328                "int b = 0;",
5329                Style);
5330   verifyFormat("FOO()\n"
5331                "int b = 0;",
5332                Style);
5333   verifyFormat("FOO\n"
5334                "int b = 0;",
5335                Style);
5336   verifyFormat("void f() {\n"
5337                "  FOO(a)\n"
5338                "  return a;\n"
5339                "}",
5340                Style);
5341   verifyFormat("FOO(a)\n"
5342                "FOO(b)",
5343                Style);
5344   verifyFormat("int a = 0;\n"
5345                "FOO(b)\n"
5346                "int c = 0;",
5347                Style);
5348   verifyFormat("int a = 0;\n"
5349                "int x = FOO(a)\n"
5350                "int b = 0;",
5351                Style);
5352   verifyFormat("void foo(int a) { FOO(a) }\n"
5353                "uint32_t bar() {}",
5354                Style);
5355 }
5356 
5357 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
5358   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
5359 
5360   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
5361                ZeroColumn);
5362 }
5363 
5364 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5365   verifyFormat("#define A \\\n"
5366                "  f({     \\\n"
5367                "    g();  \\\n"
5368                "  });",
5369                getLLVMStyleWithColumns(11));
5370 }
5371 
5372 TEST_F(FormatTest, IndentPreprocessorDirectives) {
5373   FormatStyle Style = getLLVMStyleWithColumns(40);
5374   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
5375   verifyFormat("#ifdef _WIN32\n"
5376                "#define A 0\n"
5377                "#ifdef VAR2\n"
5378                "#define B 1\n"
5379                "#include <someheader.h>\n"
5380                "#define MACRO                          \\\n"
5381                "  some_very_long_func_aaaaaaaaaa();\n"
5382                "#endif\n"
5383                "#else\n"
5384                "#define A 1\n"
5385                "#endif",
5386                Style);
5387   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
5388   verifyFormat("#ifdef _WIN32\n"
5389                "#  define A 0\n"
5390                "#  ifdef VAR2\n"
5391                "#    define B 1\n"
5392                "#    include <someheader.h>\n"
5393                "#    define MACRO                      \\\n"
5394                "      some_very_long_func_aaaaaaaaaa();\n"
5395                "#  endif\n"
5396                "#else\n"
5397                "#  define A 1\n"
5398                "#endif",
5399                Style);
5400   verifyFormat("#if A\n"
5401                "#  define MACRO                        \\\n"
5402                "    void a(int x) {                    \\\n"
5403                "      b();                             \\\n"
5404                "      c();                             \\\n"
5405                "      d();                             \\\n"
5406                "      e();                             \\\n"
5407                "      f();                             \\\n"
5408                "    }\n"
5409                "#endif",
5410                Style);
5411   // Comments before include guard.
5412   verifyFormat("// file comment\n"
5413                "// file comment\n"
5414                "#ifndef HEADER_H\n"
5415                "#define HEADER_H\n"
5416                "code();\n"
5417                "#endif",
5418                Style);
5419   // Test with include guards.
5420   verifyFormat("#ifndef HEADER_H\n"
5421                "#define HEADER_H\n"
5422                "code();\n"
5423                "#endif",
5424                Style);
5425   // Include guards must have a #define with the same variable immediately
5426   // after #ifndef.
5427   verifyFormat("#ifndef NOT_GUARD\n"
5428                "#  define FOO\n"
5429                "code();\n"
5430                "#endif",
5431                Style);
5432 
5433   // Include guards must cover the entire file.
5434   verifyFormat("code();\n"
5435                "code();\n"
5436                "#ifndef NOT_GUARD\n"
5437                "#  define NOT_GUARD\n"
5438                "code();\n"
5439                "#endif",
5440                Style);
5441   verifyFormat("#ifndef NOT_GUARD\n"
5442                "#  define NOT_GUARD\n"
5443                "code();\n"
5444                "#endif\n"
5445                "code();",
5446                Style);
5447   // Test with trailing blank lines.
5448   verifyFormat("#ifndef HEADER_H\n"
5449                "#define HEADER_H\n"
5450                "code();\n"
5451                "#endif\n",
5452                Style);
5453   // Include guards don't have #else.
5454   verifyFormat("#ifndef NOT_GUARD\n"
5455                "#  define NOT_GUARD\n"
5456                "code();\n"
5457                "#else\n"
5458                "#endif",
5459                Style);
5460   verifyFormat("#ifndef NOT_GUARD\n"
5461                "#  define NOT_GUARD\n"
5462                "code();\n"
5463                "#elif FOO\n"
5464                "#endif",
5465                Style);
5466   // Non-identifier #define after potential include guard.
5467   verifyFormat("#ifndef FOO\n"
5468                "#  define 1\n"
5469                "#endif\n",
5470                Style);
5471   // #if closes past last non-preprocessor line.
5472   verifyFormat("#ifndef FOO\n"
5473                "#define FOO\n"
5474                "#if 1\n"
5475                "int i;\n"
5476                "#  define A 0\n"
5477                "#endif\n"
5478                "#endif\n",
5479                Style);
5480   // Don't crash if there is an #elif directive without a condition.
5481   verifyFormat("#if 1\n"
5482                "int x;\n"
5483                "#elif\n"
5484                "int y;\n"
5485                "#else\n"
5486                "int z;\n"
5487                "#endif",
5488                Style);
5489   // FIXME: This doesn't handle the case where there's code between the
5490   // #ifndef and #define but all other conditions hold. This is because when
5491   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5492   // previous code line yet, so we can't detect it.
5493   EXPECT_EQ("#ifndef NOT_GUARD\n"
5494             "code();\n"
5495             "#define NOT_GUARD\n"
5496             "code();\n"
5497             "#endif",
5498             format("#ifndef NOT_GUARD\n"
5499                    "code();\n"
5500                    "#  define NOT_GUARD\n"
5501                    "code();\n"
5502                    "#endif",
5503                    Style));
5504   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5505   // be outside an include guard. Examples are #pragma once and
5506   // #pragma GCC diagnostic, or anything else that does not change the meaning
5507   // of the file if it's included multiple times.
5508   EXPECT_EQ("#ifdef WIN32\n"
5509             "#  pragma once\n"
5510             "#endif\n"
5511             "#ifndef HEADER_H\n"
5512             "#  define HEADER_H\n"
5513             "code();\n"
5514             "#endif",
5515             format("#ifdef WIN32\n"
5516                    "#  pragma once\n"
5517                    "#endif\n"
5518                    "#ifndef HEADER_H\n"
5519                    "#define HEADER_H\n"
5520                    "code();\n"
5521                    "#endif",
5522                    Style));
5523   // FIXME: This does not detect when there is a single non-preprocessor line
5524   // in front of an include-guard-like structure where other conditions hold
5525   // because ScopedLineState hides the line.
5526   EXPECT_EQ("code();\n"
5527             "#ifndef HEADER_H\n"
5528             "#define HEADER_H\n"
5529             "code();\n"
5530             "#endif",
5531             format("code();\n"
5532                    "#ifndef HEADER_H\n"
5533                    "#  define HEADER_H\n"
5534                    "code();\n"
5535                    "#endif",
5536                    Style));
5537   // Keep comments aligned with #, otherwise indent comments normally. These
5538   // tests cannot use verifyFormat because messUp manipulates leading
5539   // whitespace.
5540   {
5541     const char *Expected = ""
5542                            "void f() {\n"
5543                            "#if 1\n"
5544                            "// Preprocessor aligned.\n"
5545                            "#  define A 0\n"
5546                            "  // Code. Separated by blank line.\n"
5547                            "\n"
5548                            "#  define B 0\n"
5549                            "  // Code. Not aligned with #\n"
5550                            "#  define C 0\n"
5551                            "#endif";
5552     const char *ToFormat = ""
5553                            "void f() {\n"
5554                            "#if 1\n"
5555                            "// Preprocessor aligned.\n"
5556                            "#  define A 0\n"
5557                            "// Code. Separated by blank line.\n"
5558                            "\n"
5559                            "#  define B 0\n"
5560                            "   // Code. Not aligned with #\n"
5561                            "#  define C 0\n"
5562                            "#endif";
5563     EXPECT_EQ(Expected, format(ToFormat, Style));
5564     EXPECT_EQ(Expected, format(Expected, Style));
5565   }
5566   // Keep block quotes aligned.
5567   {
5568     const char *Expected = ""
5569                            "void f() {\n"
5570                            "#if 1\n"
5571                            "/* Preprocessor aligned. */\n"
5572                            "#  define A 0\n"
5573                            "  /* Code. Separated by blank line. */\n"
5574                            "\n"
5575                            "#  define B 0\n"
5576                            "  /* Code. Not aligned with # */\n"
5577                            "#  define C 0\n"
5578                            "#endif";
5579     const char *ToFormat = ""
5580                            "void f() {\n"
5581                            "#if 1\n"
5582                            "/* Preprocessor aligned. */\n"
5583                            "#  define A 0\n"
5584                            "/* Code. Separated by blank line. */\n"
5585                            "\n"
5586                            "#  define B 0\n"
5587                            "   /* Code. Not aligned with # */\n"
5588                            "#  define C 0\n"
5589                            "#endif";
5590     EXPECT_EQ(Expected, format(ToFormat, Style));
5591     EXPECT_EQ(Expected, format(Expected, Style));
5592   }
5593   // Keep comments aligned with un-indented directives.
5594   {
5595     const char *Expected = ""
5596                            "void f() {\n"
5597                            "// Preprocessor aligned.\n"
5598                            "#define A 0\n"
5599                            "  // Code. Separated by blank line.\n"
5600                            "\n"
5601                            "#define B 0\n"
5602                            "  // Code. Not aligned with #\n"
5603                            "#define C 0\n";
5604     const char *ToFormat = ""
5605                            "void f() {\n"
5606                            "// Preprocessor aligned.\n"
5607                            "#define A 0\n"
5608                            "// Code. Separated by blank line.\n"
5609                            "\n"
5610                            "#define B 0\n"
5611                            "   // Code. Not aligned with #\n"
5612                            "#define C 0\n";
5613     EXPECT_EQ(Expected, format(ToFormat, Style));
5614     EXPECT_EQ(Expected, format(Expected, Style));
5615   }
5616   // Test AfterHash with tabs.
5617   {
5618     FormatStyle Tabbed = Style;
5619     Tabbed.UseTab = FormatStyle::UT_Always;
5620     Tabbed.IndentWidth = 8;
5621     Tabbed.TabWidth = 8;
5622     verifyFormat("#ifdef _WIN32\n"
5623                  "#\tdefine A 0\n"
5624                  "#\tifdef VAR2\n"
5625                  "#\t\tdefine B 1\n"
5626                  "#\t\tinclude <someheader.h>\n"
5627                  "#\t\tdefine MACRO          \\\n"
5628                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5629                  "#\tendif\n"
5630                  "#else\n"
5631                  "#\tdefine A 1\n"
5632                  "#endif",
5633                  Tabbed);
5634   }
5635 
5636   // Regression test: Multiline-macro inside include guards.
5637   verifyFormat("#ifndef HEADER_H\n"
5638                "#define HEADER_H\n"
5639                "#define A()        \\\n"
5640                "  int i;           \\\n"
5641                "  int j;\n"
5642                "#endif // HEADER_H",
5643                getLLVMStyleWithColumns(20));
5644 
5645   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5646   // Basic before hash indent tests
5647   verifyFormat("#ifdef _WIN32\n"
5648                "  #define A 0\n"
5649                "  #ifdef VAR2\n"
5650                "    #define B 1\n"
5651                "    #include <someheader.h>\n"
5652                "    #define MACRO                      \\\n"
5653                "      some_very_long_func_aaaaaaaaaa();\n"
5654                "  #endif\n"
5655                "#else\n"
5656                "  #define A 1\n"
5657                "#endif",
5658                Style);
5659   verifyFormat("#if A\n"
5660                "  #define MACRO                        \\\n"
5661                "    void a(int x) {                    \\\n"
5662                "      b();                             \\\n"
5663                "      c();                             \\\n"
5664                "      d();                             \\\n"
5665                "      e();                             \\\n"
5666                "      f();                             \\\n"
5667                "    }\n"
5668                "#endif",
5669                Style);
5670   // Keep comments aligned with indented directives. These
5671   // tests cannot use verifyFormat because messUp manipulates leading
5672   // whitespace.
5673   {
5674     const char *Expected = "void f() {\n"
5675                            "// Aligned to preprocessor.\n"
5676                            "#if 1\n"
5677                            "  // Aligned to code.\n"
5678                            "  int a;\n"
5679                            "  #if 1\n"
5680                            "    // Aligned to preprocessor.\n"
5681                            "    #define A 0\n"
5682                            "  // Aligned to code.\n"
5683                            "  int b;\n"
5684                            "  #endif\n"
5685                            "#endif\n"
5686                            "}";
5687     const char *ToFormat = "void f() {\n"
5688                            "// Aligned to preprocessor.\n"
5689                            "#if 1\n"
5690                            "// Aligned to code.\n"
5691                            "int a;\n"
5692                            "#if 1\n"
5693                            "// Aligned to preprocessor.\n"
5694                            "#define A 0\n"
5695                            "// Aligned to code.\n"
5696                            "int b;\n"
5697                            "#endif\n"
5698                            "#endif\n"
5699                            "}";
5700     EXPECT_EQ(Expected, format(ToFormat, Style));
5701     EXPECT_EQ(Expected, format(Expected, Style));
5702   }
5703   {
5704     const char *Expected = "void f() {\n"
5705                            "/* Aligned to preprocessor. */\n"
5706                            "#if 1\n"
5707                            "  /* Aligned to code. */\n"
5708                            "  int a;\n"
5709                            "  #if 1\n"
5710                            "    /* Aligned to preprocessor. */\n"
5711                            "    #define A 0\n"
5712                            "  /* Aligned to code. */\n"
5713                            "  int b;\n"
5714                            "  #endif\n"
5715                            "#endif\n"
5716                            "}";
5717     const char *ToFormat = "void f() {\n"
5718                            "/* Aligned to preprocessor. */\n"
5719                            "#if 1\n"
5720                            "/* Aligned to code. */\n"
5721                            "int a;\n"
5722                            "#if 1\n"
5723                            "/* Aligned to preprocessor. */\n"
5724                            "#define A 0\n"
5725                            "/* Aligned to code. */\n"
5726                            "int b;\n"
5727                            "#endif\n"
5728                            "#endif\n"
5729                            "}";
5730     EXPECT_EQ(Expected, format(ToFormat, Style));
5731     EXPECT_EQ(Expected, format(Expected, Style));
5732   }
5733 
5734   // Test single comment before preprocessor
5735   verifyFormat("// Comment\n"
5736                "\n"
5737                "#if 1\n"
5738                "#endif",
5739                Style);
5740 }
5741 
5742 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5743   verifyFormat("{\n  { a #c; }\n}");
5744 }
5745 
5746 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5747   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5748             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5749   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5750             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5751 }
5752 
5753 TEST_F(FormatTest, EscapedNewlines) {
5754   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5755   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5756             format("#define A \\\nint i;\\\n  int j;", Narrow));
5757   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5758   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5759   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5760   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5761 
5762   FormatStyle AlignLeft = getLLVMStyle();
5763   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5764   EXPECT_EQ("#define MACRO(x) \\\n"
5765             "private:         \\\n"
5766             "  int x(int a);\n",
5767             format("#define MACRO(x) \\\n"
5768                    "private:         \\\n"
5769                    "  int x(int a);\n",
5770                    AlignLeft));
5771 
5772   // CRLF line endings
5773   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5774             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5775   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5776   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5777   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5778   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5779   EXPECT_EQ("#define MACRO(x) \\\r\n"
5780             "private:         \\\r\n"
5781             "  int x(int a);\r\n",
5782             format("#define MACRO(x) \\\r\n"
5783                    "private:         \\\r\n"
5784                    "  int x(int a);\r\n",
5785                    AlignLeft));
5786 
5787   FormatStyle DontAlign = getLLVMStyle();
5788   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5789   DontAlign.MaxEmptyLinesToKeep = 3;
5790   // FIXME: can't use verifyFormat here because the newline before
5791   // "public:" is not inserted the first time it's reformatted
5792   EXPECT_EQ("#define A \\\n"
5793             "  class Foo { \\\n"
5794             "    void bar(); \\\n"
5795             "\\\n"
5796             "\\\n"
5797             "\\\n"
5798             "  public: \\\n"
5799             "    void baz(); \\\n"
5800             "  };",
5801             format("#define A \\\n"
5802                    "  class Foo { \\\n"
5803                    "    void bar(); \\\n"
5804                    "\\\n"
5805                    "\\\n"
5806                    "\\\n"
5807                    "  public: \\\n"
5808                    "    void baz(); \\\n"
5809                    "  };",
5810                    DontAlign));
5811 }
5812 
5813 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5814   verifyFormat("#define A \\\n"
5815                "  int v(  \\\n"
5816                "      a); \\\n"
5817                "  int i;",
5818                getLLVMStyleWithColumns(11));
5819 }
5820 
5821 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5822   EXPECT_EQ(
5823       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5824       "                      \\\n"
5825       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5826       "\n"
5827       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5828       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5829       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5830              "\\\n"
5831              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5832              "  \n"
5833              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5834              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5835 }
5836 
5837 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5838   EXPECT_EQ("int\n"
5839             "#define A\n"
5840             "    a;",
5841             format("int\n#define A\na;"));
5842   verifyFormat("functionCallTo(\n"
5843                "    someOtherFunction(\n"
5844                "        withSomeParameters, whichInSequence,\n"
5845                "        areLongerThanALine(andAnotherCall,\n"
5846                "#define A B\n"
5847                "                           withMoreParamters,\n"
5848                "                           whichStronglyInfluenceTheLayout),\n"
5849                "        andMoreParameters),\n"
5850                "    trailing);",
5851                getLLVMStyleWithColumns(69));
5852   verifyFormat("Foo::Foo()\n"
5853                "#ifdef BAR\n"
5854                "    : baz(0)\n"
5855                "#endif\n"
5856                "{\n"
5857                "}");
5858   verifyFormat("void f() {\n"
5859                "  if (true)\n"
5860                "#ifdef A\n"
5861                "    f(42);\n"
5862                "  x();\n"
5863                "#else\n"
5864                "    g();\n"
5865                "  x();\n"
5866                "#endif\n"
5867                "}");
5868   verifyFormat("void f(param1, param2,\n"
5869                "       param3,\n"
5870                "#ifdef A\n"
5871                "       param4(param5,\n"
5872                "#ifdef A1\n"
5873                "              param6,\n"
5874                "#ifdef A2\n"
5875                "              param7),\n"
5876                "#else\n"
5877                "              param8),\n"
5878                "       param9,\n"
5879                "#endif\n"
5880                "       param10,\n"
5881                "#endif\n"
5882                "       param11)\n"
5883                "#else\n"
5884                "       param12)\n"
5885                "#endif\n"
5886                "{\n"
5887                "  x();\n"
5888                "}",
5889                getLLVMStyleWithColumns(28));
5890   verifyFormat("#if 1\n"
5891                "int i;");
5892   verifyFormat("#if 1\n"
5893                "#endif\n"
5894                "#if 1\n"
5895                "#else\n"
5896                "#endif\n");
5897   verifyFormat("DEBUG({\n"
5898                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5899                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5900                "});\n"
5901                "#if a\n"
5902                "#else\n"
5903                "#endif");
5904 
5905   verifyIncompleteFormat("void f(\n"
5906                          "#if A\n"
5907                          ");\n"
5908                          "#else\n"
5909                          "#endif");
5910 }
5911 
5912 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5913   verifyFormat("#endif\n"
5914                "#if B");
5915 }
5916 
5917 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5918   FormatStyle SingleLine = getLLVMStyle();
5919   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5920   verifyFormat("#if 0\n"
5921                "#elif 1\n"
5922                "#endif\n"
5923                "void foo() {\n"
5924                "  if (test) foo2();\n"
5925                "}",
5926                SingleLine);
5927 }
5928 
5929 TEST_F(FormatTest, LayoutBlockInsideParens) {
5930   verifyFormat("functionCall({ int i; });");
5931   verifyFormat("functionCall({\n"
5932                "  int i;\n"
5933                "  int j;\n"
5934                "});");
5935   verifyFormat("functionCall(\n"
5936                "    {\n"
5937                "      int i;\n"
5938                "      int j;\n"
5939                "    },\n"
5940                "    aaaa, bbbb, cccc);");
5941   verifyFormat("functionA(functionB({\n"
5942                "            int i;\n"
5943                "            int j;\n"
5944                "          }),\n"
5945                "          aaaa, bbbb, cccc);");
5946   verifyFormat("functionCall(\n"
5947                "    {\n"
5948                "      int i;\n"
5949                "      int j;\n"
5950                "    },\n"
5951                "    aaaa, bbbb, // comment\n"
5952                "    cccc);");
5953   verifyFormat("functionA(functionB({\n"
5954                "            int i;\n"
5955                "            int j;\n"
5956                "          }),\n"
5957                "          aaaa, bbbb, // comment\n"
5958                "          cccc);");
5959   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5960   verifyFormat("functionCall(aaaa, bbbb, {\n"
5961                "  int i;\n"
5962                "  int j;\n"
5963                "});");
5964   verifyFormat(
5965       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5966       "    {\n"
5967       "      int i; // break\n"
5968       "    },\n"
5969       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5970       "                                     ccccccccccccccccc));");
5971   verifyFormat("DEBUG({\n"
5972                "  if (a)\n"
5973                "    f();\n"
5974                "});");
5975 }
5976 
5977 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5978   EXPECT_EQ("SOME_MACRO { int i; }\n"
5979             "int i;",
5980             format("  SOME_MACRO  {int i;}  int i;"));
5981 }
5982 
5983 TEST_F(FormatTest, LayoutNestedBlocks) {
5984   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5985                "  struct s {\n"
5986                "    int i;\n"
5987                "  };\n"
5988                "  s kBitsToOs[] = {{10}};\n"
5989                "  for (int i = 0; i < 10; ++i)\n"
5990                "    return;\n"
5991                "}");
5992   verifyFormat("call(parameter, {\n"
5993                "  something();\n"
5994                "  // Comment using all columns.\n"
5995                "  somethingelse();\n"
5996                "});",
5997                getLLVMStyleWithColumns(40));
5998   verifyFormat("DEBUG( //\n"
5999                "    { f(); }, a);");
6000   verifyFormat("DEBUG( //\n"
6001                "    {\n"
6002                "      f(); //\n"
6003                "    },\n"
6004                "    a);");
6005 
6006   EXPECT_EQ("call(parameter, {\n"
6007             "  something();\n"
6008             "  // Comment too\n"
6009             "  // looooooooooong.\n"
6010             "  somethingElse();\n"
6011             "});",
6012             format("call(parameter, {\n"
6013                    "  something();\n"
6014                    "  // Comment too looooooooooong.\n"
6015                    "  somethingElse();\n"
6016                    "});",
6017                    getLLVMStyleWithColumns(29)));
6018   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
6019   EXPECT_EQ("DEBUG({ // comment\n"
6020             "  int i;\n"
6021             "});",
6022             format("DEBUG({ // comment\n"
6023                    "int  i;\n"
6024                    "});"));
6025   EXPECT_EQ("DEBUG({\n"
6026             "  int i;\n"
6027             "\n"
6028             "  // comment\n"
6029             "  int j;\n"
6030             "});",
6031             format("DEBUG({\n"
6032                    "  int  i;\n"
6033                    "\n"
6034                    "  // comment\n"
6035                    "  int  j;\n"
6036                    "});"));
6037 
6038   verifyFormat("DEBUG({\n"
6039                "  if (a)\n"
6040                "    return;\n"
6041                "});");
6042   verifyGoogleFormat("DEBUG({\n"
6043                      "  if (a) return;\n"
6044                      "});");
6045   FormatStyle Style = getGoogleStyle();
6046   Style.ColumnLimit = 45;
6047   verifyFormat("Debug(\n"
6048                "    aaaaa,\n"
6049                "    {\n"
6050                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
6051                "    },\n"
6052                "    a);",
6053                Style);
6054 
6055   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
6056 
6057   verifyNoCrash("^{v^{a}}");
6058 }
6059 
6060 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
6061   EXPECT_EQ("#define MACRO()                     \\\n"
6062             "  Debug(aaa, /* force line break */ \\\n"
6063             "        {                           \\\n"
6064             "          int i;                    \\\n"
6065             "          int j;                    \\\n"
6066             "        })",
6067             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
6068                    "          {  int   i;  int  j;   })",
6069                    getGoogleStyle()));
6070 
6071   EXPECT_EQ("#define A                                       \\\n"
6072             "  [] {                                          \\\n"
6073             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
6074             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
6075             "  }",
6076             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
6077                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
6078                    getGoogleStyle()));
6079 }
6080 
6081 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
6082   EXPECT_EQ("{}", format("{}"));
6083   verifyFormat("enum E {};");
6084   verifyFormat("enum E {}");
6085   FormatStyle Style = getLLVMStyle();
6086   Style.SpaceInEmptyBlock = true;
6087   EXPECT_EQ("void f() { }", format("void f() {}", Style));
6088   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
6089   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
6090   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
6091   Style.BraceWrapping.BeforeElse = false;
6092   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
6093   verifyFormat("if (a)\n"
6094                "{\n"
6095                "} else if (b)\n"
6096                "{\n"
6097                "} else\n"
6098                "{ }",
6099                Style);
6100   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
6101   verifyFormat("if (a) {\n"
6102                "} else if (b) {\n"
6103                "} else {\n"
6104                "}",
6105                Style);
6106   Style.BraceWrapping.BeforeElse = true;
6107   verifyFormat("if (a) { }\n"
6108                "else if (b) { }\n"
6109                "else { }",
6110                Style);
6111 }
6112 
6113 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
6114   FormatStyle Style = getLLVMStyle();
6115   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
6116   Style.MacroBlockEnd = "^[A-Z_]+_END$";
6117   verifyFormat("FOO_BEGIN\n"
6118                "  FOO_ENTRY\n"
6119                "FOO_END",
6120                Style);
6121   verifyFormat("FOO_BEGIN\n"
6122                "  NESTED_FOO_BEGIN\n"
6123                "    NESTED_FOO_ENTRY\n"
6124                "  NESTED_FOO_END\n"
6125                "FOO_END",
6126                Style);
6127   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
6128                "  int x;\n"
6129                "  x = 1;\n"
6130                "FOO_END(Baz)",
6131                Style);
6132 }
6133 
6134 //===----------------------------------------------------------------------===//
6135 // Line break tests.
6136 //===----------------------------------------------------------------------===//
6137 
6138 TEST_F(FormatTest, PreventConfusingIndents) {
6139   verifyFormat(
6140       "void f() {\n"
6141       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
6142       "                         parameter, parameter, parameter)),\n"
6143       "                     SecondLongCall(parameter));\n"
6144       "}");
6145   verifyFormat(
6146       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6147       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6148       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6149       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
6150   verifyFormat(
6151       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6152       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
6153       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6154       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
6155   verifyFormat(
6156       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
6157       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
6158       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
6159       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
6160   verifyFormat("int a = bbbb && ccc &&\n"
6161                "        fffff(\n"
6162                "#define A Just forcing a new line\n"
6163                "            ddd);");
6164 }
6165 
6166 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
6167   verifyFormat(
6168       "bool aaaaaaa =\n"
6169       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
6170       "    bbbbbbbb();");
6171   verifyFormat(
6172       "bool aaaaaaa =\n"
6173       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
6174       "    bbbbbbbb();");
6175 
6176   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6177                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
6178                "    ccccccccc == ddddddddddd;");
6179   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6180                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
6181                "    ccccccccc == ddddddddddd;");
6182   verifyFormat(
6183       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6184       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
6185       "    ccccccccc == ddddddddddd;");
6186 
6187   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6188                "                 aaaaaa) &&\n"
6189                "         bbbbbb && cccccc;");
6190   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6191                "                 aaaaaa) >>\n"
6192                "         bbbbbb;");
6193   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
6194                "    SourceMgr.getSpellingColumnNumber(\n"
6195                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
6196                "    1);");
6197 
6198   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6199                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
6200                "    cccccc) {\n}");
6201   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6202                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6203                "              cccccc) {\n}");
6204   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6205                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6206                "              cccccc) {\n}");
6207   verifyFormat("b = a &&\n"
6208                "    // Comment\n"
6209                "    b.c && d;");
6210 
6211   // If the LHS of a comparison is not a binary expression itself, the
6212   // additional linebreak confuses many people.
6213   verifyFormat(
6214       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6215       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
6216       "}");
6217   verifyFormat(
6218       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6219       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6220       "}");
6221   verifyFormat(
6222       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
6223       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6224       "}");
6225   verifyFormat(
6226       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6227       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
6228       "}");
6229   // Even explicit parentheses stress the precedence enough to make the
6230   // additional break unnecessary.
6231   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6232                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6233                "}");
6234   // This cases is borderline, but with the indentation it is still readable.
6235   verifyFormat(
6236       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6237       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6238       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
6239       "}",
6240       getLLVMStyleWithColumns(75));
6241 
6242   // If the LHS is a binary expression, we should still use the additional break
6243   // as otherwise the formatting hides the operator precedence.
6244   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6245                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6246                "    5) {\n"
6247                "}");
6248   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6249                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
6250                "    5) {\n"
6251                "}");
6252 
6253   FormatStyle OnePerLine = getLLVMStyle();
6254   OnePerLine.BinPackParameters = false;
6255   verifyFormat(
6256       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6257       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6258       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
6259       OnePerLine);
6260 
6261   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
6262                "                .aaa(aaaaaaaaaaaaa) *\n"
6263                "            aaaaaaa +\n"
6264                "        aaaaaaa;",
6265                getLLVMStyleWithColumns(40));
6266 }
6267 
6268 TEST_F(FormatTest, ExpressionIndentation) {
6269   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6270                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6271                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6272                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6273                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6274                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
6275                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6276                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
6277                "                 ccccccccccccccccccccccccccccccccccccccccc;");
6278   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6279                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6280                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6281                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6282   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6283                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6284                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6285                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6286   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6287                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6288                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6289                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6290   verifyFormat("if () {\n"
6291                "} else if (aaaaa && bbbbb > // break\n"
6292                "                        ccccc) {\n"
6293                "}");
6294   verifyFormat("if () {\n"
6295                "} else if constexpr (aaaaa && bbbbb > // break\n"
6296                "                                  ccccc) {\n"
6297                "}");
6298   verifyFormat("if () {\n"
6299                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
6300                "                                  ccccc) {\n"
6301                "}");
6302   verifyFormat("if () {\n"
6303                "} else if (aaaaa &&\n"
6304                "           bbbbb > // break\n"
6305                "               ccccc &&\n"
6306                "           ddddd) {\n"
6307                "}");
6308 
6309   // Presence of a trailing comment used to change indentation of b.
6310   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
6311                "       b;\n"
6312                "return aaaaaaaaaaaaaaaaaaa +\n"
6313                "       b; //",
6314                getLLVMStyleWithColumns(30));
6315 }
6316 
6317 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
6318   // Not sure what the best system is here. Like this, the LHS can be found
6319   // immediately above an operator (everything with the same or a higher
6320   // indent). The RHS is aligned right of the operator and so compasses
6321   // everything until something with the same indent as the operator is found.
6322   // FIXME: Is this a good system?
6323   FormatStyle Style = getLLVMStyle();
6324   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6325   verifyFormat(
6326       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6327       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6328       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6329       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6330       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6331       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6332       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6333       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6334       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
6335       Style);
6336   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6337                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6338                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6339                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6340                Style);
6341   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6342                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6343                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6344                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6345                Style);
6346   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6347                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6348                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6349                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6350                Style);
6351   verifyFormat("if () {\n"
6352                "} else if (aaaaa\n"
6353                "           && bbbbb // break\n"
6354                "                  > ccccc) {\n"
6355                "}",
6356                Style);
6357   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6358                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6359                Style);
6360   verifyFormat("return (a)\n"
6361                "       // comment\n"
6362                "       + b;",
6363                Style);
6364   verifyFormat(
6365       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6366       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6367       "             + cc;",
6368       Style);
6369 
6370   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6371                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6372                Style);
6373 
6374   // Forced by comments.
6375   verifyFormat(
6376       "unsigned ContentSize =\n"
6377       "    sizeof(int16_t)   // DWARF ARange version number\n"
6378       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6379       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6380       "    + sizeof(int8_t); // Segment Size (in bytes)");
6381 
6382   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6383                "       == boost::fusion::at_c<1>(iiii).second;",
6384                Style);
6385 
6386   Style.ColumnLimit = 60;
6387   verifyFormat("zzzzzzzzzz\n"
6388                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6389                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6390                Style);
6391 
6392   Style.ColumnLimit = 80;
6393   Style.IndentWidth = 4;
6394   Style.TabWidth = 4;
6395   Style.UseTab = FormatStyle::UT_Always;
6396   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6397   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6398   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
6399             "\t&& (someOtherLongishConditionPart1\n"
6400             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
6401             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
6402                    "(someOtherLongishConditionPart1 || "
6403                    "someOtherEvenLongerNestedConditionPart2);",
6404                    Style));
6405 }
6406 
6407 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
6408   FormatStyle Style = getLLVMStyle();
6409   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6410   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
6411 
6412   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6413                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6414                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6415                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6416                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6417                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6418                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6419                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6420                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
6421                Style);
6422   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6423                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6424                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6425                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6426                Style);
6427   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6428                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6429                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6430                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6431                Style);
6432   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6433                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6434                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6435                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6436                Style);
6437   verifyFormat("if () {\n"
6438                "} else if (aaaaa\n"
6439                "           && bbbbb // break\n"
6440                "                  > ccccc) {\n"
6441                "}",
6442                Style);
6443   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6444                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6445                Style);
6446   verifyFormat("return (a)\n"
6447                "     // comment\n"
6448                "     + b;",
6449                Style);
6450   verifyFormat(
6451       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6452       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6453       "           + cc;",
6454       Style);
6455   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6456                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6457                "                        : 3333333333333333;",
6458                Style);
6459   verifyFormat(
6460       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6461       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6462       "                                             : eeeeeeeeeeeeeeeeee)\n"
6463       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6464       "                        : 3333333333333333;",
6465       Style);
6466   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6467                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6468                Style);
6469 
6470   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6471                "    == boost::fusion::at_c<1>(iiii).second;",
6472                Style);
6473 
6474   Style.ColumnLimit = 60;
6475   verifyFormat("zzzzzzzzzzzzz\n"
6476                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6477                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6478                Style);
6479 
6480   // Forced by comments.
6481   Style.ColumnLimit = 80;
6482   verifyFormat(
6483       "unsigned ContentSize\n"
6484       "    = sizeof(int16_t) // DWARF ARange version number\n"
6485       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6486       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6487       "    + sizeof(int8_t); // Segment Size (in bytes)",
6488       Style);
6489 
6490   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6491   verifyFormat(
6492       "unsigned ContentSize =\n"
6493       "    sizeof(int16_t)   // DWARF ARange version number\n"
6494       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6495       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6496       "    + sizeof(int8_t); // Segment Size (in bytes)",
6497       Style);
6498 
6499   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6500   verifyFormat(
6501       "unsigned ContentSize =\n"
6502       "    sizeof(int16_t)   // DWARF ARange version number\n"
6503       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6504       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6505       "    + sizeof(int8_t); // Segment Size (in bytes)",
6506       Style);
6507 }
6508 
6509 TEST_F(FormatTest, EnforcedOperatorWraps) {
6510   // Here we'd like to wrap after the || operators, but a comment is forcing an
6511   // earlier wrap.
6512   verifyFormat("bool x = aaaaa //\n"
6513                "         || bbbbb\n"
6514                "         //\n"
6515                "         || cccc;");
6516 }
6517 
6518 TEST_F(FormatTest, NoOperandAlignment) {
6519   FormatStyle Style = getLLVMStyle();
6520   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6521   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6522                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6523                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6524                Style);
6525   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6526   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6527                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6528                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6529                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6530                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6531                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6532                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6533                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6534                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6535                Style);
6536 
6537   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6538                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6539                "    + cc;",
6540                Style);
6541   verifyFormat("int a = aa\n"
6542                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6543                "        * cccccccccccccccccccccccccccccccccccc;\n",
6544                Style);
6545 
6546   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6547   verifyFormat("return (a > b\n"
6548                "    // comment1\n"
6549                "    // comment2\n"
6550                "    || c);",
6551                Style);
6552 }
6553 
6554 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6555   FormatStyle Style = getLLVMStyle();
6556   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6557   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6558                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6559                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6560                Style);
6561 }
6562 
6563 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6564   FormatStyle Style = getLLVMStyleWithColumns(40);
6565   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6566   Style.BinPackArguments = false;
6567   verifyFormat("void test() {\n"
6568                "  someFunction(\n"
6569                "      this + argument + is + quite\n"
6570                "      + long + so + it + gets + wrapped\n"
6571                "      + but + remains + bin - packed);\n"
6572                "}",
6573                Style);
6574   verifyFormat("void test() {\n"
6575                "  someFunction(arg1,\n"
6576                "               this + argument + is\n"
6577                "                   + quite + long + so\n"
6578                "                   + it + gets + wrapped\n"
6579                "                   + but + remains + bin\n"
6580                "                   - packed,\n"
6581                "               arg3);\n"
6582                "}",
6583                Style);
6584   verifyFormat("void test() {\n"
6585                "  someFunction(\n"
6586                "      arg1,\n"
6587                "      this + argument + has\n"
6588                "          + anotherFunc(nested,\n"
6589                "                        calls + whose\n"
6590                "                            + arguments\n"
6591                "                            + are + also\n"
6592                "                            + wrapped,\n"
6593                "                        in + addition)\n"
6594                "          + to + being + bin - packed,\n"
6595                "      arg3);\n"
6596                "}",
6597                Style);
6598 
6599   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6600   verifyFormat("void test() {\n"
6601                "  someFunction(\n"
6602                "      arg1,\n"
6603                "      this + argument + has +\n"
6604                "          anotherFunc(nested,\n"
6605                "                      calls + whose +\n"
6606                "                          arguments +\n"
6607                "                          are + also +\n"
6608                "                          wrapped,\n"
6609                "                      in + addition) +\n"
6610                "          to + being + bin - packed,\n"
6611                "      arg3);\n"
6612                "}",
6613                Style);
6614 }
6615 
6616 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) {
6617   auto Style = getLLVMStyleWithColumns(45);
6618   EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None);
6619   verifyFormat("bool b =\n"
6620                "    is_default_constructible_v<hash<T>> and\n"
6621                "    is_copy_constructible_v<hash<T>> and\n"
6622                "    is_move_constructible_v<hash<T>> and\n"
6623                "    is_copy_assignable_v<hash<T>> and\n"
6624                "    is_move_assignable_v<hash<T>> and\n"
6625                "    is_destructible_v<hash<T>> and\n"
6626                "    is_swappable_v<hash<T>> and\n"
6627                "    is_callable_v<hash<T>(T)>;",
6628                Style);
6629 
6630   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6631   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6632                "         and is_copy_constructible_v<hash<T>>\n"
6633                "         and is_move_constructible_v<hash<T>>\n"
6634                "         and is_copy_assignable_v<hash<T>>\n"
6635                "         and is_move_assignable_v<hash<T>>\n"
6636                "         and is_destructible_v<hash<T>>\n"
6637                "         and is_swappable_v<hash<T>>\n"
6638                "         and is_callable_v<hash<T>(T)>;",
6639                Style);
6640 
6641   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6642   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6643                "         and is_copy_constructible_v<hash<T>>\n"
6644                "         and is_move_constructible_v<hash<T>>\n"
6645                "         and is_copy_assignable_v<hash<T>>\n"
6646                "         and is_move_assignable_v<hash<T>>\n"
6647                "         and is_destructible_v<hash<T>>\n"
6648                "         and is_swappable_v<hash<T>>\n"
6649                "         and is_callable_v<hash<T>(T)>;",
6650                Style);
6651 }
6652 
6653 TEST_F(FormatTest, ConstructorInitializers) {
6654   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6655   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6656                getLLVMStyleWithColumns(45));
6657   verifyFormat("Constructor()\n"
6658                "    : Inttializer(FitsOnTheLine) {}",
6659                getLLVMStyleWithColumns(44));
6660   verifyFormat("Constructor()\n"
6661                "    : Inttializer(FitsOnTheLine) {}",
6662                getLLVMStyleWithColumns(43));
6663 
6664   verifyFormat("template <typename T>\n"
6665                "Constructor() : Initializer(FitsOnTheLine) {}",
6666                getLLVMStyleWithColumns(45));
6667 
6668   verifyFormat(
6669       "SomeClass::Constructor()\n"
6670       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6671 
6672   verifyFormat(
6673       "SomeClass::Constructor()\n"
6674       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6675       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6676   verifyFormat(
6677       "SomeClass::Constructor()\n"
6678       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6679       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6680   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6681                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6682                "    : aaaaaaaaaa(aaaaaa) {}");
6683 
6684   verifyFormat("Constructor()\n"
6685                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6686                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6687                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6688                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6689 
6690   verifyFormat("Constructor()\n"
6691                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6692                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6693 
6694   verifyFormat("Constructor(int Parameter = 0)\n"
6695                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6696                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6697   verifyFormat("Constructor()\n"
6698                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6699                "}",
6700                getLLVMStyleWithColumns(60));
6701   verifyFormat("Constructor()\n"
6702                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6703                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6704 
6705   // Here a line could be saved by splitting the second initializer onto two
6706   // lines, but that is not desirable.
6707   verifyFormat("Constructor()\n"
6708                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6709                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6710                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6711 
6712   FormatStyle OnePerLine = getLLVMStyle();
6713   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6714   verifyFormat("MyClass::MyClass()\n"
6715                "    : a(a),\n"
6716                "      b(b),\n"
6717                "      c(c) {}",
6718                OnePerLine);
6719   verifyFormat("MyClass::MyClass()\n"
6720                "    : a(a), // comment\n"
6721                "      b(b),\n"
6722                "      c(c) {}",
6723                OnePerLine);
6724   verifyFormat("MyClass::MyClass(int a)\n"
6725                "    : b(a),      // comment\n"
6726                "      c(a + 1) { // lined up\n"
6727                "}",
6728                OnePerLine);
6729   verifyFormat("Constructor()\n"
6730                "    : a(b, b, b) {}",
6731                OnePerLine);
6732   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6733   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6734   verifyFormat("SomeClass::Constructor()\n"
6735                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6736                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6737                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6738                OnePerLine);
6739   verifyFormat("SomeClass::Constructor()\n"
6740                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6741                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6742                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6743                OnePerLine);
6744   verifyFormat("MyClass::MyClass(int var)\n"
6745                "    : some_var_(var),            // 4 space indent\n"
6746                "      some_other_var_(var + 1) { // lined up\n"
6747                "}",
6748                OnePerLine);
6749   verifyFormat("Constructor()\n"
6750                "    : aaaaa(aaaaaa),\n"
6751                "      aaaaa(aaaaaa),\n"
6752                "      aaaaa(aaaaaa),\n"
6753                "      aaaaa(aaaaaa),\n"
6754                "      aaaaa(aaaaaa) {}",
6755                OnePerLine);
6756   verifyFormat("Constructor()\n"
6757                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6758                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6759                OnePerLine);
6760   OnePerLine.BinPackParameters = false;
6761   verifyFormat(
6762       "Constructor()\n"
6763       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6764       "          aaaaaaaaaaa().aaa(),\n"
6765       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6766       OnePerLine);
6767   OnePerLine.ColumnLimit = 60;
6768   verifyFormat("Constructor()\n"
6769                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6770                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6771                OnePerLine);
6772 
6773   EXPECT_EQ("Constructor()\n"
6774             "    : // Comment forcing unwanted break.\n"
6775             "      aaaa(aaaa) {}",
6776             format("Constructor() :\n"
6777                    "    // Comment forcing unwanted break.\n"
6778                    "    aaaa(aaaa) {}"));
6779 }
6780 
6781 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6782   FormatStyle Style = getLLVMStyleWithColumns(60);
6783   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6784   Style.BinPackParameters = false;
6785 
6786   for (int i = 0; i < 4; ++i) {
6787     // Test all combinations of parameters that should not have an effect.
6788     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6789     Style.AllowAllArgumentsOnNextLine = i & 2;
6790 
6791     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6792     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6793     verifyFormat("Constructor()\n"
6794                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6795                  Style);
6796     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6797 
6798     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6799     verifyFormat("Constructor()\n"
6800                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6801                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6802                  Style);
6803     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6804 
6805     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6806     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6807     verifyFormat("Constructor()\n"
6808                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6809                  Style);
6810 
6811     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6812     verifyFormat("Constructor()\n"
6813                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6814                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6815                  Style);
6816 
6817     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6818     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6819     verifyFormat("Constructor() :\n"
6820                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6821                  Style);
6822 
6823     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6824     verifyFormat("Constructor() :\n"
6825                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6826                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6827                  Style);
6828   }
6829 
6830   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6831   // AllowAllConstructorInitializersOnNextLine in all
6832   // BreakConstructorInitializers modes
6833   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6834   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6835   verifyFormat("SomeClassWithALongName::Constructor(\n"
6836                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6837                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6838                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6839                Style);
6840 
6841   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6842   verifyFormat("SomeClassWithALongName::Constructor(\n"
6843                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6844                "    int bbbbbbbbbbbbb,\n"
6845                "    int cccccccccccccccc)\n"
6846                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6847                Style);
6848 
6849   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6850   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6851   verifyFormat("SomeClassWithALongName::Constructor(\n"
6852                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6853                "    int bbbbbbbbbbbbb)\n"
6854                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6855                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6856                Style);
6857 
6858   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6859 
6860   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6861   verifyFormat("SomeClassWithALongName::Constructor(\n"
6862                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6863                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6864                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6865                Style);
6866 
6867   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6868   verifyFormat("SomeClassWithALongName::Constructor(\n"
6869                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6870                "    int bbbbbbbbbbbbb,\n"
6871                "    int cccccccccccccccc)\n"
6872                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6873                Style);
6874 
6875   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6876   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6877   verifyFormat("SomeClassWithALongName::Constructor(\n"
6878                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6879                "    int bbbbbbbbbbbbb)\n"
6880                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6881                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6882                Style);
6883 
6884   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6885   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6886   verifyFormat("SomeClassWithALongName::Constructor(\n"
6887                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6888                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6889                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6890                Style);
6891 
6892   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6893   verifyFormat("SomeClassWithALongName::Constructor(\n"
6894                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6895                "    int bbbbbbbbbbbbb,\n"
6896                "    int cccccccccccccccc) :\n"
6897                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6898                Style);
6899 
6900   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6901   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6902   verifyFormat("SomeClassWithALongName::Constructor(\n"
6903                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6904                "    int bbbbbbbbbbbbb) :\n"
6905                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6906                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6907                Style);
6908 }
6909 
6910 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6911   FormatStyle Style = getLLVMStyleWithColumns(60);
6912   Style.BinPackArguments = false;
6913   for (int i = 0; i < 4; ++i) {
6914     // Test all combinations of parameters that should not have an effect.
6915     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6916     Style.PackConstructorInitializers =
6917         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6918 
6919     Style.AllowAllArgumentsOnNextLine = true;
6920     verifyFormat("void foo() {\n"
6921                  "  FunctionCallWithReallyLongName(\n"
6922                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6923                  "}",
6924                  Style);
6925     Style.AllowAllArgumentsOnNextLine = false;
6926     verifyFormat("void foo() {\n"
6927                  "  FunctionCallWithReallyLongName(\n"
6928                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6929                  "      bbbbbbbbbbbb);\n"
6930                  "}",
6931                  Style);
6932 
6933     Style.AllowAllArgumentsOnNextLine = true;
6934     verifyFormat("void foo() {\n"
6935                  "  auto VariableWithReallyLongName = {\n"
6936                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6937                  "}",
6938                  Style);
6939     Style.AllowAllArgumentsOnNextLine = false;
6940     verifyFormat("void foo() {\n"
6941                  "  auto VariableWithReallyLongName = {\n"
6942                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6943                  "      bbbbbbbbbbbb};\n"
6944                  "}",
6945                  Style);
6946   }
6947 
6948   // This parameter should not affect declarations.
6949   Style.BinPackParameters = false;
6950   Style.AllowAllArgumentsOnNextLine = false;
6951   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6952   verifyFormat("void FunctionCallWithReallyLongName(\n"
6953                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6954                Style);
6955   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6956   verifyFormat("void FunctionCallWithReallyLongName(\n"
6957                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6958                "    int bbbbbbbbbbbb);",
6959                Style);
6960 }
6961 
6962 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6963   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6964   // and BAS_Align.
6965   FormatStyle Style = getLLVMStyleWithColumns(35);
6966   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6967                     "void functionDecl(int A, int B, int C);";
6968   Style.AllowAllArgumentsOnNextLine = false;
6969   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6970   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6971                       "    paramC);\n"
6972                       "void functionDecl(int A, int B,\n"
6973                       "    int C);"),
6974             format(Input, Style));
6975   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6976   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6977                       "             paramC);\n"
6978                       "void functionDecl(int A, int B,\n"
6979                       "                  int C);"),
6980             format(Input, Style));
6981   // However, BAS_AlwaysBreak should take precedence over
6982   // AllowAllArgumentsOnNextLine.
6983   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6984   EXPECT_EQ(StringRef("functionCall(\n"
6985                       "    paramA, paramB, paramC);\n"
6986                       "void functionDecl(\n"
6987                       "    int A, int B, int C);"),
6988             format(Input, Style));
6989 
6990   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6991   // first argument.
6992   Style.AllowAllArgumentsOnNextLine = true;
6993   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6994   EXPECT_EQ(StringRef("functionCall(\n"
6995                       "    paramA, paramB, paramC);\n"
6996                       "void functionDecl(\n"
6997                       "    int A, int B, int C);"),
6998             format(Input, Style));
6999   // It wouldn't fit on one line with aligned parameters so this setting
7000   // doesn't change anything for BAS_Align.
7001   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7002   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
7003                       "             paramC);\n"
7004                       "void functionDecl(int A, int B,\n"
7005                       "                  int C);"),
7006             format(Input, Style));
7007   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7008   EXPECT_EQ(StringRef("functionCall(\n"
7009                       "    paramA, paramB, paramC);\n"
7010                       "void functionDecl(\n"
7011                       "    int A, int B, int C);"),
7012             format(Input, Style));
7013 }
7014 
7015 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
7016   FormatStyle Style = getLLVMStyle();
7017   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
7018 
7019   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
7020   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
7021                getStyleWithColumns(Style, 45));
7022   verifyFormat("Constructor() :\n"
7023                "    Initializer(FitsOnTheLine) {}",
7024                getStyleWithColumns(Style, 44));
7025   verifyFormat("Constructor() :\n"
7026                "    Initializer(FitsOnTheLine) {}",
7027                getStyleWithColumns(Style, 43));
7028 
7029   verifyFormat("template <typename T>\n"
7030                "Constructor() : Initializer(FitsOnTheLine) {}",
7031                getStyleWithColumns(Style, 50));
7032   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
7033   verifyFormat(
7034       "SomeClass::Constructor() :\n"
7035       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
7036       Style);
7037   verifyFormat(
7038       "SomeClass::Constructor() : // NOLINT\n"
7039       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
7040       Style);
7041 
7042   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
7043   verifyFormat(
7044       "SomeClass::Constructor() :\n"
7045       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
7046       Style);
7047 
7048   verifyFormat(
7049       "SomeClass::Constructor() :\n"
7050       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7051       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7052       Style);
7053   verifyFormat(
7054       "SomeClass::Constructor() :\n"
7055       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7056       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
7057       Style);
7058   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7059                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7060                "    aaaaaaaaaa(aaaaaa) {}",
7061                Style);
7062 
7063   verifyFormat("Constructor() :\n"
7064                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7065                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7066                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7067                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
7068                Style);
7069 
7070   verifyFormat("Constructor() :\n"
7071                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7072                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7073                Style);
7074 
7075   verifyFormat("Constructor(int Parameter = 0) :\n"
7076                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
7077                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
7078                Style);
7079   verifyFormat("Constructor() :\n"
7080                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
7081                "}",
7082                getStyleWithColumns(Style, 60));
7083   verifyFormat("Constructor() :\n"
7084                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7085                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
7086                Style);
7087 
7088   // Here a line could be saved by splitting the second initializer onto two
7089   // lines, but that is not desirable.
7090   verifyFormat("Constructor() :\n"
7091                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
7092                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
7093                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7094                Style);
7095 
7096   FormatStyle OnePerLine = Style;
7097   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
7098   verifyFormat("SomeClass::Constructor() :\n"
7099                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7100                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7101                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7102                OnePerLine);
7103   verifyFormat("SomeClass::Constructor() :\n"
7104                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
7105                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7106                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7107                OnePerLine);
7108   verifyFormat("Foo::Foo(int i, int j) : // NOLINT\n"
7109                "    i(i),                // comment\n"
7110                "    j(j) {}",
7111                OnePerLine);
7112   verifyFormat("MyClass::MyClass(int var) :\n"
7113                "    some_var_(var),            // 4 space indent\n"
7114                "    some_other_var_(var + 1) { // lined up\n"
7115                "}",
7116                OnePerLine);
7117   verifyFormat("Constructor() :\n"
7118                "    aaaaa(aaaaaa),\n"
7119                "    aaaaa(aaaaaa),\n"
7120                "    aaaaa(aaaaaa),\n"
7121                "    aaaaa(aaaaaa),\n"
7122                "    aaaaa(aaaaaa) {}",
7123                OnePerLine);
7124   verifyFormat("Constructor() :\n"
7125                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
7126                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
7127                OnePerLine);
7128   OnePerLine.BinPackParameters = false;
7129   verifyFormat("Constructor() :\n"
7130                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7131                "        aaaaaaaaaaa().aaa(),\n"
7132                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7133                OnePerLine);
7134   OnePerLine.ColumnLimit = 60;
7135   verifyFormat("Constructor() :\n"
7136                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
7137                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
7138                OnePerLine);
7139 
7140   verifyFormat("Constructor() :\n"
7141                "    // Comment forcing unwanted break.\n"
7142                "    aaaa(aaaa) {}",
7143                Style);
7144   verifyFormat("Constructor() : // NOLINT\n"
7145                "    aaaa(aaaa) {}",
7146                Style);
7147   verifyFormat("Constructor() : // A very long trailing comment that cannot fit"
7148                " on a single\n"
7149                "                // line.\n"
7150                "    aaaa(aaaa) {}",
7151                "Constructor() : // A very long trailing comment that cannot fit"
7152                " on a single line.\n"
7153                "    aaaa(aaaa) {}",
7154                Style);
7155 
7156   Style.ColumnLimit = 0;
7157   verifyFormat("SomeClass::Constructor() :\n"
7158                "    a(a) {}",
7159                Style);
7160   verifyFormat("SomeClass::Constructor() noexcept :\n"
7161                "    a(a) {}",
7162                Style);
7163   verifyFormat("SomeClass::Constructor() :\n"
7164                "    a(a), b(b), c(c) {}",
7165                Style);
7166   verifyFormat("SomeClass::Constructor() :\n"
7167                "    a(a) {\n"
7168                "  foo();\n"
7169                "  bar();\n"
7170                "}",
7171                Style);
7172 
7173   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
7174   verifyFormat("SomeClass::Constructor() :\n"
7175                "    a(a), b(b), c(c) {\n"
7176                "}",
7177                Style);
7178   verifyFormat("SomeClass::Constructor() :\n"
7179                "    a(a) {\n"
7180                "}",
7181                Style);
7182 
7183   Style.ColumnLimit = 80;
7184   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
7185   Style.ConstructorInitializerIndentWidth = 2;
7186   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
7187   verifyFormat("SomeClass::Constructor() :\n"
7188                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7189                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
7190                Style);
7191 
7192   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
7193   // well
7194   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
7195   verifyFormat(
7196       "class SomeClass\n"
7197       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7198       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7199       Style);
7200   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
7201   verifyFormat(
7202       "class SomeClass\n"
7203       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7204       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7205       Style);
7206   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
7207   verifyFormat(
7208       "class SomeClass :\n"
7209       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7210       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7211       Style);
7212   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
7213   verifyFormat(
7214       "class SomeClass\n"
7215       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7216       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7217       Style);
7218 }
7219 
7220 #ifndef EXPENSIVE_CHECKS
7221 // Expensive checks enables libstdc++ checking which includes validating the
7222 // state of ranges used in std::priority_queue - this blows out the
7223 // runtime/scalability of the function and makes this test unacceptably slow.
7224 TEST_F(FormatTest, MemoizationTests) {
7225   // This breaks if the memoization lookup does not take \c Indent and
7226   // \c LastSpace into account.
7227   verifyFormat(
7228       "extern CFRunLoopTimerRef\n"
7229       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
7230       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
7231       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
7232       "                     CFRunLoopTimerContext *context) {}");
7233 
7234   // Deep nesting somewhat works around our memoization.
7235   verifyFormat(
7236       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7237       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7238       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7239       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7240       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
7241       getLLVMStyleWithColumns(65));
7242   verifyFormat(
7243       "aaaaa(\n"
7244       "    aaaaa,\n"
7245       "    aaaaa(\n"
7246       "        aaaaa,\n"
7247       "        aaaaa(\n"
7248       "            aaaaa,\n"
7249       "            aaaaa(\n"
7250       "                aaaaa,\n"
7251       "                aaaaa(\n"
7252       "                    aaaaa,\n"
7253       "                    aaaaa(\n"
7254       "                        aaaaa,\n"
7255       "                        aaaaa(\n"
7256       "                            aaaaa,\n"
7257       "                            aaaaa(\n"
7258       "                                aaaaa,\n"
7259       "                                aaaaa(\n"
7260       "                                    aaaaa,\n"
7261       "                                    aaaaa(\n"
7262       "                                        aaaaa,\n"
7263       "                                        aaaaa(\n"
7264       "                                            aaaaa,\n"
7265       "                                            aaaaa(\n"
7266       "                                                aaaaa,\n"
7267       "                                                aaaaa))))))))))));",
7268       getLLVMStyleWithColumns(65));
7269   verifyFormat(
7270       "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"
7271       "                                  a),\n"
7272       "                                a),\n"
7273       "                              a),\n"
7274       "                            a),\n"
7275       "                          a),\n"
7276       "                        a),\n"
7277       "                      a),\n"
7278       "                    a),\n"
7279       "                  a),\n"
7280       "                a),\n"
7281       "              a),\n"
7282       "            a),\n"
7283       "          a),\n"
7284       "        a),\n"
7285       "      a),\n"
7286       "    a),\n"
7287       "  a)",
7288       getLLVMStyleWithColumns(65));
7289 
7290   // This test takes VERY long when memoization is broken.
7291   FormatStyle OnePerLine = getLLVMStyle();
7292   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
7293   OnePerLine.BinPackParameters = false;
7294   std::string input = "Constructor()\n"
7295                       "    : aaaa(a,\n";
7296   for (unsigned i = 0, e = 80; i != e; ++i)
7297     input += "           a,\n";
7298   input += "           a) {}";
7299   verifyFormat(input, OnePerLine);
7300 }
7301 #endif
7302 
7303 TEST_F(FormatTest, BreaksAsHighAsPossible) {
7304   verifyFormat(
7305       "void f() {\n"
7306       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
7307       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
7308       "    f();\n"
7309       "}");
7310   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
7311                "    Intervals[i - 1].getRange().getLast()) {\n}");
7312 }
7313 
7314 TEST_F(FormatTest, BreaksFunctionDeclarations) {
7315   // Principially, we break function declarations in a certain order:
7316   // 1) break amongst arguments.
7317   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
7318                "                              Cccccccccccccc cccccccccccccc);");
7319   verifyFormat("template <class TemplateIt>\n"
7320                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
7321                "                            TemplateIt *stop) {}");
7322 
7323   // 2) break after return type.
7324   verifyFormat(
7325       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7326       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
7327       getGoogleStyle());
7328 
7329   // 3) break after (.
7330   verifyFormat(
7331       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
7332       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
7333       getGoogleStyle());
7334 
7335   // 4) break before after nested name specifiers.
7336   verifyFormat(
7337       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7338       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
7339       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
7340       getGoogleStyle());
7341 
7342   // However, there are exceptions, if a sufficient amount of lines can be
7343   // saved.
7344   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
7345   // more adjusting.
7346   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7347                "                                  Cccccccccccccc cccccccccc,\n"
7348                "                                  Cccccccccccccc cccccccccc,\n"
7349                "                                  Cccccccccccccc cccccccccc,\n"
7350                "                                  Cccccccccccccc cccccccccc);");
7351   verifyFormat(
7352       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7353       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7354       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7355       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
7356       getGoogleStyle());
7357   verifyFormat(
7358       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7359       "                                          Cccccccccccccc cccccccccc,\n"
7360       "                                          Cccccccccccccc cccccccccc,\n"
7361       "                                          Cccccccccccccc cccccccccc,\n"
7362       "                                          Cccccccccccccc cccccccccc,\n"
7363       "                                          Cccccccccccccc cccccccccc,\n"
7364       "                                          Cccccccccccccc cccccccccc);");
7365   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7366                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7367                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7368                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7369                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
7370 
7371   // Break after multi-line parameters.
7372   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7373                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7374                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7375                "    bbbb bbbb);");
7376   verifyFormat("void SomeLoooooooooooongFunction(\n"
7377                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
7378                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7379                "    int bbbbbbbbbbbbb);");
7380 
7381   // Treat overloaded operators like other functions.
7382   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7383                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
7384   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7385                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
7386   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7387                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
7388   verifyGoogleFormat(
7389       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
7390       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7391   verifyGoogleFormat(
7392       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
7393       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7394   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7395                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7396   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
7397                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7398   verifyGoogleFormat(
7399       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
7400       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7401       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
7402   verifyGoogleFormat("template <typename T>\n"
7403                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7404                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
7405                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
7406 
7407   FormatStyle Style = getLLVMStyle();
7408   Style.PointerAlignment = FormatStyle::PAS_Left;
7409   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7410                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
7411                Style);
7412   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
7413                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7414                Style);
7415 }
7416 
7417 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
7418   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
7419   // Prefer keeping `::` followed by `operator` together.
7420   EXPECT_EQ("const aaaa::bbbbbbb &\n"
7421             "ccccccccc::operator++() {\n"
7422             "  stuff();\n"
7423             "}",
7424             format("const aaaa::bbbbbbb\n"
7425                    "&ccccccccc::operator++() { stuff(); }",
7426                    getLLVMStyleWithColumns(40)));
7427 }
7428 
7429 TEST_F(FormatTest, TrailingReturnType) {
7430   verifyFormat("auto foo() -> int;\n");
7431   // correct trailing return type spacing
7432   verifyFormat("auto operator->() -> int;\n");
7433   verifyFormat("auto operator++(int) -> int;\n");
7434 
7435   verifyFormat("struct S {\n"
7436                "  auto bar() const -> int;\n"
7437                "};");
7438   verifyFormat("template <size_t Order, typename T>\n"
7439                "auto load_img(const std::string &filename)\n"
7440                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
7441   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
7442                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
7443   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
7444   verifyFormat("template <typename T>\n"
7445                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
7446                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
7447 
7448   // Not trailing return types.
7449   verifyFormat("void f() { auto a = b->c(); }");
7450   verifyFormat("auto a = p->foo();");
7451   verifyFormat("int a = p->foo();");
7452   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
7453 }
7454 
7455 TEST_F(FormatTest, DeductionGuides) {
7456   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
7457   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
7458   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
7459   verifyFormat(
7460       "template <class... T>\n"
7461       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
7462   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
7463   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
7464   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
7465   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
7466   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
7467   verifyFormat("template <class T> x() -> x<1>;");
7468   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
7469 
7470   // Ensure not deduction guides.
7471   verifyFormat("c()->f<int>();");
7472   verifyFormat("x()->foo<1>;");
7473   verifyFormat("x = p->foo<3>();");
7474   verifyFormat("x()->x<1>();");
7475   verifyFormat("x()->x<1>;");
7476 }
7477 
7478 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
7479   // Avoid breaking before trailing 'const' or other trailing annotations, if
7480   // they are not function-like.
7481   FormatStyle Style = getGoogleStyleWithColumns(47);
7482   verifyFormat("void someLongFunction(\n"
7483                "    int someLoooooooooooooongParameter) const {\n}",
7484                getLLVMStyleWithColumns(47));
7485   verifyFormat("LoooooongReturnType\n"
7486                "someLoooooooongFunction() const {}",
7487                getLLVMStyleWithColumns(47));
7488   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
7489                "    const {}",
7490                Style);
7491   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7492                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
7493   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7494                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
7495   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7496                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
7497   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
7498                "                   aaaaaaaaaaa aaaaa) const override;");
7499   verifyGoogleFormat(
7500       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7501       "    const override;");
7502 
7503   // Even if the first parameter has to be wrapped.
7504   verifyFormat("void someLongFunction(\n"
7505                "    int someLongParameter) const {}",
7506                getLLVMStyleWithColumns(46));
7507   verifyFormat("void someLongFunction(\n"
7508                "    int someLongParameter) const {}",
7509                Style);
7510   verifyFormat("void someLongFunction(\n"
7511                "    int someLongParameter) override {}",
7512                Style);
7513   verifyFormat("void someLongFunction(\n"
7514                "    int someLongParameter) OVERRIDE {}",
7515                Style);
7516   verifyFormat("void someLongFunction(\n"
7517                "    int someLongParameter) final {}",
7518                Style);
7519   verifyFormat("void someLongFunction(\n"
7520                "    int someLongParameter) FINAL {}",
7521                Style);
7522   verifyFormat("void someLongFunction(\n"
7523                "    int parameter) const override {}",
7524                Style);
7525 
7526   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
7527   verifyFormat("void someLongFunction(\n"
7528                "    int someLongParameter) const\n"
7529                "{\n"
7530                "}",
7531                Style);
7532 
7533   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
7534   verifyFormat("void someLongFunction(\n"
7535                "    int someLongParameter) const\n"
7536                "  {\n"
7537                "  }",
7538                Style);
7539 
7540   // Unless these are unknown annotations.
7541   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
7542                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7543                "    LONG_AND_UGLY_ANNOTATION;");
7544 
7545   // Breaking before function-like trailing annotations is fine to keep them
7546   // close to their arguments.
7547   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7548                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7549   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7550                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7551   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7552                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
7553   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
7554                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
7555   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
7556 
7557   verifyFormat(
7558       "void aaaaaaaaaaaaaaaaaa()\n"
7559       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
7560       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
7561   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7562                "    __attribute__((unused));");
7563   verifyGoogleFormat(
7564       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7565       "    GUARDED_BY(aaaaaaaaaaaa);");
7566   verifyGoogleFormat(
7567       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7568       "    GUARDED_BY(aaaaaaaaaaaa);");
7569   verifyGoogleFormat(
7570       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7571       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7572   verifyGoogleFormat(
7573       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7574       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
7575 }
7576 
7577 TEST_F(FormatTest, FunctionAnnotations) {
7578   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7579                "int OldFunction(const string &parameter) {}");
7580   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7581                "string OldFunction(const string &parameter) {}");
7582   verifyFormat("template <typename T>\n"
7583                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7584                "string OldFunction(const string &parameter) {}");
7585 
7586   // Not function annotations.
7587   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7588                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
7589   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
7590                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
7591   verifyFormat("MACRO(abc).function() // wrap\n"
7592                "    << abc;");
7593   verifyFormat("MACRO(abc)->function() // wrap\n"
7594                "    << abc;");
7595   verifyFormat("MACRO(abc)::function() // wrap\n"
7596                "    << abc;");
7597 }
7598 
7599 TEST_F(FormatTest, BreaksDesireably) {
7600   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7601                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7602                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
7603   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7604                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
7605                "}");
7606 
7607   verifyFormat(
7608       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7609       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7610 
7611   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7612                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7613                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7614 
7615   verifyFormat(
7616       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7617       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7618       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7619       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7620       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7621 
7622   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7623                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7624 
7625   verifyFormat(
7626       "void f() {\n"
7627       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7628       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7629       "}");
7630   verifyFormat(
7631       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7632       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7633   verifyFormat(
7634       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7635       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7636   verifyFormat(
7637       "aaaaaa(aaa,\n"
7638       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7639       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7640       "       aaaa);");
7641   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7642                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7643                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7644 
7645   // Indent consistently independent of call expression and unary operator.
7646   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7647                "    dddddddddddddddddddddddddddddd));");
7648   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7649                "    dddddddddddddddddddddddddddddd));");
7650   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7651                "    dddddddddddddddddddddddddddddd));");
7652 
7653   // This test case breaks on an incorrect memoization, i.e. an optimization not
7654   // taking into account the StopAt value.
7655   verifyFormat(
7656       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7657       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7658       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7659       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7660 
7661   verifyFormat("{\n  {\n    {\n"
7662                "      Annotation.SpaceRequiredBefore =\n"
7663                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7664                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7665                "    }\n  }\n}");
7666 
7667   // Break on an outer level if there was a break on an inner level.
7668   EXPECT_EQ("f(g(h(a, // comment\n"
7669             "      b, c),\n"
7670             "    d, e),\n"
7671             "  x, y);",
7672             format("f(g(h(a, // comment\n"
7673                    "    b, c), d, e), x, y);"));
7674 
7675   // Prefer breaking similar line breaks.
7676   verifyFormat(
7677       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7678       "                             NSTrackingMouseEnteredAndExited |\n"
7679       "                             NSTrackingActiveAlways;");
7680 }
7681 
7682 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7683   FormatStyle NoBinPacking = getGoogleStyle();
7684   NoBinPacking.BinPackParameters = false;
7685   NoBinPacking.BinPackArguments = true;
7686   verifyFormat("void f() {\n"
7687                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7688                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7689                "}",
7690                NoBinPacking);
7691   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7692                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7693                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7694                NoBinPacking);
7695 
7696   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7697   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7698                "                        vector<int> bbbbbbbbbbbbbbb);",
7699                NoBinPacking);
7700   // FIXME: This behavior difference is probably not wanted. However, currently
7701   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7702   // template arguments from BreakBeforeParameter being set because of the
7703   // one-per-line formatting.
7704   verifyFormat(
7705       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7706       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7707       NoBinPacking);
7708   verifyFormat(
7709       "void fffffffffff(\n"
7710       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7711       "        aaaaaaaaaa);");
7712 }
7713 
7714 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7715   FormatStyle NoBinPacking = getGoogleStyle();
7716   NoBinPacking.BinPackParameters = false;
7717   NoBinPacking.BinPackArguments = false;
7718   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7719                "  aaaaaaaaaaaaaaaaaaaa,\n"
7720                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7721                NoBinPacking);
7722   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7723                "        aaaaaaaaaaaaa,\n"
7724                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7725                NoBinPacking);
7726   verifyFormat(
7727       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7728       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7729       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7730       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7731       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7732       NoBinPacking);
7733   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7734                "    .aaaaaaaaaaaaaaaaaa();",
7735                NoBinPacking);
7736   verifyFormat("void f() {\n"
7737                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7738                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7739                "}",
7740                NoBinPacking);
7741 
7742   verifyFormat(
7743       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7744       "             aaaaaaaaaaaa,\n"
7745       "             aaaaaaaaaaaa);",
7746       NoBinPacking);
7747   verifyFormat(
7748       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7749       "                               ddddddddddddddddddddddddddddd),\n"
7750       "             test);",
7751       NoBinPacking);
7752 
7753   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7754                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7755                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7756                "    aaaaaaaaaaaaaaaaaa;",
7757                NoBinPacking);
7758   verifyFormat("a(\"a\"\n"
7759                "  \"a\",\n"
7760                "  a);");
7761 
7762   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7763   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7764                "                aaaaaaaaa,\n"
7765                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7766                NoBinPacking);
7767   verifyFormat(
7768       "void f() {\n"
7769       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7770       "      .aaaaaaa();\n"
7771       "}",
7772       NoBinPacking);
7773   verifyFormat(
7774       "template <class SomeType, class SomeOtherType>\n"
7775       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7776       NoBinPacking);
7777 }
7778 
7779 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7780   FormatStyle Style = getLLVMStyleWithColumns(15);
7781   Style.ExperimentalAutoDetectBinPacking = true;
7782   EXPECT_EQ("aaa(aaaa,\n"
7783             "    aaaa,\n"
7784             "    aaaa);\n"
7785             "aaa(aaaa,\n"
7786             "    aaaa,\n"
7787             "    aaaa);",
7788             format("aaa(aaaa,\n" // one-per-line
7789                    "  aaaa,\n"
7790                    "    aaaa  );\n"
7791                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7792                    Style));
7793   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7794             "    aaaa);\n"
7795             "aaa(aaaa, aaaa,\n"
7796             "    aaaa);",
7797             format("aaa(aaaa,  aaaa,\n" // bin-packed
7798                    "    aaaa  );\n"
7799                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7800                    Style));
7801 }
7802 
7803 TEST_F(FormatTest, FormatsBuilderPattern) {
7804   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7805                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7806                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7807                "    .StartsWith(\".init\", ORDER_INIT)\n"
7808                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7809                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7810                "    .Default(ORDER_TEXT);\n");
7811 
7812   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7813                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7814   verifyFormat("aaaaaaa->aaaaaaa\n"
7815                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7816                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7817                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7818   verifyFormat(
7819       "aaaaaaa->aaaaaaa\n"
7820       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7821       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7822   verifyFormat(
7823       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7824       "    aaaaaaaaaaaaaa);");
7825   verifyFormat(
7826       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7827       "    aaaaaa->aaaaaaaaaaaa()\n"
7828       "        ->aaaaaaaaaaaaaaaa(\n"
7829       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7830       "        ->aaaaaaaaaaaaaaaaa();");
7831   verifyGoogleFormat(
7832       "void f() {\n"
7833       "  someo->Add((new util::filetools::Handler(dir))\n"
7834       "                 ->OnEvent1(NewPermanentCallback(\n"
7835       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7836       "                 ->OnEvent2(NewPermanentCallback(\n"
7837       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7838       "                 ->OnEvent3(NewPermanentCallback(\n"
7839       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7840       "                 ->OnEvent5(NewPermanentCallback(\n"
7841       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7842       "                 ->OnEvent6(NewPermanentCallback(\n"
7843       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7844       "}");
7845 
7846   verifyFormat(
7847       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7848   verifyFormat("aaaaaaaaaaaaaaa()\n"
7849                "    .aaaaaaaaaaaaaaa()\n"
7850                "    .aaaaaaaaaaaaaaa()\n"
7851                "    .aaaaaaaaaaaaaaa()\n"
7852                "    .aaaaaaaaaaaaaaa();");
7853   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7854                "    .aaaaaaaaaaaaaaa()\n"
7855                "    .aaaaaaaaaaaaaaa()\n"
7856                "    .aaaaaaaaaaaaaaa();");
7857   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7858                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7859                "    .aaaaaaaaaaaaaaa();");
7860   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7861                "    ->aaaaaaaaaaaaaae(0)\n"
7862                "    ->aaaaaaaaaaaaaaa();");
7863 
7864   // Don't linewrap after very short segments.
7865   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7866                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7867                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7868   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7869                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7870                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7871   verifyFormat("aaa()\n"
7872                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7873                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7874                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7875 
7876   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7877                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7878                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7879   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7880                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7881                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7882 
7883   // Prefer not to break after empty parentheses.
7884   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7885                "    First->LastNewlineOffset);");
7886 
7887   // Prefer not to create "hanging" indents.
7888   verifyFormat(
7889       "return !soooooooooooooome_map\n"
7890       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7891       "            .second;");
7892   verifyFormat(
7893       "return aaaaaaaaaaaaaaaa\n"
7894       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7895       "    .aaaa(aaaaaaaaaaaaaa);");
7896   // No hanging indent here.
7897   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7898                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7899   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7900                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7901   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7902                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7903                getLLVMStyleWithColumns(60));
7904   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7905                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7906                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7907                getLLVMStyleWithColumns(59));
7908   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7909                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7910                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7911 
7912   // Dont break if only closing statements before member call
7913   verifyFormat("test() {\n"
7914                "  ([]() -> {\n"
7915                "    int b = 32;\n"
7916                "    return 3;\n"
7917                "  }).foo();\n"
7918                "}");
7919   verifyFormat("test() {\n"
7920                "  (\n"
7921                "      []() -> {\n"
7922                "        int b = 32;\n"
7923                "        return 3;\n"
7924                "      },\n"
7925                "      foo, bar)\n"
7926                "      .foo();\n"
7927                "}");
7928   verifyFormat("test() {\n"
7929                "  ([]() -> {\n"
7930                "    int b = 32;\n"
7931                "    return 3;\n"
7932                "  })\n"
7933                "      .foo()\n"
7934                "      .bar();\n"
7935                "}");
7936   verifyFormat("test() {\n"
7937                "  ([]() -> {\n"
7938                "    int b = 32;\n"
7939                "    return 3;\n"
7940                "  })\n"
7941                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7942                "           \"bbbb\");\n"
7943                "}",
7944                getLLVMStyleWithColumns(30));
7945 }
7946 
7947 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7948   verifyFormat(
7949       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7950       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7951   verifyFormat(
7952       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7953       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7954 
7955   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7956                "    ccccccccccccccccccccccccc) {\n}");
7957   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7958                "    ccccccccccccccccccccccccc) {\n}");
7959 
7960   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7961                "    ccccccccccccccccccccccccc) {\n}");
7962   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7963                "    ccccccccccccccccccccccccc) {\n}");
7964 
7965   verifyFormat(
7966       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7967       "    ccccccccccccccccccccccccc) {\n}");
7968   verifyFormat(
7969       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7970       "    ccccccccccccccccccccccccc) {\n}");
7971 
7972   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7973                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7974                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7975                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7976   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7977                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7978                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7979                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7980 
7981   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7982                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7983                "    aaaaaaaaaaaaaaa != aa) {\n}");
7984   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7985                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7986                "    aaaaaaaaaaaaaaa != aa) {\n}");
7987 }
7988 
7989 TEST_F(FormatTest, BreaksAfterAssignments) {
7990   verifyFormat(
7991       "unsigned Cost =\n"
7992       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7993       "                        SI->getPointerAddressSpaceee());\n");
7994   verifyFormat(
7995       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7996       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7997 
7998   verifyFormat(
7999       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
8000       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
8001   verifyFormat("unsigned OriginalStartColumn =\n"
8002                "    SourceMgr.getSpellingColumnNumber(\n"
8003                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
8004                "    1;");
8005 }
8006 
8007 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
8008   FormatStyle Style = getLLVMStyle();
8009   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8010                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
8011                Style);
8012 
8013   Style.PenaltyBreakAssignment = 20;
8014   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
8015                "                                 cccccccccccccccccccccccccc;",
8016                Style);
8017 }
8018 
8019 TEST_F(FormatTest, AlignsAfterAssignments) {
8020   verifyFormat(
8021       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8022       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
8023   verifyFormat(
8024       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8025       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
8026   verifyFormat(
8027       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8028       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
8029   verifyFormat(
8030       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8031       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
8032   verifyFormat(
8033       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
8034       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
8035       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
8036 }
8037 
8038 TEST_F(FormatTest, AlignsAfterReturn) {
8039   verifyFormat(
8040       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8041       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
8042   verifyFormat(
8043       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8044       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
8045   verifyFormat(
8046       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
8047       "       aaaaaaaaaaaaaaaaaaaaaa();");
8048   verifyFormat(
8049       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
8050       "        aaaaaaaaaaaaaaaaaaaaaa());");
8051   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8052                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8053   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8054                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
8055                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8056   verifyFormat("return\n"
8057                "    // true if code is one of a or b.\n"
8058                "    code == a || code == b;");
8059 }
8060 
8061 TEST_F(FormatTest, AlignsAfterOpenBracket) {
8062   verifyFormat(
8063       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
8064       "                                                aaaaaaaaa aaaaaaa) {}");
8065   verifyFormat(
8066       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
8067       "                                               aaaaaaaaaaa aaaaaaaaa);");
8068   verifyFormat(
8069       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
8070       "                                             aaaaaaaaaaaaaaaaaaaaa));");
8071   FormatStyle Style = getLLVMStyle();
8072   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8073   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8074                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
8075                Style);
8076   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8077                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
8078                Style);
8079   verifyFormat("SomeLongVariableName->someFunction(\n"
8080                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
8081                Style);
8082   verifyFormat(
8083       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
8084       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8085       Style);
8086   verifyFormat(
8087       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
8088       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8089       Style);
8090   verifyFormat(
8091       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
8092       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8093       Style);
8094 
8095   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
8096                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
8097                "        b));",
8098                Style);
8099 
8100   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8101   Style.BinPackArguments = false;
8102   Style.BinPackParameters = false;
8103   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8104                "    aaaaaaaaaaa aaaaaaaa,\n"
8105                "    aaaaaaaaa aaaaaaa,\n"
8106                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8107                Style);
8108   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8109                "    aaaaaaaaaaa aaaaaaaaa,\n"
8110                "    aaaaaaaaaaa aaaaaaaaa,\n"
8111                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8112                Style);
8113   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
8114                "    aaaaaaaaaaaaaaa,\n"
8115                "    aaaaaaaaaaaaaaaaaaaaa,\n"
8116                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8117                Style);
8118   verifyFormat(
8119       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
8120       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8121       Style);
8122   verifyFormat(
8123       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
8124       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8125       Style);
8126   verifyFormat(
8127       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8128       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8129       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
8130       "    aaaaaaaaaaaaaaaa);",
8131       Style);
8132   verifyFormat(
8133       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8134       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8135       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
8136       "    aaaaaaaaaaaaaaaa);",
8137       Style);
8138 }
8139 
8140 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
8141   FormatStyle Style = getLLVMStyleWithColumns(40);
8142   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8143                "          bbbbbbbbbbbbbbbbbbbbbb);",
8144                Style);
8145   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
8146   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8147   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8148                "          bbbbbbbbbbbbbbbbbbbbbb);",
8149                Style);
8150   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8151   Style.AlignOperands = FormatStyle::OAS_Align;
8152   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8153                "          bbbbbbbbbbbbbbbbbbbbbb);",
8154                Style);
8155   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8156   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8157   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8158                "    bbbbbbbbbbbbbbbbbbbbbb);",
8159                Style);
8160 }
8161 
8162 TEST_F(FormatTest, BreaksConditionalExpressions) {
8163   verifyFormat(
8164       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8165       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8166       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8167   verifyFormat(
8168       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8169       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8170       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8171   verifyFormat(
8172       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8173       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8174   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
8175                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8176                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8177   verifyFormat(
8178       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
8179       "                                                    : aaaaaaaaaaaaa);");
8180   verifyFormat(
8181       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8182       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8183       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8184       "                   aaaaaaaaaaaaa);");
8185   verifyFormat(
8186       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8187       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8188       "                   aaaaaaaaaaaaa);");
8189   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8190                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8191                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8192                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8193                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8194   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8195                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8196                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8197                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8198                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8199                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8200                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8201   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8202                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8203                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8204                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8205                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8206   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8207                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8208                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8209   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8210                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8211                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8212                "        : aaaaaaaaaaaaaaaa;");
8213   verifyFormat(
8214       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8215       "    ? aaaaaaaaaaaaaaa\n"
8216       "    : aaaaaaaaaaaaaaa;");
8217   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8218                "          aaaaaaaaa\n"
8219                "      ? b\n"
8220                "      : c);");
8221   verifyFormat("return aaaa == bbbb\n"
8222                "           // comment\n"
8223                "           ? aaaa\n"
8224                "           : bbbb;");
8225   verifyFormat("unsigned Indent =\n"
8226                "    format(TheLine.First,\n"
8227                "           IndentForLevel[TheLine.Level] >= 0\n"
8228                "               ? IndentForLevel[TheLine.Level]\n"
8229                "               : TheLine * 2,\n"
8230                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8231                getLLVMStyleWithColumns(60));
8232   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8233                "                  ? aaaaaaaaaaaaaaa\n"
8234                "                  : bbbbbbbbbbbbbbb //\n"
8235                "                        ? ccccccccccccccc\n"
8236                "                        : ddddddddddddddd;");
8237   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8238                "                  ? aaaaaaaaaaaaaaa\n"
8239                "                  : (bbbbbbbbbbbbbbb //\n"
8240                "                         ? ccccccccccccccc\n"
8241                "                         : ddddddddddddddd);");
8242   verifyFormat(
8243       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8244       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8245       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
8246       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
8247       "                                      : aaaaaaaaaa;");
8248   verifyFormat(
8249       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8250       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
8251       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8252 
8253   FormatStyle NoBinPacking = getLLVMStyle();
8254   NoBinPacking.BinPackArguments = false;
8255   verifyFormat(
8256       "void f() {\n"
8257       "  g(aaa,\n"
8258       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8259       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8260       "        ? aaaaaaaaaaaaaaa\n"
8261       "        : aaaaaaaaaaaaaaa);\n"
8262       "}",
8263       NoBinPacking);
8264   verifyFormat(
8265       "void f() {\n"
8266       "  g(aaa,\n"
8267       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8268       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8269       "        ?: aaaaaaaaaaaaaaa);\n"
8270       "}",
8271       NoBinPacking);
8272 
8273   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
8274                "             // comment.\n"
8275                "             ccccccccccccccccccccccccccccccccccccccc\n"
8276                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8277                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
8278 
8279   // Assignments in conditional expressions. Apparently not uncommon :-(.
8280   verifyFormat("return a != b\n"
8281                "           // comment\n"
8282                "           ? a = b\n"
8283                "           : a = b;");
8284   verifyFormat("return a != b\n"
8285                "           // comment\n"
8286                "           ? a = a != b\n"
8287                "                     // comment\n"
8288                "                     ? a = b\n"
8289                "                     : a\n"
8290                "           : a;\n");
8291   verifyFormat("return a != b\n"
8292                "           // comment\n"
8293                "           ? a\n"
8294                "           : a = a != b\n"
8295                "                     // comment\n"
8296                "                     ? a = b\n"
8297                "                     : a;");
8298 
8299   // Chained conditionals
8300   FormatStyle Style = getLLVMStyleWithColumns(70);
8301   Style.AlignOperands = FormatStyle::OAS_Align;
8302   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8303                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8304                "                        : 3333333333333333;",
8305                Style);
8306   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8307                "       : bbbbbbbbbb     ? 2222222222222222\n"
8308                "                        : 3333333333333333;",
8309                Style);
8310   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
8311                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
8312                "                          : 3333333333333333;",
8313                Style);
8314   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8315                "       : bbbbbbbbbbbbbb ? 222222\n"
8316                "                        : 333333;",
8317                Style);
8318   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8319                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8320                "       : cccccccccccccc ? 3333333333333333\n"
8321                "                        : 4444444444444444;",
8322                Style);
8323   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
8324                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8325                "                        : 3333333333333333;",
8326                Style);
8327   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8328                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8329                "                        : (aaa ? bbb : ccc);",
8330                Style);
8331   verifyFormat(
8332       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8333       "                                             : cccccccccccccccccc)\n"
8334       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8335       "                        : 3333333333333333;",
8336       Style);
8337   verifyFormat(
8338       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8339       "                                             : cccccccccccccccccc)\n"
8340       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8341       "                        : 3333333333333333;",
8342       Style);
8343   verifyFormat(
8344       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8345       "                                             : dddddddddddddddddd)\n"
8346       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8347       "                        : 3333333333333333;",
8348       Style);
8349   verifyFormat(
8350       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8351       "                                             : dddddddddddddddddd)\n"
8352       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8353       "                        : 3333333333333333;",
8354       Style);
8355   verifyFormat(
8356       "return aaaaaaaaa        ? 1111111111111111\n"
8357       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8358       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8359       "                                             : dddddddddddddddddd)\n",
8360       Style);
8361   verifyFormat(
8362       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8363       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8364       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8365       "                                             : cccccccccccccccccc);",
8366       Style);
8367   verifyFormat(
8368       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8369       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8370       "                                             : eeeeeeeeeeeeeeeeee)\n"
8371       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8372       "                        : 3333333333333333;",
8373       Style);
8374   verifyFormat(
8375       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
8376       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8377       "                                             : eeeeeeeeeeeeeeeeee)\n"
8378       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8379       "                        : 3333333333333333;",
8380       Style);
8381   verifyFormat(
8382       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8383       "                           : cccccccccccc    ? dddddddddddddddddd\n"
8384       "                                             : eeeeeeeeeeeeeeeeee)\n"
8385       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8386       "                        : 3333333333333333;",
8387       Style);
8388   verifyFormat(
8389       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8390       "                                             : cccccccccccccccccc\n"
8391       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8392       "                        : 3333333333333333;",
8393       Style);
8394   verifyFormat(
8395       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8396       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
8397       "                                             : eeeeeeeeeeeeeeeeee\n"
8398       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8399       "                        : 3333333333333333;",
8400       Style);
8401   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
8402                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
8403                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
8404                "                                   : eeeeeeeeeeeeeeeeee)\n"
8405                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8406                "                             : 3333333333333333;",
8407                Style);
8408   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
8409                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8410                "             : cccccccccccccccc ? dddddddddddddddddd\n"
8411                "                                : eeeeeeeeeeeeeeeeee\n"
8412                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8413                "                                 : 3333333333333333;",
8414                Style);
8415 
8416   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8417   Style.BreakBeforeTernaryOperators = false;
8418   // FIXME: Aligning the question marks is weird given DontAlign.
8419   // Consider disabling this alignment in this case. Also check whether this
8420   // will render the adjustment from https://reviews.llvm.org/D82199
8421   // unnecessary.
8422   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
8423                "    bbbb                ? cccccccccccccccccc :\n"
8424                "                          ddddd;\n",
8425                Style);
8426 
8427   EXPECT_EQ(
8428       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8429       "    /*\n"
8430       "     */\n"
8431       "    function() {\n"
8432       "      try {\n"
8433       "        return JJJJJJJJJJJJJJ(\n"
8434       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8435       "      }\n"
8436       "    } :\n"
8437       "    function() {};",
8438       format(
8439           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8440           "     /*\n"
8441           "      */\n"
8442           "     function() {\n"
8443           "      try {\n"
8444           "        return JJJJJJJJJJJJJJ(\n"
8445           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8446           "      }\n"
8447           "    } :\n"
8448           "    function() {};",
8449           getGoogleStyle(FormatStyle::LK_JavaScript)));
8450 }
8451 
8452 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
8453   FormatStyle Style = getLLVMStyleWithColumns(70);
8454   Style.BreakBeforeTernaryOperators = false;
8455   verifyFormat(
8456       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8457       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8458       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8459       Style);
8460   verifyFormat(
8461       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8462       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8463       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8464       Style);
8465   verifyFormat(
8466       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8467       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8468       Style);
8469   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
8470                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8471                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8472                Style);
8473   verifyFormat(
8474       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
8475       "                                                      aaaaaaaaaaaaa);",
8476       Style);
8477   verifyFormat(
8478       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8479       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8480       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8481       "                   aaaaaaaaaaaaa);",
8482       Style);
8483   verifyFormat(
8484       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8485       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8486       "                   aaaaaaaaaaaaa);",
8487       Style);
8488   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8489                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8490                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8491                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8492                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8493                Style);
8494   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8495                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8496                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8497                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8498                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8499                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8500                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8501                Style);
8502   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8503                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
8504                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8505                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8506                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8507                Style);
8508   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8509                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8510                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8511                Style);
8512   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8513                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8514                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8515                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8516                Style);
8517   verifyFormat(
8518       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8519       "    aaaaaaaaaaaaaaa :\n"
8520       "    aaaaaaaaaaaaaaa;",
8521       Style);
8522   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8523                "          aaaaaaaaa ?\n"
8524                "      b :\n"
8525                "      c);",
8526                Style);
8527   verifyFormat("unsigned Indent =\n"
8528                "    format(TheLine.First,\n"
8529                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
8530                "               IndentForLevel[TheLine.Level] :\n"
8531                "               TheLine * 2,\n"
8532                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8533                Style);
8534   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8535                "                  aaaaaaaaaaaaaaa :\n"
8536                "                  bbbbbbbbbbbbbbb ? //\n"
8537                "                      ccccccccccccccc :\n"
8538                "                      ddddddddddddddd;",
8539                Style);
8540   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8541                "                  aaaaaaaaaaaaaaa :\n"
8542                "                  (bbbbbbbbbbbbbbb ? //\n"
8543                "                       ccccccccccccccc :\n"
8544                "                       ddddddddddddddd);",
8545                Style);
8546   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8547                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
8548                "            ccccccccccccccccccccccccccc;",
8549                Style);
8550   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8551                "           aaaaa :\n"
8552                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
8553                Style);
8554 
8555   // Chained conditionals
8556   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8557                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8558                "                          3333333333333333;",
8559                Style);
8560   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8561                "       bbbbbbbbbb       ? 2222222222222222 :\n"
8562                "                          3333333333333333;",
8563                Style);
8564   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
8565                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8566                "                          3333333333333333;",
8567                Style);
8568   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8569                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
8570                "                          333333;",
8571                Style);
8572   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8573                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8574                "       cccccccccccccccc ? 3333333333333333 :\n"
8575                "                          4444444444444444;",
8576                Style);
8577   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
8578                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8579                "                          3333333333333333;",
8580                Style);
8581   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8582                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8583                "                          (aaa ? bbb : ccc);",
8584                Style);
8585   verifyFormat(
8586       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8587       "                                               cccccccccccccccccc) :\n"
8588       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8589       "                          3333333333333333;",
8590       Style);
8591   verifyFormat(
8592       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8593       "                                               cccccccccccccccccc) :\n"
8594       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8595       "                          3333333333333333;",
8596       Style);
8597   verifyFormat(
8598       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8599       "                                               dddddddddddddddddd) :\n"
8600       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8601       "                          3333333333333333;",
8602       Style);
8603   verifyFormat(
8604       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8605       "                                               dddddddddddddddddd) :\n"
8606       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8607       "                          3333333333333333;",
8608       Style);
8609   verifyFormat(
8610       "return aaaaaaaaa        ? 1111111111111111 :\n"
8611       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8612       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8613       "                                               dddddddddddddddddd)\n",
8614       Style);
8615   verifyFormat(
8616       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8617       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8618       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8619       "                                               cccccccccccccccccc);",
8620       Style);
8621   verifyFormat(
8622       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8623       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8624       "                                               eeeeeeeeeeeeeeeeee) :\n"
8625       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8626       "                          3333333333333333;",
8627       Style);
8628   verifyFormat(
8629       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8630       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8631       "                                               eeeeeeeeeeeeeeeeee) :\n"
8632       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8633       "                          3333333333333333;",
8634       Style);
8635   verifyFormat(
8636       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8637       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8638       "                                               eeeeeeeeeeeeeeeeee) :\n"
8639       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8640       "                          3333333333333333;",
8641       Style);
8642   verifyFormat(
8643       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8644       "                                               cccccccccccccccccc :\n"
8645       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8646       "                          3333333333333333;",
8647       Style);
8648   verifyFormat(
8649       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8650       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8651       "                                               eeeeeeeeeeeeeeeeee :\n"
8652       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8653       "                          3333333333333333;",
8654       Style);
8655   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8656                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8657                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8658                "                                 eeeeeeeeeeeeeeeeee) :\n"
8659                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8660                "                               3333333333333333;",
8661                Style);
8662   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8663                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8664                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8665                "                                  eeeeeeeeeeeeeeeeee :\n"
8666                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8667                "                               3333333333333333;",
8668                Style);
8669 }
8670 
8671 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8672   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8673                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8674   verifyFormat("bool a = true, b = false;");
8675 
8676   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8677                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8678                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8679                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8680   verifyFormat(
8681       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8682       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8683       "     d = e && f;");
8684   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8685                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8686   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8687                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8688   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8689                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8690 
8691   FormatStyle Style = getGoogleStyle();
8692   Style.PointerAlignment = FormatStyle::PAS_Left;
8693   Style.DerivePointerAlignment = false;
8694   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8695                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8696                "    *b = bbbbbbbbbbbbbbbbbbb;",
8697                Style);
8698   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8699                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8700                Style);
8701   verifyFormat("vector<int*> a, b;", Style);
8702   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8703   verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style);
8704   verifyFormat("if (int *p, *q; p != q) {\n  p = p->next;\n}", Style);
8705   verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n  p = p->next;\n}",
8706                Style);
8707   verifyFormat("switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8708                Style);
8709   verifyFormat(
8710       "/*comment*/ switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8711       Style);
8712 
8713   verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style);
8714   verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style);
8715   verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style);
8716   verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style);
8717   verifyFormat("switch ([](int* p, int* q) {}()) {\n  default:\n    break;\n}",
8718                Style);
8719 }
8720 
8721 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8722   verifyFormat("arr[foo ? bar : baz];");
8723   verifyFormat("f()[foo ? bar : baz];");
8724   verifyFormat("(a + b)[foo ? bar : baz];");
8725   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8726 }
8727 
8728 TEST_F(FormatTest, AlignsStringLiterals) {
8729   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8730                "                                      \"short literal\");");
8731   verifyFormat(
8732       "looooooooooooooooooooooooongFunction(\n"
8733       "    \"short literal\"\n"
8734       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8735   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8736                "             \" string literals\",\n"
8737                "             and, other, parameters);");
8738   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8739             "      \"5678\";",
8740             format("fun + \"1243\" /* comment */\n"
8741                    "    \"5678\";",
8742                    getLLVMStyleWithColumns(28)));
8743   EXPECT_EQ(
8744       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8745       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8746       "         \"aaaaaaaaaaaaaaaa\";",
8747       format("aaaaaa ="
8748              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8749              "aaaaaaaaaaaaaaaaaaaaa\" "
8750              "\"aaaaaaaaaaaaaaaa\";"));
8751   verifyFormat("a = a + \"a\"\n"
8752                "        \"a\"\n"
8753                "        \"a\";");
8754   verifyFormat("f(\"a\", \"b\"\n"
8755                "       \"c\");");
8756 
8757   verifyFormat(
8758       "#define LL_FORMAT \"ll\"\n"
8759       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8760       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8761 
8762   verifyFormat("#define A(X)          \\\n"
8763                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8764                "  \"ccccc\"",
8765                getLLVMStyleWithColumns(23));
8766   verifyFormat("#define A \"def\"\n"
8767                "f(\"abc\" A \"ghi\"\n"
8768                "  \"jkl\");");
8769 
8770   verifyFormat("f(L\"a\"\n"
8771                "  L\"b\");");
8772   verifyFormat("#define A(X)            \\\n"
8773                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8774                "  L\"ccccc\"",
8775                getLLVMStyleWithColumns(25));
8776 
8777   verifyFormat("f(@\"a\"\n"
8778                "  @\"b\");");
8779   verifyFormat("NSString s = @\"a\"\n"
8780                "             @\"b\"\n"
8781                "             @\"c\";");
8782   verifyFormat("NSString s = @\"a\"\n"
8783                "              \"b\"\n"
8784                "              \"c\";");
8785 }
8786 
8787 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8788   FormatStyle Style = getLLVMStyle();
8789   // No declarations or definitions should be moved to own line.
8790   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8791   verifyFormat("class A {\n"
8792                "  int f() { return 1; }\n"
8793                "  int g();\n"
8794                "};\n"
8795                "int f() { return 1; }\n"
8796                "int g();\n",
8797                Style);
8798 
8799   // All declarations and definitions should have the return type moved to its
8800   // own line.
8801   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8802   Style.TypenameMacros = {"LIST"};
8803   verifyFormat("SomeType\n"
8804                "funcdecl(LIST(uint64_t));",
8805                Style);
8806   verifyFormat("class E {\n"
8807                "  int\n"
8808                "  f() {\n"
8809                "    return 1;\n"
8810                "  }\n"
8811                "  int\n"
8812                "  g();\n"
8813                "};\n"
8814                "int\n"
8815                "f() {\n"
8816                "  return 1;\n"
8817                "}\n"
8818                "int\n"
8819                "g();\n",
8820                Style);
8821 
8822   // Top-level definitions, and no kinds of declarations should have the
8823   // return type moved to its own line.
8824   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8825   verifyFormat("class B {\n"
8826                "  int f() { return 1; }\n"
8827                "  int g();\n"
8828                "};\n"
8829                "int\n"
8830                "f() {\n"
8831                "  return 1;\n"
8832                "}\n"
8833                "int g();\n",
8834                Style);
8835 
8836   // Top-level definitions and declarations should have the return type moved
8837   // to its own line.
8838   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8839   verifyFormat("class C {\n"
8840                "  int f() { return 1; }\n"
8841                "  int g();\n"
8842                "};\n"
8843                "int\n"
8844                "f() {\n"
8845                "  return 1;\n"
8846                "}\n"
8847                "int\n"
8848                "g();\n",
8849                Style);
8850 
8851   // All definitions should have the return type moved to its own line, but no
8852   // kinds of declarations.
8853   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8854   verifyFormat("class D {\n"
8855                "  int\n"
8856                "  f() {\n"
8857                "    return 1;\n"
8858                "  }\n"
8859                "  int g();\n"
8860                "};\n"
8861                "int\n"
8862                "f() {\n"
8863                "  return 1;\n"
8864                "}\n"
8865                "int g();\n",
8866                Style);
8867   verifyFormat("const char *\n"
8868                "f(void) {\n" // Break here.
8869                "  return \"\";\n"
8870                "}\n"
8871                "const char *bar(void);\n", // No break here.
8872                Style);
8873   verifyFormat("template <class T>\n"
8874                "T *\n"
8875                "f(T &c) {\n" // Break here.
8876                "  return NULL;\n"
8877                "}\n"
8878                "template <class T> T *f(T &c);\n", // No break here.
8879                Style);
8880   verifyFormat("class C {\n"
8881                "  int\n"
8882                "  operator+() {\n"
8883                "    return 1;\n"
8884                "  }\n"
8885                "  int\n"
8886                "  operator()() {\n"
8887                "    return 1;\n"
8888                "  }\n"
8889                "};\n",
8890                Style);
8891   verifyFormat("void\n"
8892                "A::operator()() {}\n"
8893                "void\n"
8894                "A::operator>>() {}\n"
8895                "void\n"
8896                "A::operator+() {}\n"
8897                "void\n"
8898                "A::operator*() {}\n"
8899                "void\n"
8900                "A::operator->() {}\n"
8901                "void\n"
8902                "A::operator void *() {}\n"
8903                "void\n"
8904                "A::operator void &() {}\n"
8905                "void\n"
8906                "A::operator void &&() {}\n"
8907                "void\n"
8908                "A::operator char *() {}\n"
8909                "void\n"
8910                "A::operator[]() {}\n"
8911                "void\n"
8912                "A::operator!() {}\n"
8913                "void\n"
8914                "A::operator**() {}\n"
8915                "void\n"
8916                "A::operator<Foo> *() {}\n"
8917                "void\n"
8918                "A::operator<Foo> **() {}\n"
8919                "void\n"
8920                "A::operator<Foo> &() {}\n"
8921                "void\n"
8922                "A::operator void **() {}\n",
8923                Style);
8924   verifyFormat("constexpr auto\n"
8925                "operator()() const -> reference {}\n"
8926                "constexpr auto\n"
8927                "operator>>() const -> reference {}\n"
8928                "constexpr auto\n"
8929                "operator+() const -> reference {}\n"
8930                "constexpr auto\n"
8931                "operator*() const -> reference {}\n"
8932                "constexpr auto\n"
8933                "operator->() const -> reference {}\n"
8934                "constexpr auto\n"
8935                "operator++() const -> reference {}\n"
8936                "constexpr auto\n"
8937                "operator void *() const -> reference {}\n"
8938                "constexpr auto\n"
8939                "operator void **() const -> reference {}\n"
8940                "constexpr auto\n"
8941                "operator void *() const -> reference {}\n"
8942                "constexpr auto\n"
8943                "operator void &() const -> reference {}\n"
8944                "constexpr auto\n"
8945                "operator void &&() const -> reference {}\n"
8946                "constexpr auto\n"
8947                "operator char *() const -> reference {}\n"
8948                "constexpr auto\n"
8949                "operator!() const -> reference {}\n"
8950                "constexpr auto\n"
8951                "operator[]() const -> reference {}\n",
8952                Style);
8953   verifyFormat("void *operator new(std::size_t s);", // No break here.
8954                Style);
8955   verifyFormat("void *\n"
8956                "operator new(std::size_t s) {}",
8957                Style);
8958   verifyFormat("void *\n"
8959                "operator delete[](void *ptr) {}",
8960                Style);
8961   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8962   verifyFormat("const char *\n"
8963                "f(void)\n" // Break here.
8964                "{\n"
8965                "  return \"\";\n"
8966                "}\n"
8967                "const char *bar(void);\n", // No break here.
8968                Style);
8969   verifyFormat("template <class T>\n"
8970                "T *\n"     // Problem here: no line break
8971                "f(T &c)\n" // Break here.
8972                "{\n"
8973                "  return NULL;\n"
8974                "}\n"
8975                "template <class T> T *f(T &c);\n", // No break here.
8976                Style);
8977   verifyFormat("int\n"
8978                "foo(A<bool> a)\n"
8979                "{\n"
8980                "  return a;\n"
8981                "}\n",
8982                Style);
8983   verifyFormat("int\n"
8984                "foo(A<8> a)\n"
8985                "{\n"
8986                "  return a;\n"
8987                "}\n",
8988                Style);
8989   verifyFormat("int\n"
8990                "foo(A<B<bool>, 8> a)\n"
8991                "{\n"
8992                "  return a;\n"
8993                "}\n",
8994                Style);
8995   verifyFormat("int\n"
8996                "foo(A<B<8>, bool> a)\n"
8997                "{\n"
8998                "  return a;\n"
8999                "}\n",
9000                Style);
9001   verifyFormat("int\n"
9002                "foo(A<B<bool>, bool> a)\n"
9003                "{\n"
9004                "  return a;\n"
9005                "}\n",
9006                Style);
9007   verifyFormat("int\n"
9008                "foo(A<B<8>, 8> a)\n"
9009                "{\n"
9010                "  return a;\n"
9011                "}\n",
9012                Style);
9013 
9014   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9015   Style.BraceWrapping.AfterFunction = true;
9016   verifyFormat("int f(i);\n" // No break here.
9017                "int\n"       // Break here.
9018                "f(i)\n"
9019                "{\n"
9020                "  return i + 1;\n"
9021                "}\n"
9022                "int\n" // Break here.
9023                "f(i)\n"
9024                "{\n"
9025                "  return i + 1;\n"
9026                "};",
9027                Style);
9028   verifyFormat("int f(a, b, c);\n" // No break here.
9029                "int\n"             // Break here.
9030                "f(a, b, c)\n"      // Break here.
9031                "short a, b;\n"
9032                "float c;\n"
9033                "{\n"
9034                "  return a + b < c;\n"
9035                "}\n"
9036                "int\n"        // Break here.
9037                "f(a, b, c)\n" // Break here.
9038                "short a, b;\n"
9039                "float c;\n"
9040                "{\n"
9041                "  return a + b < c;\n"
9042                "};",
9043                Style);
9044   verifyFormat("byte *\n" // Break here.
9045                "f(a)\n"   // Break here.
9046                "byte a[];\n"
9047                "{\n"
9048                "  return a;\n"
9049                "}",
9050                Style);
9051   verifyFormat("bool f(int a, int) override;\n"
9052                "Bar g(int a, Bar) final;\n"
9053                "Bar h(a, Bar) final;",
9054                Style);
9055   verifyFormat("int\n"
9056                "f(a)",
9057                Style);
9058   verifyFormat("bool\n"
9059                "f(size_t = 0, bool b = false)\n"
9060                "{\n"
9061                "  return !b;\n"
9062                "}",
9063                Style);
9064 
9065   // The return breaking style doesn't affect:
9066   // * function and object definitions with attribute-like macros
9067   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9068                "    ABSL_GUARDED_BY(mutex) = {};",
9069                getGoogleStyleWithColumns(40));
9070   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9071                "    ABSL_GUARDED_BY(mutex);  // comment",
9072                getGoogleStyleWithColumns(40));
9073   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9074                "    ABSL_GUARDED_BY(mutex1)\n"
9075                "        ABSL_GUARDED_BY(mutex2);",
9076                getGoogleStyleWithColumns(40));
9077   verifyFormat("Tttttt f(int a, int b)\n"
9078                "    ABSL_GUARDED_BY(mutex1)\n"
9079                "        ABSL_GUARDED_BY(mutex2);",
9080                getGoogleStyleWithColumns(40));
9081   // * typedefs
9082   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
9083 
9084   Style = getGNUStyle();
9085 
9086   // Test for comments at the end of function declarations.
9087   verifyFormat("void\n"
9088                "foo (int a, /*abc*/ int b) // def\n"
9089                "{\n"
9090                "}\n",
9091                Style);
9092 
9093   verifyFormat("void\n"
9094                "foo (int a, /* abc */ int b) /* def */\n"
9095                "{\n"
9096                "}\n",
9097                Style);
9098 
9099   // Definitions that should not break after return type
9100   verifyFormat("void foo (int a, int b); // def\n", Style);
9101   verifyFormat("void foo (int a, int b); /* def */\n", Style);
9102   verifyFormat("void foo (int a, int b);\n", Style);
9103 }
9104 
9105 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
9106   FormatStyle NoBreak = getLLVMStyle();
9107   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
9108   FormatStyle Break = getLLVMStyle();
9109   Break.AlwaysBreakBeforeMultilineStrings = true;
9110   verifyFormat("aaaa = \"bbbb\"\n"
9111                "       \"cccc\";",
9112                NoBreak);
9113   verifyFormat("aaaa =\n"
9114                "    \"bbbb\"\n"
9115                "    \"cccc\";",
9116                Break);
9117   verifyFormat("aaaa(\"bbbb\"\n"
9118                "     \"cccc\");",
9119                NoBreak);
9120   verifyFormat("aaaa(\n"
9121                "    \"bbbb\"\n"
9122                "    \"cccc\");",
9123                Break);
9124   verifyFormat("aaaa(qqq, \"bbbb\"\n"
9125                "          \"cccc\");",
9126                NoBreak);
9127   verifyFormat("aaaa(qqq,\n"
9128                "     \"bbbb\"\n"
9129                "     \"cccc\");",
9130                Break);
9131   verifyFormat("aaaa(qqq,\n"
9132                "     L\"bbbb\"\n"
9133                "     L\"cccc\");",
9134                Break);
9135   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
9136                "                      \"bbbb\"));",
9137                Break);
9138   verifyFormat("string s = someFunction(\n"
9139                "    \"abc\"\n"
9140                "    \"abc\");",
9141                Break);
9142 
9143   // As we break before unary operators, breaking right after them is bad.
9144   verifyFormat("string foo = abc ? \"x\"\n"
9145                "                   \"blah blah blah blah blah blah\"\n"
9146                "                 : \"y\";",
9147                Break);
9148 
9149   // Don't break if there is no column gain.
9150   verifyFormat("f(\"aaaa\"\n"
9151                "  \"bbbb\");",
9152                Break);
9153 
9154   // Treat literals with escaped newlines like multi-line string literals.
9155   EXPECT_EQ("x = \"a\\\n"
9156             "b\\\n"
9157             "c\";",
9158             format("x = \"a\\\n"
9159                    "b\\\n"
9160                    "c\";",
9161                    NoBreak));
9162   EXPECT_EQ("xxxx =\n"
9163             "    \"a\\\n"
9164             "b\\\n"
9165             "c\";",
9166             format("xxxx = \"a\\\n"
9167                    "b\\\n"
9168                    "c\";",
9169                    Break));
9170 
9171   EXPECT_EQ("NSString *const kString =\n"
9172             "    @\"aaaa\"\n"
9173             "    @\"bbbb\";",
9174             format("NSString *const kString = @\"aaaa\"\n"
9175                    "@\"bbbb\";",
9176                    Break));
9177 
9178   Break.ColumnLimit = 0;
9179   verifyFormat("const char *hello = \"hello llvm\";", Break);
9180 }
9181 
9182 TEST_F(FormatTest, AlignsPipes) {
9183   verifyFormat(
9184       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9185       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9186       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9187   verifyFormat(
9188       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
9189       "                     << aaaaaaaaaaaaaaaaaaaa;");
9190   verifyFormat(
9191       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9192       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9193   verifyFormat(
9194       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
9195       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9196   verifyFormat(
9197       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
9198       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
9199       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
9200   verifyFormat(
9201       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9202       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9203       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9204   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9205                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9206                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9207                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9208   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
9209                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
9210   verifyFormat(
9211       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9212       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9213   verifyFormat(
9214       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
9215       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
9216 
9217   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
9218                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
9219   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9220                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9221                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
9222                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
9223   verifyFormat("LOG_IF(aaa == //\n"
9224                "       bbb)\n"
9225                "    << a << b;");
9226 
9227   // But sometimes, breaking before the first "<<" is desirable.
9228   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9229                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
9230   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
9231                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9232                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9233   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
9234                "    << BEF << IsTemplate << Description << E->getType();");
9235   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9236                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9237                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9238   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9239                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9240                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9241                "    << aaa;");
9242 
9243   verifyFormat(
9244       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9245       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9246 
9247   // Incomplete string literal.
9248   EXPECT_EQ("llvm::errs() << \"\n"
9249             "             << a;",
9250             format("llvm::errs() << \"\n<<a;"));
9251 
9252   verifyFormat("void f() {\n"
9253                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
9254                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
9255                "}");
9256 
9257   // Handle 'endl'.
9258   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
9259                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9260   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9261 
9262   // Handle '\n'.
9263   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
9264                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9265   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
9266                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
9267   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
9268                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
9269   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9270 }
9271 
9272 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
9273   verifyFormat("return out << \"somepacket = {\\n\"\n"
9274                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
9275                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
9276                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
9277                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
9278                "           << \"}\";");
9279 
9280   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9281                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9282                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
9283   verifyFormat(
9284       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
9285       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
9286       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
9287       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
9288       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
9289   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
9290                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9291   verifyFormat(
9292       "void f() {\n"
9293       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
9294       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
9295       "}");
9296 
9297   // Breaking before the first "<<" is generally not desirable.
9298   verifyFormat(
9299       "llvm::errs()\n"
9300       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9301       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9302       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9303       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9304       getLLVMStyleWithColumns(70));
9305   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9306                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9307                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9308                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9309                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9310                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9311                getLLVMStyleWithColumns(70));
9312 
9313   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9314                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9315                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
9316   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9317                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9318                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
9319   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
9320                "           (aaaa + aaaa);",
9321                getLLVMStyleWithColumns(40));
9322   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
9323                "                  (aaaaaaa + aaaaa));",
9324                getLLVMStyleWithColumns(40));
9325   verifyFormat(
9326       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
9327       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
9328       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
9329 }
9330 
9331 TEST_F(FormatTest, UnderstandsEquals) {
9332   verifyFormat(
9333       "aaaaaaaaaaaaaaaaa =\n"
9334       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9335   verifyFormat(
9336       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9337       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9338   verifyFormat(
9339       "if (a) {\n"
9340       "  f();\n"
9341       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9342       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
9343       "}");
9344 
9345   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9346                "        100000000 + 10000000) {\n}");
9347 }
9348 
9349 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
9350   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9351                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
9352 
9353   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9354                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
9355 
9356   verifyFormat(
9357       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
9358       "                                                          Parameter2);");
9359 
9360   verifyFormat(
9361       "ShortObject->shortFunction(\n"
9362       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
9363       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
9364 
9365   verifyFormat("loooooooooooooongFunction(\n"
9366                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
9367 
9368   verifyFormat(
9369       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
9370       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
9371 
9372   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9373                "    .WillRepeatedly(Return(SomeValue));");
9374   verifyFormat("void f() {\n"
9375                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9376                "      .Times(2)\n"
9377                "      .WillRepeatedly(Return(SomeValue));\n"
9378                "}");
9379   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
9380                "    ccccccccccccccccccccccc);");
9381   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9382                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9383                "          .aaaaa(aaaaa),\n"
9384                "      aaaaaaaaaaaaaaaaaaaaa);");
9385   verifyFormat("void f() {\n"
9386                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9387                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
9388                "}");
9389   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9390                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9391                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9392                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9393                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9394   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9395                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9396                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9397                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
9398                "}");
9399 
9400   // Here, it is not necessary to wrap at "." or "->".
9401   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
9402                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9403   verifyFormat(
9404       "aaaaaaaaaaa->aaaaaaaaa(\n"
9405       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9406       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
9407 
9408   verifyFormat(
9409       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9410       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
9411   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
9412                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9413   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
9414                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9415 
9416   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9417                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9418                "    .a();");
9419 
9420   FormatStyle NoBinPacking = getLLVMStyle();
9421   NoBinPacking.BinPackParameters = false;
9422   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9423                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9424                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
9425                "                         aaaaaaaaaaaaaaaaaaa,\n"
9426                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
9427                NoBinPacking);
9428 
9429   // If there is a subsequent call, change to hanging indentation.
9430   verifyFormat(
9431       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9432       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
9433       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9434   verifyFormat(
9435       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9436       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
9437   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9438                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9439                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9440   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9441                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9442                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9443 }
9444 
9445 TEST_F(FormatTest, WrapsTemplateDeclarations) {
9446   verifyFormat("template <typename T>\n"
9447                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9448   verifyFormat("template <typename T>\n"
9449                "// T should be one of {A, B}.\n"
9450                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9451   verifyFormat(
9452       "template <typename T>\n"
9453       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
9454   verifyFormat("template <typename T>\n"
9455                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
9456                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
9457   verifyFormat(
9458       "template <typename T>\n"
9459       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
9460       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
9461   verifyFormat(
9462       "template <typename T>\n"
9463       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
9464       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
9465       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9466   verifyFormat("template <typename T>\n"
9467                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9468                "    int aaaaaaaaaaaaaaaaaaaaaa);");
9469   verifyFormat(
9470       "template <typename T1, typename T2 = char, typename T3 = char,\n"
9471       "          typename T4 = char>\n"
9472       "void f();");
9473   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
9474                "          template <typename> class cccccccccccccccccccccc,\n"
9475                "          typename ddddddddddddd>\n"
9476                "class C {};");
9477   verifyFormat(
9478       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
9479       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9480 
9481   verifyFormat("void f() {\n"
9482                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
9483                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
9484                "}");
9485 
9486   verifyFormat("template <typename T> class C {};");
9487   verifyFormat("template <typename T> void f();");
9488   verifyFormat("template <typename T> void f() {}");
9489   verifyFormat(
9490       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9491       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9492       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
9493       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9494       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9495       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
9496       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
9497       getLLVMStyleWithColumns(72));
9498   EXPECT_EQ("static_cast<A< //\n"
9499             "    B> *>(\n"
9500             "\n"
9501             ");",
9502             format("static_cast<A<//\n"
9503                    "    B>*>(\n"
9504                    "\n"
9505                    "    );"));
9506   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9507                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
9508 
9509   FormatStyle AlwaysBreak = getLLVMStyle();
9510   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9511   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
9512   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
9513   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
9514   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9515                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9516                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
9517   verifyFormat("template <template <typename> class Fooooooo,\n"
9518                "          template <typename> class Baaaaaaar>\n"
9519                "struct C {};",
9520                AlwaysBreak);
9521   verifyFormat("template <typename T> // T can be A, B or C.\n"
9522                "struct C {};",
9523                AlwaysBreak);
9524   verifyFormat("template <enum E> class A {\n"
9525                "public:\n"
9526                "  E *f();\n"
9527                "};");
9528 
9529   FormatStyle NeverBreak = getLLVMStyle();
9530   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
9531   verifyFormat("template <typename T> class C {};", NeverBreak);
9532   verifyFormat("template <typename T> void f();", NeverBreak);
9533   verifyFormat("template <typename T> void f() {}", NeverBreak);
9534   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9535                "bbbbbbbbbbbbbbbbbbbb) {}",
9536                NeverBreak);
9537   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9538                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9539                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
9540                NeverBreak);
9541   verifyFormat("template <template <typename> class Fooooooo,\n"
9542                "          template <typename> class Baaaaaaar>\n"
9543                "struct C {};",
9544                NeverBreak);
9545   verifyFormat("template <typename T> // T can be A, B or C.\n"
9546                "struct C {};",
9547                NeverBreak);
9548   verifyFormat("template <enum E> class A {\n"
9549                "public:\n"
9550                "  E *f();\n"
9551                "};",
9552                NeverBreak);
9553   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
9554   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9555                "bbbbbbbbbbbbbbbbbbbb) {}",
9556                NeverBreak);
9557 }
9558 
9559 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
9560   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9561   Style.ColumnLimit = 60;
9562   EXPECT_EQ("// Baseline - no comments.\n"
9563             "template <\n"
9564             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9565             "void f() {}",
9566             format("// Baseline - no comments.\n"
9567                    "template <\n"
9568                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9569                    "void f() {}",
9570                    Style));
9571 
9572   EXPECT_EQ("template <\n"
9573             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9574             "void f() {}",
9575             format("template <\n"
9576                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9577                    "void f() {}",
9578                    Style));
9579 
9580   EXPECT_EQ(
9581       "template <\n"
9582       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
9583       "void f() {}",
9584       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
9585              "void f() {}",
9586              Style));
9587 
9588   EXPECT_EQ(
9589       "template <\n"
9590       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9591       "                                               // multiline\n"
9592       "void f() {}",
9593       format("template <\n"
9594              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9595              "                                              // multiline\n"
9596              "void f() {}",
9597              Style));
9598 
9599   EXPECT_EQ(
9600       "template <typename aaaaaaaaaa<\n"
9601       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
9602       "void f() {}",
9603       format(
9604           "template <\n"
9605           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
9606           "void f() {}",
9607           Style));
9608 }
9609 
9610 TEST_F(FormatTest, WrapsTemplateParameters) {
9611   FormatStyle Style = getLLVMStyle();
9612   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9613   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9614   verifyFormat(
9615       "template <typename... a> struct q {};\n"
9616       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9617       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9618       "    y;",
9619       Style);
9620   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9621   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9622   verifyFormat(
9623       "template <typename... a> struct r {};\n"
9624       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9625       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9626       "    y;",
9627       Style);
9628   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9629   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9630   verifyFormat("template <typename... a> struct s {};\n"
9631                "extern s<\n"
9632                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9633                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9634                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9635                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9636                "    y;",
9637                Style);
9638   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9639   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9640   verifyFormat("template <typename... a> struct t {};\n"
9641                "extern t<\n"
9642                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9643                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9644                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9645                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9646                "    y;",
9647                Style);
9648 }
9649 
9650 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9651   verifyFormat(
9652       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9653       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9654   verifyFormat(
9655       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9656       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9657       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9658 
9659   // FIXME: Should we have the extra indent after the second break?
9660   verifyFormat(
9661       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9662       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9663       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9664 
9665   verifyFormat(
9666       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9667       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9668 
9669   // Breaking at nested name specifiers is generally not desirable.
9670   verifyFormat(
9671       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9672       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9673 
9674   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9675                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9676                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9677                "                   aaaaaaaaaaaaaaaaaaaaa);",
9678                getLLVMStyleWithColumns(74));
9679 
9680   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9681                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9682                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9683 }
9684 
9685 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9686   verifyFormat("A<int> a;");
9687   verifyFormat("A<A<A<int>>> a;");
9688   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9689   verifyFormat("bool x = a < 1 || 2 > a;");
9690   verifyFormat("bool x = 5 < f<int>();");
9691   verifyFormat("bool x = f<int>() > 5;");
9692   verifyFormat("bool x = 5 < a<int>::x;");
9693   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9694   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9695 
9696   verifyGoogleFormat("A<A<int>> a;");
9697   verifyGoogleFormat("A<A<A<int>>> a;");
9698   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9699   verifyGoogleFormat("A<A<int> > a;");
9700   verifyGoogleFormat("A<A<A<int> > > a;");
9701   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9702   verifyGoogleFormat("A<::A<int>> a;");
9703   verifyGoogleFormat("A<::A> a;");
9704   verifyGoogleFormat("A< ::A> a;");
9705   verifyGoogleFormat("A< ::A<int> > a;");
9706   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9707   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9708   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9709   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9710   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9711             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9712 
9713   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9714 
9715   // template closer followed by a token that starts with > or =
9716   verifyFormat("bool b = a<1> > 1;");
9717   verifyFormat("bool b = a<1> >= 1;");
9718   verifyFormat("int i = a<1> >> 1;");
9719   FormatStyle Style = getLLVMStyle();
9720   Style.SpaceBeforeAssignmentOperators = false;
9721   verifyFormat("bool b= a<1> == 1;", Style);
9722   verifyFormat("a<int> = 1;", Style);
9723   verifyFormat("a<int> >>= 1;", Style);
9724 
9725   verifyFormat("test < a | b >> c;");
9726   verifyFormat("test<test<a | b>> c;");
9727   verifyFormat("test >> a >> b;");
9728   verifyFormat("test << a >> b;");
9729 
9730   verifyFormat("f<int>();");
9731   verifyFormat("template <typename T> void f() {}");
9732   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9733   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9734                "sizeof(char)>::type>;");
9735   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9736   verifyFormat("f(a.operator()<A>());");
9737   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9738                "      .template operator()<A>());",
9739                getLLVMStyleWithColumns(35));
9740   verifyFormat("bool_constant<a && noexcept(f())>");
9741   verifyFormat("bool_constant<a || noexcept(f())>");
9742 
9743   // Not template parameters.
9744   verifyFormat("return a < b && c > d;");
9745   verifyFormat("void f() {\n"
9746                "  while (a < b && c > d) {\n"
9747                "  }\n"
9748                "}");
9749   verifyFormat("template <typename... Types>\n"
9750                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9751 
9752   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9753                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9754                getLLVMStyleWithColumns(60));
9755   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9756   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9757   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9758   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9759 }
9760 
9761 TEST_F(FormatTest, UnderstandsShiftOperators) {
9762   verifyFormat("if (i < x >> 1)");
9763   verifyFormat("while (i < x >> 1)");
9764   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9765   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9766   verifyFormat(
9767       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9768   verifyFormat("Foo.call<Bar<Function>>()");
9769   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9770   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9771                "++i, v = v >> 1)");
9772   verifyFormat("if (w<u<v<x>>, 1>::t)");
9773 }
9774 
9775 TEST_F(FormatTest, BitshiftOperatorWidth) {
9776   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9777             "                   bar */",
9778             format("int    a=1<<2;  /* foo\n"
9779                    "                   bar */"));
9780 
9781   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9782             "                     bar */",
9783             format("int  b  =256>>1 ;  /* foo\n"
9784                    "                      bar */"));
9785 }
9786 
9787 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9788   verifyFormat("COMPARE(a, ==, b);");
9789   verifyFormat("auto s = sizeof...(Ts) - 1;");
9790 }
9791 
9792 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9793   verifyFormat("int A::*x;");
9794   verifyFormat("int (S::*func)(void *);");
9795   verifyFormat("void f() { int (S::*func)(void *); }");
9796   verifyFormat("typedef bool *(Class::*Member)() const;");
9797   verifyFormat("void f() {\n"
9798                "  (a->*f)();\n"
9799                "  a->*x;\n"
9800                "  (a.*f)();\n"
9801                "  ((*a).*f)();\n"
9802                "  a.*x;\n"
9803                "}");
9804   verifyFormat("void f() {\n"
9805                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9806                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9807                "}");
9808   verifyFormat(
9809       "(aaaaaaaaaa->*bbbbbbb)(\n"
9810       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9811   FormatStyle Style = getLLVMStyle();
9812   Style.PointerAlignment = FormatStyle::PAS_Left;
9813   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9814 }
9815 
9816 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9817   verifyFormat("int a = -2;");
9818   verifyFormat("f(-1, -2, -3);");
9819   verifyFormat("a[-1] = 5;");
9820   verifyFormat("int a = 5 + -2;");
9821   verifyFormat("if (i == -1) {\n}");
9822   verifyFormat("if (i != -1) {\n}");
9823   verifyFormat("if (i > -1) {\n}");
9824   verifyFormat("if (i < -1) {\n}");
9825   verifyFormat("++(a->f());");
9826   verifyFormat("--(a->f());");
9827   verifyFormat("(a->f())++;");
9828   verifyFormat("a[42]++;");
9829   verifyFormat("if (!(a->f())) {\n}");
9830   verifyFormat("if (!+i) {\n}");
9831   verifyFormat("~&a;");
9832   verifyFormat("for (x = 0; -10 < x; --x) {\n}");
9833   verifyFormat("sizeof -x");
9834   verifyFormat("sizeof +x");
9835   verifyFormat("sizeof *x");
9836   verifyFormat("sizeof &x");
9837   verifyFormat("delete +x;");
9838   verifyFormat("co_await +x;");
9839   verifyFormat("case *x:");
9840   verifyFormat("case &x:");
9841 
9842   verifyFormat("a-- > b;");
9843   verifyFormat("b ? -a : c;");
9844   verifyFormat("n * sizeof char16;");
9845   verifyFormat("n * alignof char16;", getGoogleStyle());
9846   verifyFormat("sizeof(char);");
9847   verifyFormat("alignof(char);", getGoogleStyle());
9848 
9849   verifyFormat("return -1;");
9850   verifyFormat("throw -1;");
9851   verifyFormat("switch (a) {\n"
9852                "case -1:\n"
9853                "  break;\n"
9854                "}");
9855   verifyFormat("#define X -1");
9856   verifyFormat("#define X -kConstant");
9857 
9858   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9859   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9860 
9861   verifyFormat("int a = /* confusing comment */ -1;");
9862   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9863   verifyFormat("int a = i /* confusing comment */++;");
9864 
9865   verifyFormat("co_yield -1;");
9866   verifyFormat("co_return -1;");
9867 
9868   // Check that * is not treated as a binary operator when we set
9869   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9870   FormatStyle PASLeftStyle = getLLVMStyle();
9871   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9872   verifyFormat("co_return *a;", PASLeftStyle);
9873   verifyFormat("co_await *a;", PASLeftStyle);
9874   verifyFormat("co_yield *a", PASLeftStyle);
9875   verifyFormat("return *a;", PASLeftStyle);
9876 }
9877 
9878 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9879   verifyFormat("if (!aaaaaaaaaa( // break\n"
9880                "        aaaaa)) {\n"
9881                "}");
9882   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9883                "    aaaaa));");
9884   verifyFormat("*aaa = aaaaaaa( // break\n"
9885                "    bbbbbb);");
9886 }
9887 
9888 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9889   verifyFormat("bool operator<();");
9890   verifyFormat("bool operator>();");
9891   verifyFormat("bool operator=();");
9892   verifyFormat("bool operator==();");
9893   verifyFormat("bool operator!=();");
9894   verifyFormat("int operator+();");
9895   verifyFormat("int operator++();");
9896   verifyFormat("int operator++(int) volatile noexcept;");
9897   verifyFormat("bool operator,();");
9898   verifyFormat("bool operator();");
9899   verifyFormat("bool operator()();");
9900   verifyFormat("bool operator[]();");
9901   verifyFormat("operator bool();");
9902   verifyFormat("operator int();");
9903   verifyFormat("operator void *();");
9904   verifyFormat("operator SomeType<int>();");
9905   verifyFormat("operator SomeType<int, int>();");
9906   verifyFormat("operator SomeType<SomeType<int>>();");
9907   verifyFormat("operator< <>();");
9908   verifyFormat("operator<< <>();");
9909   verifyFormat("< <>");
9910 
9911   verifyFormat("void *operator new(std::size_t size);");
9912   verifyFormat("void *operator new[](std::size_t size);");
9913   verifyFormat("void operator delete(void *ptr);");
9914   verifyFormat("void operator delete[](void *ptr);");
9915   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9916                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9917   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9918                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9919 
9920   verifyFormat(
9921       "ostream &operator<<(ostream &OutputStream,\n"
9922       "                    SomeReallyLongType WithSomeReallyLongValue);");
9923   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9924                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9925                "  return left.group < right.group;\n"
9926                "}");
9927   verifyFormat("SomeType &operator=(const SomeType &S);");
9928   verifyFormat("f.template operator()<int>();");
9929 
9930   verifyGoogleFormat("operator void*();");
9931   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9932   verifyGoogleFormat("operator ::A();");
9933 
9934   verifyFormat("using A::operator+;");
9935   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9936                "int i;");
9937 
9938   // Calling an operator as a member function.
9939   verifyFormat("void f() { a.operator*(); }");
9940   verifyFormat("void f() { a.operator*(b & b); }");
9941   verifyFormat("void f() { a->operator&(a * b); }");
9942   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9943   // TODO: Calling an operator as a non-member function is hard to distinguish.
9944   // https://llvm.org/PR50629
9945   // verifyFormat("void f() { operator*(a & a); }");
9946   // verifyFormat("void f() { operator&(a, b * b); }");
9947 
9948   verifyFormat("::operator delete(foo);");
9949   verifyFormat("::operator new(n * sizeof(foo));");
9950   verifyFormat("foo() { ::operator delete(foo); }");
9951   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9952 }
9953 
9954 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9955   verifyFormat("void A::b() && {}");
9956   verifyFormat("void A::b() &&noexcept {}");
9957   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9958   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9959   verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
9960   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9961   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9962   verifyFormat("Deleted &operator=(const Deleted &) &;");
9963   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9964   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9965   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9966   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9967   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9968   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9969   verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
9970   verifyFormat("void Fn(T const &) const &;");
9971   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9972   verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
9973   verifyFormat("template <typename T>\n"
9974                "void F(T) && = delete;",
9975                getGoogleStyle());
9976   verifyFormat("template <typename T> void operator=(T) &;");
9977   verifyFormat("template <typename T> void operator=(T) const &;");
9978   verifyFormat("template <typename T> void operator=(T) &noexcept;");
9979   verifyFormat("template <typename T> void operator=(T) & = default;");
9980   verifyFormat("template <typename T> void operator=(T) &&;");
9981   verifyFormat("template <typename T> void operator=(T) && = delete;");
9982   verifyFormat("template <typename T> void operator=(T) & {}");
9983   verifyFormat("template <typename T> void operator=(T) && {}");
9984 
9985   FormatStyle AlignLeft = getLLVMStyle();
9986   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9987   verifyFormat("void A::b() && {}", AlignLeft);
9988   verifyFormat("void A::b() && noexcept {}", AlignLeft);
9989   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9990   verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
9991                AlignLeft);
9992   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9993                AlignLeft);
9994   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9995   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9996   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9997   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9998   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9999   verifyFormat("auto Function(T) & -> void;", AlignLeft);
10000   verifyFormat("void Fn(T const&) const&;", AlignLeft);
10001   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
10002   verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
10003                AlignLeft);
10004   verifyFormat("template <typename T> void operator=(T) &;", AlignLeft);
10005   verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft);
10006   verifyFormat("template <typename T> void operator=(T) & noexcept;",
10007                AlignLeft);
10008   verifyFormat("template <typename T> void operator=(T) & = default;",
10009                AlignLeft);
10010   verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft);
10011   verifyFormat("template <typename T> void operator=(T) && = delete;",
10012                AlignLeft);
10013   verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft);
10014   verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft);
10015 
10016   FormatStyle AlignMiddle = getLLVMStyle();
10017   AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10018   verifyFormat("void A::b() && {}", AlignMiddle);
10019   verifyFormat("void A::b() && noexcept {}", AlignMiddle);
10020   verifyFormat("Deleted & operator=(const Deleted &) & = default;",
10021                AlignMiddle);
10022   verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
10023                AlignMiddle);
10024   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
10025                AlignMiddle);
10026   verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
10027   verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
10028   verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
10029   verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
10030   verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
10031   verifyFormat("auto Function(T) & -> void;", AlignMiddle);
10032   verifyFormat("void Fn(T const &) const &;", AlignMiddle);
10033   verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
10034   verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
10035                AlignMiddle);
10036   verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle);
10037   verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle);
10038   verifyFormat("template <typename T> void operator=(T) & noexcept;",
10039                AlignMiddle);
10040   verifyFormat("template <typename T> void operator=(T) & = default;",
10041                AlignMiddle);
10042   verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle);
10043   verifyFormat("template <typename T> void operator=(T) && = delete;",
10044                AlignMiddle);
10045   verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle);
10046   verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle);
10047 
10048   FormatStyle Spaces = getLLVMStyle();
10049   Spaces.SpacesInCStyleCastParentheses = true;
10050   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
10051   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
10052   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
10053   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
10054 
10055   Spaces.SpacesInCStyleCastParentheses = false;
10056   Spaces.SpacesInParentheses = true;
10057   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
10058   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
10059                Spaces);
10060   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
10061   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
10062 
10063   FormatStyle BreakTemplate = getLLVMStyle();
10064   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
10065 
10066   verifyFormat("struct f {\n"
10067                "  template <class T>\n"
10068                "  int &foo(const std::string &str) &noexcept {}\n"
10069                "};",
10070                BreakTemplate);
10071 
10072   verifyFormat("struct f {\n"
10073                "  template <class T>\n"
10074                "  int &foo(const std::string &str) &&noexcept {}\n"
10075                "};",
10076                BreakTemplate);
10077 
10078   verifyFormat("struct f {\n"
10079                "  template <class T>\n"
10080                "  int &foo(const std::string &str) const &noexcept {}\n"
10081                "};",
10082                BreakTemplate);
10083 
10084   verifyFormat("struct f {\n"
10085                "  template <class T>\n"
10086                "  int &foo(const std::string &str) const &noexcept {}\n"
10087                "};",
10088                BreakTemplate);
10089 
10090   verifyFormat("struct f {\n"
10091                "  template <class T>\n"
10092                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
10093                "};",
10094                BreakTemplate);
10095 
10096   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
10097   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
10098       FormatStyle::BTDS_Yes;
10099   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
10100 
10101   verifyFormat("struct f {\n"
10102                "  template <class T>\n"
10103                "  int& foo(const std::string& str) & noexcept {}\n"
10104                "};",
10105                AlignLeftBreakTemplate);
10106 
10107   verifyFormat("struct f {\n"
10108                "  template <class T>\n"
10109                "  int& foo(const std::string& str) && noexcept {}\n"
10110                "};",
10111                AlignLeftBreakTemplate);
10112 
10113   verifyFormat("struct f {\n"
10114                "  template <class T>\n"
10115                "  int& foo(const std::string& str) const& noexcept {}\n"
10116                "};",
10117                AlignLeftBreakTemplate);
10118 
10119   verifyFormat("struct f {\n"
10120                "  template <class T>\n"
10121                "  int& foo(const std::string& str) const&& noexcept {}\n"
10122                "};",
10123                AlignLeftBreakTemplate);
10124 
10125   verifyFormat("struct f {\n"
10126                "  template <class T>\n"
10127                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
10128                "};",
10129                AlignLeftBreakTemplate);
10130 
10131   // The `&` in `Type&` should not be confused with a trailing `&` of
10132   // DEPRECATED(reason) member function.
10133   verifyFormat("struct f {\n"
10134                "  template <class T>\n"
10135                "  DEPRECATED(reason)\n"
10136                "  Type &foo(arguments) {}\n"
10137                "};",
10138                BreakTemplate);
10139 
10140   verifyFormat("struct f {\n"
10141                "  template <class T>\n"
10142                "  DEPRECATED(reason)\n"
10143                "  Type& foo(arguments) {}\n"
10144                "};",
10145                AlignLeftBreakTemplate);
10146 
10147   verifyFormat("void (*foopt)(int) = &func;");
10148 
10149   FormatStyle DerivePointerAlignment = getLLVMStyle();
10150   DerivePointerAlignment.DerivePointerAlignment = true;
10151   // There's always a space between the function and its trailing qualifiers.
10152   // This isn't evidence for PAS_Right (or for PAS_Left).
10153   std::string Prefix = "void a() &;\n"
10154                        "void b() &;\n";
10155   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10156   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10157   // Same if the function is an overloaded operator, and with &&.
10158   Prefix = "void operator()() &&;\n"
10159            "void operator()() &&;\n";
10160   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10161   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10162   // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
10163   Prefix = "void a() const &;\n"
10164            "void b() const &;\n";
10165   EXPECT_EQ(Prefix + "int *x;",
10166             format(Prefix + "int* x;", DerivePointerAlignment));
10167 }
10168 
10169 TEST_F(FormatTest, UnderstandsNewAndDelete) {
10170   verifyFormat("void f() {\n"
10171                "  A *a = new A;\n"
10172                "  A *a = new (placement) A;\n"
10173                "  delete a;\n"
10174                "  delete (A *)a;\n"
10175                "}");
10176   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10177                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10178   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10179                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10180                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10181   verifyFormat("delete[] h->p;");
10182   verifyFormat("delete[] (void *)p;");
10183 
10184   verifyFormat("void operator delete(void *foo) ATTRIB;");
10185   verifyFormat("void operator new(void *foo) ATTRIB;");
10186   verifyFormat("void operator delete[](void *foo) ATTRIB;");
10187   verifyFormat("void operator delete(void *ptr) noexcept;");
10188 
10189   EXPECT_EQ("void new(link p);\n"
10190             "void delete(link p);\n",
10191             format("void new (link p);\n"
10192                    "void delete (link p);\n"));
10193 }
10194 
10195 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
10196   verifyFormat("int *f(int *a) {}");
10197   verifyFormat("int main(int argc, char **argv) {}");
10198   verifyFormat("Test::Test(int b) : a(b * b) {}");
10199   verifyIndependentOfContext("f(a, *a);");
10200   verifyFormat("void g() { f(*a); }");
10201   verifyIndependentOfContext("int a = b * 10;");
10202   verifyIndependentOfContext("int a = 10 * b;");
10203   verifyIndependentOfContext("int a = b * c;");
10204   verifyIndependentOfContext("int a += b * c;");
10205   verifyIndependentOfContext("int a -= b * c;");
10206   verifyIndependentOfContext("int a *= b * c;");
10207   verifyIndependentOfContext("int a /= b * c;");
10208   verifyIndependentOfContext("int a = *b;");
10209   verifyIndependentOfContext("int a = *b * c;");
10210   verifyIndependentOfContext("int a = b * *c;");
10211   verifyIndependentOfContext("int a = b * (10);");
10212   verifyIndependentOfContext("S << b * (10);");
10213   verifyIndependentOfContext("return 10 * b;");
10214   verifyIndependentOfContext("return *b * *c;");
10215   verifyIndependentOfContext("return a & ~b;");
10216   verifyIndependentOfContext("f(b ? *c : *d);");
10217   verifyIndependentOfContext("int a = b ? *c : *d;");
10218   verifyIndependentOfContext("*b = a;");
10219   verifyIndependentOfContext("a * ~b;");
10220   verifyIndependentOfContext("a * !b;");
10221   verifyIndependentOfContext("a * +b;");
10222   verifyIndependentOfContext("a * -b;");
10223   verifyIndependentOfContext("a * ++b;");
10224   verifyIndependentOfContext("a * --b;");
10225   verifyIndependentOfContext("a[4] * b;");
10226   verifyIndependentOfContext("a[a * a] = 1;");
10227   verifyIndependentOfContext("f() * b;");
10228   verifyIndependentOfContext("a * [self dostuff];");
10229   verifyIndependentOfContext("int x = a * (a + b);");
10230   verifyIndependentOfContext("(a *)(a + b);");
10231   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
10232   verifyIndependentOfContext("int *pa = (int *)&a;");
10233   verifyIndependentOfContext("return sizeof(int **);");
10234   verifyIndependentOfContext("return sizeof(int ******);");
10235   verifyIndependentOfContext("return (int **&)a;");
10236   verifyIndependentOfContext("f((*PointerToArray)[10]);");
10237   verifyFormat("void f(Type (*parameter)[10]) {}");
10238   verifyFormat("void f(Type (&parameter)[10]) {}");
10239   verifyGoogleFormat("return sizeof(int**);");
10240   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
10241   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
10242   verifyFormat("auto a = [](int **&, int ***) {};");
10243   verifyFormat("auto PointerBinding = [](const char *S) {};");
10244   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
10245   verifyFormat("[](const decltype(*a) &value) {}");
10246   verifyFormat("[](const typeof(*a) &value) {}");
10247   verifyFormat("[](const _Atomic(a *) &value) {}");
10248   verifyFormat("[](const __underlying_type(a) &value) {}");
10249   verifyFormat("decltype(a * b) F();");
10250   verifyFormat("typeof(a * b) F();");
10251   verifyFormat("#define MACRO() [](A *a) { return 1; }");
10252   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
10253   verifyIndependentOfContext("typedef void (*f)(int *a);");
10254   verifyIndependentOfContext("int i{a * b};");
10255   verifyIndependentOfContext("aaa && aaa->f();");
10256   verifyIndependentOfContext("int x = ~*p;");
10257   verifyFormat("Constructor() : a(a), area(width * height) {}");
10258   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
10259   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
10260   verifyFormat("void f() { f(a, c * d); }");
10261   verifyFormat("void f() { f(new a(), c * d); }");
10262   verifyFormat("void f(const MyOverride &override);");
10263   verifyFormat("void f(const MyFinal &final);");
10264   verifyIndependentOfContext("bool a = f() && override.f();");
10265   verifyIndependentOfContext("bool a = f() && final.f();");
10266 
10267   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
10268 
10269   verifyIndependentOfContext("A<int *> a;");
10270   verifyIndependentOfContext("A<int **> a;");
10271   verifyIndependentOfContext("A<int *, int *> a;");
10272   verifyIndependentOfContext("A<int *[]> a;");
10273   verifyIndependentOfContext(
10274       "const char *const p = reinterpret_cast<const char *const>(q);");
10275   verifyIndependentOfContext("A<int **, int **> a;");
10276   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
10277   verifyFormat("for (char **a = b; *a; ++a) {\n}");
10278   verifyFormat("for (; a && b;) {\n}");
10279   verifyFormat("bool foo = true && [] { return false; }();");
10280 
10281   verifyFormat(
10282       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10283       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10284 
10285   verifyGoogleFormat("int const* a = &b;");
10286   verifyGoogleFormat("**outparam = 1;");
10287   verifyGoogleFormat("*outparam = a * b;");
10288   verifyGoogleFormat("int main(int argc, char** argv) {}");
10289   verifyGoogleFormat("A<int*> a;");
10290   verifyGoogleFormat("A<int**> a;");
10291   verifyGoogleFormat("A<int*, int*> a;");
10292   verifyGoogleFormat("A<int**, int**> a;");
10293   verifyGoogleFormat("f(b ? *c : *d);");
10294   verifyGoogleFormat("int a = b ? *c : *d;");
10295   verifyGoogleFormat("Type* t = **x;");
10296   verifyGoogleFormat("Type* t = *++*x;");
10297   verifyGoogleFormat("*++*x;");
10298   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
10299   verifyGoogleFormat("Type* t = x++ * y;");
10300   verifyGoogleFormat(
10301       "const char* const p = reinterpret_cast<const char* const>(q);");
10302   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
10303   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
10304   verifyGoogleFormat("template <typename T>\n"
10305                      "void f(int i = 0, SomeType** temps = NULL);");
10306 
10307   FormatStyle Left = getLLVMStyle();
10308   Left.PointerAlignment = FormatStyle::PAS_Left;
10309   verifyFormat("x = *a(x) = *a(y);", Left);
10310   verifyFormat("for (;; *a = b) {\n}", Left);
10311   verifyFormat("return *this += 1;", Left);
10312   verifyFormat("throw *x;", Left);
10313   verifyFormat("delete *x;", Left);
10314   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
10315   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
10316   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
10317   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
10318   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
10319   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
10320   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
10321   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
10322   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
10323 
10324   verifyIndependentOfContext("a = *(x + y);");
10325   verifyIndependentOfContext("a = &(x + y);");
10326   verifyIndependentOfContext("*(x + y).call();");
10327   verifyIndependentOfContext("&(x + y)->call();");
10328   verifyFormat("void f() { &(*I).first; }");
10329 
10330   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
10331   verifyFormat("f(* /* confusing comment */ foo);");
10332   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
10333   verifyFormat("void foo(int * // this is the first paramters\n"
10334                "         ,\n"
10335                "         int second);");
10336   verifyFormat("double term = a * // first\n"
10337                "              b;");
10338   verifyFormat(
10339       "int *MyValues = {\n"
10340       "    *A, // Operator detection might be confused by the '{'\n"
10341       "    *BB // Operator detection might be confused by previous comment\n"
10342       "};");
10343 
10344   verifyIndependentOfContext("if (int *a = &b)");
10345   verifyIndependentOfContext("if (int &a = *b)");
10346   verifyIndependentOfContext("if (a & b[i])");
10347   verifyIndependentOfContext("if constexpr (a & b[i])");
10348   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
10349   verifyIndependentOfContext("if (a * (b * c))");
10350   verifyIndependentOfContext("if constexpr (a * (b * c))");
10351   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
10352   verifyIndependentOfContext("if (a::b::c::d & b[i])");
10353   verifyIndependentOfContext("if (*b[i])");
10354   verifyIndependentOfContext("if (int *a = (&b))");
10355   verifyIndependentOfContext("while (int *a = &b)");
10356   verifyIndependentOfContext("while (a * (b * c))");
10357   verifyIndependentOfContext("size = sizeof *a;");
10358   verifyIndependentOfContext("if (a && (b = c))");
10359   verifyFormat("void f() {\n"
10360                "  for (const int &v : Values) {\n"
10361                "  }\n"
10362                "}");
10363   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
10364   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
10365   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
10366 
10367   verifyFormat("#define A (!a * b)");
10368   verifyFormat("#define MACRO     \\\n"
10369                "  int *i = a * b; \\\n"
10370                "  void f(a *b);",
10371                getLLVMStyleWithColumns(19));
10372 
10373   verifyIndependentOfContext("A = new SomeType *[Length];");
10374   verifyIndependentOfContext("A = new SomeType *[Length]();");
10375   verifyIndependentOfContext("T **t = new T *;");
10376   verifyIndependentOfContext("T **t = new T *();");
10377   verifyGoogleFormat("A = new SomeType*[Length]();");
10378   verifyGoogleFormat("A = new SomeType*[Length];");
10379   verifyGoogleFormat("T** t = new T*;");
10380   verifyGoogleFormat("T** t = new T*();");
10381 
10382   verifyFormat("STATIC_ASSERT((a & b) == 0);");
10383   verifyFormat("STATIC_ASSERT(0 == (a & b));");
10384   verifyFormat("template <bool a, bool b> "
10385                "typename t::if<x && y>::type f() {}");
10386   verifyFormat("template <int *y> f() {}");
10387   verifyFormat("vector<int *> v;");
10388   verifyFormat("vector<int *const> v;");
10389   verifyFormat("vector<int *const **const *> v;");
10390   verifyFormat("vector<int *volatile> v;");
10391   verifyFormat("vector<a *_Nonnull> v;");
10392   verifyFormat("vector<a *_Nullable> v;");
10393   verifyFormat("vector<a *_Null_unspecified> v;");
10394   verifyFormat("vector<a *__ptr32> v;");
10395   verifyFormat("vector<a *__ptr64> v;");
10396   verifyFormat("vector<a *__capability> v;");
10397   FormatStyle TypeMacros = getLLVMStyle();
10398   TypeMacros.TypenameMacros = {"LIST"};
10399   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
10400   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
10401   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
10402   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
10403   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
10404 
10405   FormatStyle CustomQualifier = getLLVMStyle();
10406   // Add identifiers that should not be parsed as a qualifier by default.
10407   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10408   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
10409   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
10410   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
10411   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
10412   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
10413   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
10414   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
10415   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
10416   verifyFormat("vector<a * _NotAQualifier> v;");
10417   verifyFormat("vector<a * __not_a_qualifier> v;");
10418   verifyFormat("vector<a * b> v;");
10419   verifyFormat("foo<b && false>();");
10420   verifyFormat("foo<b & 1>();");
10421   verifyFormat("foo<b & (1)>();");
10422   verifyFormat("foo<b & (~0)>();");
10423   verifyFormat("foo<b & (true)>();");
10424   verifyFormat("foo<b & ((1))>();");
10425   verifyFormat("foo<b & (/*comment*/ 1)>();");
10426   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
10427   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
10428   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
10429   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
10430   verifyFormat(
10431       "template <class T, class = typename std::enable_if<\n"
10432       "                       std::is_integral<T>::value &&\n"
10433       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
10434       "void F();",
10435       getLLVMStyleWithColumns(70));
10436   verifyFormat("template <class T,\n"
10437                "          class = typename std::enable_if<\n"
10438                "              std::is_integral<T>::value &&\n"
10439                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
10440                "          class U>\n"
10441                "void F();",
10442                getLLVMStyleWithColumns(70));
10443   verifyFormat(
10444       "template <class T,\n"
10445       "          class = typename ::std::enable_if<\n"
10446       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
10447       "void F();",
10448       getGoogleStyleWithColumns(68));
10449 
10450   FormatStyle Style = getLLVMStyle();
10451   Style.PointerAlignment = FormatStyle::PAS_Left;
10452   verifyFormat("struct {\n"
10453                "}* ptr;",
10454                Style);
10455   verifyFormat("union {\n"
10456                "}* ptr;",
10457                Style);
10458   verifyFormat("class {\n"
10459                "}* ptr;",
10460                Style);
10461   // Don't confuse a multiplication after a brace-initialized expression with
10462   // a class pointer.
10463   verifyFormat("int i = int{42} * 34;", Style);
10464   verifyFormat("struct {\n"
10465                "}&& ptr = {};",
10466                Style);
10467   verifyFormat("union {\n"
10468                "}&& ptr = {};",
10469                Style);
10470   verifyFormat("class {\n"
10471                "}&& ptr = {};",
10472                Style);
10473 
10474   Style.PointerAlignment = FormatStyle::PAS_Middle;
10475   verifyFormat("struct {\n"
10476                "} * ptr;",
10477                Style);
10478   verifyFormat("union {\n"
10479                "} * ptr;",
10480                Style);
10481   verifyFormat("class {\n"
10482                "} * ptr;",
10483                Style);
10484   verifyFormat("struct {\n"
10485                "} && ptr = {};",
10486                Style);
10487   verifyFormat("union {\n"
10488                "} && ptr = {};",
10489                Style);
10490   verifyFormat("class {\n"
10491                "} && ptr = {};",
10492                Style);
10493 
10494   Style.PointerAlignment = FormatStyle::PAS_Right;
10495   verifyFormat("struct {\n"
10496                "} *ptr;",
10497                Style);
10498   verifyFormat("union {\n"
10499                "} *ptr;",
10500                Style);
10501   verifyFormat("class {\n"
10502                "} *ptr;",
10503                Style);
10504   verifyFormat("struct {\n"
10505                "} &&ptr = {};",
10506                Style);
10507   verifyFormat("union {\n"
10508                "} &&ptr = {};",
10509                Style);
10510   verifyFormat("class {\n"
10511                "} &&ptr = {};",
10512                Style);
10513 
10514   verifyIndependentOfContext("MACRO(int *i);");
10515   verifyIndependentOfContext("MACRO(auto *a);");
10516   verifyIndependentOfContext("MACRO(const A *a);");
10517   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
10518   verifyIndependentOfContext("MACRO(decltype(A) *a);");
10519   verifyIndependentOfContext("MACRO(typeof(A) *a);");
10520   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
10521   verifyIndependentOfContext("MACRO(A *const a);");
10522   verifyIndependentOfContext("MACRO(A *restrict a);");
10523   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
10524   verifyIndependentOfContext("MACRO(A *__restrict a);");
10525   verifyIndependentOfContext("MACRO(A *volatile a);");
10526   verifyIndependentOfContext("MACRO(A *__volatile a);");
10527   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
10528   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
10529   verifyIndependentOfContext("MACRO(A *_Nullable a);");
10530   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
10531   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
10532   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
10533   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
10534   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
10535   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
10536   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
10537   verifyIndependentOfContext("MACRO(A *__capability);");
10538   verifyIndependentOfContext("MACRO(A &__capability);");
10539   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
10540   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
10541   // If we add __my_qualifier to AttributeMacros it should always be parsed as
10542   // a type declaration:
10543   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
10544   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
10545   // Also check that TypenameMacros prevents parsing it as multiplication:
10546   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
10547   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
10548 
10549   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
10550   verifyFormat("void f() { f(float{1}, a * a); }");
10551   verifyFormat("void f() { f(float(1), a * a); }");
10552 
10553   verifyFormat("f((void (*)(int))g);");
10554   verifyFormat("f((void (&)(int))g);");
10555   verifyFormat("f((void (^)(int))g);");
10556 
10557   // FIXME: Is there a way to make this work?
10558   // verifyIndependentOfContext("MACRO(A *a);");
10559   verifyFormat("MACRO(A &B);");
10560   verifyFormat("MACRO(A *B);");
10561   verifyFormat("void f() { MACRO(A * B); }");
10562   verifyFormat("void f() { MACRO(A & B); }");
10563 
10564   // This lambda was mis-formatted after D88956 (treating it as a binop):
10565   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
10566   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
10567   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
10568   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
10569 
10570   verifyFormat("DatumHandle const *operator->() const { return input_; }");
10571   verifyFormat("return options != nullptr && operator==(*options);");
10572 
10573   EXPECT_EQ("#define OP(x)                                    \\\n"
10574             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
10575             "    return s << a.DebugString();                 \\\n"
10576             "  }",
10577             format("#define OP(x) \\\n"
10578                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
10579                    "    return s << a.DebugString(); \\\n"
10580                    "  }",
10581                    getLLVMStyleWithColumns(50)));
10582 
10583   // FIXME: We cannot handle this case yet; we might be able to figure out that
10584   // foo<x> d > v; doesn't make sense.
10585   verifyFormat("foo<a<b && c> d> v;");
10586 
10587   FormatStyle PointerMiddle = getLLVMStyle();
10588   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10589   verifyFormat("delete *x;", PointerMiddle);
10590   verifyFormat("int * x;", PointerMiddle);
10591   verifyFormat("int *[] x;", PointerMiddle);
10592   verifyFormat("template <int * y> f() {}", PointerMiddle);
10593   verifyFormat("int * f(int * a) {}", PointerMiddle);
10594   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
10595   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10596   verifyFormat("A<int *> a;", PointerMiddle);
10597   verifyFormat("A<int **> a;", PointerMiddle);
10598   verifyFormat("A<int *, int *> a;", PointerMiddle);
10599   verifyFormat("A<int *[]> a;", PointerMiddle);
10600   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10601   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10602   verifyFormat("T ** t = new T *;", PointerMiddle);
10603 
10604   // Member function reference qualifiers aren't binary operators.
10605   verifyFormat("string // break\n"
10606                "operator()() & {}");
10607   verifyFormat("string // break\n"
10608                "operator()() && {}");
10609   verifyGoogleFormat("template <typename T>\n"
10610                      "auto x() & -> int {}");
10611 
10612   // Should be binary operators when used as an argument expression (overloaded
10613   // operator invoked as a member function).
10614   verifyFormat("void f() { a.operator()(a * a); }");
10615   verifyFormat("void f() { a->operator()(a & a); }");
10616   verifyFormat("void f() { a.operator()(*a & *a); }");
10617   verifyFormat("void f() { a->operator()(*a * *a); }");
10618 
10619   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10620   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10621 }
10622 
10623 TEST_F(FormatTest, UnderstandsAttributes) {
10624   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10625   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10626                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10627   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10628   FormatStyle AfterType = getLLVMStyle();
10629   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10630   verifyFormat("__attribute__((nodebug)) void\n"
10631                "foo() {}\n",
10632                AfterType);
10633   verifyFormat("__unused void\n"
10634                "foo() {}",
10635                AfterType);
10636 
10637   FormatStyle CustomAttrs = getLLVMStyle();
10638   CustomAttrs.AttributeMacros.push_back("__unused");
10639   CustomAttrs.AttributeMacros.push_back("__attr1");
10640   CustomAttrs.AttributeMacros.push_back("__attr2");
10641   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10642   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10643   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10644   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10645   // Check that it is parsed as a multiplication without AttributeMacros and
10646   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10647   verifyFormat("vector<SomeType * __attr1> v;");
10648   verifyFormat("vector<SomeType __attr1 *> v;");
10649   verifyFormat("vector<SomeType __attr1 *const> v;");
10650   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10651   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10652   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10653   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10654   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10655   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10656   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10657   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10658 
10659   // Check that these are not parsed as function declarations:
10660   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10661   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10662   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10663   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10664   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10665   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10666   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10667   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10668   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10669   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10670 }
10671 
10672 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10673   // Check that qualifiers on pointers don't break parsing of casts.
10674   verifyFormat("x = (foo *const)*v;");
10675   verifyFormat("x = (foo *volatile)*v;");
10676   verifyFormat("x = (foo *restrict)*v;");
10677   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10678   verifyFormat("x = (foo *_Nonnull)*v;");
10679   verifyFormat("x = (foo *_Nullable)*v;");
10680   verifyFormat("x = (foo *_Null_unspecified)*v;");
10681   verifyFormat("x = (foo *_Nonnull)*v;");
10682   verifyFormat("x = (foo *[[clang::attr]])*v;");
10683   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10684   verifyFormat("x = (foo *__ptr32)*v;");
10685   verifyFormat("x = (foo *__ptr64)*v;");
10686   verifyFormat("x = (foo *__capability)*v;");
10687 
10688   // Check that we handle multiple trailing qualifiers and skip them all to
10689   // determine that the expression is a cast to a pointer type.
10690   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10691   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10692   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10693   StringRef AllQualifiers =
10694       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10695       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10696   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10697   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10698 
10699   // Also check that address-of is not parsed as a binary bitwise-and:
10700   verifyFormat("x = (foo *const)&v;");
10701   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10702   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10703 
10704   // Check custom qualifiers:
10705   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10706   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10707   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10708   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10709   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10710                CustomQualifier);
10711   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10712                CustomQualifier);
10713 
10714   // Check that unknown identifiers result in binary operator parsing:
10715   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10716   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10717 }
10718 
10719 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10720   verifyFormat("SomeType s [[unused]] (InitValue);");
10721   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10722   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10723   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10724   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10725   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10726                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10727   verifyFormat("[[nodiscard]] bool f() { return false; }");
10728   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10729   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10730   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10731   verifyFormat("[[nodiscard]] ::qualified_type f();");
10732 
10733   // Make sure we do not mistake attributes for array subscripts.
10734   verifyFormat("int a() {}\n"
10735                "[[unused]] int b() {}\n");
10736   verifyFormat("NSArray *arr;\n"
10737                "arr[[Foo() bar]];");
10738 
10739   // On the other hand, we still need to correctly find array subscripts.
10740   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10741 
10742   // Make sure that we do not mistake Objective-C method inside array literals
10743   // as attributes, even if those method names are also keywords.
10744   verifyFormat("@[ [foo bar] ];");
10745   verifyFormat("@[ [NSArray class] ];");
10746   verifyFormat("@[ [foo enum] ];");
10747 
10748   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10749 
10750   // Make sure we do not parse attributes as lambda introducers.
10751   FormatStyle MultiLineFunctions = getLLVMStyle();
10752   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10753   verifyFormat("[[unused]] int b() {\n"
10754                "  return 42;\n"
10755                "}\n",
10756                MultiLineFunctions);
10757 }
10758 
10759 TEST_F(FormatTest, AttributeClass) {
10760   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10761   verifyFormat("class S {\n"
10762                "  S(S&&) = default;\n"
10763                "};",
10764                Style);
10765   verifyFormat("class [[nodiscard]] S {\n"
10766                "  S(S&&) = default;\n"
10767                "};",
10768                Style);
10769   verifyFormat("class __attribute((maybeunused)) S {\n"
10770                "  S(S&&) = default;\n"
10771                "};",
10772                Style);
10773   verifyFormat("struct S {\n"
10774                "  S(S&&) = default;\n"
10775                "};",
10776                Style);
10777   verifyFormat("struct [[nodiscard]] S {\n"
10778                "  S(S&&) = default;\n"
10779                "};",
10780                Style);
10781 }
10782 
10783 TEST_F(FormatTest, AttributesAfterMacro) {
10784   FormatStyle Style = getLLVMStyle();
10785   verifyFormat("MACRO;\n"
10786                "__attribute__((maybe_unused)) int foo() {\n"
10787                "  //...\n"
10788                "}");
10789 
10790   verifyFormat("MACRO;\n"
10791                "[[nodiscard]] int foo() {\n"
10792                "  //...\n"
10793                "}");
10794 
10795   EXPECT_EQ("MACRO\n\n"
10796             "__attribute__((maybe_unused)) int foo() {\n"
10797             "  //...\n"
10798             "}",
10799             format("MACRO\n\n"
10800                    "__attribute__((maybe_unused)) int foo() {\n"
10801                    "  //...\n"
10802                    "}"));
10803 
10804   EXPECT_EQ("MACRO\n\n"
10805             "[[nodiscard]] int foo() {\n"
10806             "  //...\n"
10807             "}",
10808             format("MACRO\n\n"
10809                    "[[nodiscard]] int foo() {\n"
10810                    "  //...\n"
10811                    "}"));
10812 }
10813 
10814 TEST_F(FormatTest, AttributePenaltyBreaking) {
10815   FormatStyle Style = getLLVMStyle();
10816   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10817                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10818                Style);
10819   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10820                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10821                Style);
10822   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10823                "shared_ptr<ALongTypeName> &C d) {\n}",
10824                Style);
10825 }
10826 
10827 TEST_F(FormatTest, UnderstandsEllipsis) {
10828   FormatStyle Style = getLLVMStyle();
10829   verifyFormat("int printf(const char *fmt, ...);");
10830   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10831   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10832 
10833   verifyFormat("template <int *...PP> a;", Style);
10834 
10835   Style.PointerAlignment = FormatStyle::PAS_Left;
10836   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10837 
10838   verifyFormat("template <int*... PP> a;", Style);
10839 
10840   Style.PointerAlignment = FormatStyle::PAS_Middle;
10841   verifyFormat("template <int *... PP> a;", Style);
10842 }
10843 
10844 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10845   EXPECT_EQ("int *a;\n"
10846             "int *a;\n"
10847             "int *a;",
10848             format("int *a;\n"
10849                    "int* a;\n"
10850                    "int *a;",
10851                    getGoogleStyle()));
10852   EXPECT_EQ("int* a;\n"
10853             "int* a;\n"
10854             "int* a;",
10855             format("int* a;\n"
10856                    "int* a;\n"
10857                    "int *a;",
10858                    getGoogleStyle()));
10859   EXPECT_EQ("int *a;\n"
10860             "int *a;\n"
10861             "int *a;",
10862             format("int *a;\n"
10863                    "int * a;\n"
10864                    "int *  a;",
10865                    getGoogleStyle()));
10866   EXPECT_EQ("auto x = [] {\n"
10867             "  int *a;\n"
10868             "  int *a;\n"
10869             "  int *a;\n"
10870             "};",
10871             format("auto x=[]{int *a;\n"
10872                    "int * a;\n"
10873                    "int *  a;};",
10874                    getGoogleStyle()));
10875 }
10876 
10877 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10878   verifyFormat("int f(int &&a) {}");
10879   verifyFormat("int f(int a, char &&b) {}");
10880   verifyFormat("void f() { int &&a = b; }");
10881   verifyGoogleFormat("int f(int a, char&& b) {}");
10882   verifyGoogleFormat("void f() { int&& a = b; }");
10883 
10884   verifyIndependentOfContext("A<int &&> a;");
10885   verifyIndependentOfContext("A<int &&, int &&> a;");
10886   verifyGoogleFormat("A<int&&> a;");
10887   verifyGoogleFormat("A<int&&, int&&> a;");
10888 
10889   // Not rvalue references:
10890   verifyFormat("template <bool B, bool C> class A {\n"
10891                "  static_assert(B && C, \"Something is wrong\");\n"
10892                "};");
10893   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10894   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10895   verifyFormat("#define A(a, b) (a && b)");
10896 }
10897 
10898 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10899   verifyFormat("void f() {\n"
10900                "  x[aaaaaaaaa -\n"
10901                "    b] = 23;\n"
10902                "}",
10903                getLLVMStyleWithColumns(15));
10904 }
10905 
10906 TEST_F(FormatTest, FormatsCasts) {
10907   verifyFormat("Type *A = static_cast<Type *>(P);");
10908   verifyFormat("static_cast<Type *>(P);");
10909   verifyFormat("static_cast<Type &>(Fun)(Args);");
10910   verifyFormat("static_cast<Type &>(*Fun)(Args);");
10911   verifyFormat("if (static_cast<int>(A) + B >= 0)\n  ;");
10912   // Check that static_cast<...>(...) does not require the next token to be on
10913   // the same line.
10914   verifyFormat("some_loooong_output << something_something__ << "
10915                "static_cast<const void *>(R)\n"
10916                "                    << something;");
10917   verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
10918   verifyFormat("const_cast<Type &>(*Fun)(Args);");
10919   verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
10920   verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
10921   verifyFormat("Type *A = (Type *)P;");
10922   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10923   verifyFormat("int a = (int)(2.0f);");
10924   verifyFormat("int a = (int)2.0f;");
10925   verifyFormat("x[(int32)y];");
10926   verifyFormat("x = (int32)y;");
10927   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10928   verifyFormat("int a = (int)*b;");
10929   verifyFormat("int a = (int)2.0f;");
10930   verifyFormat("int a = (int)~0;");
10931   verifyFormat("int a = (int)++a;");
10932   verifyFormat("int a = (int)sizeof(int);");
10933   verifyFormat("int a = (int)+2;");
10934   verifyFormat("my_int a = (my_int)2.0f;");
10935   verifyFormat("my_int a = (my_int)sizeof(int);");
10936   verifyFormat("return (my_int)aaa;");
10937   verifyFormat("#define x ((int)-1)");
10938   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10939   verifyFormat("#define p(q) ((int *)&q)");
10940   verifyFormat("fn(a)(b) + 1;");
10941 
10942   verifyFormat("void f() { my_int a = (my_int)*b; }");
10943   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10944   verifyFormat("my_int a = (my_int)~0;");
10945   verifyFormat("my_int a = (my_int)++a;");
10946   verifyFormat("my_int a = (my_int)-2;");
10947   verifyFormat("my_int a = (my_int)1;");
10948   verifyFormat("my_int a = (my_int *)1;");
10949   verifyFormat("my_int a = (const my_int)-1;");
10950   verifyFormat("my_int a = (const my_int *)-1;");
10951   verifyFormat("my_int a = (my_int)(my_int)-1;");
10952   verifyFormat("my_int a = (ns::my_int)-2;");
10953   verifyFormat("case (my_int)ONE:");
10954   verifyFormat("auto x = (X)this;");
10955   // Casts in Obj-C style calls used to not be recognized as such.
10956   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10957 
10958   // FIXME: single value wrapped with paren will be treated as cast.
10959   verifyFormat("void f(int i = (kValue)*kMask) {}");
10960 
10961   verifyFormat("{ (void)F; }");
10962 
10963   // Don't break after a cast's
10964   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10965                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10966                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10967 
10968   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10969   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10970   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10971   verifyFormat("bool *y = (bool *)(void *)(x);");
10972   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10973   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10974   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10975   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10976 
10977   // These are not casts.
10978   verifyFormat("void f(int *) {}");
10979   verifyFormat("f(foo)->b;");
10980   verifyFormat("f(foo).b;");
10981   verifyFormat("f(foo)(b);");
10982   verifyFormat("f(foo)[b];");
10983   verifyFormat("[](foo) { return 4; }(bar);");
10984   verifyFormat("(*funptr)(foo)[4];");
10985   verifyFormat("funptrs[4](foo)[4];");
10986   verifyFormat("void f(int *);");
10987   verifyFormat("void f(int *) = 0;");
10988   verifyFormat("void f(SmallVector<int>) {}");
10989   verifyFormat("void f(SmallVector<int>);");
10990   verifyFormat("void f(SmallVector<int>) = 0;");
10991   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10992   verifyFormat("int a = sizeof(int) * b;");
10993   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10994   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10995   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10996   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10997 
10998   // These are not casts, but at some point were confused with casts.
10999   verifyFormat("virtual void foo(int *) override;");
11000   verifyFormat("virtual void foo(char &) const;");
11001   verifyFormat("virtual void foo(int *a, char *) const;");
11002   verifyFormat("int a = sizeof(int *) + b;");
11003   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
11004   verifyFormat("bool b = f(g<int>) && c;");
11005   verifyFormat("typedef void (*f)(int i) func;");
11006   verifyFormat("void operator++(int) noexcept;");
11007   verifyFormat("void operator++(int &) noexcept;");
11008   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
11009                "&) noexcept;");
11010   verifyFormat(
11011       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
11012   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
11013   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
11014   verifyFormat("void operator delete(nothrow_t &) noexcept;");
11015   verifyFormat("void operator delete(foo &) noexcept;");
11016   verifyFormat("void operator delete(foo) noexcept;");
11017   verifyFormat("void operator delete(int) noexcept;");
11018   verifyFormat("void operator delete(int &) noexcept;");
11019   verifyFormat("void operator delete(int &) volatile noexcept;");
11020   verifyFormat("void operator delete(int &) const");
11021   verifyFormat("void operator delete(int &) = default");
11022   verifyFormat("void operator delete(int &) = delete");
11023   verifyFormat("void operator delete(int &) [[noreturn]]");
11024   verifyFormat("void operator delete(int &) throw();");
11025   verifyFormat("void operator delete(int &) throw(int);");
11026   verifyFormat("auto operator delete(int &) -> int;");
11027   verifyFormat("auto operator delete(int &) override");
11028   verifyFormat("auto operator delete(int &) final");
11029 
11030   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
11031                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
11032   // FIXME: The indentation here is not ideal.
11033   verifyFormat(
11034       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11035       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
11036       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
11037 }
11038 
11039 TEST_F(FormatTest, FormatsFunctionTypes) {
11040   verifyFormat("A<bool()> a;");
11041   verifyFormat("A<SomeType()> a;");
11042   verifyFormat("A<void (*)(int, std::string)> a;");
11043   verifyFormat("A<void *(int)>;");
11044   verifyFormat("void *(*a)(int *, SomeType *);");
11045   verifyFormat("int (*func)(void *);");
11046   verifyFormat("void f() { int (*func)(void *); }");
11047   verifyFormat("template <class CallbackClass>\n"
11048                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
11049 
11050   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
11051   verifyGoogleFormat("void* (*a)(int);");
11052   verifyGoogleFormat(
11053       "template <class CallbackClass>\n"
11054       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
11055 
11056   // Other constructs can look somewhat like function types:
11057   verifyFormat("A<sizeof(*x)> a;");
11058   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
11059   verifyFormat("some_var = function(*some_pointer_var)[0];");
11060   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
11061   verifyFormat("int x = f(&h)();");
11062   verifyFormat("returnsFunction(&param1, &param2)(param);");
11063   verifyFormat("std::function<\n"
11064                "    LooooooooooongTemplatedType<\n"
11065                "        SomeType>*(\n"
11066                "        LooooooooooooooooongType type)>\n"
11067                "    function;",
11068                getGoogleStyleWithColumns(40));
11069 }
11070 
11071 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
11072   verifyFormat("A (*foo_)[6];");
11073   verifyFormat("vector<int> (*foo_)[6];");
11074 }
11075 
11076 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
11077   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11078                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
11079   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
11080                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
11081   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11082                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
11083 
11084   // Different ways of ()-initializiation.
11085   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11086                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
11087   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11088                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
11089   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11090                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
11091   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11092                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
11093 
11094   // Lambdas should not confuse the variable declaration heuristic.
11095   verifyFormat("LooooooooooooooooongType\n"
11096                "    variable(nullptr, [](A *a) {});",
11097                getLLVMStyleWithColumns(40));
11098 }
11099 
11100 TEST_F(FormatTest, BreaksLongDeclarations) {
11101   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
11102                "    AnotherNameForTheLongType;");
11103   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
11104                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
11105   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11106                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
11107   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
11108                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
11109   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11110                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11111   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
11112                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11113   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
11114                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11115   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
11116                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11117   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
11118                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11119   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
11120                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11121   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
11122                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11123   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11124                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
11125   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11126                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
11127   FormatStyle Indented = getLLVMStyle();
11128   Indented.IndentWrappedFunctionNames = true;
11129   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11130                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
11131                Indented);
11132   verifyFormat(
11133       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11134       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11135       Indented);
11136   verifyFormat(
11137       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
11138       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11139       Indented);
11140   verifyFormat(
11141       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
11142       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11143       Indented);
11144 
11145   // FIXME: Without the comment, this breaks after "(".
11146   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
11147                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
11148                getGoogleStyle());
11149 
11150   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
11151                "                  int LoooooooooooooooooooongParam2) {}");
11152   verifyFormat(
11153       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
11154       "                                   SourceLocation L, IdentifierIn *II,\n"
11155       "                                   Type *T) {}");
11156   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
11157                "ReallyReaaallyLongFunctionName(\n"
11158                "    const std::string &SomeParameter,\n"
11159                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11160                "        &ReallyReallyLongParameterName,\n"
11161                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11162                "        &AnotherLongParameterName) {}");
11163   verifyFormat("template <typename A>\n"
11164                "SomeLoooooooooooooooooooooongType<\n"
11165                "    typename some_namespace::SomeOtherType<A>::Type>\n"
11166                "Function() {}");
11167 
11168   verifyGoogleFormat(
11169       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
11170       "    aaaaaaaaaaaaaaaaaaaaaaa;");
11171   verifyGoogleFormat(
11172       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
11173       "                                   SourceLocation L) {}");
11174   verifyGoogleFormat(
11175       "some_namespace::LongReturnType\n"
11176       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
11177       "    int first_long_parameter, int second_parameter) {}");
11178 
11179   verifyGoogleFormat("template <typename T>\n"
11180                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11181                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
11182   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11183                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
11184 
11185   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
11186                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11187                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11188   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11189                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11190                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
11191   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11192                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
11193                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
11194                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11195 
11196   verifyFormat("template <typename T> // Templates on own line.\n"
11197                "static int            // Some comment.\n"
11198                "MyFunction(int a);",
11199                getLLVMStyle());
11200 }
11201 
11202 TEST_F(FormatTest, FormatsAccessModifiers) {
11203   FormatStyle Style = getLLVMStyle();
11204   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
11205             FormatStyle::ELBAMS_LogicalBlock);
11206   verifyFormat("struct foo {\n"
11207                "private:\n"
11208                "  void f() {}\n"
11209                "\n"
11210                "private:\n"
11211                "  int i;\n"
11212                "\n"
11213                "protected:\n"
11214                "  int j;\n"
11215                "};\n",
11216                Style);
11217   verifyFormat("struct foo {\n"
11218                "private:\n"
11219                "  void f() {}\n"
11220                "\n"
11221                "private:\n"
11222                "  int i;\n"
11223                "\n"
11224                "protected:\n"
11225                "  int j;\n"
11226                "};\n",
11227                "struct foo {\n"
11228                "private:\n"
11229                "  void f() {}\n"
11230                "private:\n"
11231                "  int i;\n"
11232                "protected:\n"
11233                "  int j;\n"
11234                "};\n",
11235                Style);
11236   verifyFormat("struct foo { /* comment */\n"
11237                "private:\n"
11238                "  int i;\n"
11239                "  // comment\n"
11240                "private:\n"
11241                "  int j;\n"
11242                "};\n",
11243                Style);
11244   verifyFormat("struct foo {\n"
11245                "#ifdef FOO\n"
11246                "#endif\n"
11247                "private:\n"
11248                "  int i;\n"
11249                "#ifdef FOO\n"
11250                "private:\n"
11251                "#endif\n"
11252                "  int j;\n"
11253                "};\n",
11254                Style);
11255   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11256   verifyFormat("struct foo {\n"
11257                "private:\n"
11258                "  void f() {}\n"
11259                "private:\n"
11260                "  int i;\n"
11261                "protected:\n"
11262                "  int j;\n"
11263                "};\n",
11264                Style);
11265   verifyFormat("struct foo {\n"
11266                "private:\n"
11267                "  void f() {}\n"
11268                "private:\n"
11269                "  int i;\n"
11270                "protected:\n"
11271                "  int j;\n"
11272                "};\n",
11273                "struct foo {\n"
11274                "\n"
11275                "private:\n"
11276                "  void f() {}\n"
11277                "\n"
11278                "private:\n"
11279                "  int i;\n"
11280                "\n"
11281                "protected:\n"
11282                "  int j;\n"
11283                "};\n",
11284                Style);
11285   verifyFormat("struct foo { /* comment */\n"
11286                "private:\n"
11287                "  int i;\n"
11288                "  // comment\n"
11289                "private:\n"
11290                "  int j;\n"
11291                "};\n",
11292                "struct foo { /* comment */\n"
11293                "\n"
11294                "private:\n"
11295                "  int i;\n"
11296                "  // comment\n"
11297                "\n"
11298                "private:\n"
11299                "  int j;\n"
11300                "};\n",
11301                Style);
11302   verifyFormat("struct foo {\n"
11303                "#ifdef FOO\n"
11304                "#endif\n"
11305                "private:\n"
11306                "  int i;\n"
11307                "#ifdef FOO\n"
11308                "private:\n"
11309                "#endif\n"
11310                "  int j;\n"
11311                "};\n",
11312                "struct foo {\n"
11313                "#ifdef FOO\n"
11314                "#endif\n"
11315                "\n"
11316                "private:\n"
11317                "  int i;\n"
11318                "#ifdef FOO\n"
11319                "\n"
11320                "private:\n"
11321                "#endif\n"
11322                "  int j;\n"
11323                "};\n",
11324                Style);
11325   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11326   verifyFormat("struct foo {\n"
11327                "private:\n"
11328                "  void f() {}\n"
11329                "\n"
11330                "private:\n"
11331                "  int i;\n"
11332                "\n"
11333                "protected:\n"
11334                "  int j;\n"
11335                "};\n",
11336                Style);
11337   verifyFormat("struct foo {\n"
11338                "private:\n"
11339                "  void f() {}\n"
11340                "\n"
11341                "private:\n"
11342                "  int i;\n"
11343                "\n"
11344                "protected:\n"
11345                "  int j;\n"
11346                "};\n",
11347                "struct foo {\n"
11348                "private:\n"
11349                "  void f() {}\n"
11350                "private:\n"
11351                "  int i;\n"
11352                "protected:\n"
11353                "  int j;\n"
11354                "};\n",
11355                Style);
11356   verifyFormat("struct foo { /* comment */\n"
11357                "private:\n"
11358                "  int i;\n"
11359                "  // comment\n"
11360                "\n"
11361                "private:\n"
11362                "  int j;\n"
11363                "};\n",
11364                "struct foo { /* comment */\n"
11365                "private:\n"
11366                "  int i;\n"
11367                "  // comment\n"
11368                "\n"
11369                "private:\n"
11370                "  int j;\n"
11371                "};\n",
11372                Style);
11373   verifyFormat("struct foo {\n"
11374                "#ifdef FOO\n"
11375                "#endif\n"
11376                "\n"
11377                "private:\n"
11378                "  int i;\n"
11379                "#ifdef FOO\n"
11380                "\n"
11381                "private:\n"
11382                "#endif\n"
11383                "  int j;\n"
11384                "};\n",
11385                "struct foo {\n"
11386                "#ifdef FOO\n"
11387                "#endif\n"
11388                "private:\n"
11389                "  int i;\n"
11390                "#ifdef FOO\n"
11391                "private:\n"
11392                "#endif\n"
11393                "  int j;\n"
11394                "};\n",
11395                Style);
11396   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11397   EXPECT_EQ("struct foo {\n"
11398             "\n"
11399             "private:\n"
11400             "  void f() {}\n"
11401             "\n"
11402             "private:\n"
11403             "  int i;\n"
11404             "\n"
11405             "protected:\n"
11406             "  int j;\n"
11407             "};\n",
11408             format("struct foo {\n"
11409                    "\n"
11410                    "private:\n"
11411                    "  void f() {}\n"
11412                    "\n"
11413                    "private:\n"
11414                    "  int i;\n"
11415                    "\n"
11416                    "protected:\n"
11417                    "  int j;\n"
11418                    "};\n",
11419                    Style));
11420   verifyFormat("struct foo {\n"
11421                "private:\n"
11422                "  void f() {}\n"
11423                "private:\n"
11424                "  int i;\n"
11425                "protected:\n"
11426                "  int j;\n"
11427                "};\n",
11428                Style);
11429   EXPECT_EQ("struct foo { /* comment */\n"
11430             "\n"
11431             "private:\n"
11432             "  int i;\n"
11433             "  // comment\n"
11434             "\n"
11435             "private:\n"
11436             "  int j;\n"
11437             "};\n",
11438             format("struct foo { /* comment */\n"
11439                    "\n"
11440                    "private:\n"
11441                    "  int i;\n"
11442                    "  // comment\n"
11443                    "\n"
11444                    "private:\n"
11445                    "  int j;\n"
11446                    "};\n",
11447                    Style));
11448   verifyFormat("struct foo { /* comment */\n"
11449                "private:\n"
11450                "  int i;\n"
11451                "  // comment\n"
11452                "private:\n"
11453                "  int j;\n"
11454                "};\n",
11455                Style);
11456   EXPECT_EQ("struct foo {\n"
11457             "#ifdef FOO\n"
11458             "#endif\n"
11459             "\n"
11460             "private:\n"
11461             "  int i;\n"
11462             "#ifdef FOO\n"
11463             "\n"
11464             "private:\n"
11465             "#endif\n"
11466             "  int j;\n"
11467             "};\n",
11468             format("struct foo {\n"
11469                    "#ifdef FOO\n"
11470                    "#endif\n"
11471                    "\n"
11472                    "private:\n"
11473                    "  int i;\n"
11474                    "#ifdef FOO\n"
11475                    "\n"
11476                    "private:\n"
11477                    "#endif\n"
11478                    "  int j;\n"
11479                    "};\n",
11480                    Style));
11481   verifyFormat("struct foo {\n"
11482                "#ifdef FOO\n"
11483                "#endif\n"
11484                "private:\n"
11485                "  int i;\n"
11486                "#ifdef FOO\n"
11487                "private:\n"
11488                "#endif\n"
11489                "  int j;\n"
11490                "};\n",
11491                Style);
11492 
11493   FormatStyle NoEmptyLines = getLLVMStyle();
11494   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11495   verifyFormat("struct foo {\n"
11496                "private:\n"
11497                "  void f() {}\n"
11498                "\n"
11499                "private:\n"
11500                "  int i;\n"
11501                "\n"
11502                "public:\n"
11503                "protected:\n"
11504                "  int j;\n"
11505                "};\n",
11506                NoEmptyLines);
11507 
11508   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11509   verifyFormat("struct foo {\n"
11510                "private:\n"
11511                "  void f() {}\n"
11512                "private:\n"
11513                "  int i;\n"
11514                "public:\n"
11515                "protected:\n"
11516                "  int j;\n"
11517                "};\n",
11518                NoEmptyLines);
11519 
11520   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11521   verifyFormat("struct foo {\n"
11522                "private:\n"
11523                "  void f() {}\n"
11524                "\n"
11525                "private:\n"
11526                "  int i;\n"
11527                "\n"
11528                "public:\n"
11529                "\n"
11530                "protected:\n"
11531                "  int j;\n"
11532                "};\n",
11533                NoEmptyLines);
11534 }
11535 
11536 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
11537 
11538   FormatStyle Style = getLLVMStyle();
11539   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
11540   verifyFormat("struct foo {\n"
11541                "private:\n"
11542                "  void f() {}\n"
11543                "\n"
11544                "private:\n"
11545                "  int i;\n"
11546                "\n"
11547                "protected:\n"
11548                "  int j;\n"
11549                "};\n",
11550                Style);
11551 
11552   // Check if lines are removed.
11553   verifyFormat("struct foo {\n"
11554                "private:\n"
11555                "  void f() {}\n"
11556                "\n"
11557                "private:\n"
11558                "  int i;\n"
11559                "\n"
11560                "protected:\n"
11561                "  int j;\n"
11562                "};\n",
11563                "struct foo {\n"
11564                "private:\n"
11565                "\n"
11566                "  void f() {}\n"
11567                "\n"
11568                "private:\n"
11569                "\n"
11570                "  int i;\n"
11571                "\n"
11572                "protected:\n"
11573                "\n"
11574                "  int j;\n"
11575                "};\n",
11576                Style);
11577 
11578   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11579   verifyFormat("struct foo {\n"
11580                "private:\n"
11581                "\n"
11582                "  void f() {}\n"
11583                "\n"
11584                "private:\n"
11585                "\n"
11586                "  int i;\n"
11587                "\n"
11588                "protected:\n"
11589                "\n"
11590                "  int j;\n"
11591                "};\n",
11592                Style);
11593 
11594   // Check if lines are added.
11595   verifyFormat("struct foo {\n"
11596                "private:\n"
11597                "\n"
11598                "  void f() {}\n"
11599                "\n"
11600                "private:\n"
11601                "\n"
11602                "  int i;\n"
11603                "\n"
11604                "protected:\n"
11605                "\n"
11606                "  int j;\n"
11607                "};\n",
11608                "struct foo {\n"
11609                "private:\n"
11610                "  void f() {}\n"
11611                "\n"
11612                "private:\n"
11613                "  int i;\n"
11614                "\n"
11615                "protected:\n"
11616                "  int j;\n"
11617                "};\n",
11618                Style);
11619 
11620   // Leave tests rely on the code layout, test::messUp can not be used.
11621   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11622   Style.MaxEmptyLinesToKeep = 0u;
11623   verifyFormat("struct foo {\n"
11624                "private:\n"
11625                "  void f() {}\n"
11626                "\n"
11627                "private:\n"
11628                "  int i;\n"
11629                "\n"
11630                "protected:\n"
11631                "  int j;\n"
11632                "};\n",
11633                Style);
11634 
11635   // Check if MaxEmptyLinesToKeep is respected.
11636   EXPECT_EQ("struct foo {\n"
11637             "private:\n"
11638             "  void f() {}\n"
11639             "\n"
11640             "private:\n"
11641             "  int i;\n"
11642             "\n"
11643             "protected:\n"
11644             "  int j;\n"
11645             "};\n",
11646             format("struct foo {\n"
11647                    "private:\n"
11648                    "\n\n\n"
11649                    "  void f() {}\n"
11650                    "\n"
11651                    "private:\n"
11652                    "\n\n\n"
11653                    "  int i;\n"
11654                    "\n"
11655                    "protected:\n"
11656                    "\n\n\n"
11657                    "  int j;\n"
11658                    "};\n",
11659                    Style));
11660 
11661   Style.MaxEmptyLinesToKeep = 1u;
11662   EXPECT_EQ("struct foo {\n"
11663             "private:\n"
11664             "\n"
11665             "  void f() {}\n"
11666             "\n"
11667             "private:\n"
11668             "\n"
11669             "  int i;\n"
11670             "\n"
11671             "protected:\n"
11672             "\n"
11673             "  int j;\n"
11674             "};\n",
11675             format("struct foo {\n"
11676                    "private:\n"
11677                    "\n"
11678                    "  void f() {}\n"
11679                    "\n"
11680                    "private:\n"
11681                    "\n"
11682                    "  int i;\n"
11683                    "\n"
11684                    "protected:\n"
11685                    "\n"
11686                    "  int j;\n"
11687                    "};\n",
11688                    Style));
11689   // Check if no lines are kept.
11690   EXPECT_EQ("struct foo {\n"
11691             "private:\n"
11692             "  void f() {}\n"
11693             "\n"
11694             "private:\n"
11695             "  int i;\n"
11696             "\n"
11697             "protected:\n"
11698             "  int j;\n"
11699             "};\n",
11700             format("struct foo {\n"
11701                    "private:\n"
11702                    "  void f() {}\n"
11703                    "\n"
11704                    "private:\n"
11705                    "  int i;\n"
11706                    "\n"
11707                    "protected:\n"
11708                    "  int j;\n"
11709                    "};\n",
11710                    Style));
11711   // Check if MaxEmptyLinesToKeep is respected.
11712   EXPECT_EQ("struct foo {\n"
11713             "private:\n"
11714             "\n"
11715             "  void f() {}\n"
11716             "\n"
11717             "private:\n"
11718             "\n"
11719             "  int i;\n"
11720             "\n"
11721             "protected:\n"
11722             "\n"
11723             "  int j;\n"
11724             "};\n",
11725             format("struct foo {\n"
11726                    "private:\n"
11727                    "\n\n\n"
11728                    "  void f() {}\n"
11729                    "\n"
11730                    "private:\n"
11731                    "\n\n\n"
11732                    "  int i;\n"
11733                    "\n"
11734                    "protected:\n"
11735                    "\n\n\n"
11736                    "  int j;\n"
11737                    "};\n",
11738                    Style));
11739 
11740   Style.MaxEmptyLinesToKeep = 10u;
11741   EXPECT_EQ("struct foo {\n"
11742             "private:\n"
11743             "\n\n\n"
11744             "  void f() {}\n"
11745             "\n"
11746             "private:\n"
11747             "\n\n\n"
11748             "  int i;\n"
11749             "\n"
11750             "protected:\n"
11751             "\n\n\n"
11752             "  int j;\n"
11753             "};\n",
11754             format("struct foo {\n"
11755                    "private:\n"
11756                    "\n\n\n"
11757                    "  void f() {}\n"
11758                    "\n"
11759                    "private:\n"
11760                    "\n\n\n"
11761                    "  int i;\n"
11762                    "\n"
11763                    "protected:\n"
11764                    "\n\n\n"
11765                    "  int j;\n"
11766                    "};\n",
11767                    Style));
11768 
11769   // Test with comments.
11770   Style = getLLVMStyle();
11771   verifyFormat("struct foo {\n"
11772                "private:\n"
11773                "  // comment\n"
11774                "  void f() {}\n"
11775                "\n"
11776                "private: /* comment */\n"
11777                "  int i;\n"
11778                "};\n",
11779                Style);
11780   verifyFormat("struct foo {\n"
11781                "private:\n"
11782                "  // comment\n"
11783                "  void f() {}\n"
11784                "\n"
11785                "private: /* comment */\n"
11786                "  int i;\n"
11787                "};\n",
11788                "struct foo {\n"
11789                "private:\n"
11790                "\n"
11791                "  // comment\n"
11792                "  void f() {}\n"
11793                "\n"
11794                "private: /* comment */\n"
11795                "\n"
11796                "  int i;\n"
11797                "};\n",
11798                Style);
11799 
11800   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11801   verifyFormat("struct foo {\n"
11802                "private:\n"
11803                "\n"
11804                "  // comment\n"
11805                "  void f() {}\n"
11806                "\n"
11807                "private: /* comment */\n"
11808                "\n"
11809                "  int i;\n"
11810                "};\n",
11811                "struct foo {\n"
11812                "private:\n"
11813                "  // comment\n"
11814                "  void f() {}\n"
11815                "\n"
11816                "private: /* comment */\n"
11817                "  int i;\n"
11818                "};\n",
11819                Style);
11820   verifyFormat("struct foo {\n"
11821                "private:\n"
11822                "\n"
11823                "  // comment\n"
11824                "  void f() {}\n"
11825                "\n"
11826                "private: /* comment */\n"
11827                "\n"
11828                "  int i;\n"
11829                "};\n",
11830                Style);
11831 
11832   // Test with preprocessor defines.
11833   Style = getLLVMStyle();
11834   verifyFormat("struct foo {\n"
11835                "private:\n"
11836                "#ifdef FOO\n"
11837                "#endif\n"
11838                "  void f() {}\n"
11839                "};\n",
11840                Style);
11841   verifyFormat("struct foo {\n"
11842                "private:\n"
11843                "#ifdef FOO\n"
11844                "#endif\n"
11845                "  void f() {}\n"
11846                "};\n",
11847                "struct foo {\n"
11848                "private:\n"
11849                "\n"
11850                "#ifdef FOO\n"
11851                "#endif\n"
11852                "  void f() {}\n"
11853                "};\n",
11854                Style);
11855 
11856   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11857   verifyFormat("struct foo {\n"
11858                "private:\n"
11859                "\n"
11860                "#ifdef FOO\n"
11861                "#endif\n"
11862                "  void f() {}\n"
11863                "};\n",
11864                "struct foo {\n"
11865                "private:\n"
11866                "#ifdef FOO\n"
11867                "#endif\n"
11868                "  void f() {}\n"
11869                "};\n",
11870                Style);
11871   verifyFormat("struct foo {\n"
11872                "private:\n"
11873                "\n"
11874                "#ifdef FOO\n"
11875                "#endif\n"
11876                "  void f() {}\n"
11877                "};\n",
11878                Style);
11879 }
11880 
11881 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11882   // Combined tests of EmptyLineAfterAccessModifier and
11883   // EmptyLineBeforeAccessModifier.
11884   FormatStyle Style = getLLVMStyle();
11885   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11886   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11887   verifyFormat("struct foo {\n"
11888                "private:\n"
11889                "\n"
11890                "protected:\n"
11891                "};\n",
11892                Style);
11893 
11894   Style.MaxEmptyLinesToKeep = 10u;
11895   // Both remove all new lines.
11896   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11897   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11898   verifyFormat("struct foo {\n"
11899                "private:\n"
11900                "protected:\n"
11901                "};\n",
11902                "struct foo {\n"
11903                "private:\n"
11904                "\n\n\n"
11905                "protected:\n"
11906                "};\n",
11907                Style);
11908 
11909   // Leave tests rely on the code layout, test::messUp can not be used.
11910   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11911   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11912   Style.MaxEmptyLinesToKeep = 10u;
11913   EXPECT_EQ("struct foo {\n"
11914             "private:\n"
11915             "\n\n\n"
11916             "protected:\n"
11917             "};\n",
11918             format("struct foo {\n"
11919                    "private:\n"
11920                    "\n\n\n"
11921                    "protected:\n"
11922                    "};\n",
11923                    Style));
11924   Style.MaxEmptyLinesToKeep = 3u;
11925   EXPECT_EQ("struct foo {\n"
11926             "private:\n"
11927             "\n\n\n"
11928             "protected:\n"
11929             "};\n",
11930             format("struct foo {\n"
11931                    "private:\n"
11932                    "\n\n\n"
11933                    "protected:\n"
11934                    "};\n",
11935                    Style));
11936   Style.MaxEmptyLinesToKeep = 1u;
11937   EXPECT_EQ("struct foo {\n"
11938             "private:\n"
11939             "\n\n\n"
11940             "protected:\n"
11941             "};\n",
11942             format("struct foo {\n"
11943                    "private:\n"
11944                    "\n\n\n"
11945                    "protected:\n"
11946                    "};\n",
11947                    Style)); // Based on new lines in original document and not
11948                             // on the setting.
11949 
11950   Style.MaxEmptyLinesToKeep = 10u;
11951   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11952   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11953   // Newlines are kept if they are greater than zero,
11954   // test::messUp removes all new lines which changes the logic
11955   EXPECT_EQ("struct foo {\n"
11956             "private:\n"
11957             "\n\n\n"
11958             "protected:\n"
11959             "};\n",
11960             format("struct foo {\n"
11961                    "private:\n"
11962                    "\n\n\n"
11963                    "protected:\n"
11964                    "};\n",
11965                    Style));
11966 
11967   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11968   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11969   // test::messUp removes all new lines which changes the logic
11970   EXPECT_EQ("struct foo {\n"
11971             "private:\n"
11972             "\n\n\n"
11973             "protected:\n"
11974             "};\n",
11975             format("struct foo {\n"
11976                    "private:\n"
11977                    "\n\n\n"
11978                    "protected:\n"
11979                    "};\n",
11980                    Style));
11981 
11982   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11983   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11984   EXPECT_EQ("struct foo {\n"
11985             "private:\n"
11986             "\n\n\n"
11987             "protected:\n"
11988             "};\n",
11989             format("struct foo {\n"
11990                    "private:\n"
11991                    "\n\n\n"
11992                    "protected:\n"
11993                    "};\n",
11994                    Style)); // test::messUp removes all new lines which changes
11995                             // the logic.
11996 
11997   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11998   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11999   verifyFormat("struct foo {\n"
12000                "private:\n"
12001                "protected:\n"
12002                "};\n",
12003                "struct foo {\n"
12004                "private:\n"
12005                "\n\n\n"
12006                "protected:\n"
12007                "};\n",
12008                Style);
12009 
12010   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
12011   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
12012   EXPECT_EQ("struct foo {\n"
12013             "private:\n"
12014             "\n\n\n"
12015             "protected:\n"
12016             "};\n",
12017             format("struct foo {\n"
12018                    "private:\n"
12019                    "\n\n\n"
12020                    "protected:\n"
12021                    "};\n",
12022                    Style)); // test::messUp removes all new lines which changes
12023                             // the logic.
12024 
12025   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
12026   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
12027   verifyFormat("struct foo {\n"
12028                "private:\n"
12029                "protected:\n"
12030                "};\n",
12031                "struct foo {\n"
12032                "private:\n"
12033                "\n\n\n"
12034                "protected:\n"
12035                "};\n",
12036                Style);
12037 
12038   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
12039   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
12040   verifyFormat("struct foo {\n"
12041                "private:\n"
12042                "protected:\n"
12043                "};\n",
12044                "struct foo {\n"
12045                "private:\n"
12046                "\n\n\n"
12047                "protected:\n"
12048                "};\n",
12049                Style);
12050 
12051   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
12052   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
12053   verifyFormat("struct foo {\n"
12054                "private:\n"
12055                "protected:\n"
12056                "};\n",
12057                "struct foo {\n"
12058                "private:\n"
12059                "\n\n\n"
12060                "protected:\n"
12061                "};\n",
12062                Style);
12063 
12064   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
12065   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
12066   verifyFormat("struct foo {\n"
12067                "private:\n"
12068                "protected:\n"
12069                "};\n",
12070                "struct foo {\n"
12071                "private:\n"
12072                "\n\n\n"
12073                "protected:\n"
12074                "};\n",
12075                Style);
12076 }
12077 
12078 TEST_F(FormatTest, FormatsArrays) {
12079   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
12080                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
12081   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
12082                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
12083   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
12084                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
12085   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12086                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
12087   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12088                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
12089   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12090                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
12091                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
12092   verifyFormat(
12093       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
12094       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
12095       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
12096   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
12097                "    .aaaaaaaaaaaaaaaaaaaaaa();");
12098 
12099   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
12100                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
12101   verifyFormat(
12102       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
12103       "                                  .aaaaaaa[0]\n"
12104       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
12105   verifyFormat("a[::b::c];");
12106 
12107   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
12108 
12109   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12110   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
12111 }
12112 
12113 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
12114   verifyFormat("(a)->b();");
12115   verifyFormat("--a;");
12116 }
12117 
12118 TEST_F(FormatTest, HandlesIncludeDirectives) {
12119   verifyFormat("#include <string>\n"
12120                "#include <a/b/c.h>\n"
12121                "#include \"a/b/string\"\n"
12122                "#include \"string.h\"\n"
12123                "#include \"string.h\"\n"
12124                "#include <a-a>\n"
12125                "#include < path with space >\n"
12126                "#include_next <test.h>"
12127                "#include \"abc.h\" // this is included for ABC\n"
12128                "#include \"some long include\" // with a comment\n"
12129                "#include \"some very long include path\"\n"
12130                "#include <some/very/long/include/path>\n",
12131                getLLVMStyleWithColumns(35));
12132   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
12133   EXPECT_EQ("#include <a>", format("#include<a>"));
12134 
12135   verifyFormat("#import <string>");
12136   verifyFormat("#import <a/b/c.h>");
12137   verifyFormat("#import \"a/b/string\"");
12138   verifyFormat("#import \"string.h\"");
12139   verifyFormat("#import \"string.h\"");
12140   verifyFormat("#if __has_include(<strstream>)\n"
12141                "#include <strstream>\n"
12142                "#endif");
12143 
12144   verifyFormat("#define MY_IMPORT <a/b>");
12145 
12146   verifyFormat("#if __has_include(<a/b>)");
12147   verifyFormat("#if __has_include_next(<a/b>)");
12148   verifyFormat("#define F __has_include(<a/b>)");
12149   verifyFormat("#define F __has_include_next(<a/b>)");
12150 
12151   // Protocol buffer definition or missing "#".
12152   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
12153                getLLVMStyleWithColumns(30));
12154 
12155   FormatStyle Style = getLLVMStyle();
12156   Style.AlwaysBreakBeforeMultilineStrings = true;
12157   Style.ColumnLimit = 0;
12158   verifyFormat("#import \"abc.h\"", Style);
12159 
12160   // But 'import' might also be a regular C++ namespace.
12161   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12162                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
12163 }
12164 
12165 //===----------------------------------------------------------------------===//
12166 // Error recovery tests.
12167 //===----------------------------------------------------------------------===//
12168 
12169 TEST_F(FormatTest, IncompleteParameterLists) {
12170   FormatStyle NoBinPacking = getLLVMStyle();
12171   NoBinPacking.BinPackParameters = false;
12172   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
12173                "                        double *min_x,\n"
12174                "                        double *max_x,\n"
12175                "                        double *min_y,\n"
12176                "                        double *max_y,\n"
12177                "                        double *min_z,\n"
12178                "                        double *max_z, ) {}",
12179                NoBinPacking);
12180 }
12181 
12182 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
12183   verifyFormat("void f() { return; }\n42");
12184   verifyFormat("void f() {\n"
12185                "  if (0)\n"
12186                "    return;\n"
12187                "}\n"
12188                "42");
12189   verifyFormat("void f() { return }\n42");
12190   verifyFormat("void f() {\n"
12191                "  if (0)\n"
12192                "    return\n"
12193                "}\n"
12194                "42");
12195 }
12196 
12197 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
12198   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
12199   EXPECT_EQ("void f() {\n"
12200             "  if (a)\n"
12201             "    return\n"
12202             "}",
12203             format("void  f  (  )  {  if  ( a )  return  }"));
12204   EXPECT_EQ("namespace N {\n"
12205             "void f()\n"
12206             "}",
12207             format("namespace  N  {  void f()  }"));
12208   EXPECT_EQ("namespace N {\n"
12209             "void f() {}\n"
12210             "void g()\n"
12211             "} // namespace N",
12212             format("namespace N  { void f( ) { } void g( ) }"));
12213 }
12214 
12215 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
12216   verifyFormat("int aaaaaaaa =\n"
12217                "    // Overlylongcomment\n"
12218                "    b;",
12219                getLLVMStyleWithColumns(20));
12220   verifyFormat("function(\n"
12221                "    ShortArgument,\n"
12222                "    LoooooooooooongArgument);\n",
12223                getLLVMStyleWithColumns(20));
12224 }
12225 
12226 TEST_F(FormatTest, IncorrectAccessSpecifier) {
12227   verifyFormat("public:");
12228   verifyFormat("class A {\n"
12229                "public\n"
12230                "  void f() {}\n"
12231                "};");
12232   verifyFormat("public\n"
12233                "int qwerty;");
12234   verifyFormat("public\n"
12235                "B {}");
12236   verifyFormat("public\n"
12237                "{}");
12238   verifyFormat("public\n"
12239                "B { int x; }");
12240 }
12241 
12242 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
12243   verifyFormat("{");
12244   verifyFormat("#})");
12245   verifyNoCrash("(/**/[:!] ?[).");
12246 }
12247 
12248 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
12249   // Found by oss-fuzz:
12250   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
12251   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
12252   Style.ColumnLimit = 60;
12253   verifyNoCrash(
12254       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
12255       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
12256       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
12257       Style);
12258 }
12259 
12260 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
12261   verifyFormat("do {\n}");
12262   verifyFormat("do {\n}\n"
12263                "f();");
12264   verifyFormat("do {\n}\n"
12265                "wheeee(fun);");
12266   verifyFormat("do {\n"
12267                "  f();\n"
12268                "}");
12269 }
12270 
12271 TEST_F(FormatTest, IncorrectCodeMissingParens) {
12272   verifyFormat("if {\n  foo;\n  foo();\n}");
12273   verifyFormat("switch {\n  foo;\n  foo();\n}");
12274   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
12275   verifyIncompleteFormat("ERROR: for target;");
12276   verifyFormat("while {\n  foo;\n  foo();\n}");
12277   verifyFormat("do {\n  foo;\n  foo();\n} while;");
12278 }
12279 
12280 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
12281   verifyIncompleteFormat("namespace {\n"
12282                          "class Foo { Foo (\n"
12283                          "};\n"
12284                          "} // namespace");
12285 }
12286 
12287 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
12288   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
12289   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
12290   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
12291   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
12292 
12293   EXPECT_EQ("{\n"
12294             "  {\n"
12295             "    breakme(\n"
12296             "        qwe);\n"
12297             "  }\n",
12298             format("{\n"
12299                    "    {\n"
12300                    " breakme(qwe);\n"
12301                    "}\n",
12302                    getLLVMStyleWithColumns(10)));
12303 }
12304 
12305 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
12306   verifyFormat("int x = {\n"
12307                "    avariable,\n"
12308                "    b(alongervariable)};",
12309                getLLVMStyleWithColumns(25));
12310 }
12311 
12312 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
12313   verifyFormat("return (a)(b){1, 2, 3};");
12314 }
12315 
12316 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
12317   verifyFormat("vector<int> x{1, 2, 3, 4};");
12318   verifyFormat("vector<int> x{\n"
12319                "    1,\n"
12320                "    2,\n"
12321                "    3,\n"
12322                "    4,\n"
12323                "};");
12324   verifyFormat("vector<T> x{{}, {}, {}, {}};");
12325   verifyFormat("f({1, 2});");
12326   verifyFormat("auto v = Foo{-1};");
12327   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
12328   verifyFormat("Class::Class : member{1, 2, 3} {}");
12329   verifyFormat("new vector<int>{1, 2, 3};");
12330   verifyFormat("new int[3]{1, 2, 3};");
12331   verifyFormat("new int{1};");
12332   verifyFormat("return {arg1, arg2};");
12333   verifyFormat("return {arg1, SomeType{parameter}};");
12334   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
12335   verifyFormat("new T{arg1, arg2};");
12336   verifyFormat("f(MyMap[{composite, key}]);");
12337   verifyFormat("class Class {\n"
12338                "  T member = {arg1, arg2};\n"
12339                "};");
12340   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
12341   verifyFormat("const struct A a = {.a = 1, .b = 2};");
12342   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
12343   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
12344   verifyFormat("int a = std::is_integral<int>{} + 0;");
12345 
12346   verifyFormat("int foo(int i) { return fo1{}(i); }");
12347   verifyFormat("int foo(int i) { return fo1{}(i); }");
12348   verifyFormat("auto i = decltype(x){};");
12349   verifyFormat("auto i = typeof(x){};");
12350   verifyFormat("auto i = _Atomic(x){};");
12351   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
12352   verifyFormat("Node n{1, Node{1000}, //\n"
12353                "       2};");
12354   verifyFormat("Aaaa aaaaaaa{\n"
12355                "    {\n"
12356                "        aaaa,\n"
12357                "    },\n"
12358                "};");
12359   verifyFormat("class C : public D {\n"
12360                "  SomeClass SC{2};\n"
12361                "};");
12362   verifyFormat("class C : public A {\n"
12363                "  class D : public B {\n"
12364                "    void f() { int i{2}; }\n"
12365                "  };\n"
12366                "};");
12367   verifyFormat("#define A {a, a},");
12368   // Don't confuse braced list initializers with compound statements.
12369   verifyFormat(
12370       "class A {\n"
12371       "  A() : a{} {}\n"
12372       "  A(int b) : b(b) {}\n"
12373       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
12374       "  int a, b;\n"
12375       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
12376       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
12377       "{}\n"
12378       "};");
12379 
12380   // Avoid breaking between equal sign and opening brace
12381   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
12382   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
12383   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
12384                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
12385                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
12386                "     {\"ccccccccccccccccccccc\", 2}};",
12387                AvoidBreakingFirstArgument);
12388 
12389   // Binpacking only if there is no trailing comma
12390   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
12391                "                      cccccccccc, dddddddddd};",
12392                getLLVMStyleWithColumns(50));
12393   verifyFormat("const Aaaaaa aaaaa = {\n"
12394                "    aaaaaaaaaaa,\n"
12395                "    bbbbbbbbbbb,\n"
12396                "    ccccccccccc,\n"
12397                "    ddddddddddd,\n"
12398                "};",
12399                getLLVMStyleWithColumns(50));
12400 
12401   // Cases where distinguising braced lists and blocks is hard.
12402   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
12403   verifyFormat("void f() {\n"
12404                "  return; // comment\n"
12405                "}\n"
12406                "SomeType t;");
12407   verifyFormat("void f() {\n"
12408                "  if (a) {\n"
12409                "    f();\n"
12410                "  }\n"
12411                "}\n"
12412                "SomeType t;");
12413 
12414   // In combination with BinPackArguments = false.
12415   FormatStyle NoBinPacking = getLLVMStyle();
12416   NoBinPacking.BinPackArguments = false;
12417   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
12418                "                      bbbbb,\n"
12419                "                      ccccc,\n"
12420                "                      ddddd,\n"
12421                "                      eeeee,\n"
12422                "                      ffffff,\n"
12423                "                      ggggg,\n"
12424                "                      hhhhhh,\n"
12425                "                      iiiiii,\n"
12426                "                      jjjjjj,\n"
12427                "                      kkkkkk};",
12428                NoBinPacking);
12429   verifyFormat("const Aaaaaa aaaaa = {\n"
12430                "    aaaaa,\n"
12431                "    bbbbb,\n"
12432                "    ccccc,\n"
12433                "    ddddd,\n"
12434                "    eeeee,\n"
12435                "    ffffff,\n"
12436                "    ggggg,\n"
12437                "    hhhhhh,\n"
12438                "    iiiiii,\n"
12439                "    jjjjjj,\n"
12440                "    kkkkkk,\n"
12441                "};",
12442                NoBinPacking);
12443   verifyFormat(
12444       "const Aaaaaa aaaaa = {\n"
12445       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
12446       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
12447       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
12448       "};",
12449       NoBinPacking);
12450 
12451   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12452   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
12453             "    CDDDP83848_BMCR_REGISTER,\n"
12454             "    CDDDP83848_BMSR_REGISTER,\n"
12455             "    CDDDP83848_RBR_REGISTER};",
12456             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
12457                    "                                CDDDP83848_BMSR_REGISTER,\n"
12458                    "                                CDDDP83848_RBR_REGISTER};",
12459                    NoBinPacking));
12460 
12461   // FIXME: The alignment of these trailing comments might be bad. Then again,
12462   // this might be utterly useless in real code.
12463   verifyFormat("Constructor::Constructor()\n"
12464                "    : some_value{         //\n"
12465                "                 aaaaaaa, //\n"
12466                "                 bbbbbbb} {}");
12467 
12468   // In braced lists, the first comment is always assumed to belong to the
12469   // first element. Thus, it can be moved to the next or previous line as
12470   // appropriate.
12471   EXPECT_EQ("function({// First element:\n"
12472             "          1,\n"
12473             "          // Second element:\n"
12474             "          2});",
12475             format("function({\n"
12476                    "    // First element:\n"
12477                    "    1,\n"
12478                    "    // Second element:\n"
12479                    "    2});"));
12480   EXPECT_EQ("std::vector<int> MyNumbers{\n"
12481             "    // First element:\n"
12482             "    1,\n"
12483             "    // Second element:\n"
12484             "    2};",
12485             format("std::vector<int> MyNumbers{// First element:\n"
12486                    "                           1,\n"
12487                    "                           // Second element:\n"
12488                    "                           2};",
12489                    getLLVMStyleWithColumns(30)));
12490   // A trailing comma should still lead to an enforced line break and no
12491   // binpacking.
12492   EXPECT_EQ("vector<int> SomeVector = {\n"
12493             "    // aaa\n"
12494             "    1,\n"
12495             "    2,\n"
12496             "};",
12497             format("vector<int> SomeVector = { // aaa\n"
12498                    "    1, 2, };"));
12499 
12500   // C++11 brace initializer list l-braces should not be treated any differently
12501   // when breaking before lambda bodies is enabled
12502   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
12503   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
12504   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
12505   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
12506   verifyFormat(
12507       "std::runtime_error{\n"
12508       "    \"Long string which will force a break onto the next line...\"};",
12509       BreakBeforeLambdaBody);
12510 
12511   FormatStyle ExtraSpaces = getLLVMStyle();
12512   ExtraSpaces.Cpp11BracedListStyle = false;
12513   ExtraSpaces.ColumnLimit = 75;
12514   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
12515   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
12516   verifyFormat("f({ 1, 2 });", ExtraSpaces);
12517   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
12518   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
12519   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
12520   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
12521   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
12522   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
12523   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
12524   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
12525   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
12526   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
12527   verifyFormat("class Class {\n"
12528                "  T member = { arg1, arg2 };\n"
12529                "};",
12530                ExtraSpaces);
12531   verifyFormat(
12532       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12533       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
12534       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
12535       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
12536       ExtraSpaces);
12537   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
12538   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
12539                ExtraSpaces);
12540   verifyFormat(
12541       "someFunction(OtherParam,\n"
12542       "             BracedList{ // comment 1 (Forcing interesting break)\n"
12543       "                         param1, param2,\n"
12544       "                         // comment 2\n"
12545       "                         param3, param4 });",
12546       ExtraSpaces);
12547   verifyFormat(
12548       "std::this_thread::sleep_for(\n"
12549       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
12550       ExtraSpaces);
12551   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
12552                "    aaaaaaa,\n"
12553                "    aaaaaaaaaa,\n"
12554                "    aaaaa,\n"
12555                "    aaaaaaaaaaaaaaa,\n"
12556                "    aaa,\n"
12557                "    aaaaaaaaaa,\n"
12558                "    a,\n"
12559                "    aaaaaaaaaaaaaaaaaaaaa,\n"
12560                "    aaaaaaaaaaaa,\n"
12561                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
12562                "    aaaaaaa,\n"
12563                "    a};");
12564   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
12565   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
12566   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
12567 
12568   // Avoid breaking between initializer/equal sign and opening brace
12569   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
12570   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
12571                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12572                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12573                "  { \"ccccccccccccccccccccc\", 2 }\n"
12574                "};",
12575                ExtraSpaces);
12576   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
12577                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12578                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12579                "  { \"ccccccccccccccccccccc\", 2 }\n"
12580                "};",
12581                ExtraSpaces);
12582 
12583   FormatStyle SpaceBeforeBrace = getLLVMStyle();
12584   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
12585   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
12586   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
12587 
12588   FormatStyle SpaceBetweenBraces = getLLVMStyle();
12589   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
12590   SpaceBetweenBraces.SpacesInParentheses = true;
12591   SpaceBetweenBraces.SpacesInSquareBrackets = true;
12592   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
12593   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
12594   verifyFormat("vector< int > x{ // comment 1\n"
12595                "                 1, 2, 3, 4 };",
12596                SpaceBetweenBraces);
12597   SpaceBetweenBraces.ColumnLimit = 20;
12598   EXPECT_EQ("vector< int > x{\n"
12599             "    1, 2, 3, 4 };",
12600             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12601   SpaceBetweenBraces.ColumnLimit = 24;
12602   EXPECT_EQ("vector< int > x{ 1, 2,\n"
12603             "                 3, 4 };",
12604             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12605   EXPECT_EQ("vector< int > x{\n"
12606             "    1,\n"
12607             "    2,\n"
12608             "    3,\n"
12609             "    4,\n"
12610             "};",
12611             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12612   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12613   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12614   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12615 }
12616 
12617 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12618   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12619                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12620                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12621                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12622                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12623                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12624   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12625                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12626                "                 1, 22, 333, 4444, 55555, //\n"
12627                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12628                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12629   verifyFormat(
12630       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12631       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12632       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12633       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12634       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12635       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12636       "                 7777777};");
12637   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12638                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12639                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12640   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12641                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12642                "    // Separating comment.\n"
12643                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12644   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12645                "    // Leading comment\n"
12646                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12647                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12648   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12649                "                 1, 1, 1, 1};",
12650                getLLVMStyleWithColumns(39));
12651   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12652                "                 1, 1, 1, 1};",
12653                getLLVMStyleWithColumns(38));
12654   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12655                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12656                getLLVMStyleWithColumns(43));
12657   verifyFormat(
12658       "static unsigned SomeValues[10][3] = {\n"
12659       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12660       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12661   verifyFormat("static auto fields = new vector<string>{\n"
12662                "    \"aaaaaaaaaaaaa\",\n"
12663                "    \"aaaaaaaaaaaaa\",\n"
12664                "    \"aaaaaaaaaaaa\",\n"
12665                "    \"aaaaaaaaaaaaaa\",\n"
12666                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12667                "    \"aaaaaaaaaaaa\",\n"
12668                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12669                "};");
12670   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12671   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12672                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12673                "                 3, cccccccccccccccccccccc};",
12674                getLLVMStyleWithColumns(60));
12675 
12676   // Trailing commas.
12677   verifyFormat("vector<int> x = {\n"
12678                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12679                "};",
12680                getLLVMStyleWithColumns(39));
12681   verifyFormat("vector<int> x = {\n"
12682                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12683                "};",
12684                getLLVMStyleWithColumns(39));
12685   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12686                "                 1, 1, 1, 1,\n"
12687                "                 /**/ /**/};",
12688                getLLVMStyleWithColumns(39));
12689 
12690   // Trailing comment in the first line.
12691   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12692                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12693                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12694                "    11111111,   22222222,   333333333,   44444444};");
12695   // Trailing comment in the last line.
12696   verifyFormat("int aaaaa[] = {\n"
12697                "    1, 2, 3, // comment\n"
12698                "    4, 5, 6  // comment\n"
12699                "};");
12700 
12701   // With nested lists, we should either format one item per line or all nested
12702   // lists one on line.
12703   // FIXME: For some nested lists, we can do better.
12704   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12705                "        {aaaaaaaaaaaaaaaaaaa},\n"
12706                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12707                "        {aaaaaaaaaaaaaaaaa}};",
12708                getLLVMStyleWithColumns(60));
12709   verifyFormat(
12710       "SomeStruct my_struct_array = {\n"
12711       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12712       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12713       "    {aaa, aaa},\n"
12714       "    {aaa, aaa},\n"
12715       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12716       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12717       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12718 
12719   // No column layout should be used here.
12720   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12721                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12722 
12723   verifyNoCrash("a<,");
12724 
12725   // No braced initializer here.
12726   verifyFormat("void f() {\n"
12727                "  struct Dummy {};\n"
12728                "  f(v);\n"
12729                "}");
12730 
12731   // Long lists should be formatted in columns even if they are nested.
12732   verifyFormat(
12733       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12734       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12735       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12736       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12737       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12738       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12739 
12740   // Allow "single-column" layout even if that violates the column limit. There
12741   // isn't going to be a better way.
12742   verifyFormat("std::vector<int> a = {\n"
12743                "    aaaaaaaa,\n"
12744                "    aaaaaaaa,\n"
12745                "    aaaaaaaa,\n"
12746                "    aaaaaaaa,\n"
12747                "    aaaaaaaaaa,\n"
12748                "    aaaaaaaa,\n"
12749                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12750                getLLVMStyleWithColumns(30));
12751   verifyFormat("vector<int> aaaa = {\n"
12752                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12753                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12754                "    aaaaaa.aaaaaaa,\n"
12755                "    aaaaaa.aaaaaaa,\n"
12756                "    aaaaaa.aaaaaaa,\n"
12757                "    aaaaaa.aaaaaaa,\n"
12758                "};");
12759 
12760   // Don't create hanging lists.
12761   verifyFormat("someFunction(Param, {List1, List2,\n"
12762                "                     List3});",
12763                getLLVMStyleWithColumns(35));
12764   verifyFormat("someFunction(Param, Param,\n"
12765                "             {List1, List2,\n"
12766                "              List3});",
12767                getLLVMStyleWithColumns(35));
12768   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12769                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12770 }
12771 
12772 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12773   FormatStyle DoNotMerge = getLLVMStyle();
12774   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12775 
12776   verifyFormat("void f() { return 42; }");
12777   verifyFormat("void f() {\n"
12778                "  return 42;\n"
12779                "}",
12780                DoNotMerge);
12781   verifyFormat("void f() {\n"
12782                "  // Comment\n"
12783                "}");
12784   verifyFormat("{\n"
12785                "#error {\n"
12786                "  int a;\n"
12787                "}");
12788   verifyFormat("{\n"
12789                "  int a;\n"
12790                "#error {\n"
12791                "}");
12792   verifyFormat("void f() {} // comment");
12793   verifyFormat("void f() { int a; } // comment");
12794   verifyFormat("void f() {\n"
12795                "} // comment",
12796                DoNotMerge);
12797   verifyFormat("void f() {\n"
12798                "  int a;\n"
12799                "} // comment",
12800                DoNotMerge);
12801   verifyFormat("void f() {\n"
12802                "} // comment",
12803                getLLVMStyleWithColumns(15));
12804 
12805   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12806   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12807 
12808   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12809   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12810   verifyFormat("class C {\n"
12811                "  C()\n"
12812                "      : iiiiiiii(nullptr),\n"
12813                "        kkkkkkk(nullptr),\n"
12814                "        mmmmmmm(nullptr),\n"
12815                "        nnnnnnn(nullptr) {}\n"
12816                "};",
12817                getGoogleStyle());
12818 
12819   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12820   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12821   EXPECT_EQ("class C {\n"
12822             "  A() : b(0) {}\n"
12823             "};",
12824             format("class C{A():b(0){}};", NoColumnLimit));
12825   EXPECT_EQ("A()\n"
12826             "    : b(0) {\n"
12827             "}",
12828             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12829 
12830   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12831   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12832       FormatStyle::SFS_None;
12833   EXPECT_EQ("A()\n"
12834             "    : b(0) {\n"
12835             "}",
12836             format("A():b(0){}", DoNotMergeNoColumnLimit));
12837   EXPECT_EQ("A()\n"
12838             "    : b(0) {\n"
12839             "}",
12840             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12841 
12842   verifyFormat("#define A          \\\n"
12843                "  void f() {       \\\n"
12844                "    int i;         \\\n"
12845                "  }",
12846                getLLVMStyleWithColumns(20));
12847   verifyFormat("#define A           \\\n"
12848                "  void f() { int i; }",
12849                getLLVMStyleWithColumns(21));
12850   verifyFormat("#define A            \\\n"
12851                "  void f() {         \\\n"
12852                "    int i;           \\\n"
12853                "  }                  \\\n"
12854                "  int j;",
12855                getLLVMStyleWithColumns(22));
12856   verifyFormat("#define A             \\\n"
12857                "  void f() { int i; } \\\n"
12858                "  int j;",
12859                getLLVMStyleWithColumns(23));
12860 }
12861 
12862 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12863   FormatStyle MergeEmptyOnly = getLLVMStyle();
12864   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12865   verifyFormat("class C {\n"
12866                "  int f() {}\n"
12867                "};",
12868                MergeEmptyOnly);
12869   verifyFormat("class C {\n"
12870                "  int f() {\n"
12871                "    return 42;\n"
12872                "  }\n"
12873                "};",
12874                MergeEmptyOnly);
12875   verifyFormat("int f() {}", MergeEmptyOnly);
12876   verifyFormat("int f() {\n"
12877                "  return 42;\n"
12878                "}",
12879                MergeEmptyOnly);
12880 
12881   // Also verify behavior when BraceWrapping.AfterFunction = true
12882   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12883   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12884   verifyFormat("int f() {}", MergeEmptyOnly);
12885   verifyFormat("class C {\n"
12886                "  int f() {}\n"
12887                "};",
12888                MergeEmptyOnly);
12889 }
12890 
12891 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12892   FormatStyle MergeInlineOnly = getLLVMStyle();
12893   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12894   verifyFormat("class C {\n"
12895                "  int f() { return 42; }\n"
12896                "};",
12897                MergeInlineOnly);
12898   verifyFormat("int f() {\n"
12899                "  return 42;\n"
12900                "}",
12901                MergeInlineOnly);
12902 
12903   // SFS_Inline implies SFS_Empty
12904   verifyFormat("class C {\n"
12905                "  int f() {}\n"
12906                "};",
12907                MergeInlineOnly);
12908   verifyFormat("int f() {}", MergeInlineOnly);
12909   // https://llvm.org/PR54147
12910   verifyFormat("auto lambda = []() {\n"
12911                "  // comment\n"
12912                "  f();\n"
12913                "  g();\n"
12914                "};",
12915                MergeInlineOnly);
12916 
12917   verifyFormat("class C {\n"
12918                "#ifdef A\n"
12919                "  int f() { return 42; }\n"
12920                "#endif\n"
12921                "};",
12922                MergeInlineOnly);
12923 
12924   verifyFormat("struct S {\n"
12925                "// comment\n"
12926                "#ifdef FOO\n"
12927                "  int foo() { bar(); }\n"
12928                "#endif\n"
12929                "};",
12930                MergeInlineOnly);
12931 
12932   // Also verify behavior when BraceWrapping.AfterFunction = true
12933   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12934   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12935   verifyFormat("class C {\n"
12936                "  int f() { return 42; }\n"
12937                "};",
12938                MergeInlineOnly);
12939   verifyFormat("int f()\n"
12940                "{\n"
12941                "  return 42;\n"
12942                "}",
12943                MergeInlineOnly);
12944 
12945   // SFS_Inline implies SFS_Empty
12946   verifyFormat("int f() {}", MergeInlineOnly);
12947   verifyFormat("class C {\n"
12948                "  int f() {}\n"
12949                "};",
12950                MergeInlineOnly);
12951 
12952   MergeInlineOnly.BraceWrapping.AfterClass = true;
12953   MergeInlineOnly.BraceWrapping.AfterStruct = true;
12954   verifyFormat("class C\n"
12955                "{\n"
12956                "  int f() { return 42; }\n"
12957                "};",
12958                MergeInlineOnly);
12959   verifyFormat("struct C\n"
12960                "{\n"
12961                "  int f() { return 42; }\n"
12962                "};",
12963                MergeInlineOnly);
12964   verifyFormat("int f()\n"
12965                "{\n"
12966                "  return 42;\n"
12967                "}",
12968                MergeInlineOnly);
12969   verifyFormat("int f() {}", MergeInlineOnly);
12970   verifyFormat("class C\n"
12971                "{\n"
12972                "  int f() { return 42; }\n"
12973                "};",
12974                MergeInlineOnly);
12975   verifyFormat("struct C\n"
12976                "{\n"
12977                "  int f() { return 42; }\n"
12978                "};",
12979                MergeInlineOnly);
12980   verifyFormat("struct C\n"
12981                "// comment\n"
12982                "/* comment */\n"
12983                "// comment\n"
12984                "{\n"
12985                "  int f() { return 42; }\n"
12986                "};",
12987                MergeInlineOnly);
12988   verifyFormat("/* comment */ struct C\n"
12989                "{\n"
12990                "  int f() { return 42; }\n"
12991                "};",
12992                MergeInlineOnly);
12993 }
12994 
12995 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12996   FormatStyle MergeInlineOnly = getLLVMStyle();
12997   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12998       FormatStyle::SFS_InlineOnly;
12999   verifyFormat("class C {\n"
13000                "  int f() { return 42; }\n"
13001                "};",
13002                MergeInlineOnly);
13003   verifyFormat("int f() {\n"
13004                "  return 42;\n"
13005                "}",
13006                MergeInlineOnly);
13007 
13008   // SFS_InlineOnly does not imply SFS_Empty
13009   verifyFormat("class C {\n"
13010                "  int f() {}\n"
13011                "};",
13012                MergeInlineOnly);
13013   verifyFormat("int f() {\n"
13014                "}",
13015                MergeInlineOnly);
13016 
13017   // Also verify behavior when BraceWrapping.AfterFunction = true
13018   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
13019   MergeInlineOnly.BraceWrapping.AfterFunction = true;
13020   verifyFormat("class C {\n"
13021                "  int f() { return 42; }\n"
13022                "};",
13023                MergeInlineOnly);
13024   verifyFormat("int f()\n"
13025                "{\n"
13026                "  return 42;\n"
13027                "}",
13028                MergeInlineOnly);
13029 
13030   // SFS_InlineOnly does not imply SFS_Empty
13031   verifyFormat("int f()\n"
13032                "{\n"
13033                "}",
13034                MergeInlineOnly);
13035   verifyFormat("class C {\n"
13036                "  int f() {}\n"
13037                "};",
13038                MergeInlineOnly);
13039 }
13040 
13041 TEST_F(FormatTest, SplitEmptyFunction) {
13042   FormatStyle Style = getLLVMStyleWithColumns(40);
13043   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
13044   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13045   Style.BraceWrapping.AfterFunction = true;
13046   Style.BraceWrapping.SplitEmptyFunction = false;
13047 
13048   verifyFormat("int f()\n"
13049                "{}",
13050                Style);
13051   verifyFormat("int f()\n"
13052                "{\n"
13053                "  return 42;\n"
13054                "}",
13055                Style);
13056   verifyFormat("int f()\n"
13057                "{\n"
13058                "  // some comment\n"
13059                "}",
13060                Style);
13061 
13062   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
13063   verifyFormat("int f() {}", Style);
13064   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13065                "{}",
13066                Style);
13067   verifyFormat("int f()\n"
13068                "{\n"
13069                "  return 0;\n"
13070                "}",
13071                Style);
13072 
13073   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
13074   verifyFormat("class Foo {\n"
13075                "  int f() {}\n"
13076                "};\n",
13077                Style);
13078   verifyFormat("class Foo {\n"
13079                "  int f() { return 0; }\n"
13080                "};\n",
13081                Style);
13082   verifyFormat("class Foo {\n"
13083                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13084                "  {}\n"
13085                "};\n",
13086                Style);
13087   verifyFormat("class Foo {\n"
13088                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13089                "  {\n"
13090                "    return 0;\n"
13091                "  }\n"
13092                "};\n",
13093                Style);
13094 
13095   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
13096   verifyFormat("int f() {}", Style);
13097   verifyFormat("int f() { return 0; }", Style);
13098   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13099                "{}",
13100                Style);
13101   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13102                "{\n"
13103                "  return 0;\n"
13104                "}",
13105                Style);
13106 }
13107 
13108 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
13109   FormatStyle Style = getLLVMStyleWithColumns(40);
13110   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
13111   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13112   Style.BraceWrapping.AfterFunction = true;
13113   Style.BraceWrapping.SplitEmptyFunction = true;
13114   Style.BraceWrapping.SplitEmptyRecord = false;
13115 
13116   verifyFormat("class C {};", Style);
13117   verifyFormat("struct C {};", Style);
13118   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
13119                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
13120                "{\n"
13121                "}",
13122                Style);
13123   verifyFormat("class C {\n"
13124                "  C()\n"
13125                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
13126                "        bbbbbbbbbbbbbbbbbbb()\n"
13127                "  {\n"
13128                "  }\n"
13129                "  void\n"
13130                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
13131                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
13132                "  {\n"
13133                "  }\n"
13134                "};",
13135                Style);
13136 }
13137 
13138 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
13139   FormatStyle Style = getLLVMStyle();
13140   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
13141   verifyFormat("#ifdef A\n"
13142                "int f() {}\n"
13143                "#else\n"
13144                "int g() {}\n"
13145                "#endif",
13146                Style);
13147 }
13148 
13149 TEST_F(FormatTest, SplitEmptyClass) {
13150   FormatStyle Style = getLLVMStyle();
13151   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13152   Style.BraceWrapping.AfterClass = true;
13153   Style.BraceWrapping.SplitEmptyRecord = false;
13154 
13155   verifyFormat("class Foo\n"
13156                "{};",
13157                Style);
13158   verifyFormat("/* something */ class Foo\n"
13159                "{};",
13160                Style);
13161   verifyFormat("template <typename X> class Foo\n"
13162                "{};",
13163                Style);
13164   verifyFormat("class Foo\n"
13165                "{\n"
13166                "  Foo();\n"
13167                "};",
13168                Style);
13169   verifyFormat("typedef class Foo\n"
13170                "{\n"
13171                "} Foo_t;",
13172                Style);
13173 
13174   Style.BraceWrapping.SplitEmptyRecord = true;
13175   Style.BraceWrapping.AfterStruct = true;
13176   verifyFormat("class rep\n"
13177                "{\n"
13178                "};",
13179                Style);
13180   verifyFormat("struct rep\n"
13181                "{\n"
13182                "};",
13183                Style);
13184   verifyFormat("template <typename T> class rep\n"
13185                "{\n"
13186                "};",
13187                Style);
13188   verifyFormat("template <typename T> struct rep\n"
13189                "{\n"
13190                "};",
13191                Style);
13192   verifyFormat("class rep\n"
13193                "{\n"
13194                "  int x;\n"
13195                "};",
13196                Style);
13197   verifyFormat("struct rep\n"
13198                "{\n"
13199                "  int x;\n"
13200                "};",
13201                Style);
13202   verifyFormat("template <typename T> class rep\n"
13203                "{\n"
13204                "  int x;\n"
13205                "};",
13206                Style);
13207   verifyFormat("template <typename T> struct rep\n"
13208                "{\n"
13209                "  int x;\n"
13210                "};",
13211                Style);
13212   verifyFormat("template <typename T> class rep // Foo\n"
13213                "{\n"
13214                "  int x;\n"
13215                "};",
13216                Style);
13217   verifyFormat("template <typename T> struct rep // Bar\n"
13218                "{\n"
13219                "  int x;\n"
13220                "};",
13221                Style);
13222 
13223   verifyFormat("template <typename T> class rep<T>\n"
13224                "{\n"
13225                "  int x;\n"
13226                "};",
13227                Style);
13228 
13229   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13230                "{\n"
13231                "  int x;\n"
13232                "};",
13233                Style);
13234   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13235                "{\n"
13236                "};",
13237                Style);
13238 
13239   verifyFormat("#include \"stdint.h\"\n"
13240                "namespace rep {}",
13241                Style);
13242   verifyFormat("#include <stdint.h>\n"
13243                "namespace rep {}",
13244                Style);
13245   verifyFormat("#include <stdint.h>\n"
13246                "namespace rep {}",
13247                "#include <stdint.h>\n"
13248                "namespace rep {\n"
13249                "\n"
13250                "\n"
13251                "}",
13252                Style);
13253 }
13254 
13255 TEST_F(FormatTest, SplitEmptyStruct) {
13256   FormatStyle Style = getLLVMStyle();
13257   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13258   Style.BraceWrapping.AfterStruct = true;
13259   Style.BraceWrapping.SplitEmptyRecord = false;
13260 
13261   verifyFormat("struct Foo\n"
13262                "{};",
13263                Style);
13264   verifyFormat("/* something */ struct Foo\n"
13265                "{};",
13266                Style);
13267   verifyFormat("template <typename X> struct Foo\n"
13268                "{};",
13269                Style);
13270   verifyFormat("struct Foo\n"
13271                "{\n"
13272                "  Foo();\n"
13273                "};",
13274                Style);
13275   verifyFormat("typedef struct Foo\n"
13276                "{\n"
13277                "} Foo_t;",
13278                Style);
13279   // typedef struct Bar {} Bar_t;
13280 }
13281 
13282 TEST_F(FormatTest, SplitEmptyUnion) {
13283   FormatStyle Style = getLLVMStyle();
13284   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13285   Style.BraceWrapping.AfterUnion = true;
13286   Style.BraceWrapping.SplitEmptyRecord = false;
13287 
13288   verifyFormat("union Foo\n"
13289                "{};",
13290                Style);
13291   verifyFormat("/* something */ union Foo\n"
13292                "{};",
13293                Style);
13294   verifyFormat("union Foo\n"
13295                "{\n"
13296                "  A,\n"
13297                "};",
13298                Style);
13299   verifyFormat("typedef union Foo\n"
13300                "{\n"
13301                "} Foo_t;",
13302                Style);
13303 }
13304 
13305 TEST_F(FormatTest, SplitEmptyNamespace) {
13306   FormatStyle Style = getLLVMStyle();
13307   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13308   Style.BraceWrapping.AfterNamespace = true;
13309   Style.BraceWrapping.SplitEmptyNamespace = false;
13310 
13311   verifyFormat("namespace Foo\n"
13312                "{};",
13313                Style);
13314   verifyFormat("/* something */ namespace Foo\n"
13315                "{};",
13316                Style);
13317   verifyFormat("inline namespace Foo\n"
13318                "{};",
13319                Style);
13320   verifyFormat("/* something */ inline namespace Foo\n"
13321                "{};",
13322                Style);
13323   verifyFormat("export namespace Foo\n"
13324                "{};",
13325                Style);
13326   verifyFormat("namespace Foo\n"
13327                "{\n"
13328                "void Bar();\n"
13329                "};",
13330                Style);
13331 }
13332 
13333 TEST_F(FormatTest, NeverMergeShortRecords) {
13334   FormatStyle Style = getLLVMStyle();
13335 
13336   verifyFormat("class Foo {\n"
13337                "  Foo();\n"
13338                "};",
13339                Style);
13340   verifyFormat("typedef class Foo {\n"
13341                "  Foo();\n"
13342                "} Foo_t;",
13343                Style);
13344   verifyFormat("struct Foo {\n"
13345                "  Foo();\n"
13346                "};",
13347                Style);
13348   verifyFormat("typedef struct Foo {\n"
13349                "  Foo();\n"
13350                "} Foo_t;",
13351                Style);
13352   verifyFormat("union Foo {\n"
13353                "  A,\n"
13354                "};",
13355                Style);
13356   verifyFormat("typedef union Foo {\n"
13357                "  A,\n"
13358                "} Foo_t;",
13359                Style);
13360   verifyFormat("namespace Foo {\n"
13361                "void Bar();\n"
13362                "};",
13363                Style);
13364 
13365   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13366   Style.BraceWrapping.AfterClass = true;
13367   Style.BraceWrapping.AfterStruct = true;
13368   Style.BraceWrapping.AfterUnion = true;
13369   Style.BraceWrapping.AfterNamespace = true;
13370   verifyFormat("class Foo\n"
13371                "{\n"
13372                "  Foo();\n"
13373                "};",
13374                Style);
13375   verifyFormat("typedef class Foo\n"
13376                "{\n"
13377                "  Foo();\n"
13378                "} Foo_t;",
13379                Style);
13380   verifyFormat("struct Foo\n"
13381                "{\n"
13382                "  Foo();\n"
13383                "};",
13384                Style);
13385   verifyFormat("typedef struct Foo\n"
13386                "{\n"
13387                "  Foo();\n"
13388                "} Foo_t;",
13389                Style);
13390   verifyFormat("union Foo\n"
13391                "{\n"
13392                "  A,\n"
13393                "};",
13394                Style);
13395   verifyFormat("typedef union Foo\n"
13396                "{\n"
13397                "  A,\n"
13398                "} Foo_t;",
13399                Style);
13400   verifyFormat("namespace Foo\n"
13401                "{\n"
13402                "void Bar();\n"
13403                "};",
13404                Style);
13405 }
13406 
13407 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
13408   // Elaborate type variable declarations.
13409   verifyFormat("struct foo a = {bar};\nint n;");
13410   verifyFormat("class foo a = {bar};\nint n;");
13411   verifyFormat("union foo a = {bar};\nint n;");
13412 
13413   // Elaborate types inside function definitions.
13414   verifyFormat("struct foo f() {}\nint n;");
13415   verifyFormat("class foo f() {}\nint n;");
13416   verifyFormat("union foo f() {}\nint n;");
13417 
13418   // Templates.
13419   verifyFormat("template <class X> void f() {}\nint n;");
13420   verifyFormat("template <struct X> void f() {}\nint n;");
13421   verifyFormat("template <union X> void f() {}\nint n;");
13422 
13423   // Actual definitions...
13424   verifyFormat("struct {\n} n;");
13425   verifyFormat(
13426       "template <template <class T, class Y>, class Z> class X {\n} n;");
13427   verifyFormat("union Z {\n  int n;\n} x;");
13428   verifyFormat("class MACRO Z {\n} n;");
13429   verifyFormat("class MACRO(X) Z {\n} n;");
13430   verifyFormat("class __attribute__(X) Z {\n} n;");
13431   verifyFormat("class __declspec(X) Z {\n} n;");
13432   verifyFormat("class A##B##C {\n} n;");
13433   verifyFormat("class alignas(16) Z {\n} n;");
13434   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
13435   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
13436 
13437   // Redefinition from nested context:
13438   verifyFormat("class A::B::C {\n} n;");
13439 
13440   // Template definitions.
13441   verifyFormat(
13442       "template <typename F>\n"
13443       "Matcher(const Matcher<F> &Other,\n"
13444       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
13445       "                             !is_same<F, T>::value>::type * = 0)\n"
13446       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
13447 
13448   // FIXME: This is still incorrectly handled at the formatter side.
13449   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
13450   verifyFormat("int i = SomeFunction(a<b, a> b);");
13451 
13452   // FIXME:
13453   // This now gets parsed incorrectly as class definition.
13454   // verifyFormat("class A<int> f() {\n}\nint n;");
13455 
13456   // Elaborate types where incorrectly parsing the structural element would
13457   // break the indent.
13458   verifyFormat("if (true)\n"
13459                "  class X x;\n"
13460                "else\n"
13461                "  f();\n");
13462 
13463   // This is simply incomplete. Formatting is not important, but must not crash.
13464   verifyFormat("class A:");
13465 }
13466 
13467 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
13468   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
13469             format("#error Leave     all         white!!!!! space* alone!\n"));
13470   EXPECT_EQ(
13471       "#warning Leave     all         white!!!!! space* alone!\n",
13472       format("#warning Leave     all         white!!!!! space* alone!\n"));
13473   EXPECT_EQ("#error 1", format("  #  error   1"));
13474   EXPECT_EQ("#warning 1", format("  #  warning 1"));
13475 }
13476 
13477 TEST_F(FormatTest, FormatHashIfExpressions) {
13478   verifyFormat("#if AAAA && BBBB");
13479   verifyFormat("#if (AAAA && BBBB)");
13480   verifyFormat("#elif (AAAA && BBBB)");
13481   // FIXME: Come up with a better indentation for #elif.
13482   verifyFormat(
13483       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
13484       "    defined(BBBBBBBB)\n"
13485       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
13486       "    defined(BBBBBBBB)\n"
13487       "#endif",
13488       getLLVMStyleWithColumns(65));
13489 }
13490 
13491 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
13492   FormatStyle AllowsMergedIf = getGoogleStyle();
13493   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
13494       FormatStyle::SIS_WithoutElse;
13495   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
13496   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
13497   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
13498   EXPECT_EQ("if (true) return 42;",
13499             format("if (true)\nreturn 42;", AllowsMergedIf));
13500   FormatStyle ShortMergedIf = AllowsMergedIf;
13501   ShortMergedIf.ColumnLimit = 25;
13502   verifyFormat("#define A \\\n"
13503                "  if (true) return 42;",
13504                ShortMergedIf);
13505   verifyFormat("#define A \\\n"
13506                "  f();    \\\n"
13507                "  if (true)\n"
13508                "#define B",
13509                ShortMergedIf);
13510   verifyFormat("#define A \\\n"
13511                "  f();    \\\n"
13512                "  if (true)\n"
13513                "g();",
13514                ShortMergedIf);
13515   verifyFormat("{\n"
13516                "#ifdef A\n"
13517                "  // Comment\n"
13518                "  if (true) continue;\n"
13519                "#endif\n"
13520                "  // Comment\n"
13521                "  if (true) continue;\n"
13522                "}",
13523                ShortMergedIf);
13524   ShortMergedIf.ColumnLimit = 33;
13525   verifyFormat("#define A \\\n"
13526                "  if constexpr (true) return 42;",
13527                ShortMergedIf);
13528   verifyFormat("#define A \\\n"
13529                "  if CONSTEXPR (true) return 42;",
13530                ShortMergedIf);
13531   ShortMergedIf.ColumnLimit = 29;
13532   verifyFormat("#define A                   \\\n"
13533                "  if (aaaaaaaaaa) return 1; \\\n"
13534                "  return 2;",
13535                ShortMergedIf);
13536   ShortMergedIf.ColumnLimit = 28;
13537   verifyFormat("#define A         \\\n"
13538                "  if (aaaaaaaaaa) \\\n"
13539                "    return 1;     \\\n"
13540                "  return 2;",
13541                ShortMergedIf);
13542   verifyFormat("#define A                \\\n"
13543                "  if constexpr (aaaaaaa) \\\n"
13544                "    return 1;            \\\n"
13545                "  return 2;",
13546                ShortMergedIf);
13547   verifyFormat("#define A                \\\n"
13548                "  if CONSTEXPR (aaaaaaa) \\\n"
13549                "    return 1;            \\\n"
13550                "  return 2;",
13551                ShortMergedIf);
13552 
13553   verifyFormat("//\n"
13554                "#define a \\\n"
13555                "  if      \\\n"
13556                "  0",
13557                getChromiumStyle(FormatStyle::LK_Cpp));
13558 }
13559 
13560 TEST_F(FormatTest, FormatStarDependingOnContext) {
13561   verifyFormat("void f(int *a);");
13562   verifyFormat("void f() { f(fint * b); }");
13563   verifyFormat("class A {\n  void f(int *a);\n};");
13564   verifyFormat("class A {\n  int *a;\n};");
13565   verifyFormat("namespace a {\n"
13566                "namespace b {\n"
13567                "class A {\n"
13568                "  void f() {}\n"
13569                "  int *a;\n"
13570                "};\n"
13571                "} // namespace b\n"
13572                "} // namespace a");
13573 }
13574 
13575 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13576   verifyFormat("while");
13577   verifyFormat("operator");
13578 }
13579 
13580 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13581   // This code would be painfully slow to format if we didn't skip it.
13582   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
13583                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13584                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13585                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13586                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13587                    "A(1, 1)\n"
13588                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
13589                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13590                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13591                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13592                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13593                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13594                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13595                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13596                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13597                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
13598   // Deeply nested part is untouched, rest is formatted.
13599   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13600             format(std::string("int    i;\n") + Code + "int    j;\n",
13601                    getLLVMStyle(), SC_ExpectIncomplete));
13602 }
13603 
13604 //===----------------------------------------------------------------------===//
13605 // Objective-C tests.
13606 //===----------------------------------------------------------------------===//
13607 
13608 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13609   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13610   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13611             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13612   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13613   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13614   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13615             format("-(NSInteger)Method3:(id)anObject;"));
13616   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13617             format("-(NSInteger)Method4:(id)anObject;"));
13618   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13619             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13620   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13621             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13622   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13623             "forAllCells:(BOOL)flag;",
13624             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13625                    "forAllCells:(BOOL)flag;"));
13626 
13627   // Very long objectiveC method declaration.
13628   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13629                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13630   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13631                "                    inRange:(NSRange)range\n"
13632                "                   outRange:(NSRange)out_range\n"
13633                "                  outRange1:(NSRange)out_range1\n"
13634                "                  outRange2:(NSRange)out_range2\n"
13635                "                  outRange3:(NSRange)out_range3\n"
13636                "                  outRange4:(NSRange)out_range4\n"
13637                "                  outRange5:(NSRange)out_range5\n"
13638                "                  outRange6:(NSRange)out_range6\n"
13639                "                  outRange7:(NSRange)out_range7\n"
13640                "                  outRange8:(NSRange)out_range8\n"
13641                "                  outRange9:(NSRange)out_range9;");
13642 
13643   // When the function name has to be wrapped.
13644   FormatStyle Style = getLLVMStyle();
13645   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13646   // and always indents instead.
13647   Style.IndentWrappedFunctionNames = false;
13648   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13649                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13650                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13651                "}",
13652                Style);
13653   Style.IndentWrappedFunctionNames = true;
13654   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13655                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13656                "               anotherName:(NSString)dddddddddddddd {\n"
13657                "}",
13658                Style);
13659 
13660   verifyFormat("- (int)sum:(vector<int>)numbers;");
13661   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13662   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13663   // protocol lists (but not for template classes):
13664   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13665 
13666   verifyFormat("- (int (*)())foo:(int (*)())f;");
13667   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13668 
13669   // If there's no return type (very rare in practice!), LLVM and Google style
13670   // agree.
13671   verifyFormat("- foo;");
13672   verifyFormat("- foo:(int)f;");
13673   verifyGoogleFormat("- foo:(int)foo;");
13674 }
13675 
13676 TEST_F(FormatTest, BreaksStringLiterals) {
13677   EXPECT_EQ("\"some text \"\n"
13678             "\"other\";",
13679             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13680   EXPECT_EQ("\"some text \"\n"
13681             "\"other\";",
13682             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13683   EXPECT_EQ(
13684       "#define A  \\\n"
13685       "  \"some \"  \\\n"
13686       "  \"text \"  \\\n"
13687       "  \"other\";",
13688       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13689   EXPECT_EQ(
13690       "#define A  \\\n"
13691       "  \"so \"    \\\n"
13692       "  \"text \"  \\\n"
13693       "  \"other\";",
13694       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13695 
13696   EXPECT_EQ("\"some text\"",
13697             format("\"some text\"", getLLVMStyleWithColumns(1)));
13698   EXPECT_EQ("\"some text\"",
13699             format("\"some text\"", getLLVMStyleWithColumns(11)));
13700   EXPECT_EQ("\"some \"\n"
13701             "\"text\"",
13702             format("\"some text\"", getLLVMStyleWithColumns(10)));
13703   EXPECT_EQ("\"some \"\n"
13704             "\"text\"",
13705             format("\"some text\"", getLLVMStyleWithColumns(7)));
13706   EXPECT_EQ("\"some\"\n"
13707             "\" tex\"\n"
13708             "\"t\"",
13709             format("\"some text\"", getLLVMStyleWithColumns(6)));
13710   EXPECT_EQ("\"some\"\n"
13711             "\" tex\"\n"
13712             "\" and\"",
13713             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13714   EXPECT_EQ("\"some\"\n"
13715             "\"/tex\"\n"
13716             "\"/and\"",
13717             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13718 
13719   EXPECT_EQ("variable =\n"
13720             "    \"long string \"\n"
13721             "    \"literal\";",
13722             format("variable = \"long string literal\";",
13723                    getLLVMStyleWithColumns(20)));
13724 
13725   EXPECT_EQ("variable = f(\n"
13726             "    \"long string \"\n"
13727             "    \"literal\",\n"
13728             "    short,\n"
13729             "    loooooooooooooooooooong);",
13730             format("variable = f(\"long string literal\", short, "
13731                    "loooooooooooooooooooong);",
13732                    getLLVMStyleWithColumns(20)));
13733 
13734   EXPECT_EQ(
13735       "f(g(\"long string \"\n"
13736       "    \"literal\"),\n"
13737       "  b);",
13738       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13739   EXPECT_EQ("f(g(\"long string \"\n"
13740             "    \"literal\",\n"
13741             "    a),\n"
13742             "  b);",
13743             format("f(g(\"long string literal\", a), b);",
13744                    getLLVMStyleWithColumns(20)));
13745   EXPECT_EQ(
13746       "f(\"one two\".split(\n"
13747       "    variable));",
13748       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13749   EXPECT_EQ("f(\"one two three four five six \"\n"
13750             "  \"seven\".split(\n"
13751             "      really_looooong_variable));",
13752             format("f(\"one two three four five six seven\"."
13753                    "split(really_looooong_variable));",
13754                    getLLVMStyleWithColumns(33)));
13755 
13756   EXPECT_EQ("f(\"some \"\n"
13757             "  \"text\",\n"
13758             "  other);",
13759             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13760 
13761   // Only break as a last resort.
13762   verifyFormat(
13763       "aaaaaaaaaaaaaaaaaaaa(\n"
13764       "    aaaaaaaaaaaaaaaaaaaa,\n"
13765       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13766 
13767   EXPECT_EQ("\"splitmea\"\n"
13768             "\"trandomp\"\n"
13769             "\"oint\"",
13770             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13771 
13772   EXPECT_EQ("\"split/\"\n"
13773             "\"pathat/\"\n"
13774             "\"slashes\"",
13775             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13776 
13777   EXPECT_EQ("\"split/\"\n"
13778             "\"pathat/\"\n"
13779             "\"slashes\"",
13780             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13781   EXPECT_EQ("\"split at \"\n"
13782             "\"spaces/at/\"\n"
13783             "\"slashes.at.any$\"\n"
13784             "\"non-alphanumeric%\"\n"
13785             "\"1111111111characte\"\n"
13786             "\"rs\"",
13787             format("\"split at "
13788                    "spaces/at/"
13789                    "slashes.at."
13790                    "any$non-"
13791                    "alphanumeric%"
13792                    "1111111111characte"
13793                    "rs\"",
13794                    getLLVMStyleWithColumns(20)));
13795 
13796   // Verify that splitting the strings understands
13797   // Style::AlwaysBreakBeforeMultilineStrings.
13798   EXPECT_EQ("aaaaaaaaaaaa(\n"
13799             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13800             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13801             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13802                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13803                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13804                    getGoogleStyle()));
13805   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13806             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13807             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13808                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13809                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13810                    getGoogleStyle()));
13811   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13812             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13813             format("llvm::outs() << "
13814                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13815                    "aaaaaaaaaaaaaaaaaaa\";"));
13816   EXPECT_EQ("ffff(\n"
13817             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13818             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13819             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13820                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13821                    getGoogleStyle()));
13822 
13823   FormatStyle Style = getLLVMStyleWithColumns(12);
13824   Style.BreakStringLiterals = false;
13825   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13826 
13827   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13828   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13829   EXPECT_EQ("#define A \\\n"
13830             "  \"some \" \\\n"
13831             "  \"text \" \\\n"
13832             "  \"other\";",
13833             format("#define A \"some text other\";", AlignLeft));
13834 }
13835 
13836 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13837   EXPECT_EQ("C a = \"some more \"\n"
13838             "      \"text\";",
13839             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13840 }
13841 
13842 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13843   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13844   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13845   EXPECT_EQ("int i = a(b());",
13846             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13847 }
13848 
13849 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13850   EXPECT_EQ(
13851       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13852       "(\n"
13853       "    \"x\t\");",
13854       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13855              "aaaaaaa("
13856              "\"x\t\");"));
13857 }
13858 
13859 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13860   EXPECT_EQ(
13861       "u8\"utf8 string \"\n"
13862       "u8\"literal\";",
13863       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13864   EXPECT_EQ(
13865       "u\"utf16 string \"\n"
13866       "u\"literal\";",
13867       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13868   EXPECT_EQ(
13869       "U\"utf32 string \"\n"
13870       "U\"literal\";",
13871       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13872   EXPECT_EQ("L\"wide string \"\n"
13873             "L\"literal\";",
13874             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13875   EXPECT_EQ("@\"NSString \"\n"
13876             "@\"literal\";",
13877             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13878   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13879 
13880   // This input makes clang-format try to split the incomplete unicode escape
13881   // sequence, which used to lead to a crasher.
13882   verifyNoCrash(
13883       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13884       getLLVMStyleWithColumns(60));
13885 }
13886 
13887 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13888   FormatStyle Style = getGoogleStyleWithColumns(15);
13889   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13890   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13891   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13892   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13893   EXPECT_EQ("u8R\"x(raw literal)x\";",
13894             format("u8R\"x(raw literal)x\";", Style));
13895 }
13896 
13897 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13898   FormatStyle Style = getLLVMStyleWithColumns(20);
13899   EXPECT_EQ(
13900       "_T(\"aaaaaaaaaaaaaa\")\n"
13901       "_T(\"aaaaaaaaaaaaaa\")\n"
13902       "_T(\"aaaaaaaaaaaa\")",
13903       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13904   EXPECT_EQ("f(x,\n"
13905             "  _T(\"aaaaaaaaaaaa\")\n"
13906             "  _T(\"aaa\"),\n"
13907             "  z);",
13908             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13909 
13910   // FIXME: Handle embedded spaces in one iteration.
13911   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13912   //            "_T(\"aaaaaaaaaaaaa\")\n"
13913   //            "_T(\"aaaaaaaaaaaaa\")\n"
13914   //            "_T(\"a\")",
13915   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13916   //                   getLLVMStyleWithColumns(20)));
13917   EXPECT_EQ(
13918       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13919       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13920   EXPECT_EQ("f(\n"
13921             "#if !TEST\n"
13922             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13923             "#endif\n"
13924             ");",
13925             format("f(\n"
13926                    "#if !TEST\n"
13927                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13928                    "#endif\n"
13929                    ");"));
13930   EXPECT_EQ("f(\n"
13931             "\n"
13932             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13933             format("f(\n"
13934                    "\n"
13935                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13936   // Regression test for accessing tokens past the end of a vector in the
13937   // TokenLexer.
13938   verifyNoCrash(R"(_T(
13939 "
13940 )
13941 )");
13942 }
13943 
13944 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13945   // In a function call with two operands, the second can be broken with no line
13946   // break before it.
13947   EXPECT_EQ(
13948       "func(a, \"long long \"\n"
13949       "        \"long long\");",
13950       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13951   // In a function call with three operands, the second must be broken with a
13952   // line break before it.
13953   EXPECT_EQ("func(a,\n"
13954             "     \"long long long \"\n"
13955             "     \"long\",\n"
13956             "     c);",
13957             format("func(a, \"long long long long\", c);",
13958                    getLLVMStyleWithColumns(24)));
13959   // In a function call with three operands, the third must be broken with a
13960   // line break before it.
13961   EXPECT_EQ("func(a, b,\n"
13962             "     \"long long long \"\n"
13963             "     \"long\");",
13964             format("func(a, b, \"long long long long\");",
13965                    getLLVMStyleWithColumns(24)));
13966   // In a function call with three operands, both the second and the third must
13967   // be broken with a line break before them.
13968   EXPECT_EQ("func(a,\n"
13969             "     \"long long long \"\n"
13970             "     \"long\",\n"
13971             "     \"long long long \"\n"
13972             "     \"long\");",
13973             format("func(a, \"long long long long\", \"long long long long\");",
13974                    getLLVMStyleWithColumns(24)));
13975   // In a chain of << with two operands, the second can be broken with no line
13976   // break before it.
13977   EXPECT_EQ("a << \"line line \"\n"
13978             "     \"line\";",
13979             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13980   // In a chain of << with three operands, the second can be broken with no line
13981   // break before it.
13982   EXPECT_EQ(
13983       "abcde << \"line \"\n"
13984       "         \"line line\"\n"
13985       "      << c;",
13986       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13987   // In a chain of << with three operands, the third must be broken with a line
13988   // break before it.
13989   EXPECT_EQ(
13990       "a << b\n"
13991       "  << \"line line \"\n"
13992       "     \"line\";",
13993       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13994   // In a chain of << with three operands, the second can be broken with no line
13995   // break before it and the third must be broken with a line break before it.
13996   EXPECT_EQ("abcd << \"line line \"\n"
13997             "        \"line\"\n"
13998             "     << \"line line \"\n"
13999             "        \"line\";",
14000             format("abcd << \"line line line\" << \"line line line\";",
14001                    getLLVMStyleWithColumns(20)));
14002   // In a chain of binary operators with two operands, the second can be broken
14003   // with no line break before it.
14004   EXPECT_EQ(
14005       "abcd + \"line line \"\n"
14006       "       \"line line\";",
14007       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
14008   // In a chain of binary operators with three operands, the second must be
14009   // broken with a line break before it.
14010   EXPECT_EQ("abcd +\n"
14011             "    \"line line \"\n"
14012             "    \"line line\" +\n"
14013             "    e;",
14014             format("abcd + \"line line line line\" + e;",
14015                    getLLVMStyleWithColumns(20)));
14016   // In a function call with two operands, with AlignAfterOpenBracket enabled,
14017   // the first must be broken with a line break before it.
14018   FormatStyle Style = getLLVMStyleWithColumns(25);
14019   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14020   EXPECT_EQ("someFunction(\n"
14021             "    \"long long long \"\n"
14022             "    \"long\",\n"
14023             "    a);",
14024             format("someFunction(\"long long long long\", a);", Style));
14025 }
14026 
14027 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
14028   EXPECT_EQ(
14029       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14030       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14031       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
14032       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14033              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14034              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
14035 }
14036 
14037 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
14038   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
14039             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
14040   EXPECT_EQ("fffffffffff(g(R\"x(\n"
14041             "multiline raw string literal xxxxxxxxxxxxxx\n"
14042             ")x\",\n"
14043             "              a),\n"
14044             "            b);",
14045             format("fffffffffff(g(R\"x(\n"
14046                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14047                    ")x\", a), b);",
14048                    getGoogleStyleWithColumns(20)));
14049   EXPECT_EQ("fffffffffff(\n"
14050             "    g(R\"x(qqq\n"
14051             "multiline raw string literal xxxxxxxxxxxxxx\n"
14052             ")x\",\n"
14053             "      a),\n"
14054             "    b);",
14055             format("fffffffffff(g(R\"x(qqq\n"
14056                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14057                    ")x\", a), b);",
14058                    getGoogleStyleWithColumns(20)));
14059 
14060   EXPECT_EQ("fffffffffff(R\"x(\n"
14061             "multiline raw string literal xxxxxxxxxxxxxx\n"
14062             ")x\");",
14063             format("fffffffffff(R\"x(\n"
14064                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14065                    ")x\");",
14066                    getGoogleStyleWithColumns(20)));
14067   EXPECT_EQ("fffffffffff(R\"x(\n"
14068             "multiline raw string literal xxxxxxxxxxxxxx\n"
14069             ")x\" + bbbbbb);",
14070             format("fffffffffff(R\"x(\n"
14071                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14072                    ")x\" +   bbbbbb);",
14073                    getGoogleStyleWithColumns(20)));
14074   EXPECT_EQ("fffffffffff(\n"
14075             "    R\"x(\n"
14076             "multiline raw string literal xxxxxxxxxxxxxx\n"
14077             ")x\" +\n"
14078             "    bbbbbb);",
14079             format("fffffffffff(\n"
14080                    " R\"x(\n"
14081                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14082                    ")x\" + bbbbbb);",
14083                    getGoogleStyleWithColumns(20)));
14084   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
14085             format("fffffffffff(\n"
14086                    " R\"(single line raw string)\" + bbbbbb);"));
14087 }
14088 
14089 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
14090   verifyFormat("string a = \"unterminated;");
14091   EXPECT_EQ("function(\"unterminated,\n"
14092             "         OtherParameter);",
14093             format("function(  \"unterminated,\n"
14094                    "    OtherParameter);"));
14095 }
14096 
14097 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
14098   FormatStyle Style = getLLVMStyle();
14099   Style.Standard = FormatStyle::LS_Cpp03;
14100   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
14101             format("#define x(_a) printf(\"foo\"_a);", Style));
14102 }
14103 
14104 TEST_F(FormatTest, CppLexVersion) {
14105   FormatStyle Style = getLLVMStyle();
14106   // Formatting of x * y differs if x is a type.
14107   verifyFormat("void foo() { MACRO(a * b); }", Style);
14108   verifyFormat("void foo() { MACRO(int *b); }", Style);
14109 
14110   // LLVM style uses latest lexer.
14111   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
14112   Style.Standard = FormatStyle::LS_Cpp17;
14113   // But in c++17, char8_t isn't a keyword.
14114   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
14115 }
14116 
14117 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
14118 
14119 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
14120   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
14121             "             \"ddeeefff\");",
14122             format("someFunction(\"aaabbbcccdddeeefff\");",
14123                    getLLVMStyleWithColumns(25)));
14124   EXPECT_EQ("someFunction1234567890(\n"
14125             "    \"aaabbbcccdddeeefff\");",
14126             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14127                    getLLVMStyleWithColumns(26)));
14128   EXPECT_EQ("someFunction1234567890(\n"
14129             "    \"aaabbbcccdddeeeff\"\n"
14130             "    \"f\");",
14131             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14132                    getLLVMStyleWithColumns(25)));
14133   EXPECT_EQ("someFunction1234567890(\n"
14134             "    \"aaabbbcccdddeeeff\"\n"
14135             "    \"f\");",
14136             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14137                    getLLVMStyleWithColumns(24)));
14138   EXPECT_EQ("someFunction(\n"
14139             "    \"aaabbbcc ddde \"\n"
14140             "    \"efff\");",
14141             format("someFunction(\"aaabbbcc ddde efff\");",
14142                    getLLVMStyleWithColumns(25)));
14143   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
14144             "             \"ddeeefff\");",
14145             format("someFunction(\"aaabbbccc ddeeefff\");",
14146                    getLLVMStyleWithColumns(25)));
14147   EXPECT_EQ("someFunction1234567890(\n"
14148             "    \"aaabb \"\n"
14149             "    \"cccdddeeefff\");",
14150             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
14151                    getLLVMStyleWithColumns(25)));
14152   EXPECT_EQ("#define A          \\\n"
14153             "  string s =       \\\n"
14154             "      \"123456789\"  \\\n"
14155             "      \"0\";         \\\n"
14156             "  int i;",
14157             format("#define A string s = \"1234567890\"; int i;",
14158                    getLLVMStyleWithColumns(20)));
14159   EXPECT_EQ("someFunction(\n"
14160             "    \"aaabbbcc \"\n"
14161             "    \"dddeeefff\");",
14162             format("someFunction(\"aaabbbcc dddeeefff\");",
14163                    getLLVMStyleWithColumns(25)));
14164 }
14165 
14166 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
14167   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
14168   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
14169   EXPECT_EQ("\"test\"\n"
14170             "\"\\n\"",
14171             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
14172   EXPECT_EQ("\"tes\\\\\"\n"
14173             "\"n\"",
14174             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
14175   EXPECT_EQ("\"\\\\\\\\\"\n"
14176             "\"\\n\"",
14177             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
14178   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
14179   EXPECT_EQ("\"\\uff01\"\n"
14180             "\"test\"",
14181             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
14182   EXPECT_EQ("\"\\Uff01ff02\"",
14183             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
14184   EXPECT_EQ("\"\\x000000000001\"\n"
14185             "\"next\"",
14186             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
14187   EXPECT_EQ("\"\\x000000000001next\"",
14188             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
14189   EXPECT_EQ("\"\\x000000000001\"",
14190             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
14191   EXPECT_EQ("\"test\"\n"
14192             "\"\\000000\"\n"
14193             "\"000001\"",
14194             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
14195   EXPECT_EQ("\"test\\000\"\n"
14196             "\"00000000\"\n"
14197             "\"1\"",
14198             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
14199 }
14200 
14201 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
14202   verifyFormat("void f() {\n"
14203                "  return g() {}\n"
14204                "  void h() {}");
14205   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
14206                "g();\n"
14207                "}");
14208 }
14209 
14210 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
14211   verifyFormat(
14212       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
14213 }
14214 
14215 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
14216   verifyFormat("class X {\n"
14217                "  void f() {\n"
14218                "  }\n"
14219                "};",
14220                getLLVMStyleWithColumns(12));
14221 }
14222 
14223 TEST_F(FormatTest, ConfigurableIndentWidth) {
14224   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
14225   EightIndent.IndentWidth = 8;
14226   EightIndent.ContinuationIndentWidth = 8;
14227   verifyFormat("void f() {\n"
14228                "        someFunction();\n"
14229                "        if (true) {\n"
14230                "                f();\n"
14231                "        }\n"
14232                "}",
14233                EightIndent);
14234   verifyFormat("class X {\n"
14235                "        void f() {\n"
14236                "        }\n"
14237                "};",
14238                EightIndent);
14239   verifyFormat("int x[] = {\n"
14240                "        call(),\n"
14241                "        call()};",
14242                EightIndent);
14243 }
14244 
14245 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
14246   verifyFormat("double\n"
14247                "f();",
14248                getLLVMStyleWithColumns(8));
14249 }
14250 
14251 TEST_F(FormatTest, ConfigurableUseOfTab) {
14252   FormatStyle Tab = getLLVMStyleWithColumns(42);
14253   Tab.IndentWidth = 8;
14254   Tab.UseTab = FormatStyle::UT_Always;
14255   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14256 
14257   EXPECT_EQ("if (aaaaaaaa && // q\n"
14258             "    bb)\t\t// w\n"
14259             "\t;",
14260             format("if (aaaaaaaa &&// q\n"
14261                    "bb)// w\n"
14262                    ";",
14263                    Tab));
14264   EXPECT_EQ("if (aaa && bbb) // w\n"
14265             "\t;",
14266             format("if(aaa&&bbb)// w\n"
14267                    ";",
14268                    Tab));
14269 
14270   verifyFormat("class X {\n"
14271                "\tvoid f() {\n"
14272                "\t\tsomeFunction(parameter1,\n"
14273                "\t\t\t     parameter2);\n"
14274                "\t}\n"
14275                "};",
14276                Tab);
14277   verifyFormat("#define A                        \\\n"
14278                "\tvoid f() {               \\\n"
14279                "\t\tsomeFunction(    \\\n"
14280                "\t\t    parameter1,  \\\n"
14281                "\t\t    parameter2); \\\n"
14282                "\t}",
14283                Tab);
14284   verifyFormat("int a;\t      // x\n"
14285                "int bbbbbbbb; // x\n",
14286                Tab);
14287 
14288   FormatStyle TabAlignment = Tab;
14289   TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
14290   TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
14291   verifyFormat("unsigned long long big;\n"
14292                "char*\t\t   ptr;",
14293                TabAlignment);
14294   TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
14295   verifyFormat("unsigned long long big;\n"
14296                "char *\t\t   ptr;",
14297                TabAlignment);
14298   TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
14299   verifyFormat("unsigned long long big;\n"
14300                "char\t\t  *ptr;",
14301                TabAlignment);
14302 
14303   Tab.TabWidth = 4;
14304   Tab.IndentWidth = 8;
14305   verifyFormat("class TabWidth4Indent8 {\n"
14306                "\t\tvoid f() {\n"
14307                "\t\t\t\tsomeFunction(parameter1,\n"
14308                "\t\t\t\t\t\t\t parameter2);\n"
14309                "\t\t}\n"
14310                "};",
14311                Tab);
14312 
14313   Tab.TabWidth = 4;
14314   Tab.IndentWidth = 4;
14315   verifyFormat("class TabWidth4Indent4 {\n"
14316                "\tvoid f() {\n"
14317                "\t\tsomeFunction(parameter1,\n"
14318                "\t\t\t\t\t parameter2);\n"
14319                "\t}\n"
14320                "};",
14321                Tab);
14322 
14323   Tab.TabWidth = 8;
14324   Tab.IndentWidth = 4;
14325   verifyFormat("class TabWidth8Indent4 {\n"
14326                "    void f() {\n"
14327                "\tsomeFunction(parameter1,\n"
14328                "\t\t     parameter2);\n"
14329                "    }\n"
14330                "};",
14331                Tab);
14332 
14333   Tab.TabWidth = 8;
14334   Tab.IndentWidth = 8;
14335   EXPECT_EQ("/*\n"
14336             "\t      a\t\tcomment\n"
14337             "\t      in multiple lines\n"
14338             "       */",
14339             format("   /*\t \t \n"
14340                    " \t \t a\t\tcomment\t \t\n"
14341                    " \t \t in multiple lines\t\n"
14342                    " \t  */",
14343                    Tab));
14344 
14345   TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
14346   TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
14347   verifyFormat("void f() {\n"
14348                "\tunsigned long long big;\n"
14349                "\tchar*              ptr;\n"
14350                "}",
14351                TabAlignment);
14352   TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
14353   verifyFormat("void f() {\n"
14354                "\tunsigned long long big;\n"
14355                "\tchar *             ptr;\n"
14356                "}",
14357                TabAlignment);
14358   TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
14359   verifyFormat("void f() {\n"
14360                "\tunsigned long long big;\n"
14361                "\tchar              *ptr;\n"
14362                "}",
14363                TabAlignment);
14364 
14365   Tab.UseTab = FormatStyle::UT_ForIndentation;
14366   verifyFormat("{\n"
14367                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14368                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14369                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14370                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14371                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14372                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14373                "};",
14374                Tab);
14375   verifyFormat("enum AA {\n"
14376                "\ta1, // Force multiple lines\n"
14377                "\ta2,\n"
14378                "\ta3\n"
14379                "};",
14380                Tab);
14381   EXPECT_EQ("if (aaaaaaaa && // q\n"
14382             "    bb)         // w\n"
14383             "\t;",
14384             format("if (aaaaaaaa &&// q\n"
14385                    "bb)// w\n"
14386                    ";",
14387                    Tab));
14388   verifyFormat("class X {\n"
14389                "\tvoid f() {\n"
14390                "\t\tsomeFunction(parameter1,\n"
14391                "\t\t             parameter2);\n"
14392                "\t}\n"
14393                "};",
14394                Tab);
14395   verifyFormat("{\n"
14396                "\tQ(\n"
14397                "\t    {\n"
14398                "\t\t    int a;\n"
14399                "\t\t    someFunction(aaaaaaaa,\n"
14400                "\t\t                 bbbbbbb);\n"
14401                "\t    },\n"
14402                "\t    p);\n"
14403                "}",
14404                Tab);
14405   EXPECT_EQ("{\n"
14406             "\t/* aaaa\n"
14407             "\t   bbbb */\n"
14408             "}",
14409             format("{\n"
14410                    "/* aaaa\n"
14411                    "   bbbb */\n"
14412                    "}",
14413                    Tab));
14414   EXPECT_EQ("{\n"
14415             "\t/*\n"
14416             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14417             "\t  bbbbbbbbbbbbb\n"
14418             "\t*/\n"
14419             "}",
14420             format("{\n"
14421                    "/*\n"
14422                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14423                    "*/\n"
14424                    "}",
14425                    Tab));
14426   EXPECT_EQ("{\n"
14427             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14428             "\t// bbbbbbbbbbbbb\n"
14429             "}",
14430             format("{\n"
14431                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14432                    "}",
14433                    Tab));
14434   EXPECT_EQ("{\n"
14435             "\t/*\n"
14436             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14437             "\t  bbbbbbbbbbbbb\n"
14438             "\t*/\n"
14439             "}",
14440             format("{\n"
14441                    "\t/*\n"
14442                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14443                    "\t*/\n"
14444                    "}",
14445                    Tab));
14446   EXPECT_EQ("{\n"
14447             "\t/*\n"
14448             "\n"
14449             "\t*/\n"
14450             "}",
14451             format("{\n"
14452                    "\t/*\n"
14453                    "\n"
14454                    "\t*/\n"
14455                    "}",
14456                    Tab));
14457   EXPECT_EQ("{\n"
14458             "\t/*\n"
14459             " asdf\n"
14460             "\t*/\n"
14461             "}",
14462             format("{\n"
14463                    "\t/*\n"
14464                    " asdf\n"
14465                    "\t*/\n"
14466                    "}",
14467                    Tab));
14468 
14469   verifyFormat("void f() {\n"
14470                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14471                "\t            : bbbbbbbbbbbbbbbbbb\n"
14472                "}",
14473                Tab);
14474   FormatStyle TabNoBreak = Tab;
14475   TabNoBreak.BreakBeforeTernaryOperators = false;
14476   verifyFormat("void f() {\n"
14477                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14478                "\t              bbbbbbbbbbbbbbbbbb\n"
14479                "}",
14480                TabNoBreak);
14481   verifyFormat("void f() {\n"
14482                "\treturn true ?\n"
14483                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14484                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14485                "}",
14486                TabNoBreak);
14487 
14488   Tab.UseTab = FormatStyle::UT_Never;
14489   EXPECT_EQ("/*\n"
14490             "              a\t\tcomment\n"
14491             "              in multiple lines\n"
14492             "       */",
14493             format("   /*\t \t \n"
14494                    " \t \t a\t\tcomment\t \t\n"
14495                    " \t \t in multiple lines\t\n"
14496                    " \t  */",
14497                    Tab));
14498   EXPECT_EQ("/* some\n"
14499             "   comment */",
14500             format(" \t \t /* some\n"
14501                    " \t \t    comment */",
14502                    Tab));
14503   EXPECT_EQ("int a; /* some\n"
14504             "   comment */",
14505             format(" \t \t int a; /* some\n"
14506                    " \t \t    comment */",
14507                    Tab));
14508 
14509   EXPECT_EQ("int a; /* some\n"
14510             "comment */",
14511             format(" \t \t int\ta; /* some\n"
14512                    " \t \t    comment */",
14513                    Tab));
14514   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14515             "    comment */",
14516             format(" \t \t f(\"\t\t\"); /* some\n"
14517                    " \t \t    comment */",
14518                    Tab));
14519   EXPECT_EQ("{\n"
14520             "        /*\n"
14521             "         * Comment\n"
14522             "         */\n"
14523             "        int i;\n"
14524             "}",
14525             format("{\n"
14526                    "\t/*\n"
14527                    "\t * Comment\n"
14528                    "\t */\n"
14529                    "\t int i;\n"
14530                    "}",
14531                    Tab));
14532 
14533   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14534   Tab.TabWidth = 8;
14535   Tab.IndentWidth = 8;
14536   EXPECT_EQ("if (aaaaaaaa && // q\n"
14537             "    bb)         // w\n"
14538             "\t;",
14539             format("if (aaaaaaaa &&// q\n"
14540                    "bb)// w\n"
14541                    ";",
14542                    Tab));
14543   EXPECT_EQ("if (aaa && bbb) // w\n"
14544             "\t;",
14545             format("if(aaa&&bbb)// w\n"
14546                    ";",
14547                    Tab));
14548   verifyFormat("class X {\n"
14549                "\tvoid f() {\n"
14550                "\t\tsomeFunction(parameter1,\n"
14551                "\t\t\t     parameter2);\n"
14552                "\t}\n"
14553                "};",
14554                Tab);
14555   verifyFormat("#define A                        \\\n"
14556                "\tvoid f() {               \\\n"
14557                "\t\tsomeFunction(    \\\n"
14558                "\t\t    parameter1,  \\\n"
14559                "\t\t    parameter2); \\\n"
14560                "\t}",
14561                Tab);
14562   Tab.TabWidth = 4;
14563   Tab.IndentWidth = 8;
14564   verifyFormat("class TabWidth4Indent8 {\n"
14565                "\t\tvoid f() {\n"
14566                "\t\t\t\tsomeFunction(parameter1,\n"
14567                "\t\t\t\t\t\t\t parameter2);\n"
14568                "\t\t}\n"
14569                "};",
14570                Tab);
14571   Tab.TabWidth = 4;
14572   Tab.IndentWidth = 4;
14573   verifyFormat("class TabWidth4Indent4 {\n"
14574                "\tvoid f() {\n"
14575                "\t\tsomeFunction(parameter1,\n"
14576                "\t\t\t\t\t parameter2);\n"
14577                "\t}\n"
14578                "};",
14579                Tab);
14580   Tab.TabWidth = 8;
14581   Tab.IndentWidth = 4;
14582   verifyFormat("class TabWidth8Indent4 {\n"
14583                "    void f() {\n"
14584                "\tsomeFunction(parameter1,\n"
14585                "\t\t     parameter2);\n"
14586                "    }\n"
14587                "};",
14588                Tab);
14589   Tab.TabWidth = 8;
14590   Tab.IndentWidth = 8;
14591   EXPECT_EQ("/*\n"
14592             "\t      a\t\tcomment\n"
14593             "\t      in multiple lines\n"
14594             "       */",
14595             format("   /*\t \t \n"
14596                    " \t \t a\t\tcomment\t \t\n"
14597                    " \t \t in multiple lines\t\n"
14598                    " \t  */",
14599                    Tab));
14600   verifyFormat("{\n"
14601                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14602                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14603                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14604                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14605                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14606                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14607                "};",
14608                Tab);
14609   verifyFormat("enum AA {\n"
14610                "\ta1, // Force multiple lines\n"
14611                "\ta2,\n"
14612                "\ta3\n"
14613                "};",
14614                Tab);
14615   EXPECT_EQ("if (aaaaaaaa && // q\n"
14616             "    bb)         // w\n"
14617             "\t;",
14618             format("if (aaaaaaaa &&// q\n"
14619                    "bb)// w\n"
14620                    ";",
14621                    Tab));
14622   verifyFormat("class X {\n"
14623                "\tvoid f() {\n"
14624                "\t\tsomeFunction(parameter1,\n"
14625                "\t\t\t     parameter2);\n"
14626                "\t}\n"
14627                "};",
14628                Tab);
14629   verifyFormat("{\n"
14630                "\tQ(\n"
14631                "\t    {\n"
14632                "\t\t    int a;\n"
14633                "\t\t    someFunction(aaaaaaaa,\n"
14634                "\t\t\t\t bbbbbbb);\n"
14635                "\t    },\n"
14636                "\t    p);\n"
14637                "}",
14638                Tab);
14639   EXPECT_EQ("{\n"
14640             "\t/* aaaa\n"
14641             "\t   bbbb */\n"
14642             "}",
14643             format("{\n"
14644                    "/* aaaa\n"
14645                    "   bbbb */\n"
14646                    "}",
14647                    Tab));
14648   EXPECT_EQ("{\n"
14649             "\t/*\n"
14650             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14651             "\t  bbbbbbbbbbbbb\n"
14652             "\t*/\n"
14653             "}",
14654             format("{\n"
14655                    "/*\n"
14656                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14657                    "*/\n"
14658                    "}",
14659                    Tab));
14660   EXPECT_EQ("{\n"
14661             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14662             "\t// bbbbbbbbbbbbb\n"
14663             "}",
14664             format("{\n"
14665                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14666                    "}",
14667                    Tab));
14668   EXPECT_EQ("{\n"
14669             "\t/*\n"
14670             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14671             "\t  bbbbbbbbbbbbb\n"
14672             "\t*/\n"
14673             "}",
14674             format("{\n"
14675                    "\t/*\n"
14676                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14677                    "\t*/\n"
14678                    "}",
14679                    Tab));
14680   EXPECT_EQ("{\n"
14681             "\t/*\n"
14682             "\n"
14683             "\t*/\n"
14684             "}",
14685             format("{\n"
14686                    "\t/*\n"
14687                    "\n"
14688                    "\t*/\n"
14689                    "}",
14690                    Tab));
14691   EXPECT_EQ("{\n"
14692             "\t/*\n"
14693             " asdf\n"
14694             "\t*/\n"
14695             "}",
14696             format("{\n"
14697                    "\t/*\n"
14698                    " asdf\n"
14699                    "\t*/\n"
14700                    "}",
14701                    Tab));
14702   EXPECT_EQ("/* some\n"
14703             "   comment */",
14704             format(" \t \t /* some\n"
14705                    " \t \t    comment */",
14706                    Tab));
14707   EXPECT_EQ("int a; /* some\n"
14708             "   comment */",
14709             format(" \t \t int a; /* some\n"
14710                    " \t \t    comment */",
14711                    Tab));
14712   EXPECT_EQ("int a; /* some\n"
14713             "comment */",
14714             format(" \t \t int\ta; /* some\n"
14715                    " \t \t    comment */",
14716                    Tab));
14717   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14718             "    comment */",
14719             format(" \t \t f(\"\t\t\"); /* some\n"
14720                    " \t \t    comment */",
14721                    Tab));
14722   EXPECT_EQ("{\n"
14723             "\t/*\n"
14724             "\t * Comment\n"
14725             "\t */\n"
14726             "\tint i;\n"
14727             "}",
14728             format("{\n"
14729                    "\t/*\n"
14730                    "\t * Comment\n"
14731                    "\t */\n"
14732                    "\t int i;\n"
14733                    "}",
14734                    Tab));
14735   Tab.TabWidth = 2;
14736   Tab.IndentWidth = 2;
14737   EXPECT_EQ("{\n"
14738             "\t/* aaaa\n"
14739             "\t\t bbbb */\n"
14740             "}",
14741             format("{\n"
14742                    "/* aaaa\n"
14743                    "\t bbbb */\n"
14744                    "}",
14745                    Tab));
14746   EXPECT_EQ("{\n"
14747             "\t/*\n"
14748             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14749             "\t\tbbbbbbbbbbbbb\n"
14750             "\t*/\n"
14751             "}",
14752             format("{\n"
14753                    "/*\n"
14754                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14755                    "*/\n"
14756                    "}",
14757                    Tab));
14758   Tab.AlignConsecutiveAssignments.Enabled = true;
14759   Tab.AlignConsecutiveDeclarations.Enabled = true;
14760   Tab.TabWidth = 4;
14761   Tab.IndentWidth = 4;
14762   verifyFormat("class Assign {\n"
14763                "\tvoid f() {\n"
14764                "\t\tint         x      = 123;\n"
14765                "\t\tint         random = 4;\n"
14766                "\t\tstd::string alphabet =\n"
14767                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14768                "\t}\n"
14769                "};",
14770                Tab);
14771 
14772   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14773   Tab.TabWidth = 8;
14774   Tab.IndentWidth = 8;
14775   EXPECT_EQ("if (aaaaaaaa && // q\n"
14776             "    bb)         // w\n"
14777             "\t;",
14778             format("if (aaaaaaaa &&// q\n"
14779                    "bb)// w\n"
14780                    ";",
14781                    Tab));
14782   EXPECT_EQ("if (aaa && bbb) // w\n"
14783             "\t;",
14784             format("if(aaa&&bbb)// w\n"
14785                    ";",
14786                    Tab));
14787   verifyFormat("class X {\n"
14788                "\tvoid f() {\n"
14789                "\t\tsomeFunction(parameter1,\n"
14790                "\t\t             parameter2);\n"
14791                "\t}\n"
14792                "};",
14793                Tab);
14794   verifyFormat("#define A                        \\\n"
14795                "\tvoid f() {               \\\n"
14796                "\t\tsomeFunction(    \\\n"
14797                "\t\t    parameter1,  \\\n"
14798                "\t\t    parameter2); \\\n"
14799                "\t}",
14800                Tab);
14801   Tab.TabWidth = 4;
14802   Tab.IndentWidth = 8;
14803   verifyFormat("class TabWidth4Indent8 {\n"
14804                "\t\tvoid f() {\n"
14805                "\t\t\t\tsomeFunction(parameter1,\n"
14806                "\t\t\t\t             parameter2);\n"
14807                "\t\t}\n"
14808                "};",
14809                Tab);
14810   Tab.TabWidth = 4;
14811   Tab.IndentWidth = 4;
14812   verifyFormat("class TabWidth4Indent4 {\n"
14813                "\tvoid f() {\n"
14814                "\t\tsomeFunction(parameter1,\n"
14815                "\t\t             parameter2);\n"
14816                "\t}\n"
14817                "};",
14818                Tab);
14819   Tab.TabWidth = 8;
14820   Tab.IndentWidth = 4;
14821   verifyFormat("class TabWidth8Indent4 {\n"
14822                "    void f() {\n"
14823                "\tsomeFunction(parameter1,\n"
14824                "\t             parameter2);\n"
14825                "    }\n"
14826                "};",
14827                Tab);
14828   Tab.TabWidth = 8;
14829   Tab.IndentWidth = 8;
14830   EXPECT_EQ("/*\n"
14831             "              a\t\tcomment\n"
14832             "              in multiple lines\n"
14833             "       */",
14834             format("   /*\t \t \n"
14835                    " \t \t a\t\tcomment\t \t\n"
14836                    " \t \t in multiple lines\t\n"
14837                    " \t  */",
14838                    Tab));
14839   verifyFormat("{\n"
14840                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14841                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14842                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14843                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14844                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14845                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14846                "};",
14847                Tab);
14848   verifyFormat("enum AA {\n"
14849                "\ta1, // Force multiple lines\n"
14850                "\ta2,\n"
14851                "\ta3\n"
14852                "};",
14853                Tab);
14854   EXPECT_EQ("if (aaaaaaaa && // q\n"
14855             "    bb)         // w\n"
14856             "\t;",
14857             format("if (aaaaaaaa &&// q\n"
14858                    "bb)// w\n"
14859                    ";",
14860                    Tab));
14861   verifyFormat("class X {\n"
14862                "\tvoid f() {\n"
14863                "\t\tsomeFunction(parameter1,\n"
14864                "\t\t             parameter2);\n"
14865                "\t}\n"
14866                "};",
14867                Tab);
14868   verifyFormat("{\n"
14869                "\tQ(\n"
14870                "\t    {\n"
14871                "\t\t    int a;\n"
14872                "\t\t    someFunction(aaaaaaaa,\n"
14873                "\t\t                 bbbbbbb);\n"
14874                "\t    },\n"
14875                "\t    p);\n"
14876                "}",
14877                Tab);
14878   EXPECT_EQ("{\n"
14879             "\t/* aaaa\n"
14880             "\t   bbbb */\n"
14881             "}",
14882             format("{\n"
14883                    "/* aaaa\n"
14884                    "   bbbb */\n"
14885                    "}",
14886                    Tab));
14887   EXPECT_EQ("{\n"
14888             "\t/*\n"
14889             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14890             "\t  bbbbbbbbbbbbb\n"
14891             "\t*/\n"
14892             "}",
14893             format("{\n"
14894                    "/*\n"
14895                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14896                    "*/\n"
14897                    "}",
14898                    Tab));
14899   EXPECT_EQ("{\n"
14900             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14901             "\t// bbbbbbbbbbbbb\n"
14902             "}",
14903             format("{\n"
14904                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14905                    "}",
14906                    Tab));
14907   EXPECT_EQ("{\n"
14908             "\t/*\n"
14909             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14910             "\t  bbbbbbbbbbbbb\n"
14911             "\t*/\n"
14912             "}",
14913             format("{\n"
14914                    "\t/*\n"
14915                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14916                    "\t*/\n"
14917                    "}",
14918                    Tab));
14919   EXPECT_EQ("{\n"
14920             "\t/*\n"
14921             "\n"
14922             "\t*/\n"
14923             "}",
14924             format("{\n"
14925                    "\t/*\n"
14926                    "\n"
14927                    "\t*/\n"
14928                    "}",
14929                    Tab));
14930   EXPECT_EQ("{\n"
14931             "\t/*\n"
14932             " asdf\n"
14933             "\t*/\n"
14934             "}",
14935             format("{\n"
14936                    "\t/*\n"
14937                    " asdf\n"
14938                    "\t*/\n"
14939                    "}",
14940                    Tab));
14941   EXPECT_EQ("/* some\n"
14942             "   comment */",
14943             format(" \t \t /* some\n"
14944                    " \t \t    comment */",
14945                    Tab));
14946   EXPECT_EQ("int a; /* some\n"
14947             "   comment */",
14948             format(" \t \t int a; /* some\n"
14949                    " \t \t    comment */",
14950                    Tab));
14951   EXPECT_EQ("int a; /* some\n"
14952             "comment */",
14953             format(" \t \t int\ta; /* some\n"
14954                    " \t \t    comment */",
14955                    Tab));
14956   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14957             "    comment */",
14958             format(" \t \t f(\"\t\t\"); /* some\n"
14959                    " \t \t    comment */",
14960                    Tab));
14961   EXPECT_EQ("{\n"
14962             "\t/*\n"
14963             "\t * Comment\n"
14964             "\t */\n"
14965             "\tint i;\n"
14966             "}",
14967             format("{\n"
14968                    "\t/*\n"
14969                    "\t * Comment\n"
14970                    "\t */\n"
14971                    "\t int i;\n"
14972                    "}",
14973                    Tab));
14974   Tab.TabWidth = 2;
14975   Tab.IndentWidth = 2;
14976   EXPECT_EQ("{\n"
14977             "\t/* aaaa\n"
14978             "\t   bbbb */\n"
14979             "}",
14980             format("{\n"
14981                    "/* aaaa\n"
14982                    "   bbbb */\n"
14983                    "}",
14984                    Tab));
14985   EXPECT_EQ("{\n"
14986             "\t/*\n"
14987             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14988             "\t  bbbbbbbbbbbbb\n"
14989             "\t*/\n"
14990             "}",
14991             format("{\n"
14992                    "/*\n"
14993                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14994                    "*/\n"
14995                    "}",
14996                    Tab));
14997   Tab.AlignConsecutiveAssignments.Enabled = true;
14998   Tab.AlignConsecutiveDeclarations.Enabled = true;
14999   Tab.TabWidth = 4;
15000   Tab.IndentWidth = 4;
15001   verifyFormat("class Assign {\n"
15002                "\tvoid f() {\n"
15003                "\t\tint         x      = 123;\n"
15004                "\t\tint         random = 4;\n"
15005                "\t\tstd::string alphabet =\n"
15006                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
15007                "\t}\n"
15008                "};",
15009                Tab);
15010   Tab.AlignOperands = FormatStyle::OAS_Align;
15011   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
15012                "                 cccccccccccccccccccc;",
15013                Tab);
15014   // no alignment
15015   verifyFormat("int aaaaaaaaaa =\n"
15016                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
15017                Tab);
15018   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
15019                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
15020                "                        : 333333333333333;",
15021                Tab);
15022   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15023   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
15024   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
15025                "               + cccccccccccccccccccc;",
15026                Tab);
15027 }
15028 
15029 TEST_F(FormatTest, ZeroTabWidth) {
15030   FormatStyle Tab = getLLVMStyleWithColumns(42);
15031   Tab.IndentWidth = 8;
15032   Tab.UseTab = FormatStyle::UT_Never;
15033   Tab.TabWidth = 0;
15034   EXPECT_EQ("void a(){\n"
15035             "    // line starts with '\t'\n"
15036             "};",
15037             format("void a(){\n"
15038                    "\t// line starts with '\t'\n"
15039                    "};",
15040                    Tab));
15041 
15042   EXPECT_EQ("void a(){\n"
15043             "    // line starts with '\t'\n"
15044             "};",
15045             format("void a(){\n"
15046                    "\t\t// line starts with '\t'\n"
15047                    "};",
15048                    Tab));
15049 
15050   Tab.UseTab = FormatStyle::UT_ForIndentation;
15051   EXPECT_EQ("void a(){\n"
15052             "    // line starts with '\t'\n"
15053             "};",
15054             format("void a(){\n"
15055                    "\t// line starts with '\t'\n"
15056                    "};",
15057                    Tab));
15058 
15059   EXPECT_EQ("void a(){\n"
15060             "    // line starts with '\t'\n"
15061             "};",
15062             format("void a(){\n"
15063                    "\t\t// line starts with '\t'\n"
15064                    "};",
15065                    Tab));
15066 
15067   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
15068   EXPECT_EQ("void a(){\n"
15069             "    // line starts with '\t'\n"
15070             "};",
15071             format("void a(){\n"
15072                    "\t// line starts with '\t'\n"
15073                    "};",
15074                    Tab));
15075 
15076   EXPECT_EQ("void a(){\n"
15077             "    // line starts with '\t'\n"
15078             "};",
15079             format("void a(){\n"
15080                    "\t\t// line starts with '\t'\n"
15081                    "};",
15082                    Tab));
15083 
15084   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
15085   EXPECT_EQ("void a(){\n"
15086             "    // line starts with '\t'\n"
15087             "};",
15088             format("void a(){\n"
15089                    "\t// line starts with '\t'\n"
15090                    "};",
15091                    Tab));
15092 
15093   EXPECT_EQ("void a(){\n"
15094             "    // line starts with '\t'\n"
15095             "};",
15096             format("void a(){\n"
15097                    "\t\t// line starts with '\t'\n"
15098                    "};",
15099                    Tab));
15100 
15101   Tab.UseTab = FormatStyle::UT_Always;
15102   EXPECT_EQ("void a(){\n"
15103             "// line starts with '\t'\n"
15104             "};",
15105             format("void a(){\n"
15106                    "\t// line starts with '\t'\n"
15107                    "};",
15108                    Tab));
15109 
15110   EXPECT_EQ("void a(){\n"
15111             "// line starts with '\t'\n"
15112             "};",
15113             format("void a(){\n"
15114                    "\t\t// line starts with '\t'\n"
15115                    "};",
15116                    Tab));
15117 }
15118 
15119 TEST_F(FormatTest, CalculatesOriginalColumn) {
15120   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15121             "q\"; /* some\n"
15122             "       comment */",
15123             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15124                    "q\"; /* some\n"
15125                    "       comment */",
15126                    getLLVMStyle()));
15127   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
15128             "/* some\n"
15129             "   comment */",
15130             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
15131                    " /* some\n"
15132                    "    comment */",
15133                    getLLVMStyle()));
15134   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15135             "qqq\n"
15136             "/* some\n"
15137             "   comment */",
15138             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15139                    "qqq\n"
15140                    " /* some\n"
15141                    "    comment */",
15142                    getLLVMStyle()));
15143   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15144             "wwww; /* some\n"
15145             "         comment */",
15146             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15147                    "wwww; /* some\n"
15148                    "         comment */",
15149                    getLLVMStyle()));
15150 }
15151 
15152 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
15153   FormatStyle NoSpace = getLLVMStyle();
15154   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
15155 
15156   verifyFormat("while(true)\n"
15157                "  continue;",
15158                NoSpace);
15159   verifyFormat("for(;;)\n"
15160                "  continue;",
15161                NoSpace);
15162   verifyFormat("if(true)\n"
15163                "  f();\n"
15164                "else if(true)\n"
15165                "  f();",
15166                NoSpace);
15167   verifyFormat("do {\n"
15168                "  do_something();\n"
15169                "} while(something());",
15170                NoSpace);
15171   verifyFormat("switch(x) {\n"
15172                "default:\n"
15173                "  break;\n"
15174                "}",
15175                NoSpace);
15176   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
15177   verifyFormat("size_t x = sizeof(x);", NoSpace);
15178   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
15179   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
15180   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
15181   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
15182   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
15183   verifyFormat("alignas(128) char a[128];", NoSpace);
15184   verifyFormat("size_t x = alignof(MyType);", NoSpace);
15185   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
15186   verifyFormat("int f() throw(Deprecated);", NoSpace);
15187   verifyFormat("typedef void (*cb)(int);", NoSpace);
15188   verifyFormat("T A::operator()();", NoSpace);
15189   verifyFormat("X A::operator++(T);", NoSpace);
15190   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
15191 
15192   FormatStyle Space = getLLVMStyle();
15193   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
15194 
15195   verifyFormat("int f ();", Space);
15196   verifyFormat("void f (int a, T b) {\n"
15197                "  while (true)\n"
15198                "    continue;\n"
15199                "}",
15200                Space);
15201   verifyFormat("if (true)\n"
15202                "  f ();\n"
15203                "else if (true)\n"
15204                "  f ();",
15205                Space);
15206   verifyFormat("do {\n"
15207                "  do_something ();\n"
15208                "} while (something ());",
15209                Space);
15210   verifyFormat("switch (x) {\n"
15211                "default:\n"
15212                "  break;\n"
15213                "}",
15214                Space);
15215   verifyFormat("A::A () : a (1) {}", Space);
15216   verifyFormat("void f () __attribute__ ((asdf));", Space);
15217   verifyFormat("*(&a + 1);\n"
15218                "&((&a)[1]);\n"
15219                "a[(b + c) * d];\n"
15220                "(((a + 1) * 2) + 3) * 4;",
15221                Space);
15222   verifyFormat("#define A(x) x", Space);
15223   verifyFormat("#define A (x) x", Space);
15224   verifyFormat("#if defined(x)\n"
15225                "#endif",
15226                Space);
15227   verifyFormat("auto i = std::make_unique<int> (5);", Space);
15228   verifyFormat("size_t x = sizeof (x);", Space);
15229   verifyFormat("auto f (int x) -> decltype (x);", Space);
15230   verifyFormat("auto f (int x) -> typeof (x);", Space);
15231   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
15232   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
15233   verifyFormat("int f (T x) noexcept (x.create ());", Space);
15234   verifyFormat("alignas (128) char a[128];", Space);
15235   verifyFormat("size_t x = alignof (MyType);", Space);
15236   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
15237   verifyFormat("int f () throw (Deprecated);", Space);
15238   verifyFormat("typedef void (*cb) (int);", Space);
15239   // FIXME these tests regressed behaviour.
15240   // verifyFormat("T A::operator() ();", Space);
15241   // verifyFormat("X A::operator++ (T);", Space);
15242   verifyFormat("auto lambda = [] () { return 0; };", Space);
15243   verifyFormat("int x = int (y);", Space);
15244   verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space);
15245   verifyFormat("__builtin_LINE ()", Space);
15246   verifyFormat("__builtin_UNKNOWN ()", Space);
15247 
15248   FormatStyle SomeSpace = getLLVMStyle();
15249   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
15250 
15251   verifyFormat("[]() -> float {}", SomeSpace);
15252   verifyFormat("[] (auto foo) {}", SomeSpace);
15253   verifyFormat("[foo]() -> int {}", SomeSpace);
15254   verifyFormat("int f();", SomeSpace);
15255   verifyFormat("void f (int a, T b) {\n"
15256                "  while (true)\n"
15257                "    continue;\n"
15258                "}",
15259                SomeSpace);
15260   verifyFormat("if (true)\n"
15261                "  f();\n"
15262                "else if (true)\n"
15263                "  f();",
15264                SomeSpace);
15265   verifyFormat("do {\n"
15266                "  do_something();\n"
15267                "} while (something());",
15268                SomeSpace);
15269   verifyFormat("switch (x) {\n"
15270                "default:\n"
15271                "  break;\n"
15272                "}",
15273                SomeSpace);
15274   verifyFormat("A::A() : a (1) {}", SomeSpace);
15275   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
15276   verifyFormat("*(&a + 1);\n"
15277                "&((&a)[1]);\n"
15278                "a[(b + c) * d];\n"
15279                "(((a + 1) * 2) + 3) * 4;",
15280                SomeSpace);
15281   verifyFormat("#define A(x) x", SomeSpace);
15282   verifyFormat("#define A (x) x", SomeSpace);
15283   verifyFormat("#if defined(x)\n"
15284                "#endif",
15285                SomeSpace);
15286   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
15287   verifyFormat("size_t x = sizeof (x);", SomeSpace);
15288   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
15289   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
15290   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
15291   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
15292   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
15293   verifyFormat("alignas (128) char a[128];", SomeSpace);
15294   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
15295   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15296                SomeSpace);
15297   verifyFormat("int f() throw (Deprecated);", SomeSpace);
15298   verifyFormat("typedef void (*cb) (int);", SomeSpace);
15299   verifyFormat("T A::operator()();", SomeSpace);
15300   // FIXME these tests regressed behaviour.
15301   // verifyFormat("X A::operator++ (T);", SomeSpace);
15302   verifyFormat("int x = int (y);", SomeSpace);
15303   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
15304 
15305   FormatStyle SpaceControlStatements = getLLVMStyle();
15306   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15307   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
15308 
15309   verifyFormat("while (true)\n"
15310                "  continue;",
15311                SpaceControlStatements);
15312   verifyFormat("if (true)\n"
15313                "  f();\n"
15314                "else if (true)\n"
15315                "  f();",
15316                SpaceControlStatements);
15317   verifyFormat("for (;;) {\n"
15318                "  do_something();\n"
15319                "}",
15320                SpaceControlStatements);
15321   verifyFormat("do {\n"
15322                "  do_something();\n"
15323                "} while (something());",
15324                SpaceControlStatements);
15325   verifyFormat("switch (x) {\n"
15326                "default:\n"
15327                "  break;\n"
15328                "}",
15329                SpaceControlStatements);
15330 
15331   FormatStyle SpaceFuncDecl = getLLVMStyle();
15332   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15333   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
15334 
15335   verifyFormat("int f ();", SpaceFuncDecl);
15336   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
15337   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
15338   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
15339   verifyFormat("#define A(x) x", SpaceFuncDecl);
15340   verifyFormat("#define A (x) x", SpaceFuncDecl);
15341   verifyFormat("#if defined(x)\n"
15342                "#endif",
15343                SpaceFuncDecl);
15344   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
15345   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
15346   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
15347   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
15348   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
15349   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
15350   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
15351   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
15352   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
15353   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15354                SpaceFuncDecl);
15355   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
15356   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
15357   // FIXME these tests regressed behaviour.
15358   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
15359   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
15360   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
15361   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
15362   verifyFormat("int x = int(y);", SpaceFuncDecl);
15363   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15364                SpaceFuncDecl);
15365 
15366   FormatStyle SpaceFuncDef = getLLVMStyle();
15367   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15368   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
15369 
15370   verifyFormat("int f();", SpaceFuncDef);
15371   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
15372   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
15373   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
15374   verifyFormat("#define A(x) x", SpaceFuncDef);
15375   verifyFormat("#define A (x) x", SpaceFuncDef);
15376   verifyFormat("#if defined(x)\n"
15377                "#endif",
15378                SpaceFuncDef);
15379   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
15380   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
15381   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
15382   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
15383   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
15384   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
15385   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
15386   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
15387   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
15388   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15389                SpaceFuncDef);
15390   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
15391   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
15392   verifyFormat("T A::operator()();", SpaceFuncDef);
15393   verifyFormat("X A::operator++(T);", SpaceFuncDef);
15394   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
15395   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
15396   verifyFormat("int x = int(y);", SpaceFuncDef);
15397   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15398                SpaceFuncDef);
15399 
15400   FormatStyle SpaceIfMacros = getLLVMStyle();
15401   SpaceIfMacros.IfMacros.clear();
15402   SpaceIfMacros.IfMacros.push_back("MYIF");
15403   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15404   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
15405   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
15406   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
15407   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
15408 
15409   FormatStyle SpaceForeachMacros = getLLVMStyle();
15410   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
15411             FormatStyle::SBS_Never);
15412   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
15413   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15414   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
15415   verifyFormat("for (;;) {\n"
15416                "}",
15417                SpaceForeachMacros);
15418   verifyFormat("foreach (Item *item, itemlist) {\n"
15419                "}",
15420                SpaceForeachMacros);
15421   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15422                "}",
15423                SpaceForeachMacros);
15424   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15425                "}",
15426                SpaceForeachMacros);
15427   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15428 
15429   FormatStyle SomeSpace2 = getLLVMStyle();
15430   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15431   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15432   verifyFormat("[]() -> float {}", SomeSpace2);
15433   verifyFormat("[] (auto foo) {}", SomeSpace2);
15434   verifyFormat("[foo]() -> int {}", SomeSpace2);
15435   verifyFormat("int f();", SomeSpace2);
15436   verifyFormat("void f (int a, T b) {\n"
15437                "  while (true)\n"
15438                "    continue;\n"
15439                "}",
15440                SomeSpace2);
15441   verifyFormat("if (true)\n"
15442                "  f();\n"
15443                "else if (true)\n"
15444                "  f();",
15445                SomeSpace2);
15446   verifyFormat("do {\n"
15447                "  do_something();\n"
15448                "} while (something());",
15449                SomeSpace2);
15450   verifyFormat("switch (x) {\n"
15451                "default:\n"
15452                "  break;\n"
15453                "}",
15454                SomeSpace2);
15455   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15456   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15457   verifyFormat("*(&a + 1);\n"
15458                "&((&a)[1]);\n"
15459                "a[(b + c) * d];\n"
15460                "(((a + 1) * 2) + 3) * 4;",
15461                SomeSpace2);
15462   verifyFormat("#define A(x) x", SomeSpace2);
15463   verifyFormat("#define A (x) x", SomeSpace2);
15464   verifyFormat("#if defined(x)\n"
15465                "#endif",
15466                SomeSpace2);
15467   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15468   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15469   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15470   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15471   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15472   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15473   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15474   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15475   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15476   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15477                SomeSpace2);
15478   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15479   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15480   verifyFormat("T A::operator()();", SomeSpace2);
15481   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15482   verifyFormat("int x = int (y);", SomeSpace2);
15483   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15484 
15485   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15486   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15487   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15488       .AfterOverloadedOperator = true;
15489 
15490   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15491   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15492   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15493   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15494 
15495   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15496       .AfterOverloadedOperator = false;
15497 
15498   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15499   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15500   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15501   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15502 
15503   auto SpaceAfterRequires = getLLVMStyle();
15504   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15505   EXPECT_FALSE(
15506       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15507   EXPECT_FALSE(
15508       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15509   verifyFormat("void f(auto x)\n"
15510                "  requires requires(int i) { x + i; }\n"
15511                "{}",
15512                SpaceAfterRequires);
15513   verifyFormat("void f(auto x)\n"
15514                "  requires(requires(int i) { x + i; })\n"
15515                "{}",
15516                SpaceAfterRequires);
15517   verifyFormat("if (requires(int i) { x + i; })\n"
15518                "  return;",
15519                SpaceAfterRequires);
15520   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15521   verifyFormat("template <typename T>\n"
15522                "  requires(Foo<T>)\n"
15523                "class Bar;",
15524                SpaceAfterRequires);
15525 
15526   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15527   verifyFormat("void f(auto x)\n"
15528                "  requires requires(int i) { x + i; }\n"
15529                "{}",
15530                SpaceAfterRequires);
15531   verifyFormat("void f(auto x)\n"
15532                "  requires (requires(int i) { x + i; })\n"
15533                "{}",
15534                SpaceAfterRequires);
15535   verifyFormat("if (requires(int i) { x + i; })\n"
15536                "  return;",
15537                SpaceAfterRequires);
15538   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15539   verifyFormat("template <typename T>\n"
15540                "  requires (Foo<T>)\n"
15541                "class Bar;",
15542                SpaceAfterRequires);
15543 
15544   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15545   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15546   verifyFormat("void f(auto x)\n"
15547                "  requires requires (int i) { x + i; }\n"
15548                "{}",
15549                SpaceAfterRequires);
15550   verifyFormat("void f(auto x)\n"
15551                "  requires(requires (int i) { x + i; })\n"
15552                "{}",
15553                SpaceAfterRequires);
15554   verifyFormat("if (requires (int i) { x + i; })\n"
15555                "  return;",
15556                SpaceAfterRequires);
15557   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15558   verifyFormat("template <typename T>\n"
15559                "  requires(Foo<T>)\n"
15560                "class Bar;",
15561                SpaceAfterRequires);
15562 
15563   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15564   verifyFormat("void f(auto x)\n"
15565                "  requires requires (int i) { x + i; }\n"
15566                "{}",
15567                SpaceAfterRequires);
15568   verifyFormat("void f(auto x)\n"
15569                "  requires (requires (int i) { x + i; })\n"
15570                "{}",
15571                SpaceAfterRequires);
15572   verifyFormat("if (requires (int i) { x + i; })\n"
15573                "  return;",
15574                SpaceAfterRequires);
15575   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15576   verifyFormat("template <typename T>\n"
15577                "  requires (Foo<T>)\n"
15578                "class Bar;",
15579                SpaceAfterRequires);
15580 }
15581 
15582 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15583   FormatStyle Spaces = getLLVMStyle();
15584   Spaces.SpaceAfterLogicalNot = true;
15585 
15586   verifyFormat("bool x = ! y", Spaces);
15587   verifyFormat("if (! isFailure())", Spaces);
15588   verifyFormat("if (! (a && b))", Spaces);
15589   verifyFormat("\"Error!\"", Spaces);
15590   verifyFormat("! ! x", Spaces);
15591 }
15592 
15593 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15594   FormatStyle Spaces = getLLVMStyle();
15595 
15596   Spaces.SpacesInParentheses = true;
15597   verifyFormat("do_something( ::globalVar );", Spaces);
15598   verifyFormat("call( x, y, z );", Spaces);
15599   verifyFormat("call();", Spaces);
15600   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15601   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15602                Spaces);
15603   verifyFormat("while ( (bool)1 )\n"
15604                "  continue;",
15605                Spaces);
15606   verifyFormat("for ( ;; )\n"
15607                "  continue;",
15608                Spaces);
15609   verifyFormat("if ( true )\n"
15610                "  f();\n"
15611                "else if ( true )\n"
15612                "  f();",
15613                Spaces);
15614   verifyFormat("do {\n"
15615                "  do_something( (int)i );\n"
15616                "} while ( something() );",
15617                Spaces);
15618   verifyFormat("switch ( x ) {\n"
15619                "default:\n"
15620                "  break;\n"
15621                "}",
15622                Spaces);
15623 
15624   Spaces.SpacesInParentheses = false;
15625   Spaces.SpacesInCStyleCastParentheses = true;
15626   verifyFormat("Type *A = ( Type * )P;", Spaces);
15627   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15628   verifyFormat("x = ( int32 )y;", Spaces);
15629   verifyFormat("int a = ( int )(2.0f);", Spaces);
15630   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15631   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15632   verifyFormat("#define x (( int )-1)", Spaces);
15633 
15634   // Run the first set of tests again with:
15635   Spaces.SpacesInParentheses = false;
15636   Spaces.SpaceInEmptyParentheses = true;
15637   Spaces.SpacesInCStyleCastParentheses = true;
15638   verifyFormat("call(x, y, z);", Spaces);
15639   verifyFormat("call( );", Spaces);
15640   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15641   verifyFormat("while (( bool )1)\n"
15642                "  continue;",
15643                Spaces);
15644   verifyFormat("for (;;)\n"
15645                "  continue;",
15646                Spaces);
15647   verifyFormat("if (true)\n"
15648                "  f( );\n"
15649                "else if (true)\n"
15650                "  f( );",
15651                Spaces);
15652   verifyFormat("do {\n"
15653                "  do_something(( int )i);\n"
15654                "} while (something( ));",
15655                Spaces);
15656   verifyFormat("switch (x) {\n"
15657                "default:\n"
15658                "  break;\n"
15659                "}",
15660                Spaces);
15661 
15662   // Run the first set of tests again with:
15663   Spaces.SpaceAfterCStyleCast = true;
15664   verifyFormat("call(x, y, z);", Spaces);
15665   verifyFormat("call( );", Spaces);
15666   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15667   verifyFormat("while (( bool ) 1)\n"
15668                "  continue;",
15669                Spaces);
15670   verifyFormat("for (;;)\n"
15671                "  continue;",
15672                Spaces);
15673   verifyFormat("if (true)\n"
15674                "  f( );\n"
15675                "else if (true)\n"
15676                "  f( );",
15677                Spaces);
15678   verifyFormat("do {\n"
15679                "  do_something(( int ) i);\n"
15680                "} while (something( ));",
15681                Spaces);
15682   verifyFormat("switch (x) {\n"
15683                "default:\n"
15684                "  break;\n"
15685                "}",
15686                Spaces);
15687   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15688   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15689   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15690   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15691   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15692 
15693   // Run subset of tests again with:
15694   Spaces.SpacesInCStyleCastParentheses = false;
15695   Spaces.SpaceAfterCStyleCast = true;
15696   verifyFormat("while ((bool) 1)\n"
15697                "  continue;",
15698                Spaces);
15699   verifyFormat("do {\n"
15700                "  do_something((int) i);\n"
15701                "} while (something( ));",
15702                Spaces);
15703 
15704   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15705   verifyFormat("size_t idx = (size_t) a;", Spaces);
15706   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15707   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15708   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15709   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15710   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15711   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15712   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15713   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15714   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15715   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15716   Spaces.ColumnLimit = 80;
15717   Spaces.IndentWidth = 4;
15718   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15719   verifyFormat("void foo( ) {\n"
15720                "    size_t foo = (*(function))(\n"
15721                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15722                "BarrrrrrrrrrrrLong,\n"
15723                "        FoooooooooLooooong);\n"
15724                "}",
15725                Spaces);
15726   Spaces.SpaceAfterCStyleCast = false;
15727   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15728   verifyFormat("size_t idx = (size_t)a;", Spaces);
15729   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15730   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15731   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15732   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15733   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15734 
15735   verifyFormat("void foo( ) {\n"
15736                "    size_t foo = (*(function))(\n"
15737                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15738                "BarrrrrrrrrrrrLong,\n"
15739                "        FoooooooooLooooong);\n"
15740                "}",
15741                Spaces);
15742 }
15743 
15744 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15745   verifyFormat("int a[5];");
15746   verifyFormat("a[3] += 42;");
15747 
15748   FormatStyle Spaces = getLLVMStyle();
15749   Spaces.SpacesInSquareBrackets = true;
15750   // Not lambdas.
15751   verifyFormat("int a[ 5 ];", Spaces);
15752   verifyFormat("a[ 3 ] += 42;", Spaces);
15753   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15754   verifyFormat("double &operator[](int i) { return 0; }\n"
15755                "int i;",
15756                Spaces);
15757   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15758   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15759   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15760   // Lambdas.
15761   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15762   verifyFormat("return [ i, args... ] {};", Spaces);
15763   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15764   verifyFormat("int foo = [ = ]() {};", Spaces);
15765   verifyFormat("int foo = [ & ]() {};", Spaces);
15766   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15767   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15768 }
15769 
15770 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15771   FormatStyle NoSpaceStyle = getLLVMStyle();
15772   verifyFormat("int a[5];", NoSpaceStyle);
15773   verifyFormat("a[3] += 42;", NoSpaceStyle);
15774 
15775   verifyFormat("int a[1];", NoSpaceStyle);
15776   verifyFormat("int 1 [a];", NoSpaceStyle);
15777   verifyFormat("int a[1][2];", NoSpaceStyle);
15778   verifyFormat("a[7] = 5;", NoSpaceStyle);
15779   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15780   verifyFormat("f([] {})", NoSpaceStyle);
15781 
15782   FormatStyle Space = getLLVMStyle();
15783   Space.SpaceBeforeSquareBrackets = true;
15784   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15785   verifyFormat("return [i, args...] {};", Space);
15786 
15787   verifyFormat("int a [5];", Space);
15788   verifyFormat("a [3] += 42;", Space);
15789   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15790   verifyFormat("double &operator[](int i) { return 0; }\n"
15791                "int i;",
15792                Space);
15793   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15794   verifyFormat("int i = a [a][a]->f();", Space);
15795   verifyFormat("int i = (*b) [a]->f();", Space);
15796 
15797   verifyFormat("int a [1];", Space);
15798   verifyFormat("int 1 [a];", Space);
15799   verifyFormat("int a [1][2];", Space);
15800   verifyFormat("a [7] = 5;", Space);
15801   verifyFormat("int a = (f()) [23];", Space);
15802   verifyFormat("f([] {})", Space);
15803 }
15804 
15805 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15806   verifyFormat("int a = 5;");
15807   verifyFormat("a += 42;");
15808   verifyFormat("a or_eq 8;");
15809 
15810   FormatStyle Spaces = getLLVMStyle();
15811   Spaces.SpaceBeforeAssignmentOperators = false;
15812   verifyFormat("int a= 5;", Spaces);
15813   verifyFormat("a+= 42;", Spaces);
15814   verifyFormat("a or_eq 8;", Spaces);
15815 }
15816 
15817 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15818   verifyFormat("class Foo : public Bar {};");
15819   verifyFormat("Foo::Foo() : foo(1) {}");
15820   verifyFormat("for (auto a : b) {\n}");
15821   verifyFormat("int x = a ? b : c;");
15822   verifyFormat("{\n"
15823                "label0:\n"
15824                "  int x = 0;\n"
15825                "}");
15826   verifyFormat("switch (x) {\n"
15827                "case 1:\n"
15828                "default:\n"
15829                "}");
15830   verifyFormat("switch (allBraces) {\n"
15831                "case 1: {\n"
15832                "  break;\n"
15833                "}\n"
15834                "case 2: {\n"
15835                "  [[fallthrough]];\n"
15836                "}\n"
15837                "default: {\n"
15838                "  break;\n"
15839                "}\n"
15840                "}");
15841 
15842   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15843   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15844   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15845   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15846   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15847   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15848   verifyFormat("{\n"
15849                "label1:\n"
15850                "  int x = 0;\n"
15851                "}",
15852                CtorInitializerStyle);
15853   verifyFormat("switch (x) {\n"
15854                "case 1:\n"
15855                "default:\n"
15856                "}",
15857                CtorInitializerStyle);
15858   verifyFormat("switch (allBraces) {\n"
15859                "case 1: {\n"
15860                "  break;\n"
15861                "}\n"
15862                "case 2: {\n"
15863                "  [[fallthrough]];\n"
15864                "}\n"
15865                "default: {\n"
15866                "  break;\n"
15867                "}\n"
15868                "}",
15869                CtorInitializerStyle);
15870   CtorInitializerStyle.BreakConstructorInitializers =
15871       FormatStyle::BCIS_AfterColon;
15872   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15873                "    aaaaaaaaaaaaaaaa(1),\n"
15874                "    bbbbbbbbbbbbbbbb(2) {}",
15875                CtorInitializerStyle);
15876   CtorInitializerStyle.BreakConstructorInitializers =
15877       FormatStyle::BCIS_BeforeComma;
15878   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15879                "    : aaaaaaaaaaaaaaaa(1)\n"
15880                "    , bbbbbbbbbbbbbbbb(2) {}",
15881                CtorInitializerStyle);
15882   CtorInitializerStyle.BreakConstructorInitializers =
15883       FormatStyle::BCIS_BeforeColon;
15884   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15885                "    : aaaaaaaaaaaaaaaa(1),\n"
15886                "      bbbbbbbbbbbbbbbb(2) {}",
15887                CtorInitializerStyle);
15888   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15889   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15890                ": aaaaaaaaaaaaaaaa(1),\n"
15891                "  bbbbbbbbbbbbbbbb(2) {}",
15892                CtorInitializerStyle);
15893 
15894   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15895   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15896   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15897   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15898   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15899   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15900   verifyFormat("{\n"
15901                "label2:\n"
15902                "  int x = 0;\n"
15903                "}",
15904                InheritanceStyle);
15905   verifyFormat("switch (x) {\n"
15906                "case 1:\n"
15907                "default:\n"
15908                "}",
15909                InheritanceStyle);
15910   verifyFormat("switch (allBraces) {\n"
15911                "case 1: {\n"
15912                "  break;\n"
15913                "}\n"
15914                "case 2: {\n"
15915                "  [[fallthrough]];\n"
15916                "}\n"
15917                "default: {\n"
15918                "  break;\n"
15919                "}\n"
15920                "}",
15921                InheritanceStyle);
15922   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15923   verifyFormat("class Foooooooooooooooooooooo\n"
15924                "    : public aaaaaaaaaaaaaaaaaa,\n"
15925                "      public bbbbbbbbbbbbbbbbbb {\n"
15926                "}",
15927                InheritanceStyle);
15928   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15929   verifyFormat("class Foooooooooooooooooooooo:\n"
15930                "    public aaaaaaaaaaaaaaaaaa,\n"
15931                "    public bbbbbbbbbbbbbbbbbb {\n"
15932                "}",
15933                InheritanceStyle);
15934   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15935   verifyFormat("class Foooooooooooooooooooooo\n"
15936                "    : public aaaaaaaaaaaaaaaaaa\n"
15937                "    , public bbbbbbbbbbbbbbbbbb {\n"
15938                "}",
15939                InheritanceStyle);
15940   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15941   verifyFormat("class Foooooooooooooooooooooo\n"
15942                "    : public aaaaaaaaaaaaaaaaaa,\n"
15943                "      public bbbbbbbbbbbbbbbbbb {\n"
15944                "}",
15945                InheritanceStyle);
15946   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15947   verifyFormat("class Foooooooooooooooooooooo\n"
15948                ": public aaaaaaaaaaaaaaaaaa,\n"
15949                "  public bbbbbbbbbbbbbbbbbb {}",
15950                InheritanceStyle);
15951 
15952   FormatStyle ForLoopStyle = getLLVMStyle();
15953   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15954   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15955   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15956   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15957   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15958   verifyFormat("{\n"
15959                "label2:\n"
15960                "  int x = 0;\n"
15961                "}",
15962                ForLoopStyle);
15963   verifyFormat("switch (x) {\n"
15964                "case 1:\n"
15965                "default:\n"
15966                "}",
15967                ForLoopStyle);
15968   verifyFormat("switch (allBraces) {\n"
15969                "case 1: {\n"
15970                "  break;\n"
15971                "}\n"
15972                "case 2: {\n"
15973                "  [[fallthrough]];\n"
15974                "}\n"
15975                "default: {\n"
15976                "  break;\n"
15977                "}\n"
15978                "}",
15979                ForLoopStyle);
15980 
15981   FormatStyle CaseStyle = getLLVMStyle();
15982   CaseStyle.SpaceBeforeCaseColon = true;
15983   verifyFormat("class Foo : public Bar {};", CaseStyle);
15984   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15985   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15986   verifyFormat("int x = a ? b : c;", CaseStyle);
15987   verifyFormat("switch (x) {\n"
15988                "case 1 :\n"
15989                "default :\n"
15990                "}",
15991                CaseStyle);
15992   verifyFormat("switch (allBraces) {\n"
15993                "case 1 : {\n"
15994                "  break;\n"
15995                "}\n"
15996                "case 2 : {\n"
15997                "  [[fallthrough]];\n"
15998                "}\n"
15999                "default : {\n"
16000                "  break;\n"
16001                "}\n"
16002                "}",
16003                CaseStyle);
16004 
16005   FormatStyle NoSpaceStyle = getLLVMStyle();
16006   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
16007   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
16008   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
16009   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
16010   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
16011   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
16012   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
16013   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
16014   verifyFormat("{\n"
16015                "label3:\n"
16016                "  int x = 0;\n"
16017                "}",
16018                NoSpaceStyle);
16019   verifyFormat("switch (x) {\n"
16020                "case 1:\n"
16021                "default:\n"
16022                "}",
16023                NoSpaceStyle);
16024   verifyFormat("switch (allBraces) {\n"
16025                "case 1: {\n"
16026                "  break;\n"
16027                "}\n"
16028                "case 2: {\n"
16029                "  [[fallthrough]];\n"
16030                "}\n"
16031                "default: {\n"
16032                "  break;\n"
16033                "}\n"
16034                "}",
16035                NoSpaceStyle);
16036 
16037   FormatStyle InvertedSpaceStyle = getLLVMStyle();
16038   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
16039   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
16040   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
16041   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
16042   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
16043   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
16044   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
16045   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
16046   verifyFormat("{\n"
16047                "label3:\n"
16048                "  int x = 0;\n"
16049                "}",
16050                InvertedSpaceStyle);
16051   verifyFormat("switch (x) {\n"
16052                "case 1 :\n"
16053                "case 2 : {\n"
16054                "  break;\n"
16055                "}\n"
16056                "default :\n"
16057                "  break;\n"
16058                "}",
16059                InvertedSpaceStyle);
16060   verifyFormat("switch (allBraces) {\n"
16061                "case 1 : {\n"
16062                "  break;\n"
16063                "}\n"
16064                "case 2 : {\n"
16065                "  [[fallthrough]];\n"
16066                "}\n"
16067                "default : {\n"
16068                "  break;\n"
16069                "}\n"
16070                "}",
16071                InvertedSpaceStyle);
16072 }
16073 
16074 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
16075   FormatStyle Style = getLLVMStyle();
16076 
16077   Style.PointerAlignment = FormatStyle::PAS_Left;
16078   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
16079   verifyFormat("void* const* x = NULL;", Style);
16080 
16081 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
16082   do {                                                                         \
16083     Style.PointerAlignment = FormatStyle::Pointers;                            \
16084     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
16085     verifyFormat(Code, Style);                                                 \
16086   } while (false)
16087 
16088   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
16089   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
16090   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
16091 
16092   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
16093   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
16094   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
16095 
16096   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
16097   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
16098   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
16099 
16100   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
16101   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
16102   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
16103 
16104   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
16105   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
16106                         SAPQ_Default);
16107   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
16108                         SAPQ_Default);
16109 
16110   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
16111   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
16112                         SAPQ_Before);
16113   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
16114                         SAPQ_Before);
16115 
16116   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
16117   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
16118   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
16119                         SAPQ_After);
16120 
16121   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
16122   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
16123   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
16124 
16125 #undef verifyQualifierSpaces
16126 
16127   FormatStyle Spaces = getLLVMStyle();
16128   Spaces.AttributeMacros.push_back("qualified");
16129   Spaces.PointerAlignment = FormatStyle::PAS_Right;
16130   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
16131   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
16132   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
16133   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
16134   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
16135   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16136   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
16137   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
16138   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
16139   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
16140   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
16141   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16142 
16143   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
16144   Spaces.PointerAlignment = FormatStyle::PAS_Left;
16145   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
16146   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
16147   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
16148   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
16149   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
16150   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16151   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
16152   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
16153   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
16154   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
16155   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
16156   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
16157   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16158 
16159   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
16160   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
16161   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
16162   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
16163   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
16164   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
16165   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
16166   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16167 }
16168 
16169 TEST_F(FormatTest, AlignConsecutiveMacros) {
16170   FormatStyle Style = getLLVMStyle();
16171   Style.AlignConsecutiveAssignments.Enabled = true;
16172   Style.AlignConsecutiveDeclarations.Enabled = true;
16173 
16174   verifyFormat("#define a 3\n"
16175                "#define bbbb 4\n"
16176                "#define ccc (5)",
16177                Style);
16178 
16179   verifyFormat("#define f(x) (x * x)\n"
16180                "#define fff(x, y, z) (x * y + z)\n"
16181                "#define ffff(x, y) (x - y)",
16182                Style);
16183 
16184   verifyFormat("#define foo(x, y) (x + y)\n"
16185                "#define bar (5, 6)(2 + 2)",
16186                Style);
16187 
16188   verifyFormat("#define a 3\n"
16189                "#define bbbb 4\n"
16190                "#define ccc (5)\n"
16191                "#define f(x) (x * x)\n"
16192                "#define fff(x, y, z) (x * y + z)\n"
16193                "#define ffff(x, y) (x - y)",
16194                Style);
16195 
16196   Style.AlignConsecutiveMacros.Enabled = true;
16197   verifyFormat("#define a    3\n"
16198                "#define bbbb 4\n"
16199                "#define ccc  (5)",
16200                Style);
16201 
16202   verifyFormat("#define true  1\n"
16203                "#define false 0",
16204                Style);
16205 
16206   verifyFormat("#define f(x)         (x * x)\n"
16207                "#define fff(x, y, z) (x * y + z)\n"
16208                "#define ffff(x, y)   (x - y)",
16209                Style);
16210 
16211   verifyFormat("#define foo(x, y) (x + y)\n"
16212                "#define bar       (5, 6)(2 + 2)",
16213                Style);
16214 
16215   verifyFormat("#define a            3\n"
16216                "#define bbbb         4\n"
16217                "#define ccc          (5)\n"
16218                "#define f(x)         (x * x)\n"
16219                "#define fff(x, y, z) (x * y + z)\n"
16220                "#define ffff(x, y)   (x - y)",
16221                Style);
16222 
16223   verifyFormat("#define a         5\n"
16224                "#define foo(x, y) (x + y)\n"
16225                "#define CCC       (6)\n"
16226                "auto lambda = []() {\n"
16227                "  auto  ii = 0;\n"
16228                "  float j  = 0;\n"
16229                "  return 0;\n"
16230                "};\n"
16231                "int   i  = 0;\n"
16232                "float i2 = 0;\n"
16233                "auto  v  = type{\n"
16234                "    i = 1,   //\n"
16235                "    (i = 2), //\n"
16236                "    i = 3    //\n"
16237                "};",
16238                Style);
16239 
16240   Style.AlignConsecutiveMacros.Enabled = false;
16241   Style.ColumnLimit = 20;
16242 
16243   verifyFormat("#define a          \\\n"
16244                "  \"aabbbbbbbbbbbb\"\n"
16245                "#define D          \\\n"
16246                "  \"aabbbbbbbbbbbb\" \\\n"
16247                "  \"ccddeeeeeeeee\"\n"
16248                "#define B          \\\n"
16249                "  \"QQQQQQQQQQQQQ\"  \\\n"
16250                "  \"FFFFFFFFFFFFF\"  \\\n"
16251                "  \"LLLLLLLL\"\n",
16252                Style);
16253 
16254   Style.AlignConsecutiveMacros.Enabled = true;
16255   verifyFormat("#define a          \\\n"
16256                "  \"aabbbbbbbbbbbb\"\n"
16257                "#define D          \\\n"
16258                "  \"aabbbbbbbbbbbb\" \\\n"
16259                "  \"ccddeeeeeeeee\"\n"
16260                "#define B          \\\n"
16261                "  \"QQQQQQQQQQQQQ\"  \\\n"
16262                "  \"FFFFFFFFFFFFF\"  \\\n"
16263                "  \"LLLLLLLL\"\n",
16264                Style);
16265 
16266   // Test across comments
16267   Style.MaxEmptyLinesToKeep = 10;
16268   Style.ReflowComments = false;
16269   Style.AlignConsecutiveMacros.AcrossComments = true;
16270   EXPECT_EQ("#define a    3\n"
16271             "// line comment\n"
16272             "#define bbbb 4\n"
16273             "#define ccc  (5)",
16274             format("#define a 3\n"
16275                    "// line comment\n"
16276                    "#define bbbb 4\n"
16277                    "#define ccc (5)",
16278                    Style));
16279 
16280   EXPECT_EQ("#define a    3\n"
16281             "/* block comment */\n"
16282             "#define bbbb 4\n"
16283             "#define ccc  (5)",
16284             format("#define a  3\n"
16285                    "/* block comment */\n"
16286                    "#define bbbb 4\n"
16287                    "#define ccc (5)",
16288                    Style));
16289 
16290   EXPECT_EQ("#define a    3\n"
16291             "/* multi-line *\n"
16292             " * block comment */\n"
16293             "#define bbbb 4\n"
16294             "#define ccc  (5)",
16295             format("#define a 3\n"
16296                    "/* multi-line *\n"
16297                    " * block comment */\n"
16298                    "#define bbbb 4\n"
16299                    "#define ccc (5)",
16300                    Style));
16301 
16302   EXPECT_EQ("#define a    3\n"
16303             "// multi-line line comment\n"
16304             "//\n"
16305             "#define bbbb 4\n"
16306             "#define ccc  (5)",
16307             format("#define a  3\n"
16308                    "// multi-line line comment\n"
16309                    "//\n"
16310                    "#define bbbb 4\n"
16311                    "#define ccc (5)",
16312                    Style));
16313 
16314   EXPECT_EQ("#define a 3\n"
16315             "// empty lines still break.\n"
16316             "\n"
16317             "#define bbbb 4\n"
16318             "#define ccc  (5)",
16319             format("#define a     3\n"
16320                    "// empty lines still break.\n"
16321                    "\n"
16322                    "#define bbbb     4\n"
16323                    "#define ccc  (5)",
16324                    Style));
16325 
16326   // Test across empty lines
16327   Style.AlignConsecutiveMacros.AcrossComments = false;
16328   Style.AlignConsecutiveMacros.AcrossEmptyLines = true;
16329   EXPECT_EQ("#define a    3\n"
16330             "\n"
16331             "#define bbbb 4\n"
16332             "#define ccc  (5)",
16333             format("#define a 3\n"
16334                    "\n"
16335                    "#define bbbb 4\n"
16336                    "#define ccc (5)",
16337                    Style));
16338 
16339   EXPECT_EQ("#define a    3\n"
16340             "\n"
16341             "\n"
16342             "\n"
16343             "#define bbbb 4\n"
16344             "#define ccc  (5)",
16345             format("#define a        3\n"
16346                    "\n"
16347                    "\n"
16348                    "\n"
16349                    "#define bbbb 4\n"
16350                    "#define ccc (5)",
16351                    Style));
16352 
16353   EXPECT_EQ("#define a 3\n"
16354             "// comments should break alignment\n"
16355             "//\n"
16356             "#define bbbb 4\n"
16357             "#define ccc  (5)",
16358             format("#define a        3\n"
16359                    "// comments should break alignment\n"
16360                    "//\n"
16361                    "#define bbbb 4\n"
16362                    "#define ccc (5)",
16363                    Style));
16364 
16365   // Test across empty lines and comments
16366   Style.AlignConsecutiveMacros.AcrossComments = true;
16367   verifyFormat("#define a    3\n"
16368                "\n"
16369                "// line comment\n"
16370                "#define bbbb 4\n"
16371                "#define ccc  (5)",
16372                Style);
16373 
16374   EXPECT_EQ("#define a    3\n"
16375             "\n"
16376             "\n"
16377             "/* multi-line *\n"
16378             " * block comment */\n"
16379             "\n"
16380             "\n"
16381             "#define bbbb 4\n"
16382             "#define ccc  (5)",
16383             format("#define a 3\n"
16384                    "\n"
16385                    "\n"
16386                    "/* multi-line *\n"
16387                    " * block comment */\n"
16388                    "\n"
16389                    "\n"
16390                    "#define bbbb 4\n"
16391                    "#define ccc (5)",
16392                    Style));
16393 
16394   EXPECT_EQ("#define a    3\n"
16395             "\n"
16396             "\n"
16397             "/* multi-line *\n"
16398             " * block comment */\n"
16399             "\n"
16400             "\n"
16401             "#define bbbb 4\n"
16402             "#define ccc  (5)",
16403             format("#define a 3\n"
16404                    "\n"
16405                    "\n"
16406                    "/* multi-line *\n"
16407                    " * block comment */\n"
16408                    "\n"
16409                    "\n"
16410                    "#define bbbb 4\n"
16411                    "#define ccc       (5)",
16412                    Style));
16413 }
16414 
16415 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
16416   FormatStyle Alignment = getLLVMStyle();
16417   Alignment.AlignConsecutiveMacros.Enabled = true;
16418   Alignment.AlignConsecutiveAssignments.Enabled = true;
16419   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16420 
16421   Alignment.MaxEmptyLinesToKeep = 10;
16422   /* Test alignment across empty lines */
16423   EXPECT_EQ("int a           = 5;\n"
16424             "\n"
16425             "int oneTwoThree = 123;",
16426             format("int a       = 5;\n"
16427                    "\n"
16428                    "int oneTwoThree= 123;",
16429                    Alignment));
16430   EXPECT_EQ("int a           = 5;\n"
16431             "int one         = 1;\n"
16432             "\n"
16433             "int oneTwoThree = 123;",
16434             format("int a = 5;\n"
16435                    "int one = 1;\n"
16436                    "\n"
16437                    "int oneTwoThree = 123;",
16438                    Alignment));
16439   EXPECT_EQ("int a           = 5;\n"
16440             "int one         = 1;\n"
16441             "\n"
16442             "int oneTwoThree = 123;\n"
16443             "int oneTwo      = 12;",
16444             format("int a = 5;\n"
16445                    "int one = 1;\n"
16446                    "\n"
16447                    "int oneTwoThree = 123;\n"
16448                    "int oneTwo = 12;",
16449                    Alignment));
16450 
16451   /* Test across comments */
16452   EXPECT_EQ("int a = 5;\n"
16453             "/* block comment */\n"
16454             "int oneTwoThree = 123;",
16455             format("int a = 5;\n"
16456                    "/* block comment */\n"
16457                    "int oneTwoThree=123;",
16458                    Alignment));
16459 
16460   EXPECT_EQ("int a = 5;\n"
16461             "// line comment\n"
16462             "int oneTwoThree = 123;",
16463             format("int a = 5;\n"
16464                    "// line comment\n"
16465                    "int oneTwoThree=123;",
16466                    Alignment));
16467 
16468   /* Test across comments and newlines */
16469   EXPECT_EQ("int a = 5;\n"
16470             "\n"
16471             "/* block comment */\n"
16472             "int oneTwoThree = 123;",
16473             format("int a = 5;\n"
16474                    "\n"
16475                    "/* block comment */\n"
16476                    "int oneTwoThree=123;",
16477                    Alignment));
16478 
16479   EXPECT_EQ("int a = 5;\n"
16480             "\n"
16481             "// line comment\n"
16482             "int oneTwoThree = 123;",
16483             format("int a = 5;\n"
16484                    "\n"
16485                    "// line comment\n"
16486                    "int oneTwoThree=123;",
16487                    Alignment));
16488 }
16489 
16490 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16491   FormatStyle Alignment = getLLVMStyle();
16492   Alignment.AlignConsecutiveDeclarations.Enabled = true;
16493   Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true;
16494   Alignment.AlignConsecutiveDeclarations.AcrossComments = true;
16495 
16496   Alignment.MaxEmptyLinesToKeep = 10;
16497   /* Test alignment across empty lines */
16498   EXPECT_EQ("int         a = 5;\n"
16499             "\n"
16500             "float const oneTwoThree = 123;",
16501             format("int a = 5;\n"
16502                    "\n"
16503                    "float const oneTwoThree = 123;",
16504                    Alignment));
16505   EXPECT_EQ("int         a = 5;\n"
16506             "float const one = 1;\n"
16507             "\n"
16508             "int         oneTwoThree = 123;",
16509             format("int a = 5;\n"
16510                    "float const one = 1;\n"
16511                    "\n"
16512                    "int oneTwoThree = 123;",
16513                    Alignment));
16514 
16515   /* Test across comments */
16516   EXPECT_EQ("float const a = 5;\n"
16517             "/* block comment */\n"
16518             "int         oneTwoThree = 123;",
16519             format("float const a = 5;\n"
16520                    "/* block comment */\n"
16521                    "int oneTwoThree=123;",
16522                    Alignment));
16523 
16524   EXPECT_EQ("float const a = 5;\n"
16525             "// line comment\n"
16526             "int         oneTwoThree = 123;",
16527             format("float const a = 5;\n"
16528                    "// line comment\n"
16529                    "int oneTwoThree=123;",
16530                    Alignment));
16531 
16532   /* Test across comments and newlines */
16533   EXPECT_EQ("float const a = 5;\n"
16534             "\n"
16535             "/* block comment */\n"
16536             "int         oneTwoThree = 123;",
16537             format("float const a = 5;\n"
16538                    "\n"
16539                    "/* block comment */\n"
16540                    "int         oneTwoThree=123;",
16541                    Alignment));
16542 
16543   EXPECT_EQ("float const a = 5;\n"
16544             "\n"
16545             "// line comment\n"
16546             "int         oneTwoThree = 123;",
16547             format("float const a = 5;\n"
16548                    "\n"
16549                    "// line comment\n"
16550                    "int oneTwoThree=123;",
16551                    Alignment));
16552 }
16553 
16554 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16555   FormatStyle Alignment = getLLVMStyle();
16556   Alignment.AlignConsecutiveBitFields.Enabled = true;
16557   Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true;
16558   Alignment.AlignConsecutiveBitFields.AcrossComments = true;
16559 
16560   Alignment.MaxEmptyLinesToKeep = 10;
16561   /* Test alignment across empty lines */
16562   EXPECT_EQ("int a            : 5;\n"
16563             "\n"
16564             "int longbitfield : 6;",
16565             format("int a : 5;\n"
16566                    "\n"
16567                    "int longbitfield : 6;",
16568                    Alignment));
16569   EXPECT_EQ("int a            : 5;\n"
16570             "int one          : 1;\n"
16571             "\n"
16572             "int longbitfield : 6;",
16573             format("int a : 5;\n"
16574                    "int one : 1;\n"
16575                    "\n"
16576                    "int longbitfield : 6;",
16577                    Alignment));
16578 
16579   /* Test across comments */
16580   EXPECT_EQ("int a            : 5;\n"
16581             "/* block comment */\n"
16582             "int longbitfield : 6;",
16583             format("int a : 5;\n"
16584                    "/* block comment */\n"
16585                    "int longbitfield : 6;",
16586                    Alignment));
16587   EXPECT_EQ("int a            : 5;\n"
16588             "int one          : 1;\n"
16589             "// line comment\n"
16590             "int longbitfield : 6;",
16591             format("int a : 5;\n"
16592                    "int one : 1;\n"
16593                    "// line comment\n"
16594                    "int longbitfield : 6;",
16595                    Alignment));
16596 
16597   /* Test across comments and newlines */
16598   EXPECT_EQ("int a            : 5;\n"
16599             "/* block comment */\n"
16600             "\n"
16601             "int longbitfield : 6;",
16602             format("int a : 5;\n"
16603                    "/* block comment */\n"
16604                    "\n"
16605                    "int longbitfield : 6;",
16606                    Alignment));
16607   EXPECT_EQ("int a            : 5;\n"
16608             "int one          : 1;\n"
16609             "\n"
16610             "// line comment\n"
16611             "\n"
16612             "int longbitfield : 6;",
16613             format("int a : 5;\n"
16614                    "int one : 1;\n"
16615                    "\n"
16616                    "// line comment \n"
16617                    "\n"
16618                    "int longbitfield : 6;",
16619                    Alignment));
16620 }
16621 
16622 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16623   FormatStyle Alignment = getLLVMStyle();
16624   Alignment.AlignConsecutiveMacros.Enabled = true;
16625   Alignment.AlignConsecutiveAssignments.Enabled = true;
16626   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16627 
16628   Alignment.MaxEmptyLinesToKeep = 10;
16629   /* Test alignment across empty lines */
16630   EXPECT_EQ("int a = 5;\n"
16631             "\n"
16632             "int oneTwoThree = 123;",
16633             format("int a       = 5;\n"
16634                    "\n"
16635                    "int oneTwoThree= 123;",
16636                    Alignment));
16637   EXPECT_EQ("int a   = 5;\n"
16638             "int one = 1;\n"
16639             "\n"
16640             "int oneTwoThree = 123;",
16641             format("int a = 5;\n"
16642                    "int one = 1;\n"
16643                    "\n"
16644                    "int oneTwoThree = 123;",
16645                    Alignment));
16646 
16647   /* Test across comments */
16648   EXPECT_EQ("int a           = 5;\n"
16649             "/* block comment */\n"
16650             "int oneTwoThree = 123;",
16651             format("int a = 5;\n"
16652                    "/* block comment */\n"
16653                    "int oneTwoThree=123;",
16654                    Alignment));
16655 
16656   EXPECT_EQ("int a           = 5;\n"
16657             "// line comment\n"
16658             "int oneTwoThree = 123;",
16659             format("int a = 5;\n"
16660                    "// line comment\n"
16661                    "int oneTwoThree=123;",
16662                    Alignment));
16663 
16664   EXPECT_EQ("int a           = 5;\n"
16665             "/*\n"
16666             " * multi-line block comment\n"
16667             " */\n"
16668             "int oneTwoThree = 123;",
16669             format("int a = 5;\n"
16670                    "/*\n"
16671                    " * multi-line block comment\n"
16672                    " */\n"
16673                    "int oneTwoThree=123;",
16674                    Alignment));
16675 
16676   EXPECT_EQ("int a           = 5;\n"
16677             "//\n"
16678             "// multi-line line comment\n"
16679             "//\n"
16680             "int oneTwoThree = 123;",
16681             format("int a = 5;\n"
16682                    "//\n"
16683                    "// multi-line line comment\n"
16684                    "//\n"
16685                    "int oneTwoThree=123;",
16686                    Alignment));
16687 
16688   /* Test across comments and newlines */
16689   EXPECT_EQ("int a = 5;\n"
16690             "\n"
16691             "/* block comment */\n"
16692             "int oneTwoThree = 123;",
16693             format("int a = 5;\n"
16694                    "\n"
16695                    "/* block comment */\n"
16696                    "int oneTwoThree=123;",
16697                    Alignment));
16698 
16699   EXPECT_EQ("int a = 5;\n"
16700             "\n"
16701             "// line comment\n"
16702             "int oneTwoThree = 123;",
16703             format("int a = 5;\n"
16704                    "\n"
16705                    "// line comment\n"
16706                    "int oneTwoThree=123;",
16707                    Alignment));
16708 }
16709 
16710 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16711   FormatStyle Alignment = getLLVMStyle();
16712   Alignment.AlignConsecutiveMacros.Enabled = true;
16713   Alignment.AlignConsecutiveAssignments.Enabled = true;
16714   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16715   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16716   verifyFormat("int a           = 5;\n"
16717                "int oneTwoThree = 123;",
16718                Alignment);
16719   verifyFormat("int a           = method();\n"
16720                "int oneTwoThree = 133;",
16721                Alignment);
16722   verifyFormat("a &= 5;\n"
16723                "bcd *= 5;\n"
16724                "ghtyf += 5;\n"
16725                "dvfvdb -= 5;\n"
16726                "a /= 5;\n"
16727                "vdsvsv %= 5;\n"
16728                "sfdbddfbdfbb ^= 5;\n"
16729                "dvsdsv |= 5;\n"
16730                "int dsvvdvsdvvv = 123;",
16731                Alignment);
16732   verifyFormat("int i = 1, j = 10;\n"
16733                "something = 2000;",
16734                Alignment);
16735   verifyFormat("something = 2000;\n"
16736                "int i = 1, j = 10;\n",
16737                Alignment);
16738   verifyFormat("something = 2000;\n"
16739                "another   = 911;\n"
16740                "int i = 1, j = 10;\n"
16741                "oneMore = 1;\n"
16742                "i       = 2;",
16743                Alignment);
16744   verifyFormat("int a   = 5;\n"
16745                "int one = 1;\n"
16746                "method();\n"
16747                "int oneTwoThree = 123;\n"
16748                "int oneTwo      = 12;",
16749                Alignment);
16750   verifyFormat("int oneTwoThree = 123;\n"
16751                "int oneTwo      = 12;\n"
16752                "method();\n",
16753                Alignment);
16754   verifyFormat("int oneTwoThree = 123; // comment\n"
16755                "int oneTwo      = 12;  // comment",
16756                Alignment);
16757 
16758   // Bug 25167
16759   /* Uncomment when fixed
16760     verifyFormat("#if A\n"
16761                  "#else\n"
16762                  "int aaaaaaaa = 12;\n"
16763                  "#endif\n"
16764                  "#if B\n"
16765                  "#else\n"
16766                  "int a = 12;\n"
16767                  "#endif\n",
16768                  Alignment);
16769     verifyFormat("enum foo {\n"
16770                  "#if A\n"
16771                  "#else\n"
16772                  "  aaaaaaaa = 12;\n"
16773                  "#endif\n"
16774                  "#if B\n"
16775                  "#else\n"
16776                  "  a = 12;\n"
16777                  "#endif\n"
16778                  "};\n",
16779                  Alignment);
16780   */
16781 
16782   Alignment.MaxEmptyLinesToKeep = 10;
16783   /* Test alignment across empty lines */
16784   EXPECT_EQ("int a           = 5;\n"
16785             "\n"
16786             "int oneTwoThree = 123;",
16787             format("int a       = 5;\n"
16788                    "\n"
16789                    "int oneTwoThree= 123;",
16790                    Alignment));
16791   EXPECT_EQ("int a           = 5;\n"
16792             "int one         = 1;\n"
16793             "\n"
16794             "int oneTwoThree = 123;",
16795             format("int a = 5;\n"
16796                    "int one = 1;\n"
16797                    "\n"
16798                    "int oneTwoThree = 123;",
16799                    Alignment));
16800   EXPECT_EQ("int a           = 5;\n"
16801             "int one         = 1;\n"
16802             "\n"
16803             "int oneTwoThree = 123;\n"
16804             "int oneTwo      = 12;",
16805             format("int a = 5;\n"
16806                    "int one = 1;\n"
16807                    "\n"
16808                    "int oneTwoThree = 123;\n"
16809                    "int oneTwo = 12;",
16810                    Alignment));
16811 
16812   /* Test across comments */
16813   EXPECT_EQ("int a           = 5;\n"
16814             "/* block comment */\n"
16815             "int oneTwoThree = 123;",
16816             format("int a = 5;\n"
16817                    "/* block comment */\n"
16818                    "int oneTwoThree=123;",
16819                    Alignment));
16820 
16821   EXPECT_EQ("int a           = 5;\n"
16822             "// line comment\n"
16823             "int oneTwoThree = 123;",
16824             format("int a = 5;\n"
16825                    "// line comment\n"
16826                    "int oneTwoThree=123;",
16827                    Alignment));
16828 
16829   /* Test across comments and newlines */
16830   EXPECT_EQ("int a           = 5;\n"
16831             "\n"
16832             "/* block comment */\n"
16833             "int oneTwoThree = 123;",
16834             format("int a = 5;\n"
16835                    "\n"
16836                    "/* block comment */\n"
16837                    "int oneTwoThree=123;",
16838                    Alignment));
16839 
16840   EXPECT_EQ("int a           = 5;\n"
16841             "\n"
16842             "// line comment\n"
16843             "int oneTwoThree = 123;",
16844             format("int a = 5;\n"
16845                    "\n"
16846                    "// line comment\n"
16847                    "int oneTwoThree=123;",
16848                    Alignment));
16849 
16850   EXPECT_EQ("int a           = 5;\n"
16851             "//\n"
16852             "// multi-line line comment\n"
16853             "//\n"
16854             "int oneTwoThree = 123;",
16855             format("int a = 5;\n"
16856                    "//\n"
16857                    "// multi-line line comment\n"
16858                    "//\n"
16859                    "int oneTwoThree=123;",
16860                    Alignment));
16861 
16862   EXPECT_EQ("int a           = 5;\n"
16863             "/*\n"
16864             " *  multi-line block comment\n"
16865             " */\n"
16866             "int oneTwoThree = 123;",
16867             format("int a = 5;\n"
16868                    "/*\n"
16869                    " *  multi-line block comment\n"
16870                    " */\n"
16871                    "int oneTwoThree=123;",
16872                    Alignment));
16873 
16874   EXPECT_EQ("int a           = 5;\n"
16875             "\n"
16876             "/* block comment */\n"
16877             "\n"
16878             "\n"
16879             "\n"
16880             "int oneTwoThree = 123;",
16881             format("int a = 5;\n"
16882                    "\n"
16883                    "/* block comment */\n"
16884                    "\n"
16885                    "\n"
16886                    "\n"
16887                    "int oneTwoThree=123;",
16888                    Alignment));
16889 
16890   EXPECT_EQ("int a           = 5;\n"
16891             "\n"
16892             "// line comment\n"
16893             "\n"
16894             "\n"
16895             "\n"
16896             "int oneTwoThree = 123;",
16897             format("int a = 5;\n"
16898                    "\n"
16899                    "// line comment\n"
16900                    "\n"
16901                    "\n"
16902                    "\n"
16903                    "int oneTwoThree=123;",
16904                    Alignment));
16905 
16906   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16907   verifyFormat("#define A \\\n"
16908                "  int aaaa       = 12; \\\n"
16909                "  int b          = 23; \\\n"
16910                "  int ccc        = 234; \\\n"
16911                "  int dddddddddd = 2345;",
16912                Alignment);
16913   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16914   verifyFormat("#define A               \\\n"
16915                "  int aaaa       = 12;  \\\n"
16916                "  int b          = 23;  \\\n"
16917                "  int ccc        = 234; \\\n"
16918                "  int dddddddddd = 2345;",
16919                Alignment);
16920   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16921   verifyFormat("#define A                                                      "
16922                "                \\\n"
16923                "  int aaaa       = 12;                                         "
16924                "                \\\n"
16925                "  int b          = 23;                                         "
16926                "                \\\n"
16927                "  int ccc        = 234;                                        "
16928                "                \\\n"
16929                "  int dddddddddd = 2345;",
16930                Alignment);
16931   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16932                "k = 4, int l = 5,\n"
16933                "                  int m = 6) {\n"
16934                "  int j      = 10;\n"
16935                "  otherThing = 1;\n"
16936                "}",
16937                Alignment);
16938   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16939                "  int i   = 1;\n"
16940                "  int j   = 2;\n"
16941                "  int big = 10000;\n"
16942                "}",
16943                Alignment);
16944   verifyFormat("class C {\n"
16945                "public:\n"
16946                "  int i            = 1;\n"
16947                "  virtual void f() = 0;\n"
16948                "};",
16949                Alignment);
16950   verifyFormat("int i = 1;\n"
16951                "if (SomeType t = getSomething()) {\n"
16952                "}\n"
16953                "int j   = 2;\n"
16954                "int big = 10000;",
16955                Alignment);
16956   verifyFormat("int j = 7;\n"
16957                "for (int k = 0; k < N; ++k) {\n"
16958                "}\n"
16959                "int j   = 2;\n"
16960                "int big = 10000;\n"
16961                "}",
16962                Alignment);
16963   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16964   verifyFormat("int i = 1;\n"
16965                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16966                "    = someLooooooooooooooooongFunction();\n"
16967                "int j = 2;",
16968                Alignment);
16969   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16970   verifyFormat("int i = 1;\n"
16971                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16972                "    someLooooooooooooooooongFunction();\n"
16973                "int j = 2;",
16974                Alignment);
16975 
16976   verifyFormat("auto lambda = []() {\n"
16977                "  auto i = 0;\n"
16978                "  return 0;\n"
16979                "};\n"
16980                "int i  = 0;\n"
16981                "auto v = type{\n"
16982                "    i = 1,   //\n"
16983                "    (i = 2), //\n"
16984                "    i = 3    //\n"
16985                "};",
16986                Alignment);
16987 
16988   verifyFormat(
16989       "int i      = 1;\n"
16990       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16991       "                          loooooooooooooooooooooongParameterB);\n"
16992       "int j      = 2;",
16993       Alignment);
16994 
16995   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16996                "          typename B   = very_long_type_name_1,\n"
16997                "          typename T_2 = very_long_type_name_2>\n"
16998                "auto foo() {}\n",
16999                Alignment);
17000   verifyFormat("int a, b = 1;\n"
17001                "int c  = 2;\n"
17002                "int dd = 3;\n",
17003                Alignment);
17004   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17005                "float b[1][] = {{3.f}};\n",
17006                Alignment);
17007   verifyFormat("for (int i = 0; i < 1; i++)\n"
17008                "  int x = 1;\n",
17009                Alignment);
17010   verifyFormat("for (i = 0; i < 1; i++)\n"
17011                "  x = 1;\n"
17012                "y = 1;\n",
17013                Alignment);
17014 
17015   Alignment.ReflowComments = true;
17016   Alignment.ColumnLimit = 50;
17017   EXPECT_EQ("int x   = 0;\n"
17018             "int yy  = 1; /// specificlennospace\n"
17019             "int zzz = 2;\n",
17020             format("int x   = 0;\n"
17021                    "int yy  = 1; ///specificlennospace\n"
17022                    "int zzz = 2;\n",
17023                    Alignment));
17024 }
17025 
17026 TEST_F(FormatTest, AlignCompoundAssignments) {
17027   FormatStyle Alignment = getLLVMStyle();
17028   Alignment.AlignConsecutiveAssignments.Enabled = true;
17029   Alignment.AlignConsecutiveAssignments.AlignCompound = true;
17030   Alignment.AlignConsecutiveAssignments.PadOperators = false;
17031   verifyFormat("sfdbddfbdfbb    = 5;\n"
17032                "dvsdsv          = 5;\n"
17033                "int dsvvdvsdvvv = 123;",
17034                Alignment);
17035   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
17036                "dvsdsv         |= 5;\n"
17037                "int dsvvdvsdvvv = 123;",
17038                Alignment);
17039   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
17040                "dvsdsv        <<= 5;\n"
17041                "int dsvvdvsdvvv = 123;",
17042                Alignment);
17043   // Test that `<=` is not treated as a compound assignment.
17044   verifyFormat("aa &= 5;\n"
17045                "b <= 10;\n"
17046                "c = 15;",
17047                Alignment);
17048   Alignment.AlignConsecutiveAssignments.PadOperators = true;
17049   verifyFormat("sfdbddfbdfbb    = 5;\n"
17050                "dvsdsv          = 5;\n"
17051                "int dsvvdvsdvvv = 123;",
17052                Alignment);
17053   verifyFormat("sfdbddfbdfbb    ^= 5;\n"
17054                "dvsdsv          |= 5;\n"
17055                "int dsvvdvsdvvv  = 123;",
17056                Alignment);
17057   verifyFormat("sfdbddfbdfbb     ^= 5;\n"
17058                "dvsdsv          <<= 5;\n"
17059                "int dsvvdvsdvvv   = 123;",
17060                Alignment);
17061   EXPECT_EQ("a   += 5;\n"
17062             "one  = 1;\n"
17063             "\n"
17064             "oneTwoThree = 123;\n",
17065             format("a += 5;\n"
17066                    "one = 1;\n"
17067                    "\n"
17068                    "oneTwoThree = 123;\n",
17069                    Alignment));
17070   EXPECT_EQ("a   += 5;\n"
17071             "one  = 1;\n"
17072             "//\n"
17073             "oneTwoThree = 123;\n",
17074             format("a += 5;\n"
17075                    "one = 1;\n"
17076                    "//\n"
17077                    "oneTwoThree = 123;\n",
17078                    Alignment));
17079   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
17080   EXPECT_EQ("a           += 5;\n"
17081             "one          = 1;\n"
17082             "\n"
17083             "oneTwoThree  = 123;\n",
17084             format("a += 5;\n"
17085                    "one = 1;\n"
17086                    "\n"
17087                    "oneTwoThree = 123;\n",
17088                    Alignment));
17089   EXPECT_EQ("a   += 5;\n"
17090             "one  = 1;\n"
17091             "//\n"
17092             "oneTwoThree = 123;\n",
17093             format("a += 5;\n"
17094                    "one = 1;\n"
17095                    "//\n"
17096                    "oneTwoThree = 123;\n",
17097                    Alignment));
17098   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false;
17099   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
17100   EXPECT_EQ("a   += 5;\n"
17101             "one  = 1;\n"
17102             "\n"
17103             "oneTwoThree = 123;\n",
17104             format("a += 5;\n"
17105                    "one = 1;\n"
17106                    "\n"
17107                    "oneTwoThree = 123;\n",
17108                    Alignment));
17109   EXPECT_EQ("a           += 5;\n"
17110             "one          = 1;\n"
17111             "//\n"
17112             "oneTwoThree  = 123;\n",
17113             format("a += 5;\n"
17114                    "one = 1;\n"
17115                    "//\n"
17116                    "oneTwoThree = 123;\n",
17117                    Alignment));
17118   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
17119   EXPECT_EQ("a            += 5;\n"
17120             "one         >>= 1;\n"
17121             "\n"
17122             "oneTwoThree   = 123;\n",
17123             format("a += 5;\n"
17124                    "one >>= 1;\n"
17125                    "\n"
17126                    "oneTwoThree = 123;\n",
17127                    Alignment));
17128   EXPECT_EQ("a            += 5;\n"
17129             "one           = 1;\n"
17130             "//\n"
17131             "oneTwoThree <<= 123;\n",
17132             format("a += 5;\n"
17133                    "one = 1;\n"
17134                    "//\n"
17135                    "oneTwoThree <<= 123;\n",
17136                    Alignment));
17137 }
17138 
17139 TEST_F(FormatTest, AlignConsecutiveAssignments) {
17140   FormatStyle Alignment = getLLVMStyle();
17141   Alignment.AlignConsecutiveMacros.Enabled = true;
17142   verifyFormat("int a = 5;\n"
17143                "int oneTwoThree = 123;",
17144                Alignment);
17145   verifyFormat("int a = 5;\n"
17146                "int oneTwoThree = 123;",
17147                Alignment);
17148 
17149   Alignment.AlignConsecutiveAssignments.Enabled = true;
17150   verifyFormat("int a           = 5;\n"
17151                "int oneTwoThree = 123;",
17152                Alignment);
17153   verifyFormat("int a           = method();\n"
17154                "int oneTwoThree = 133;",
17155                Alignment);
17156   verifyFormat("aa <= 5;\n"
17157                "a &= 5;\n"
17158                "bcd *= 5;\n"
17159                "ghtyf += 5;\n"
17160                "dvfvdb -= 5;\n"
17161                "a /= 5;\n"
17162                "vdsvsv %= 5;\n"
17163                "sfdbddfbdfbb ^= 5;\n"
17164                "dvsdsv |= 5;\n"
17165                "int dsvvdvsdvvv = 123;",
17166                Alignment);
17167   verifyFormat("int i = 1, j = 10;\n"
17168                "something = 2000;",
17169                Alignment);
17170   verifyFormat("something = 2000;\n"
17171                "int i = 1, j = 10;\n",
17172                Alignment);
17173   verifyFormat("something = 2000;\n"
17174                "another   = 911;\n"
17175                "int i = 1, j = 10;\n"
17176                "oneMore = 1;\n"
17177                "i       = 2;",
17178                Alignment);
17179   verifyFormat("int a   = 5;\n"
17180                "int one = 1;\n"
17181                "method();\n"
17182                "int oneTwoThree = 123;\n"
17183                "int oneTwo      = 12;",
17184                Alignment);
17185   verifyFormat("int oneTwoThree = 123;\n"
17186                "int oneTwo      = 12;\n"
17187                "method();\n",
17188                Alignment);
17189   verifyFormat("int oneTwoThree = 123; // comment\n"
17190                "int oneTwo      = 12;  // comment",
17191                Alignment);
17192   verifyFormat("int f()         = default;\n"
17193                "int &operator() = default;\n"
17194                "int &operator=() {",
17195                Alignment);
17196   verifyFormat("int f()         = delete;\n"
17197                "int &operator() = delete;\n"
17198                "int &operator=() {",
17199                Alignment);
17200   verifyFormat("int f()         = default; // comment\n"
17201                "int &operator() = default; // comment\n"
17202                "int &operator=() {",
17203                Alignment);
17204   verifyFormat("int f()         = default;\n"
17205                "int &operator() = default;\n"
17206                "int &operator==() {",
17207                Alignment);
17208   verifyFormat("int f()         = default;\n"
17209                "int &operator() = default;\n"
17210                "int &operator<=() {",
17211                Alignment);
17212   verifyFormat("int f()         = default;\n"
17213                "int &operator() = default;\n"
17214                "int &operator!=() {",
17215                Alignment);
17216   verifyFormat("int f()         = default;\n"
17217                "int &operator() = default;\n"
17218                "int &operator=();",
17219                Alignment);
17220   verifyFormat("int f()         = delete;\n"
17221                "int &operator() = delete;\n"
17222                "int &operator=();",
17223                Alignment);
17224   verifyFormat("/* long long padding */ int f() = default;\n"
17225                "int &operator()                 = default;\n"
17226                "int &operator/**/ =();",
17227                Alignment);
17228   // https://llvm.org/PR33697
17229   FormatStyle AlignmentWithPenalty = getLLVMStyle();
17230   AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true;
17231   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
17232   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
17233                "  void f() = delete;\n"
17234                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
17235                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
17236                "};\n",
17237                AlignmentWithPenalty);
17238 
17239   // Bug 25167
17240   /* Uncomment when fixed
17241     verifyFormat("#if A\n"
17242                  "#else\n"
17243                  "int aaaaaaaa = 12;\n"
17244                  "#endif\n"
17245                  "#if B\n"
17246                  "#else\n"
17247                  "int a = 12;\n"
17248                  "#endif\n",
17249                  Alignment);
17250     verifyFormat("enum foo {\n"
17251                  "#if A\n"
17252                  "#else\n"
17253                  "  aaaaaaaa = 12;\n"
17254                  "#endif\n"
17255                  "#if B\n"
17256                  "#else\n"
17257                  "  a = 12;\n"
17258                  "#endif\n"
17259                  "};\n",
17260                  Alignment);
17261   */
17262 
17263   EXPECT_EQ("int a = 5;\n"
17264             "\n"
17265             "int oneTwoThree = 123;",
17266             format("int a       = 5;\n"
17267                    "\n"
17268                    "int oneTwoThree= 123;",
17269                    Alignment));
17270   EXPECT_EQ("int a   = 5;\n"
17271             "int one = 1;\n"
17272             "\n"
17273             "int oneTwoThree = 123;",
17274             format("int a = 5;\n"
17275                    "int one = 1;\n"
17276                    "\n"
17277                    "int oneTwoThree = 123;",
17278                    Alignment));
17279   EXPECT_EQ("int a   = 5;\n"
17280             "int one = 1;\n"
17281             "\n"
17282             "int oneTwoThree = 123;\n"
17283             "int oneTwo      = 12;",
17284             format("int a = 5;\n"
17285                    "int one = 1;\n"
17286                    "\n"
17287                    "int oneTwoThree = 123;\n"
17288                    "int oneTwo = 12;",
17289                    Alignment));
17290   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17291   verifyFormat("#define A \\\n"
17292                "  int aaaa       = 12; \\\n"
17293                "  int b          = 23; \\\n"
17294                "  int ccc        = 234; \\\n"
17295                "  int dddddddddd = 2345;",
17296                Alignment);
17297   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17298   verifyFormat("#define A               \\\n"
17299                "  int aaaa       = 12;  \\\n"
17300                "  int b          = 23;  \\\n"
17301                "  int ccc        = 234; \\\n"
17302                "  int dddddddddd = 2345;",
17303                Alignment);
17304   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17305   verifyFormat("#define A                                                      "
17306                "                \\\n"
17307                "  int aaaa       = 12;                                         "
17308                "                \\\n"
17309                "  int b          = 23;                                         "
17310                "                \\\n"
17311                "  int ccc        = 234;                                        "
17312                "                \\\n"
17313                "  int dddddddddd = 2345;",
17314                Alignment);
17315   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17316                "k = 4, int l = 5,\n"
17317                "                  int m = 6) {\n"
17318                "  int j      = 10;\n"
17319                "  otherThing = 1;\n"
17320                "}",
17321                Alignment);
17322   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17323                "  int i   = 1;\n"
17324                "  int j   = 2;\n"
17325                "  int big = 10000;\n"
17326                "}",
17327                Alignment);
17328   verifyFormat("class C {\n"
17329                "public:\n"
17330                "  int i            = 1;\n"
17331                "  virtual void f() = 0;\n"
17332                "};",
17333                Alignment);
17334   verifyFormat("int i = 1;\n"
17335                "if (SomeType t = getSomething()) {\n"
17336                "}\n"
17337                "int j   = 2;\n"
17338                "int big = 10000;",
17339                Alignment);
17340   verifyFormat("int j = 7;\n"
17341                "for (int k = 0; k < N; ++k) {\n"
17342                "}\n"
17343                "int j   = 2;\n"
17344                "int big = 10000;\n"
17345                "}",
17346                Alignment);
17347   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17348   verifyFormat("int i = 1;\n"
17349                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17350                "    = someLooooooooooooooooongFunction();\n"
17351                "int j = 2;",
17352                Alignment);
17353   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17354   verifyFormat("int i = 1;\n"
17355                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17356                "    someLooooooooooooooooongFunction();\n"
17357                "int j = 2;",
17358                Alignment);
17359 
17360   verifyFormat("auto lambda = []() {\n"
17361                "  auto i = 0;\n"
17362                "  return 0;\n"
17363                "};\n"
17364                "int i  = 0;\n"
17365                "auto v = type{\n"
17366                "    i = 1,   //\n"
17367                "    (i = 2), //\n"
17368                "    i = 3    //\n"
17369                "};",
17370                Alignment);
17371 
17372   verifyFormat(
17373       "int i      = 1;\n"
17374       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17375       "                          loooooooooooooooooooooongParameterB);\n"
17376       "int j      = 2;",
17377       Alignment);
17378 
17379   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17380                "          typename B   = very_long_type_name_1,\n"
17381                "          typename T_2 = very_long_type_name_2>\n"
17382                "auto foo() {}\n",
17383                Alignment);
17384   verifyFormat("int a, b = 1;\n"
17385                "int c  = 2;\n"
17386                "int dd = 3;\n",
17387                Alignment);
17388   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17389                "float b[1][] = {{3.f}};\n",
17390                Alignment);
17391   verifyFormat("for (int i = 0; i < 1; i++)\n"
17392                "  int x = 1;\n",
17393                Alignment);
17394   verifyFormat("for (i = 0; i < 1; i++)\n"
17395                "  x = 1;\n"
17396                "y = 1;\n",
17397                Alignment);
17398 
17399   EXPECT_EQ(Alignment.ReflowComments, true);
17400   Alignment.ColumnLimit = 50;
17401   EXPECT_EQ("int x   = 0;\n"
17402             "int yy  = 1; /// specificlennospace\n"
17403             "int zzz = 2;\n",
17404             format("int x   = 0;\n"
17405                    "int yy  = 1; ///specificlennospace\n"
17406                    "int zzz = 2;\n",
17407                    Alignment));
17408 
17409   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17410                "auto b                     = [] {\n"
17411                "  f();\n"
17412                "  return;\n"
17413                "};",
17414                Alignment);
17415   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17416                "auto b                     = g([] {\n"
17417                "  f();\n"
17418                "  return;\n"
17419                "});",
17420                Alignment);
17421   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17422                "auto b                     = g(param, [] {\n"
17423                "  f();\n"
17424                "  return;\n"
17425                "});",
17426                Alignment);
17427   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17428                "auto b                     = [] {\n"
17429                "  if (condition) {\n"
17430                "    return;\n"
17431                "  }\n"
17432                "};",
17433                Alignment);
17434 
17435   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17436                "           ccc ? aaaaa : bbbbb,\n"
17437                "           dddddddddddddddddddddddddd);",
17438                Alignment);
17439   // FIXME: https://llvm.org/PR53497
17440   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
17441   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17442   //              "    ccc ? aaaaa : bbbbb,\n"
17443   //              "    dddddddddddddddddddddddddd);",
17444   //              Alignment);
17445 
17446   // Confirm proper handling of AlignConsecutiveAssignments with
17447   // BinPackArguments.
17448   // See https://llvm.org/PR55360
17449   Alignment = getLLVMStyleWithColumns(50);
17450   Alignment.AlignConsecutiveAssignments.Enabled = true;
17451   Alignment.BinPackArguments = false;
17452   verifyFormat("int a_long_name = 1;\n"
17453                "auto b          = B({a_long_name, a_long_name},\n"
17454                "                    {a_longer_name_for_wrap,\n"
17455                "                     a_longer_name_for_wrap});",
17456                Alignment);
17457   verifyFormat("int a_long_name = 1;\n"
17458                "auto b          = B{{a_long_name, a_long_name},\n"
17459                "                    {a_longer_name_for_wrap,\n"
17460                "                     a_longer_name_for_wrap}};",
17461                Alignment);
17462 }
17463 
17464 TEST_F(FormatTest, AlignConsecutiveBitFields) {
17465   FormatStyle Alignment = getLLVMStyle();
17466   Alignment.AlignConsecutiveBitFields.Enabled = true;
17467   verifyFormat("int const a     : 5;\n"
17468                "int oneTwoThree : 23;",
17469                Alignment);
17470 
17471   // Initializers are allowed starting with c++2a
17472   verifyFormat("int const a     : 5 = 1;\n"
17473                "int oneTwoThree : 23 = 0;",
17474                Alignment);
17475 
17476   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17477   verifyFormat("int const a           : 5;\n"
17478                "int       oneTwoThree : 23;",
17479                Alignment);
17480 
17481   verifyFormat("int const a           : 5;  // comment\n"
17482                "int       oneTwoThree : 23; // comment",
17483                Alignment);
17484 
17485   verifyFormat("int const a           : 5 = 1;\n"
17486                "int       oneTwoThree : 23 = 0;",
17487                Alignment);
17488 
17489   Alignment.AlignConsecutiveAssignments.Enabled = true;
17490   verifyFormat("int const a           : 5  = 1;\n"
17491                "int       oneTwoThree : 23 = 0;",
17492                Alignment);
17493   verifyFormat("int const a           : 5  = {1};\n"
17494                "int       oneTwoThree : 23 = 0;",
17495                Alignment);
17496 
17497   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
17498   verifyFormat("int const a          :5;\n"
17499                "int       oneTwoThree:23;",
17500                Alignment);
17501 
17502   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
17503   verifyFormat("int const a           :5;\n"
17504                "int       oneTwoThree :23;",
17505                Alignment);
17506 
17507   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
17508   verifyFormat("int const a          : 5;\n"
17509                "int       oneTwoThree: 23;",
17510                Alignment);
17511 
17512   // Known limitations: ':' is only recognized as a bitfield colon when
17513   // followed by a number.
17514   /*
17515   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
17516                "int a           : 5;",
17517                Alignment);
17518   */
17519 }
17520 
17521 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
17522   FormatStyle Alignment = getLLVMStyle();
17523   Alignment.AlignConsecutiveMacros.Enabled = true;
17524   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17525   verifyFormat("float const a = 5;\n"
17526                "int oneTwoThree = 123;",
17527                Alignment);
17528   verifyFormat("int a = 5;\n"
17529                "float const oneTwoThree = 123;",
17530                Alignment);
17531 
17532   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17533   verifyFormat("float const a = 5;\n"
17534                "int         oneTwoThree = 123;",
17535                Alignment);
17536   verifyFormat("int         a = method();\n"
17537                "float const oneTwoThree = 133;",
17538                Alignment);
17539   verifyFormat("int i = 1, j = 10;\n"
17540                "something = 2000;",
17541                Alignment);
17542   verifyFormat("something = 2000;\n"
17543                "int i = 1, j = 10;\n",
17544                Alignment);
17545   verifyFormat("float      something = 2000;\n"
17546                "double     another = 911;\n"
17547                "int        i = 1, j = 10;\n"
17548                "const int *oneMore = 1;\n"
17549                "unsigned   i = 2;",
17550                Alignment);
17551   verifyFormat("float a = 5;\n"
17552                "int   one = 1;\n"
17553                "method();\n"
17554                "const double       oneTwoThree = 123;\n"
17555                "const unsigned int oneTwo = 12;",
17556                Alignment);
17557   verifyFormat("int      oneTwoThree{0}; // comment\n"
17558                "unsigned oneTwo;         // comment",
17559                Alignment);
17560   verifyFormat("unsigned int       *a;\n"
17561                "int                *b;\n"
17562                "unsigned int Const *c;\n"
17563                "unsigned int const *d;\n"
17564                "unsigned int Const &e;\n"
17565                "unsigned int const &f;",
17566                Alignment);
17567   verifyFormat("Const unsigned int *c;\n"
17568                "const unsigned int *d;\n"
17569                "Const unsigned int &e;\n"
17570                "const unsigned int &f;\n"
17571                "const unsigned      g;\n"
17572                "Const unsigned      h;",
17573                Alignment);
17574   EXPECT_EQ("float const a = 5;\n"
17575             "\n"
17576             "int oneTwoThree = 123;",
17577             format("float const   a = 5;\n"
17578                    "\n"
17579                    "int           oneTwoThree= 123;",
17580                    Alignment));
17581   EXPECT_EQ("float a = 5;\n"
17582             "int   one = 1;\n"
17583             "\n"
17584             "unsigned oneTwoThree = 123;",
17585             format("float    a = 5;\n"
17586                    "int      one = 1;\n"
17587                    "\n"
17588                    "unsigned oneTwoThree = 123;",
17589                    Alignment));
17590   EXPECT_EQ("float a = 5;\n"
17591             "int   one = 1;\n"
17592             "\n"
17593             "unsigned oneTwoThree = 123;\n"
17594             "int      oneTwo = 12;",
17595             format("float    a = 5;\n"
17596                    "int one = 1;\n"
17597                    "\n"
17598                    "unsigned oneTwoThree = 123;\n"
17599                    "int oneTwo = 12;",
17600                    Alignment));
17601   // Function prototype alignment
17602   verifyFormat("int    a();\n"
17603                "double b();",
17604                Alignment);
17605   verifyFormat("int    a(int x);\n"
17606                "double b();",
17607                Alignment);
17608   unsigned OldColumnLimit = Alignment.ColumnLimit;
17609   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17610   // otherwise the function parameters will be re-flowed onto a single line.
17611   Alignment.ColumnLimit = 0;
17612   EXPECT_EQ("int    a(int   x,\n"
17613             "         float y);\n"
17614             "double b(int    x,\n"
17615             "         double y);",
17616             format("int a(int x,\n"
17617                    " float y);\n"
17618                    "double b(int x,\n"
17619                    " double y);",
17620                    Alignment));
17621   // This ensures that function parameters of function declarations are
17622   // correctly indented when their owning functions are indented.
17623   // The failure case here is for 'double y' to not be indented enough.
17624   EXPECT_EQ("double a(int x);\n"
17625             "int    b(int    y,\n"
17626             "         double z);",
17627             format("double a(int x);\n"
17628                    "int b(int y,\n"
17629                    " double z);",
17630                    Alignment));
17631   // Set ColumnLimit low so that we induce wrapping immediately after
17632   // the function name and opening paren.
17633   Alignment.ColumnLimit = 13;
17634   verifyFormat("int function(\n"
17635                "    int  x,\n"
17636                "    bool y);",
17637                Alignment);
17638   Alignment.ColumnLimit = OldColumnLimit;
17639   // Ensure function pointers don't screw up recursive alignment
17640   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17641                "double b();",
17642                Alignment);
17643   Alignment.AlignConsecutiveAssignments.Enabled = true;
17644   // Ensure recursive alignment is broken by function braces, so that the
17645   // "a = 1" does not align with subsequent assignments inside the function
17646   // body.
17647   verifyFormat("int func(int a = 1) {\n"
17648                "  int b  = 2;\n"
17649                "  int cc = 3;\n"
17650                "}",
17651                Alignment);
17652   verifyFormat("float      something = 2000;\n"
17653                "double     another   = 911;\n"
17654                "int        i = 1, j = 10;\n"
17655                "const int *oneMore = 1;\n"
17656                "unsigned   i       = 2;",
17657                Alignment);
17658   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17659                "unsigned oneTwo      = 0;   // comment",
17660                Alignment);
17661   // Make sure that scope is correctly tracked, in the absence of braces
17662   verifyFormat("for (int i = 0; i < n; i++)\n"
17663                "  j = i;\n"
17664                "double x = 1;\n",
17665                Alignment);
17666   verifyFormat("if (int i = 0)\n"
17667                "  j = i;\n"
17668                "double x = 1;\n",
17669                Alignment);
17670   // Ensure operator[] and operator() are comprehended
17671   verifyFormat("struct test {\n"
17672                "  long long int foo();\n"
17673                "  int           operator[](int a);\n"
17674                "  double        bar();\n"
17675                "};\n",
17676                Alignment);
17677   verifyFormat("struct test {\n"
17678                "  long long int foo();\n"
17679                "  int           operator()(int a);\n"
17680                "  double        bar();\n"
17681                "};\n",
17682                Alignment);
17683   // http://llvm.org/PR52914
17684   verifyFormat("char *a[]     = {\"a\", // comment\n"
17685                "                 \"bb\"};\n"
17686                "int   bbbbbbb = 0;",
17687                Alignment);
17688 
17689   // PAS_Right
17690   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17691             "  int const i   = 1;\n"
17692             "  int      *j   = 2;\n"
17693             "  int       big = 10000;\n"
17694             "\n"
17695             "  unsigned oneTwoThree = 123;\n"
17696             "  int      oneTwo      = 12;\n"
17697             "  method();\n"
17698             "  float k  = 2;\n"
17699             "  int   ll = 10000;\n"
17700             "}",
17701             format("void SomeFunction(int parameter= 0) {\n"
17702                    " int const  i= 1;\n"
17703                    "  int *j=2;\n"
17704                    " int big  =  10000;\n"
17705                    "\n"
17706                    "unsigned oneTwoThree  =123;\n"
17707                    "int oneTwo = 12;\n"
17708                    "  method();\n"
17709                    "float k= 2;\n"
17710                    "int ll=10000;\n"
17711                    "}",
17712                    Alignment));
17713   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17714             "  int const i   = 1;\n"
17715             "  int     **j   = 2, ***k;\n"
17716             "  int      &k   = i;\n"
17717             "  int     &&l   = i + j;\n"
17718             "  int       big = 10000;\n"
17719             "\n"
17720             "  unsigned oneTwoThree = 123;\n"
17721             "  int      oneTwo      = 12;\n"
17722             "  method();\n"
17723             "  float k  = 2;\n"
17724             "  int   ll = 10000;\n"
17725             "}",
17726             format("void SomeFunction(int parameter= 0) {\n"
17727                    " int const  i= 1;\n"
17728                    "  int **j=2,***k;\n"
17729                    "int &k=i;\n"
17730                    "int &&l=i+j;\n"
17731                    " int big  =  10000;\n"
17732                    "\n"
17733                    "unsigned oneTwoThree  =123;\n"
17734                    "int oneTwo = 12;\n"
17735                    "  method();\n"
17736                    "float k= 2;\n"
17737                    "int ll=10000;\n"
17738                    "}",
17739                    Alignment));
17740   // variables are aligned at their name, pointers are at the right most
17741   // position
17742   verifyFormat("int   *a;\n"
17743                "int  **b;\n"
17744                "int ***c;\n"
17745                "int    foobar;\n",
17746                Alignment);
17747 
17748   // PAS_Left
17749   FormatStyle AlignmentLeft = Alignment;
17750   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17751   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17752             "  int const i   = 1;\n"
17753             "  int*      j   = 2;\n"
17754             "  int       big = 10000;\n"
17755             "\n"
17756             "  unsigned oneTwoThree = 123;\n"
17757             "  int      oneTwo      = 12;\n"
17758             "  method();\n"
17759             "  float k  = 2;\n"
17760             "  int   ll = 10000;\n"
17761             "}",
17762             format("void SomeFunction(int parameter= 0) {\n"
17763                    " int const  i= 1;\n"
17764                    "  int *j=2;\n"
17765                    " int big  =  10000;\n"
17766                    "\n"
17767                    "unsigned oneTwoThree  =123;\n"
17768                    "int oneTwo = 12;\n"
17769                    "  method();\n"
17770                    "float k= 2;\n"
17771                    "int ll=10000;\n"
17772                    "}",
17773                    AlignmentLeft));
17774   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17775             "  int const i   = 1;\n"
17776             "  int**     j   = 2;\n"
17777             "  int&      k   = i;\n"
17778             "  int&&     l   = i + j;\n"
17779             "  int       big = 10000;\n"
17780             "\n"
17781             "  unsigned oneTwoThree = 123;\n"
17782             "  int      oneTwo      = 12;\n"
17783             "  method();\n"
17784             "  float k  = 2;\n"
17785             "  int   ll = 10000;\n"
17786             "}",
17787             format("void SomeFunction(int parameter= 0) {\n"
17788                    " int const  i= 1;\n"
17789                    "  int **j=2;\n"
17790                    "int &k=i;\n"
17791                    "int &&l=i+j;\n"
17792                    " int big  =  10000;\n"
17793                    "\n"
17794                    "unsigned oneTwoThree  =123;\n"
17795                    "int oneTwo = 12;\n"
17796                    "  method();\n"
17797                    "float k= 2;\n"
17798                    "int ll=10000;\n"
17799                    "}",
17800                    AlignmentLeft));
17801   // variables are aligned at their name, pointers are at the left most position
17802   verifyFormat("int*   a;\n"
17803                "int**  b;\n"
17804                "int*** c;\n"
17805                "int    foobar;\n",
17806                AlignmentLeft);
17807 
17808   // PAS_Middle
17809   FormatStyle AlignmentMiddle = Alignment;
17810   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17811   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17812             "  int const i   = 1;\n"
17813             "  int *     j   = 2;\n"
17814             "  int       big = 10000;\n"
17815             "\n"
17816             "  unsigned oneTwoThree = 123;\n"
17817             "  int      oneTwo      = 12;\n"
17818             "  method();\n"
17819             "  float k  = 2;\n"
17820             "  int   ll = 10000;\n"
17821             "}",
17822             format("void SomeFunction(int parameter= 0) {\n"
17823                    " int const  i= 1;\n"
17824                    "  int *j=2;\n"
17825                    " int big  =  10000;\n"
17826                    "\n"
17827                    "unsigned oneTwoThree  =123;\n"
17828                    "int oneTwo = 12;\n"
17829                    "  method();\n"
17830                    "float k= 2;\n"
17831                    "int ll=10000;\n"
17832                    "}",
17833                    AlignmentMiddle));
17834   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17835             "  int const i   = 1;\n"
17836             "  int **    j   = 2, ***k;\n"
17837             "  int &     k   = i;\n"
17838             "  int &&    l   = i + j;\n"
17839             "  int       big = 10000;\n"
17840             "\n"
17841             "  unsigned oneTwoThree = 123;\n"
17842             "  int      oneTwo      = 12;\n"
17843             "  method();\n"
17844             "  float k  = 2;\n"
17845             "  int   ll = 10000;\n"
17846             "}",
17847             format("void SomeFunction(int parameter= 0) {\n"
17848                    " int const  i= 1;\n"
17849                    "  int **j=2,***k;\n"
17850                    "int &k=i;\n"
17851                    "int &&l=i+j;\n"
17852                    " int big  =  10000;\n"
17853                    "\n"
17854                    "unsigned oneTwoThree  =123;\n"
17855                    "int oneTwo = 12;\n"
17856                    "  method();\n"
17857                    "float k= 2;\n"
17858                    "int ll=10000;\n"
17859                    "}",
17860                    AlignmentMiddle));
17861   // variables are aligned at their name, pointers are in the middle
17862   verifyFormat("int *   a;\n"
17863                "int *   b;\n"
17864                "int *** c;\n"
17865                "int     foobar;\n",
17866                AlignmentMiddle);
17867 
17868   Alignment.AlignConsecutiveAssignments.Enabled = false;
17869   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17870   verifyFormat("#define A \\\n"
17871                "  int       aaaa = 12; \\\n"
17872                "  float     b = 23; \\\n"
17873                "  const int ccc = 234; \\\n"
17874                "  unsigned  dddddddddd = 2345;",
17875                Alignment);
17876   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17877   verifyFormat("#define A              \\\n"
17878                "  int       aaaa = 12; \\\n"
17879                "  float     b = 23;    \\\n"
17880                "  const int ccc = 234; \\\n"
17881                "  unsigned  dddddddddd = 2345;",
17882                Alignment);
17883   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17884   Alignment.ColumnLimit = 30;
17885   verifyFormat("#define A                    \\\n"
17886                "  int       aaaa = 12;       \\\n"
17887                "  float     b = 23;          \\\n"
17888                "  const int ccc = 234;       \\\n"
17889                "  int       dddddddddd = 2345;",
17890                Alignment);
17891   Alignment.ColumnLimit = 80;
17892   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17893                "k = 4, int l = 5,\n"
17894                "                  int m = 6) {\n"
17895                "  const int j = 10;\n"
17896                "  otherThing = 1;\n"
17897                "}",
17898                Alignment);
17899   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17900                "  int const i = 1;\n"
17901                "  int      *j = 2;\n"
17902                "  int       big = 10000;\n"
17903                "}",
17904                Alignment);
17905   verifyFormat("class C {\n"
17906                "public:\n"
17907                "  int          i = 1;\n"
17908                "  virtual void f() = 0;\n"
17909                "};",
17910                Alignment);
17911   verifyFormat("float i = 1;\n"
17912                "if (SomeType t = getSomething()) {\n"
17913                "}\n"
17914                "const unsigned j = 2;\n"
17915                "int            big = 10000;",
17916                Alignment);
17917   verifyFormat("float j = 7;\n"
17918                "for (int k = 0; k < N; ++k) {\n"
17919                "}\n"
17920                "unsigned j = 2;\n"
17921                "int      big = 10000;\n"
17922                "}",
17923                Alignment);
17924   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17925   verifyFormat("float              i = 1;\n"
17926                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17927                "    = someLooooooooooooooooongFunction();\n"
17928                "int j = 2;",
17929                Alignment);
17930   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17931   verifyFormat("int                i = 1;\n"
17932                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17933                "    someLooooooooooooooooongFunction();\n"
17934                "int j = 2;",
17935                Alignment);
17936 
17937   Alignment.AlignConsecutiveAssignments.Enabled = true;
17938   verifyFormat("auto lambda = []() {\n"
17939                "  auto  ii = 0;\n"
17940                "  float j  = 0;\n"
17941                "  return 0;\n"
17942                "};\n"
17943                "int   i  = 0;\n"
17944                "float i2 = 0;\n"
17945                "auto  v  = type{\n"
17946                "    i = 1,   //\n"
17947                "    (i = 2), //\n"
17948                "    i = 3    //\n"
17949                "};",
17950                Alignment);
17951   Alignment.AlignConsecutiveAssignments.Enabled = false;
17952 
17953   verifyFormat(
17954       "int      i = 1;\n"
17955       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17956       "                          loooooooooooooooooooooongParameterB);\n"
17957       "int      j = 2;",
17958       Alignment);
17959 
17960   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17961   // We expect declarations and assignments to align, as long as it doesn't
17962   // exceed the column limit, starting a new alignment sequence whenever it
17963   // happens.
17964   Alignment.AlignConsecutiveAssignments.Enabled = true;
17965   Alignment.ColumnLimit = 30;
17966   verifyFormat("float    ii              = 1;\n"
17967                "unsigned j               = 2;\n"
17968                "int someVerylongVariable = 1;\n"
17969                "AnotherLongType  ll = 123456;\n"
17970                "VeryVeryLongType k  = 2;\n"
17971                "int              myvar = 1;",
17972                Alignment);
17973   Alignment.ColumnLimit = 80;
17974   Alignment.AlignConsecutiveAssignments.Enabled = false;
17975 
17976   verifyFormat(
17977       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17978       "          typename LongType, typename B>\n"
17979       "auto foo() {}\n",
17980       Alignment);
17981   verifyFormat("float a, b = 1;\n"
17982                "int   c = 2;\n"
17983                "int   dd = 3;\n",
17984                Alignment);
17985   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17986                "float b[1][] = {{3.f}};\n",
17987                Alignment);
17988   Alignment.AlignConsecutiveAssignments.Enabled = true;
17989   verifyFormat("float a, b = 1;\n"
17990                "int   c  = 2;\n"
17991                "int   dd = 3;\n",
17992                Alignment);
17993   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17994                "float b[1][] = {{3.f}};\n",
17995                Alignment);
17996   Alignment.AlignConsecutiveAssignments.Enabled = false;
17997 
17998   Alignment.ColumnLimit = 30;
17999   Alignment.BinPackParameters = false;
18000   verifyFormat("void foo(float     a,\n"
18001                "         float     b,\n"
18002                "         int       c,\n"
18003                "         uint32_t *d) {\n"
18004                "  int   *e = 0;\n"
18005                "  float  f = 0;\n"
18006                "  double g = 0;\n"
18007                "}\n"
18008                "void bar(ino_t     a,\n"
18009                "         int       b,\n"
18010                "         uint32_t *c,\n"
18011                "         bool      d) {}\n",
18012                Alignment);
18013   Alignment.BinPackParameters = true;
18014   Alignment.ColumnLimit = 80;
18015 
18016   // Bug 33507
18017   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
18018   verifyFormat(
18019       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
18020       "  static const Version verVs2017;\n"
18021       "  return true;\n"
18022       "});\n",
18023       Alignment);
18024   Alignment.PointerAlignment = FormatStyle::PAS_Right;
18025 
18026   // See llvm.org/PR35641
18027   Alignment.AlignConsecutiveDeclarations.Enabled = true;
18028   verifyFormat("int func() { //\n"
18029                "  int      b;\n"
18030                "  unsigned c;\n"
18031                "}",
18032                Alignment);
18033 
18034   // See PR37175
18035   FormatStyle Style = getMozillaStyle();
18036   Style.AlignConsecutiveDeclarations.Enabled = true;
18037   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
18038             "foo(int a);",
18039             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
18040 
18041   Alignment.PointerAlignment = FormatStyle::PAS_Left;
18042   verifyFormat("unsigned int*       a;\n"
18043                "int*                b;\n"
18044                "unsigned int Const* c;\n"
18045                "unsigned int const* d;\n"
18046                "unsigned int Const& e;\n"
18047                "unsigned int const& f;",
18048                Alignment);
18049   verifyFormat("Const unsigned int* c;\n"
18050                "const unsigned int* d;\n"
18051                "Const unsigned int& e;\n"
18052                "const unsigned int& f;\n"
18053                "const unsigned      g;\n"
18054                "Const unsigned      h;",
18055                Alignment);
18056 
18057   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
18058   verifyFormat("unsigned int *       a;\n"
18059                "int *                b;\n"
18060                "unsigned int Const * c;\n"
18061                "unsigned int const * d;\n"
18062                "unsigned int Const & e;\n"
18063                "unsigned int const & f;",
18064                Alignment);
18065   verifyFormat("Const unsigned int * c;\n"
18066                "const unsigned int * d;\n"
18067                "Const unsigned int & e;\n"
18068                "const unsigned int & f;\n"
18069                "const unsigned       g;\n"
18070                "Const unsigned       h;",
18071                Alignment);
18072 
18073   // See PR46529
18074   FormatStyle BracedAlign = getLLVMStyle();
18075   BracedAlign.AlignConsecutiveDeclarations.Enabled = true;
18076   verifyFormat("const auto result{[]() {\n"
18077                "  const auto something = 1;\n"
18078                "  return 2;\n"
18079                "}};",
18080                BracedAlign);
18081   verifyFormat("int foo{[]() {\n"
18082                "  int bar{0};\n"
18083                "  return 0;\n"
18084                "}()};",
18085                BracedAlign);
18086   BracedAlign.Cpp11BracedListStyle = false;
18087   verifyFormat("const auto result{ []() {\n"
18088                "  const auto something = 1;\n"
18089                "  return 2;\n"
18090                "} };",
18091                BracedAlign);
18092   verifyFormat("int foo{ []() {\n"
18093                "  int bar{ 0 };\n"
18094                "  return 0;\n"
18095                "}() };",
18096                BracedAlign);
18097 }
18098 
18099 TEST_F(FormatTest, AlignWithLineBreaks) {
18100   auto Style = getLLVMStyleWithColumns(120);
18101 
18102   EXPECT_EQ(Style.AlignConsecutiveAssignments,
18103             FormatStyle::AlignConsecutiveStyle(
18104                 {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
18105                  /*AcrossComments=*/false, /*AlignCompound=*/false,
18106                  /*PadOperators=*/true}));
18107   EXPECT_EQ(Style.AlignConsecutiveDeclarations,
18108             FormatStyle::AlignConsecutiveStyle({}));
18109   verifyFormat("void foo() {\n"
18110                "  int myVar = 5;\n"
18111                "  double x = 3.14;\n"
18112                "  auto str = \"Hello \"\n"
18113                "             \"World\";\n"
18114                "  auto s = \"Hello \"\n"
18115                "           \"Again\";\n"
18116                "}",
18117                Style);
18118 
18119   // clang-format off
18120   verifyFormat("void foo() {\n"
18121                "  const int capacityBefore = Entries.capacity();\n"
18122                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18123                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18124                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18125                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18126                "}",
18127                Style);
18128   // clang-format on
18129 
18130   Style.AlignConsecutiveAssignments.Enabled = true;
18131   verifyFormat("void foo() {\n"
18132                "  int myVar = 5;\n"
18133                "  double x  = 3.14;\n"
18134                "  auto str  = \"Hello \"\n"
18135                "              \"World\";\n"
18136                "  auto s    = \"Hello \"\n"
18137                "              \"Again\";\n"
18138                "}",
18139                Style);
18140 
18141   // clang-format off
18142   verifyFormat("void foo() {\n"
18143                "  const int capacityBefore = Entries.capacity();\n"
18144                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18145                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18146                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18147                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18148                "}",
18149                Style);
18150   // clang-format on
18151 
18152   Style.AlignConsecutiveAssignments.Enabled = false;
18153   Style.AlignConsecutiveDeclarations.Enabled = true;
18154   verifyFormat("void foo() {\n"
18155                "  int    myVar = 5;\n"
18156                "  double x = 3.14;\n"
18157                "  auto   str = \"Hello \"\n"
18158                "               \"World\";\n"
18159                "  auto   s = \"Hello \"\n"
18160                "             \"Again\";\n"
18161                "}",
18162                Style);
18163 
18164   // clang-format off
18165   verifyFormat("void foo() {\n"
18166                "  const int  capacityBefore = Entries.capacity();\n"
18167                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18168                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18169                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18170                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18171                "}",
18172                Style);
18173   // clang-format on
18174 
18175   Style.AlignConsecutiveAssignments.Enabled = true;
18176   Style.AlignConsecutiveDeclarations.Enabled = true;
18177 
18178   verifyFormat("void foo() {\n"
18179                "  int    myVar = 5;\n"
18180                "  double x     = 3.14;\n"
18181                "  auto   str   = \"Hello \"\n"
18182                "                 \"World\";\n"
18183                "  auto   s     = \"Hello \"\n"
18184                "                 \"Again\";\n"
18185                "}",
18186                Style);
18187 
18188   // clang-format off
18189   verifyFormat("void foo() {\n"
18190                "  const int  capacityBefore = Entries.capacity();\n"
18191                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18192                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18193                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18194                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18195                "}",
18196                Style);
18197   // clang-format on
18198 
18199   Style = getLLVMStyleWithColumns(20);
18200   Style.AlignConsecutiveAssignments.Enabled = true;
18201   Style.IndentWidth = 4;
18202 
18203   verifyFormat("void foo() {\n"
18204                "    int i1 = 1;\n"
18205                "    int j  = 0;\n"
18206                "    int k  = bar(\n"
18207                "        argument1,\n"
18208                "        argument2);\n"
18209                "}",
18210                Style);
18211 
18212   verifyFormat("unsigned i = 0;\n"
18213                "int a[]    = {\n"
18214                "    1234567890,\n"
18215                "    -1234567890};",
18216                Style);
18217 
18218   Style.ColumnLimit = 120;
18219 
18220   // clang-format off
18221   verifyFormat("void SomeFunc() {\n"
18222                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18223                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18224                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18225                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18226                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18227                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18228                "}",
18229                Style);
18230   // clang-format on
18231 
18232   Style.BinPackArguments = false;
18233 
18234   // clang-format off
18235   verifyFormat("void SomeFunc() {\n"
18236                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
18237                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18238                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
18239                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18240                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
18241                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18242                "}",
18243                Style);
18244   // clang-format on
18245 }
18246 
18247 TEST_F(FormatTest, AlignWithInitializerPeriods) {
18248   auto Style = getLLVMStyleWithColumns(60);
18249 
18250   verifyFormat("void foo1(void) {\n"
18251                "  BYTE p[1] = 1;\n"
18252                "  A B = {.one_foooooooooooooooo = 2,\n"
18253                "         .two_fooooooooooooo = 3,\n"
18254                "         .three_fooooooooooooo = 4};\n"
18255                "  BYTE payload = 2;\n"
18256                "}",
18257                Style);
18258 
18259   Style.AlignConsecutiveAssignments.Enabled = true;
18260   Style.AlignConsecutiveDeclarations.Enabled = false;
18261   verifyFormat("void foo2(void) {\n"
18262                "  BYTE p[1]    = 1;\n"
18263                "  A B          = {.one_foooooooooooooooo = 2,\n"
18264                "                  .two_fooooooooooooo    = 3,\n"
18265                "                  .three_fooooooooooooo  = 4};\n"
18266                "  BYTE payload = 2;\n"
18267                "}",
18268                Style);
18269 
18270   Style.AlignConsecutiveAssignments.Enabled = false;
18271   Style.AlignConsecutiveDeclarations.Enabled = true;
18272   verifyFormat("void foo3(void) {\n"
18273                "  BYTE p[1] = 1;\n"
18274                "  A    B = {.one_foooooooooooooooo = 2,\n"
18275                "            .two_fooooooooooooo = 3,\n"
18276                "            .three_fooooooooooooo = 4};\n"
18277                "  BYTE payload = 2;\n"
18278                "}",
18279                Style);
18280 
18281   Style.AlignConsecutiveAssignments.Enabled = true;
18282   Style.AlignConsecutiveDeclarations.Enabled = true;
18283   verifyFormat("void foo4(void) {\n"
18284                "  BYTE p[1]    = 1;\n"
18285                "  A    B       = {.one_foooooooooooooooo = 2,\n"
18286                "                  .two_fooooooooooooo    = 3,\n"
18287                "                  .three_fooooooooooooo  = 4};\n"
18288                "  BYTE payload = 2;\n"
18289                "}",
18290                Style);
18291 }
18292 
18293 TEST_F(FormatTest, LinuxBraceBreaking) {
18294   FormatStyle LinuxBraceStyle = getLLVMStyle();
18295   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
18296   verifyFormat("namespace a\n"
18297                "{\n"
18298                "class A\n"
18299                "{\n"
18300                "  void f()\n"
18301                "  {\n"
18302                "    if (true) {\n"
18303                "      a();\n"
18304                "      b();\n"
18305                "    } else {\n"
18306                "      a();\n"
18307                "    }\n"
18308                "  }\n"
18309                "  void g() { return; }\n"
18310                "};\n"
18311                "struct B {\n"
18312                "  int x;\n"
18313                "};\n"
18314                "} // namespace a\n",
18315                LinuxBraceStyle);
18316   verifyFormat("enum X {\n"
18317                "  Y = 0,\n"
18318                "}\n",
18319                LinuxBraceStyle);
18320   verifyFormat("struct S {\n"
18321                "  int Type;\n"
18322                "  union {\n"
18323                "    int x;\n"
18324                "    double y;\n"
18325                "  } Value;\n"
18326                "  class C\n"
18327                "  {\n"
18328                "    MyFavoriteType Value;\n"
18329                "  } Class;\n"
18330                "}\n",
18331                LinuxBraceStyle);
18332 }
18333 
18334 TEST_F(FormatTest, MozillaBraceBreaking) {
18335   FormatStyle MozillaBraceStyle = getLLVMStyle();
18336   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
18337   MozillaBraceStyle.FixNamespaceComments = false;
18338   verifyFormat("namespace a {\n"
18339                "class A\n"
18340                "{\n"
18341                "  void f()\n"
18342                "  {\n"
18343                "    if (true) {\n"
18344                "      a();\n"
18345                "      b();\n"
18346                "    }\n"
18347                "  }\n"
18348                "  void g() { return; }\n"
18349                "};\n"
18350                "enum E\n"
18351                "{\n"
18352                "  A,\n"
18353                "  // foo\n"
18354                "  B,\n"
18355                "  C\n"
18356                "};\n"
18357                "struct B\n"
18358                "{\n"
18359                "  int x;\n"
18360                "};\n"
18361                "}\n",
18362                MozillaBraceStyle);
18363   verifyFormat("struct S\n"
18364                "{\n"
18365                "  int Type;\n"
18366                "  union\n"
18367                "  {\n"
18368                "    int x;\n"
18369                "    double y;\n"
18370                "  } Value;\n"
18371                "  class C\n"
18372                "  {\n"
18373                "    MyFavoriteType Value;\n"
18374                "  } Class;\n"
18375                "}\n",
18376                MozillaBraceStyle);
18377 }
18378 
18379 TEST_F(FormatTest, StroustrupBraceBreaking) {
18380   FormatStyle StroustrupBraceStyle = getLLVMStyle();
18381   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18382   verifyFormat("namespace a {\n"
18383                "class A {\n"
18384                "  void f()\n"
18385                "  {\n"
18386                "    if (true) {\n"
18387                "      a();\n"
18388                "      b();\n"
18389                "    }\n"
18390                "  }\n"
18391                "  void g() { return; }\n"
18392                "};\n"
18393                "struct B {\n"
18394                "  int x;\n"
18395                "};\n"
18396                "} // namespace a\n",
18397                StroustrupBraceStyle);
18398 
18399   verifyFormat("void foo()\n"
18400                "{\n"
18401                "  if (a) {\n"
18402                "    a();\n"
18403                "  }\n"
18404                "  else {\n"
18405                "    b();\n"
18406                "  }\n"
18407                "}\n",
18408                StroustrupBraceStyle);
18409 
18410   verifyFormat("#ifdef _DEBUG\n"
18411                "int foo(int i = 0)\n"
18412                "#else\n"
18413                "int foo(int i = 5)\n"
18414                "#endif\n"
18415                "{\n"
18416                "  return i;\n"
18417                "}",
18418                StroustrupBraceStyle);
18419 
18420   verifyFormat("void foo() {}\n"
18421                "void bar()\n"
18422                "#ifdef _DEBUG\n"
18423                "{\n"
18424                "  foo();\n"
18425                "}\n"
18426                "#else\n"
18427                "{\n"
18428                "}\n"
18429                "#endif",
18430                StroustrupBraceStyle);
18431 
18432   verifyFormat("void foobar() { int i = 5; }\n"
18433                "#ifdef _DEBUG\n"
18434                "void bar() {}\n"
18435                "#else\n"
18436                "void bar() { foobar(); }\n"
18437                "#endif",
18438                StroustrupBraceStyle);
18439 }
18440 
18441 TEST_F(FormatTest, AllmanBraceBreaking) {
18442   FormatStyle AllmanBraceStyle = getLLVMStyle();
18443   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
18444 
18445   EXPECT_EQ("namespace a\n"
18446             "{\n"
18447             "void f();\n"
18448             "void g();\n"
18449             "} // namespace a\n",
18450             format("namespace a\n"
18451                    "{\n"
18452                    "void f();\n"
18453                    "void g();\n"
18454                    "}\n",
18455                    AllmanBraceStyle));
18456 
18457   verifyFormat("namespace a\n"
18458                "{\n"
18459                "class A\n"
18460                "{\n"
18461                "  void f()\n"
18462                "  {\n"
18463                "    if (true)\n"
18464                "    {\n"
18465                "      a();\n"
18466                "      b();\n"
18467                "    }\n"
18468                "  }\n"
18469                "  void g() { return; }\n"
18470                "};\n"
18471                "struct B\n"
18472                "{\n"
18473                "  int x;\n"
18474                "};\n"
18475                "union C\n"
18476                "{\n"
18477                "};\n"
18478                "} // namespace a",
18479                AllmanBraceStyle);
18480 
18481   verifyFormat("void f()\n"
18482                "{\n"
18483                "  if (true)\n"
18484                "  {\n"
18485                "    a();\n"
18486                "  }\n"
18487                "  else if (false)\n"
18488                "  {\n"
18489                "    b();\n"
18490                "  }\n"
18491                "  else\n"
18492                "  {\n"
18493                "    c();\n"
18494                "  }\n"
18495                "}\n",
18496                AllmanBraceStyle);
18497 
18498   verifyFormat("void f()\n"
18499                "{\n"
18500                "  for (int i = 0; i < 10; ++i)\n"
18501                "  {\n"
18502                "    a();\n"
18503                "  }\n"
18504                "  while (false)\n"
18505                "  {\n"
18506                "    b();\n"
18507                "  }\n"
18508                "  do\n"
18509                "  {\n"
18510                "    c();\n"
18511                "  } while (false)\n"
18512                "}\n",
18513                AllmanBraceStyle);
18514 
18515   verifyFormat("void f(int a)\n"
18516                "{\n"
18517                "  switch (a)\n"
18518                "  {\n"
18519                "  case 0:\n"
18520                "    break;\n"
18521                "  case 1:\n"
18522                "  {\n"
18523                "    break;\n"
18524                "  }\n"
18525                "  case 2:\n"
18526                "  {\n"
18527                "  }\n"
18528                "  break;\n"
18529                "  default:\n"
18530                "    break;\n"
18531                "  }\n"
18532                "}\n",
18533                AllmanBraceStyle);
18534 
18535   verifyFormat("enum X\n"
18536                "{\n"
18537                "  Y = 0,\n"
18538                "}\n",
18539                AllmanBraceStyle);
18540   verifyFormat("enum X\n"
18541                "{\n"
18542                "  Y = 0\n"
18543                "}\n",
18544                AllmanBraceStyle);
18545 
18546   verifyFormat("@interface BSApplicationController ()\n"
18547                "{\n"
18548                "@private\n"
18549                "  id _extraIvar;\n"
18550                "}\n"
18551                "@end\n",
18552                AllmanBraceStyle);
18553 
18554   verifyFormat("#ifdef _DEBUG\n"
18555                "int foo(int i = 0)\n"
18556                "#else\n"
18557                "int foo(int i = 5)\n"
18558                "#endif\n"
18559                "{\n"
18560                "  return i;\n"
18561                "}",
18562                AllmanBraceStyle);
18563 
18564   verifyFormat("void foo() {}\n"
18565                "void bar()\n"
18566                "#ifdef _DEBUG\n"
18567                "{\n"
18568                "  foo();\n"
18569                "}\n"
18570                "#else\n"
18571                "{\n"
18572                "}\n"
18573                "#endif",
18574                AllmanBraceStyle);
18575 
18576   verifyFormat("void foobar() { int i = 5; }\n"
18577                "#ifdef _DEBUG\n"
18578                "void bar() {}\n"
18579                "#else\n"
18580                "void bar() { foobar(); }\n"
18581                "#endif",
18582                AllmanBraceStyle);
18583 
18584   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18585             FormatStyle::SLS_All);
18586 
18587   verifyFormat("[](int i) { return i + 2; };\n"
18588                "[](int i, int j)\n"
18589                "{\n"
18590                "  auto x = i + j;\n"
18591                "  auto y = i * j;\n"
18592                "  return x ^ y;\n"
18593                "};\n"
18594                "void foo()\n"
18595                "{\n"
18596                "  auto shortLambda = [](int i) { return i + 2; };\n"
18597                "  auto longLambda = [](int i, int j)\n"
18598                "  {\n"
18599                "    auto x = i + j;\n"
18600                "    auto y = i * j;\n"
18601                "    return x ^ y;\n"
18602                "  };\n"
18603                "}",
18604                AllmanBraceStyle);
18605 
18606   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18607 
18608   verifyFormat("[](int i)\n"
18609                "{\n"
18610                "  return i + 2;\n"
18611                "};\n"
18612                "[](int i, int j)\n"
18613                "{\n"
18614                "  auto x = i + j;\n"
18615                "  auto y = i * j;\n"
18616                "  return x ^ y;\n"
18617                "};\n"
18618                "void foo()\n"
18619                "{\n"
18620                "  auto shortLambda = [](int i)\n"
18621                "  {\n"
18622                "    return i + 2;\n"
18623                "  };\n"
18624                "  auto longLambda = [](int i, int j)\n"
18625                "  {\n"
18626                "    auto x = i + j;\n"
18627                "    auto y = i * j;\n"
18628                "    return x ^ y;\n"
18629                "  };\n"
18630                "}",
18631                AllmanBraceStyle);
18632 
18633   // Reset
18634   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18635 
18636   // This shouldn't affect ObjC blocks..
18637   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18638                "  // ...\n"
18639                "  int i;\n"
18640                "}];",
18641                AllmanBraceStyle);
18642   verifyFormat("void (^block)(void) = ^{\n"
18643                "  // ...\n"
18644                "  int i;\n"
18645                "};",
18646                AllmanBraceStyle);
18647   // .. or dict literals.
18648   verifyFormat("void f()\n"
18649                "{\n"
18650                "  // ...\n"
18651                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18652                "}",
18653                AllmanBraceStyle);
18654   verifyFormat("void f()\n"
18655                "{\n"
18656                "  // ...\n"
18657                "  [object someMethod:@{a : @\"b\"}];\n"
18658                "}",
18659                AllmanBraceStyle);
18660   verifyFormat("int f()\n"
18661                "{ // comment\n"
18662                "  return 42;\n"
18663                "}",
18664                AllmanBraceStyle);
18665 
18666   AllmanBraceStyle.ColumnLimit = 19;
18667   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18668   AllmanBraceStyle.ColumnLimit = 18;
18669   verifyFormat("void f()\n"
18670                "{\n"
18671                "  int i;\n"
18672                "}",
18673                AllmanBraceStyle);
18674   AllmanBraceStyle.ColumnLimit = 80;
18675 
18676   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18677   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18678       FormatStyle::SIS_WithoutElse;
18679   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18680   verifyFormat("void f(bool b)\n"
18681                "{\n"
18682                "  if (b)\n"
18683                "  {\n"
18684                "    return;\n"
18685                "  }\n"
18686                "}\n",
18687                BreakBeforeBraceShortIfs);
18688   verifyFormat("void f(bool b)\n"
18689                "{\n"
18690                "  if constexpr (b)\n"
18691                "  {\n"
18692                "    return;\n"
18693                "  }\n"
18694                "}\n",
18695                BreakBeforeBraceShortIfs);
18696   verifyFormat("void f(bool b)\n"
18697                "{\n"
18698                "  if CONSTEXPR (b)\n"
18699                "  {\n"
18700                "    return;\n"
18701                "  }\n"
18702                "}\n",
18703                BreakBeforeBraceShortIfs);
18704   verifyFormat("void f(bool b)\n"
18705                "{\n"
18706                "  if (b) return;\n"
18707                "}\n",
18708                BreakBeforeBraceShortIfs);
18709   verifyFormat("void f(bool b)\n"
18710                "{\n"
18711                "  if constexpr (b) return;\n"
18712                "}\n",
18713                BreakBeforeBraceShortIfs);
18714   verifyFormat("void f(bool b)\n"
18715                "{\n"
18716                "  if CONSTEXPR (b) return;\n"
18717                "}\n",
18718                BreakBeforeBraceShortIfs);
18719   verifyFormat("void f(bool b)\n"
18720                "{\n"
18721                "  while (b)\n"
18722                "  {\n"
18723                "    return;\n"
18724                "  }\n"
18725                "}\n",
18726                BreakBeforeBraceShortIfs);
18727 }
18728 
18729 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18730   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18731   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18732 
18733   // Make a few changes to the style for testing purposes
18734   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18735       FormatStyle::SFS_Empty;
18736   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18737 
18738   // FIXME: this test case can't decide whether there should be a blank line
18739   // after the ~D() line or not. It adds one if one doesn't exist in the test
18740   // and it removes the line if one exists.
18741   /*
18742   verifyFormat("class A;\n"
18743                "namespace B\n"
18744                "  {\n"
18745                "class C;\n"
18746                "// Comment\n"
18747                "class D\n"
18748                "  {\n"
18749                "public:\n"
18750                "  D();\n"
18751                "  ~D() {}\n"
18752                "private:\n"
18753                "  enum E\n"
18754                "    {\n"
18755                "    F\n"
18756                "    }\n"
18757                "  };\n"
18758                "  } // namespace B\n",
18759                WhitesmithsBraceStyle);
18760   */
18761 
18762   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18763   verifyFormat("namespace a\n"
18764                "  {\n"
18765                "class A\n"
18766                "  {\n"
18767                "  void f()\n"
18768                "    {\n"
18769                "    if (true)\n"
18770                "      {\n"
18771                "      a();\n"
18772                "      b();\n"
18773                "      }\n"
18774                "    }\n"
18775                "  void g()\n"
18776                "    {\n"
18777                "    return;\n"
18778                "    }\n"
18779                "  };\n"
18780                "struct B\n"
18781                "  {\n"
18782                "  int x;\n"
18783                "  };\n"
18784                "  } // namespace a",
18785                WhitesmithsBraceStyle);
18786 
18787   verifyFormat("namespace a\n"
18788                "  {\n"
18789                "namespace b\n"
18790                "  {\n"
18791                "class A\n"
18792                "  {\n"
18793                "  void f()\n"
18794                "    {\n"
18795                "    if (true)\n"
18796                "      {\n"
18797                "      a();\n"
18798                "      b();\n"
18799                "      }\n"
18800                "    }\n"
18801                "  void g()\n"
18802                "    {\n"
18803                "    return;\n"
18804                "    }\n"
18805                "  };\n"
18806                "struct B\n"
18807                "  {\n"
18808                "  int x;\n"
18809                "  };\n"
18810                "  } // namespace b\n"
18811                "  } // namespace a",
18812                WhitesmithsBraceStyle);
18813 
18814   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18815   verifyFormat("namespace a\n"
18816                "  {\n"
18817                "namespace b\n"
18818                "  {\n"
18819                "  class A\n"
18820                "    {\n"
18821                "    void f()\n"
18822                "      {\n"
18823                "      if (true)\n"
18824                "        {\n"
18825                "        a();\n"
18826                "        b();\n"
18827                "        }\n"
18828                "      }\n"
18829                "    void g()\n"
18830                "      {\n"
18831                "      return;\n"
18832                "      }\n"
18833                "    };\n"
18834                "  struct B\n"
18835                "    {\n"
18836                "    int x;\n"
18837                "    };\n"
18838                "  } // namespace b\n"
18839                "  } // namespace a",
18840                WhitesmithsBraceStyle);
18841 
18842   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18843   verifyFormat("namespace a\n"
18844                "  {\n"
18845                "  namespace b\n"
18846                "    {\n"
18847                "    class A\n"
18848                "      {\n"
18849                "      void f()\n"
18850                "        {\n"
18851                "        if (true)\n"
18852                "          {\n"
18853                "          a();\n"
18854                "          b();\n"
18855                "          }\n"
18856                "        }\n"
18857                "      void g()\n"
18858                "        {\n"
18859                "        return;\n"
18860                "        }\n"
18861                "      };\n"
18862                "    struct B\n"
18863                "      {\n"
18864                "      int x;\n"
18865                "      };\n"
18866                "    } // namespace b\n"
18867                "  }   // namespace a",
18868                WhitesmithsBraceStyle);
18869 
18870   verifyFormat("void f()\n"
18871                "  {\n"
18872                "  if (true)\n"
18873                "    {\n"
18874                "    a();\n"
18875                "    }\n"
18876                "  else if (false)\n"
18877                "    {\n"
18878                "    b();\n"
18879                "    }\n"
18880                "  else\n"
18881                "    {\n"
18882                "    c();\n"
18883                "    }\n"
18884                "  }\n",
18885                WhitesmithsBraceStyle);
18886 
18887   verifyFormat("void f()\n"
18888                "  {\n"
18889                "  for (int i = 0; i < 10; ++i)\n"
18890                "    {\n"
18891                "    a();\n"
18892                "    }\n"
18893                "  while (false)\n"
18894                "    {\n"
18895                "    b();\n"
18896                "    }\n"
18897                "  do\n"
18898                "    {\n"
18899                "    c();\n"
18900                "    } while (false)\n"
18901                "  }\n",
18902                WhitesmithsBraceStyle);
18903 
18904   WhitesmithsBraceStyle.IndentCaseLabels = true;
18905   verifyFormat("void switchTest1(int a)\n"
18906                "  {\n"
18907                "  switch (a)\n"
18908                "    {\n"
18909                "    case 2:\n"
18910                "      {\n"
18911                "      }\n"
18912                "      break;\n"
18913                "    }\n"
18914                "  }\n",
18915                WhitesmithsBraceStyle);
18916 
18917   verifyFormat("void switchTest2(int a)\n"
18918                "  {\n"
18919                "  switch (a)\n"
18920                "    {\n"
18921                "    case 0:\n"
18922                "      break;\n"
18923                "    case 1:\n"
18924                "      {\n"
18925                "      break;\n"
18926                "      }\n"
18927                "    case 2:\n"
18928                "      {\n"
18929                "      }\n"
18930                "      break;\n"
18931                "    default:\n"
18932                "      break;\n"
18933                "    }\n"
18934                "  }\n",
18935                WhitesmithsBraceStyle);
18936 
18937   verifyFormat("void switchTest3(int a)\n"
18938                "  {\n"
18939                "  switch (a)\n"
18940                "    {\n"
18941                "    case 0:\n"
18942                "      {\n"
18943                "      foo(x);\n"
18944                "      }\n"
18945                "      break;\n"
18946                "    default:\n"
18947                "      {\n"
18948                "      foo(1);\n"
18949                "      }\n"
18950                "      break;\n"
18951                "    }\n"
18952                "  }\n",
18953                WhitesmithsBraceStyle);
18954 
18955   WhitesmithsBraceStyle.IndentCaseLabels = false;
18956 
18957   verifyFormat("void switchTest4(int a)\n"
18958                "  {\n"
18959                "  switch (a)\n"
18960                "    {\n"
18961                "  case 2:\n"
18962                "    {\n"
18963                "    }\n"
18964                "    break;\n"
18965                "    }\n"
18966                "  }\n",
18967                WhitesmithsBraceStyle);
18968 
18969   verifyFormat("void switchTest5(int a)\n"
18970                "  {\n"
18971                "  switch (a)\n"
18972                "    {\n"
18973                "  case 0:\n"
18974                "    break;\n"
18975                "  case 1:\n"
18976                "    {\n"
18977                "    foo();\n"
18978                "    break;\n"
18979                "    }\n"
18980                "  case 2:\n"
18981                "    {\n"
18982                "    }\n"
18983                "    break;\n"
18984                "  default:\n"
18985                "    break;\n"
18986                "    }\n"
18987                "  }\n",
18988                WhitesmithsBraceStyle);
18989 
18990   verifyFormat("void switchTest6(int a)\n"
18991                "  {\n"
18992                "  switch (a)\n"
18993                "    {\n"
18994                "  case 0:\n"
18995                "    {\n"
18996                "    foo(x);\n"
18997                "    }\n"
18998                "    break;\n"
18999                "  default:\n"
19000                "    {\n"
19001                "    foo(1);\n"
19002                "    }\n"
19003                "    break;\n"
19004                "    }\n"
19005                "  }\n",
19006                WhitesmithsBraceStyle);
19007 
19008   verifyFormat("enum X\n"
19009                "  {\n"
19010                "  Y = 0, // testing\n"
19011                "  }\n",
19012                WhitesmithsBraceStyle);
19013 
19014   verifyFormat("enum X\n"
19015                "  {\n"
19016                "  Y = 0\n"
19017                "  }\n",
19018                WhitesmithsBraceStyle);
19019   verifyFormat("enum X\n"
19020                "  {\n"
19021                "  Y = 0,\n"
19022                "  Z = 1\n"
19023                "  };\n",
19024                WhitesmithsBraceStyle);
19025 
19026   verifyFormat("@interface BSApplicationController ()\n"
19027                "  {\n"
19028                "@private\n"
19029                "  id _extraIvar;\n"
19030                "  }\n"
19031                "@end\n",
19032                WhitesmithsBraceStyle);
19033 
19034   verifyFormat("#ifdef _DEBUG\n"
19035                "int foo(int i = 0)\n"
19036                "#else\n"
19037                "int foo(int i = 5)\n"
19038                "#endif\n"
19039                "  {\n"
19040                "  return i;\n"
19041                "  }",
19042                WhitesmithsBraceStyle);
19043 
19044   verifyFormat("void foo() {}\n"
19045                "void bar()\n"
19046                "#ifdef _DEBUG\n"
19047                "  {\n"
19048                "  foo();\n"
19049                "  }\n"
19050                "#else\n"
19051                "  {\n"
19052                "  }\n"
19053                "#endif",
19054                WhitesmithsBraceStyle);
19055 
19056   verifyFormat("void foobar()\n"
19057                "  {\n"
19058                "  int i = 5;\n"
19059                "  }\n"
19060                "#ifdef _DEBUG\n"
19061                "void bar()\n"
19062                "  {\n"
19063                "  }\n"
19064                "#else\n"
19065                "void bar()\n"
19066                "  {\n"
19067                "  foobar();\n"
19068                "  }\n"
19069                "#endif",
19070                WhitesmithsBraceStyle);
19071 
19072   // This shouldn't affect ObjC blocks..
19073   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
19074                "  // ...\n"
19075                "  int i;\n"
19076                "}];",
19077                WhitesmithsBraceStyle);
19078   verifyFormat("void (^block)(void) = ^{\n"
19079                "  // ...\n"
19080                "  int i;\n"
19081                "};",
19082                WhitesmithsBraceStyle);
19083   // .. or dict literals.
19084   verifyFormat("void f()\n"
19085                "  {\n"
19086                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
19087                "  }",
19088                WhitesmithsBraceStyle);
19089 
19090   verifyFormat("int f()\n"
19091                "  { // comment\n"
19092                "  return 42;\n"
19093                "  }",
19094                WhitesmithsBraceStyle);
19095 
19096   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
19097   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
19098       FormatStyle::SIS_OnlyFirstIf;
19099   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
19100   verifyFormat("void f(bool b)\n"
19101                "  {\n"
19102                "  if (b)\n"
19103                "    {\n"
19104                "    return;\n"
19105                "    }\n"
19106                "  }\n",
19107                BreakBeforeBraceShortIfs);
19108   verifyFormat("void f(bool b)\n"
19109                "  {\n"
19110                "  if (b) return;\n"
19111                "  }\n",
19112                BreakBeforeBraceShortIfs);
19113   verifyFormat("void f(bool b)\n"
19114                "  {\n"
19115                "  while (b)\n"
19116                "    {\n"
19117                "    return;\n"
19118                "    }\n"
19119                "  }\n",
19120                BreakBeforeBraceShortIfs);
19121 }
19122 
19123 TEST_F(FormatTest, GNUBraceBreaking) {
19124   FormatStyle GNUBraceStyle = getLLVMStyle();
19125   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
19126   verifyFormat("namespace a\n"
19127                "{\n"
19128                "class A\n"
19129                "{\n"
19130                "  void f()\n"
19131                "  {\n"
19132                "    int a;\n"
19133                "    {\n"
19134                "      int b;\n"
19135                "    }\n"
19136                "    if (true)\n"
19137                "      {\n"
19138                "        a();\n"
19139                "        b();\n"
19140                "      }\n"
19141                "  }\n"
19142                "  void g() { return; }\n"
19143                "}\n"
19144                "} // namespace a",
19145                GNUBraceStyle);
19146 
19147   verifyFormat("void f()\n"
19148                "{\n"
19149                "  if (true)\n"
19150                "    {\n"
19151                "      a();\n"
19152                "    }\n"
19153                "  else if (false)\n"
19154                "    {\n"
19155                "      b();\n"
19156                "    }\n"
19157                "  else\n"
19158                "    {\n"
19159                "      c();\n"
19160                "    }\n"
19161                "}\n",
19162                GNUBraceStyle);
19163 
19164   verifyFormat("void f()\n"
19165                "{\n"
19166                "  for (int i = 0; i < 10; ++i)\n"
19167                "    {\n"
19168                "      a();\n"
19169                "    }\n"
19170                "  while (false)\n"
19171                "    {\n"
19172                "      b();\n"
19173                "    }\n"
19174                "  do\n"
19175                "    {\n"
19176                "      c();\n"
19177                "    }\n"
19178                "  while (false);\n"
19179                "}\n",
19180                GNUBraceStyle);
19181 
19182   verifyFormat("void f(int a)\n"
19183                "{\n"
19184                "  switch (a)\n"
19185                "    {\n"
19186                "    case 0:\n"
19187                "      break;\n"
19188                "    case 1:\n"
19189                "      {\n"
19190                "        break;\n"
19191                "      }\n"
19192                "    case 2:\n"
19193                "      {\n"
19194                "      }\n"
19195                "      break;\n"
19196                "    default:\n"
19197                "      break;\n"
19198                "    }\n"
19199                "}\n",
19200                GNUBraceStyle);
19201 
19202   verifyFormat("enum X\n"
19203                "{\n"
19204                "  Y = 0,\n"
19205                "}\n",
19206                GNUBraceStyle);
19207 
19208   verifyFormat("@interface BSApplicationController ()\n"
19209                "{\n"
19210                "@private\n"
19211                "  id _extraIvar;\n"
19212                "}\n"
19213                "@end\n",
19214                GNUBraceStyle);
19215 
19216   verifyFormat("#ifdef _DEBUG\n"
19217                "int foo(int i = 0)\n"
19218                "#else\n"
19219                "int foo(int i = 5)\n"
19220                "#endif\n"
19221                "{\n"
19222                "  return i;\n"
19223                "}",
19224                GNUBraceStyle);
19225 
19226   verifyFormat("void foo() {}\n"
19227                "void bar()\n"
19228                "#ifdef _DEBUG\n"
19229                "{\n"
19230                "  foo();\n"
19231                "}\n"
19232                "#else\n"
19233                "{\n"
19234                "}\n"
19235                "#endif",
19236                GNUBraceStyle);
19237 
19238   verifyFormat("void foobar() { int i = 5; }\n"
19239                "#ifdef _DEBUG\n"
19240                "void bar() {}\n"
19241                "#else\n"
19242                "void bar() { foobar(); }\n"
19243                "#endif",
19244                GNUBraceStyle);
19245 }
19246 
19247 TEST_F(FormatTest, WebKitBraceBreaking) {
19248   FormatStyle WebKitBraceStyle = getLLVMStyle();
19249   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
19250   WebKitBraceStyle.FixNamespaceComments = false;
19251   verifyFormat("namespace a {\n"
19252                "class A {\n"
19253                "  void f()\n"
19254                "  {\n"
19255                "    if (true) {\n"
19256                "      a();\n"
19257                "      b();\n"
19258                "    }\n"
19259                "  }\n"
19260                "  void g() { return; }\n"
19261                "};\n"
19262                "enum E {\n"
19263                "  A,\n"
19264                "  // foo\n"
19265                "  B,\n"
19266                "  C\n"
19267                "};\n"
19268                "struct B {\n"
19269                "  int x;\n"
19270                "};\n"
19271                "}\n",
19272                WebKitBraceStyle);
19273   verifyFormat("struct S {\n"
19274                "  int Type;\n"
19275                "  union {\n"
19276                "    int x;\n"
19277                "    double y;\n"
19278                "  } Value;\n"
19279                "  class C {\n"
19280                "    MyFavoriteType Value;\n"
19281                "  } Class;\n"
19282                "};\n",
19283                WebKitBraceStyle);
19284 }
19285 
19286 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
19287   verifyFormat("void f() {\n"
19288                "  try {\n"
19289                "  } catch (const Exception &e) {\n"
19290                "  }\n"
19291                "}\n",
19292                getLLVMStyle());
19293 }
19294 
19295 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
19296   auto Style = getLLVMStyle();
19297   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19298   Style.AlignConsecutiveAssignments.Enabled = true;
19299   Style.AlignConsecutiveDeclarations.Enabled = true;
19300   verifyFormat("struct test demo[] = {\n"
19301                "    {56,    23, \"hello\"},\n"
19302                "    {-1, 93463, \"world\"},\n"
19303                "    { 7,     5,    \"!!\"}\n"
19304                "};\n",
19305                Style);
19306 
19307   verifyFormat("struct test demo[] = {\n"
19308                "    {56,    23, \"hello\"}, // first line\n"
19309                "    {-1, 93463, \"world\"}, // second line\n"
19310                "    { 7,     5,    \"!!\"}  // third line\n"
19311                "};\n",
19312                Style);
19313 
19314   verifyFormat("struct test demo[4] = {\n"
19315                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19316                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19317                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19318                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19319                "};\n",
19320                Style);
19321 
19322   verifyFormat("struct test demo[3] = {\n"
19323                "    {56,    23, \"hello\"},\n"
19324                "    {-1, 93463, \"world\"},\n"
19325                "    { 7,     5,    \"!!\"}\n"
19326                "};\n",
19327                Style);
19328 
19329   verifyFormat("struct test demo[3] = {\n"
19330                "    {int{56},    23, \"hello\"},\n"
19331                "    {int{-1}, 93463, \"world\"},\n"
19332                "    { int{7},     5,    \"!!\"}\n"
19333                "};\n",
19334                Style);
19335 
19336   verifyFormat("struct test demo[] = {\n"
19337                "    {56,    23, \"hello\"},\n"
19338                "    {-1, 93463, \"world\"},\n"
19339                "    { 7,     5,    \"!!\"},\n"
19340                "};\n",
19341                Style);
19342 
19343   verifyFormat("test demo[] = {\n"
19344                "    {56,    23, \"hello\"},\n"
19345                "    {-1, 93463, \"world\"},\n"
19346                "    { 7,     5,    \"!!\"},\n"
19347                "};\n",
19348                Style);
19349 
19350   verifyFormat("demo = std::array<struct test, 3>{\n"
19351                "    test{56,    23, \"hello\"},\n"
19352                "    test{-1, 93463, \"world\"},\n"
19353                "    test{ 7,     5,    \"!!\"},\n"
19354                "};\n",
19355                Style);
19356 
19357   verifyFormat("test demo[] = {\n"
19358                "    {56,    23, \"hello\"},\n"
19359                "#if X\n"
19360                "    {-1, 93463, \"world\"},\n"
19361                "#endif\n"
19362                "    { 7,     5,    \"!!\"}\n"
19363                "};\n",
19364                Style);
19365 
19366   verifyFormat(
19367       "test demo[] = {\n"
19368       "    { 7,    23,\n"
19369       "     \"hello world i am a very long line that really, in any\"\n"
19370       "     \"just world, ought to be split over multiple lines\"},\n"
19371       "    {-1, 93463,                                  \"world\"},\n"
19372       "    {56,     5,                                     \"!!\"}\n"
19373       "};\n",
19374       Style);
19375 
19376   verifyFormat("return GradForUnaryCwise(g, {\n"
19377                "                                {{\"sign\"}, \"Sign\",  "
19378                "  {\"x\", \"dy\"}},\n"
19379                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
19380                ", \"sign\"}},\n"
19381                "});\n",
19382                Style);
19383 
19384   Style.ColumnLimit = 0;
19385   EXPECT_EQ(
19386       "test demo[] = {\n"
19387       "    {56,    23, \"hello world i am a very long line that really, "
19388       "in any just world, ought to be split over multiple lines\"},\n"
19389       "    {-1, 93463,                                                  "
19390       "                                                 \"world\"},\n"
19391       "    { 7,     5,                                                  "
19392       "                                                    \"!!\"},\n"
19393       "};",
19394       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19395              "that really, in any just world, ought to be split over multiple "
19396              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19397              Style));
19398 
19399   Style.ColumnLimit = 80;
19400   verifyFormat("test demo[] = {\n"
19401                "    {56,    23, /* a comment */ \"hello\"},\n"
19402                "    {-1, 93463,                 \"world\"},\n"
19403                "    { 7,     5,                    \"!!\"}\n"
19404                "};\n",
19405                Style);
19406 
19407   verifyFormat("test demo[] = {\n"
19408                "    {56,    23,                    \"hello\"},\n"
19409                "    {-1, 93463, \"world\" /* comment here */},\n"
19410                "    { 7,     5,                       \"!!\"}\n"
19411                "};\n",
19412                Style);
19413 
19414   verifyFormat("test demo[] = {\n"
19415                "    {56, /* a comment */ 23, \"hello\"},\n"
19416                "    {-1,              93463, \"world\"},\n"
19417                "    { 7,                  5,    \"!!\"}\n"
19418                "};\n",
19419                Style);
19420 
19421   Style.ColumnLimit = 20;
19422   EXPECT_EQ(
19423       "demo = std::array<\n"
19424       "    struct test, 3>{\n"
19425       "    test{\n"
19426       "         56,    23,\n"
19427       "         \"hello \"\n"
19428       "         \"world i \"\n"
19429       "         \"am a very \"\n"
19430       "         \"long line \"\n"
19431       "         \"that \"\n"
19432       "         \"really, \"\n"
19433       "         \"in any \"\n"
19434       "         \"just \"\n"
19435       "         \"world, \"\n"
19436       "         \"ought to \"\n"
19437       "         \"be split \"\n"
19438       "         \"over \"\n"
19439       "         \"multiple \"\n"
19440       "         \"lines\"},\n"
19441       "    test{-1, 93463,\n"
19442       "         \"world\"},\n"
19443       "    test{ 7,     5,\n"
19444       "         \"!!\"   },\n"
19445       "};",
19446       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19447              "i am a very long line that really, in any just world, ought "
19448              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19449              "test{7, 5, \"!!\"},};",
19450              Style));
19451   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19452   Style = getLLVMStyleWithColumns(50);
19453   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19454   verifyFormat("static A x = {\n"
19455                "    {{init1, init2, init3, init4},\n"
19456                "     {init1, init2, init3, init4}}\n"
19457                "};",
19458                Style);
19459   // TODO: Fix the indentations below when this option is fully functional.
19460   verifyFormat("int a[][] = {\n"
19461                "    {\n"
19462                "     {0, 2}, //\n"
19463                " {1, 2}  //\n"
19464                "    }\n"
19465                "};",
19466                Style);
19467   Style.ColumnLimit = 100;
19468   EXPECT_EQ(
19469       "test demo[] = {\n"
19470       "    {56,    23,\n"
19471       "     \"hello world i am a very long line that really, in any just world"
19472       ", ought to be split over \"\n"
19473       "     \"multiple lines\"  },\n"
19474       "    {-1, 93463, \"world\"},\n"
19475       "    { 7,     5,    \"!!\"},\n"
19476       "};",
19477       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19478              "that really, in any just world, ought to be split over multiple "
19479              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19480              Style));
19481 
19482   Style = getLLVMStyleWithColumns(50);
19483   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19484   verifyFormat("struct test demo[] = {\n"
19485                "    {56,    23, \"hello\"},\n"
19486                "    {-1, 93463, \"world\"},\n"
19487                "    { 7,     5,    \"!!\"}\n"
19488                "};\n"
19489                "static A x = {\n"
19490                "    {{init1, init2, init3, init4},\n"
19491                "     {init1, init2, init3, init4}}\n"
19492                "};",
19493                Style);
19494   Style.ColumnLimit = 100;
19495   Style.AlignConsecutiveAssignments.AcrossComments = true;
19496   Style.AlignConsecutiveDeclarations.AcrossComments = true;
19497   verifyFormat("struct test demo[] = {\n"
19498                "    {56,    23, \"hello\"},\n"
19499                "    {-1, 93463, \"world\"},\n"
19500                "    { 7,     5,    \"!!\"}\n"
19501                "};\n"
19502                "struct test demo[4] = {\n"
19503                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19504                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19505                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19506                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19507                "};\n",
19508                Style);
19509   EXPECT_EQ(
19510       "test demo[] = {\n"
19511       "    {56,\n"
19512       "     \"hello world i am a very long line that really, in any just world"
19513       ", ought to be split over \"\n"
19514       "     \"multiple lines\",    23},\n"
19515       "    {-1,      \"world\", 93463},\n"
19516       "    { 7,         \"!!\",     5},\n"
19517       "};",
19518       format("test demo[] = {{56, \"hello world i am a very long line "
19519              "that really, in any just world, ought to be split over multiple "
19520              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
19521              Style));
19522 }
19523 
19524 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
19525   auto Style = getLLVMStyle();
19526   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19527   /* FIXME: This case gets misformatted.
19528   verifyFormat("auto foo = Items{\n"
19529                "    Section{0, bar(), },\n"
19530                "    Section{1, boo()  }\n"
19531                "};\n",
19532                Style);
19533   */
19534   verifyFormat("auto foo = Items{\n"
19535                "    Section{\n"
19536                "            0, bar(),\n"
19537                "            }\n"
19538                "};\n",
19539                Style);
19540   verifyFormat("struct test demo[] = {\n"
19541                "    {56, 23,    \"hello\"},\n"
19542                "    {-1, 93463, \"world\"},\n"
19543                "    {7,  5,     \"!!\"   }\n"
19544                "};\n",
19545                Style);
19546   verifyFormat("struct test demo[] = {\n"
19547                "    {56, 23,    \"hello\"}, // first line\n"
19548                "    {-1, 93463, \"world\"}, // second line\n"
19549                "    {7,  5,     \"!!\"   }  // third line\n"
19550                "};\n",
19551                Style);
19552   verifyFormat("struct test demo[4] = {\n"
19553                "    {56,  23,    21, \"oh\"      }, // first line\n"
19554                "    {-1,  93463, 22, \"my\"      }, // second line\n"
19555                "    {7,   5,     1,  \"goodness\"}  // third line\n"
19556                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
19557                "};\n",
19558                Style);
19559   verifyFormat("struct test demo[3] = {\n"
19560                "    {56, 23,    \"hello\"},\n"
19561                "    {-1, 93463, \"world\"},\n"
19562                "    {7,  5,     \"!!\"   }\n"
19563                "};\n",
19564                Style);
19565 
19566   verifyFormat("struct test demo[3] = {\n"
19567                "    {int{56}, 23,    \"hello\"},\n"
19568                "    {int{-1}, 93463, \"world\"},\n"
19569                "    {int{7},  5,     \"!!\"   }\n"
19570                "};\n",
19571                Style);
19572   verifyFormat("struct test demo[] = {\n"
19573                "    {56, 23,    \"hello\"},\n"
19574                "    {-1, 93463, \"world\"},\n"
19575                "    {7,  5,     \"!!\"   },\n"
19576                "};\n",
19577                Style);
19578   verifyFormat("test demo[] = {\n"
19579                "    {56, 23,    \"hello\"},\n"
19580                "    {-1, 93463, \"world\"},\n"
19581                "    {7,  5,     \"!!\"   },\n"
19582                "};\n",
19583                Style);
19584   verifyFormat("demo = std::array<struct test, 3>{\n"
19585                "    test{56, 23,    \"hello\"},\n"
19586                "    test{-1, 93463, \"world\"},\n"
19587                "    test{7,  5,     \"!!\"   },\n"
19588                "};\n",
19589                Style);
19590   verifyFormat("test demo[] = {\n"
19591                "    {56, 23,    \"hello\"},\n"
19592                "#if X\n"
19593                "    {-1, 93463, \"world\"},\n"
19594                "#endif\n"
19595                "    {7,  5,     \"!!\"   }\n"
19596                "};\n",
19597                Style);
19598   verifyFormat(
19599       "test demo[] = {\n"
19600       "    {7,  23,\n"
19601       "     \"hello world i am a very long line that really, in any\"\n"
19602       "     \"just world, ought to be split over multiple lines\"},\n"
19603       "    {-1, 93463, \"world\"                                 },\n"
19604       "    {56, 5,     \"!!\"                                    }\n"
19605       "};\n",
19606       Style);
19607 
19608   verifyFormat("return GradForUnaryCwise(g, {\n"
19609                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19610                "\"dy\"}   },\n"
19611                "                                {{\"dx\"},   \"Mul\",  "
19612                "{\"dy\", \"sign\"}},\n"
19613                "});\n",
19614                Style);
19615 
19616   Style.ColumnLimit = 0;
19617   EXPECT_EQ(
19618       "test demo[] = {\n"
19619       "    {56, 23,    \"hello world i am a very long line that really, in any "
19620       "just world, ought to be split over multiple lines\"},\n"
19621       "    {-1, 93463, \"world\"                                               "
19622       "                                                   },\n"
19623       "    {7,  5,     \"!!\"                                                  "
19624       "                                                   },\n"
19625       "};",
19626       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19627              "that really, in any just world, ought to be split over multiple "
19628              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19629              Style));
19630 
19631   Style.ColumnLimit = 80;
19632   verifyFormat("test demo[] = {\n"
19633                "    {56, 23,    /* a comment */ \"hello\"},\n"
19634                "    {-1, 93463, \"world\"                },\n"
19635                "    {7,  5,     \"!!\"                   }\n"
19636                "};\n",
19637                Style);
19638 
19639   verifyFormat("test demo[] = {\n"
19640                "    {56, 23,    \"hello\"                   },\n"
19641                "    {-1, 93463, \"world\" /* comment here */},\n"
19642                "    {7,  5,     \"!!\"                      }\n"
19643                "};\n",
19644                Style);
19645 
19646   verifyFormat("test demo[] = {\n"
19647                "    {56, /* a comment */ 23, \"hello\"},\n"
19648                "    {-1, 93463,              \"world\"},\n"
19649                "    {7,  5,                  \"!!\"   }\n"
19650                "};\n",
19651                Style);
19652 
19653   Style.ColumnLimit = 20;
19654   EXPECT_EQ(
19655       "demo = std::array<\n"
19656       "    struct test, 3>{\n"
19657       "    test{\n"
19658       "         56, 23,\n"
19659       "         \"hello \"\n"
19660       "         \"world i \"\n"
19661       "         \"am a very \"\n"
19662       "         \"long line \"\n"
19663       "         \"that \"\n"
19664       "         \"really, \"\n"
19665       "         \"in any \"\n"
19666       "         \"just \"\n"
19667       "         \"world, \"\n"
19668       "         \"ought to \"\n"
19669       "         \"be split \"\n"
19670       "         \"over \"\n"
19671       "         \"multiple \"\n"
19672       "         \"lines\"},\n"
19673       "    test{-1, 93463,\n"
19674       "         \"world\"},\n"
19675       "    test{7,  5,\n"
19676       "         \"!!\"   },\n"
19677       "};",
19678       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19679              "i am a very long line that really, in any just world, ought "
19680              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19681              "test{7, 5, \"!!\"},};",
19682              Style));
19683 
19684   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19685   Style = getLLVMStyleWithColumns(50);
19686   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19687   verifyFormat("static A x = {\n"
19688                "    {{init1, init2, init3, init4},\n"
19689                "     {init1, init2, init3, init4}}\n"
19690                "};",
19691                Style);
19692   Style.ColumnLimit = 100;
19693   EXPECT_EQ(
19694       "test demo[] = {\n"
19695       "    {56, 23,\n"
19696       "     \"hello world i am a very long line that really, in any just world"
19697       ", ought to be split over \"\n"
19698       "     \"multiple lines\"  },\n"
19699       "    {-1, 93463, \"world\"},\n"
19700       "    {7,  5,     \"!!\"   },\n"
19701       "};",
19702       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19703              "that really, in any just world, ought to be split over multiple "
19704              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19705              Style));
19706 }
19707 
19708 TEST_F(FormatTest, UnderstandsPragmas) {
19709   verifyFormat("#pragma omp reduction(| : var)");
19710   verifyFormat("#pragma omp reduction(+ : var)");
19711 
19712   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19713             "(including parentheses).",
19714             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19715                    "(including parentheses)."));
19716 }
19717 
19718 TEST_F(FormatTest, UnderstandPragmaOption) {
19719   verifyFormat("#pragma option -C -A");
19720 
19721   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19722 }
19723 
19724 TEST_F(FormatTest, UnderstandPragmaRegion) {
19725   auto Style = getLLVMStyleWithColumns(0);
19726   verifyFormat("#pragma region TEST(FOO : BAR)", Style);
19727 
19728   EXPECT_EQ("#pragma region TEST(FOO : BAR)",
19729             format("#pragma region TEST(FOO : BAR)", Style));
19730 }
19731 
19732 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19733   FormatStyle Style = getLLVMStyleWithColumns(20);
19734 
19735   // See PR41213
19736   EXPECT_EQ("/*\n"
19737             " *\t9012345\n"
19738             " * /8901\n"
19739             " */",
19740             format("/*\n"
19741                    " *\t9012345 /8901\n"
19742                    " */",
19743                    Style));
19744   EXPECT_EQ("/*\n"
19745             " *345678\n"
19746             " *\t/8901\n"
19747             " */",
19748             format("/*\n"
19749                    " *345678\t/8901\n"
19750                    " */",
19751                    Style));
19752 
19753   verifyFormat("int a; // the\n"
19754                "       // comment",
19755                Style);
19756   EXPECT_EQ("int a; /* first line\n"
19757             "        * second\n"
19758             "        * line third\n"
19759             "        * line\n"
19760             "        */",
19761             format("int a; /* first line\n"
19762                    "        * second\n"
19763                    "        * line third\n"
19764                    "        * line\n"
19765                    "        */",
19766                    Style));
19767   EXPECT_EQ("int a; // first line\n"
19768             "       // second\n"
19769             "       // line third\n"
19770             "       // line",
19771             format("int a; // first line\n"
19772                    "       // second line\n"
19773                    "       // third line",
19774                    Style));
19775 
19776   Style.PenaltyExcessCharacter = 90;
19777   verifyFormat("int a; // the comment", Style);
19778   EXPECT_EQ("int a; // the comment\n"
19779             "       // aaa",
19780             format("int a; // the comment aaa", Style));
19781   EXPECT_EQ("int a; /* first line\n"
19782             "        * second line\n"
19783             "        * third line\n"
19784             "        */",
19785             format("int a; /* first line\n"
19786                    "        * second line\n"
19787                    "        * third line\n"
19788                    "        */",
19789                    Style));
19790   EXPECT_EQ("int a; // first line\n"
19791             "       // second line\n"
19792             "       // third line",
19793             format("int a; // first line\n"
19794                    "       // second line\n"
19795                    "       // third line",
19796                    Style));
19797   // FIXME: Investigate why this is not getting the same layout as the test
19798   // above.
19799   EXPECT_EQ("int a; /* first line\n"
19800             "        * second line\n"
19801             "        * third line\n"
19802             "        */",
19803             format("int a; /* first line second line third line"
19804                    "\n*/",
19805                    Style));
19806 
19807   EXPECT_EQ("// foo bar baz bazfoo\n"
19808             "// foo bar foo bar\n",
19809             format("// foo bar baz bazfoo\n"
19810                    "// foo bar foo           bar\n",
19811                    Style));
19812   EXPECT_EQ("// foo bar baz bazfoo\n"
19813             "// foo bar foo bar\n",
19814             format("// foo bar baz      bazfoo\n"
19815                    "// foo            bar foo bar\n",
19816                    Style));
19817 
19818   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19819   // next one.
19820   EXPECT_EQ("// foo bar baz bazfoo\n"
19821             "// bar foo bar\n",
19822             format("// foo bar baz      bazfoo bar\n"
19823                    "// foo            bar\n",
19824                    Style));
19825 
19826   EXPECT_EQ("// foo bar baz bazfoo\n"
19827             "// foo bar baz bazfoo\n"
19828             "// bar foo bar\n",
19829             format("// foo bar baz      bazfoo\n"
19830                    "// foo bar baz      bazfoo bar\n"
19831                    "// foo bar\n",
19832                    Style));
19833 
19834   EXPECT_EQ("// foo bar baz bazfoo\n"
19835             "// foo bar baz bazfoo\n"
19836             "// bar foo bar\n",
19837             format("// foo bar baz      bazfoo\n"
19838                    "// foo bar baz      bazfoo bar\n"
19839                    "// foo           bar\n",
19840                    Style));
19841 
19842   // Make sure we do not keep protruding characters if strict mode reflow is
19843   // cheaper than keeping protruding characters.
19844   Style.ColumnLimit = 21;
19845   EXPECT_EQ(
19846       "// foo foo foo foo\n"
19847       "// foo foo foo foo\n"
19848       "// foo foo foo foo\n",
19849       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19850 
19851   EXPECT_EQ("int a = /* long block\n"
19852             "           comment */\n"
19853             "    42;",
19854             format("int a = /* long block comment */ 42;", Style));
19855 }
19856 
19857 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19858   FormatStyle Style = getLLVMStyle();
19859   Style.ColumnLimit = 8;
19860   Style.PenaltyExcessCharacter = 15;
19861   verifyFormat("int foo(\n"
19862                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19863                Style);
19864   Style.PenaltyBreakOpenParenthesis = 200;
19865   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19866             format("int foo(\n"
19867                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19868                    Style));
19869 }
19870 
19871 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19872   FormatStyle Style = getLLVMStyle();
19873   Style.ColumnLimit = 5;
19874   Style.PenaltyExcessCharacter = 150;
19875   verifyFormat("foo((\n"
19876                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19877 
19878                Style);
19879   Style.PenaltyBreakOpenParenthesis = 100000;
19880   EXPECT_EQ("foo((int)\n"
19881             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19882             format("foo((\n"
19883                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19884                    Style));
19885 }
19886 
19887 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19888   FormatStyle Style = getLLVMStyle();
19889   Style.ColumnLimit = 4;
19890   Style.PenaltyExcessCharacter = 100;
19891   verifyFormat("for (\n"
19892                "    int iiiiiiiiiiiiiiiii =\n"
19893                "        0;\n"
19894                "    iiiiiiiiiiiiiiiii <\n"
19895                "    2;\n"
19896                "    iiiiiiiiiiiiiiiii++) {\n"
19897                "}",
19898 
19899                Style);
19900   Style.PenaltyBreakOpenParenthesis = 1250;
19901   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19902             "         0;\n"
19903             "     iiiiiiiiiiiiiiiii <\n"
19904             "     2;\n"
19905             "     iiiiiiiiiiiiiiiii++) {\n"
19906             "}",
19907             format("for (\n"
19908                    "    int iiiiiiiiiiiiiiiii =\n"
19909                    "        0;\n"
19910                    "    iiiiiiiiiiiiiiiii <\n"
19911                    "    2;\n"
19912                    "    iiiiiiiiiiiiiiiii++) {\n"
19913                    "}",
19914                    Style));
19915 }
19916 
19917 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19918   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19919   EXPECT_EQ(Styles[0], Styles[i])                                              \
19920       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19921 
19922 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19923   SmallVector<FormatStyle, 3> Styles;
19924   Styles.resize(3);
19925 
19926   Styles[0] = getLLVMStyle();
19927   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19928   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19929   EXPECT_ALL_STYLES_EQUAL(Styles);
19930 
19931   Styles[0] = getGoogleStyle();
19932   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19933   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19934   EXPECT_ALL_STYLES_EQUAL(Styles);
19935 
19936   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19937   EXPECT_TRUE(
19938       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19939   EXPECT_TRUE(
19940       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19941   EXPECT_ALL_STYLES_EQUAL(Styles);
19942 
19943   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19944   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19945   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19946   EXPECT_ALL_STYLES_EQUAL(Styles);
19947 
19948   Styles[0] = getMozillaStyle();
19949   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19950   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19951   EXPECT_ALL_STYLES_EQUAL(Styles);
19952 
19953   Styles[0] = getWebKitStyle();
19954   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19955   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19956   EXPECT_ALL_STYLES_EQUAL(Styles);
19957 
19958   Styles[0] = getGNUStyle();
19959   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19960   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19961   EXPECT_ALL_STYLES_EQUAL(Styles);
19962 
19963   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19964 }
19965 
19966 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19967   SmallVector<FormatStyle, 8> Styles;
19968   Styles.resize(2);
19969 
19970   Styles[0] = getGoogleStyle();
19971   Styles[1] = getLLVMStyle();
19972   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19973   EXPECT_ALL_STYLES_EQUAL(Styles);
19974 
19975   Styles.resize(5);
19976   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19977   Styles[1] = getLLVMStyle();
19978   Styles[1].Language = FormatStyle::LK_JavaScript;
19979   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19980 
19981   Styles[2] = getLLVMStyle();
19982   Styles[2].Language = FormatStyle::LK_JavaScript;
19983   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19984                                   "BasedOnStyle: Google",
19985                                   &Styles[2])
19986                    .value());
19987 
19988   Styles[3] = getLLVMStyle();
19989   Styles[3].Language = FormatStyle::LK_JavaScript;
19990   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19991                                   "Language: JavaScript",
19992                                   &Styles[3])
19993                    .value());
19994 
19995   Styles[4] = getLLVMStyle();
19996   Styles[4].Language = FormatStyle::LK_JavaScript;
19997   EXPECT_EQ(0, parseConfiguration("---\n"
19998                                   "BasedOnStyle: LLVM\n"
19999                                   "IndentWidth: 123\n"
20000                                   "---\n"
20001                                   "BasedOnStyle: Google\n"
20002                                   "Language: JavaScript",
20003                                   &Styles[4])
20004                    .value());
20005   EXPECT_ALL_STYLES_EQUAL(Styles);
20006 }
20007 
20008 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
20009   Style.FIELD = false;                                                         \
20010   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
20011   EXPECT_TRUE(Style.FIELD);                                                    \
20012   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
20013   EXPECT_FALSE(Style.FIELD);
20014 
20015 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
20016 
20017 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
20018   Style.STRUCT.FIELD = false;                                                  \
20019   EXPECT_EQ(0,                                                                 \
20020             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
20021                 .value());                                                     \
20022   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
20023   EXPECT_EQ(0,                                                                 \
20024             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
20025                 .value());                                                     \
20026   EXPECT_FALSE(Style.STRUCT.FIELD);
20027 
20028 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
20029   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
20030 
20031 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
20032   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
20033   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
20034   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
20035 
20036 TEST_F(FormatTest, ParsesConfigurationBools) {
20037   FormatStyle Style = {};
20038   Style.Language = FormatStyle::LK_Cpp;
20039   CHECK_PARSE_BOOL(AlignTrailingComments);
20040   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
20041   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
20042   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
20043   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
20044   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
20045   CHECK_PARSE_BOOL(BinPackArguments);
20046   CHECK_PARSE_BOOL(BinPackParameters);
20047   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
20048   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
20049   CHECK_PARSE_BOOL(BreakStringLiterals);
20050   CHECK_PARSE_BOOL(CompactNamespaces);
20051   CHECK_PARSE_BOOL(DeriveLineEnding);
20052   CHECK_PARSE_BOOL(DerivePointerAlignment);
20053   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
20054   CHECK_PARSE_BOOL(DisableFormat);
20055   CHECK_PARSE_BOOL(IndentAccessModifiers);
20056   CHECK_PARSE_BOOL(IndentCaseLabels);
20057   CHECK_PARSE_BOOL(IndentCaseBlocks);
20058   CHECK_PARSE_BOOL(IndentGotoLabels);
20059   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
20060   CHECK_PARSE_BOOL(IndentRequiresClause);
20061   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
20062   CHECK_PARSE_BOOL(InsertBraces);
20063   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
20064   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
20065   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
20066   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
20067   CHECK_PARSE_BOOL(ReflowComments);
20068   CHECK_PARSE_BOOL(RemoveBracesLLVM);
20069   CHECK_PARSE_BOOL(SortUsingDeclarations);
20070   CHECK_PARSE_BOOL(SpacesInParentheses);
20071   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
20072   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
20073   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
20074   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
20075   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
20076   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
20077   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
20078   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
20079   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
20080   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
20081   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
20082   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
20083   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
20084   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
20085   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
20086   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
20087   CHECK_PARSE_BOOL(UseCRLF);
20088 
20089   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
20090   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
20091   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
20092   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
20093   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
20094   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
20095   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
20096   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
20097   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
20098   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
20099   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
20100   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
20101   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
20102   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
20103   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
20104   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
20105   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
20106   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
20107   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
20108   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
20109                           AfterFunctionDeclarationName);
20110   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
20111                           AfterFunctionDefinitionName);
20112   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
20113   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
20114   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
20115 }
20116 
20117 #undef CHECK_PARSE_BOOL
20118 
20119 TEST_F(FormatTest, ParsesConfiguration) {
20120   FormatStyle Style = {};
20121   Style.Language = FormatStyle::LK_Cpp;
20122   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
20123   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
20124               ConstructorInitializerIndentWidth, 1234u);
20125   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
20126   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
20127   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
20128   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
20129   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
20130               PenaltyBreakBeforeFirstCallParameter, 1234u);
20131   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
20132               PenaltyBreakTemplateDeclaration, 1234u);
20133   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
20134               1234u);
20135   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
20136   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
20137               PenaltyReturnTypeOnItsOwnLine, 1234u);
20138   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
20139               SpacesBeforeTrailingComments, 1234u);
20140   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
20141   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
20142   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
20143 
20144   Style.QualifierAlignment = FormatStyle::QAS_Right;
20145   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
20146               FormatStyle::QAS_Leave);
20147   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
20148               FormatStyle::QAS_Right);
20149   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
20150               FormatStyle::QAS_Left);
20151   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
20152               FormatStyle::QAS_Custom);
20153 
20154   Style.QualifierOrder.clear();
20155   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
20156               std::vector<std::string>({"const", "volatile", "type"}));
20157   Style.QualifierOrder.clear();
20158   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
20159               std::vector<std::string>({"const", "type"}));
20160   Style.QualifierOrder.clear();
20161   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
20162               std::vector<std::string>({"volatile", "type"}));
20163 
20164 #define CHECK_ALIGN_CONSECUTIVE(FIELD)                                         \
20165   do {                                                                         \
20166     Style.FIELD.Enabled = true;                                                \
20167     CHECK_PARSE(#FIELD ": None", FIELD,                                        \
20168                 FormatStyle::AlignConsecutiveStyle(                            \
20169                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
20170                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20171                      /*PadOperators=*/true}));                                 \
20172     CHECK_PARSE(#FIELD ": Consecutive", FIELD,                                 \
20173                 FormatStyle::AlignConsecutiveStyle(                            \
20174                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
20175                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20176                      /*PadOperators=*/true}));                                 \
20177     CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD,                            \
20178                 FormatStyle::AlignConsecutiveStyle(                            \
20179                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
20180                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20181                      /*PadOperators=*/true}));                                 \
20182     CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD,                 \
20183                 FormatStyle::AlignConsecutiveStyle(                            \
20184                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
20185                      /*AcrossComments=*/true, /*AlignCompound=*/false,         \
20186                      /*PadOperators=*/true}));                                 \
20187     /* For backwards compability, false / true should still parse */           \
20188     CHECK_PARSE(#FIELD ": false", FIELD,                                       \
20189                 FormatStyle::AlignConsecutiveStyle(                            \
20190                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
20191                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20192                      /*PadOperators=*/true}));                                 \
20193     CHECK_PARSE(#FIELD ": true", FIELD,                                        \
20194                 FormatStyle::AlignConsecutiveStyle(                            \
20195                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
20196                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20197                      /*PadOperators=*/true}));                                 \
20198                                                                                \
20199     CHECK_PARSE_NESTED_BOOL(FIELD, Enabled);                                   \
20200     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines);                          \
20201     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments);                            \
20202     CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound);                             \
20203     CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators);                              \
20204   } while (false)
20205 
20206   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments);
20207   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields);
20208   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros);
20209   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations);
20210 
20211 #undef CHECK_ALIGN_CONSECUTIVE
20212 
20213   Style.PointerAlignment = FormatStyle::PAS_Middle;
20214   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
20215               FormatStyle::PAS_Left);
20216   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
20217               FormatStyle::PAS_Right);
20218   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
20219               FormatStyle::PAS_Middle);
20220   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
20221   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
20222               FormatStyle::RAS_Pointer);
20223   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
20224               FormatStyle::RAS_Left);
20225   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
20226               FormatStyle::RAS_Right);
20227   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
20228               FormatStyle::RAS_Middle);
20229   // For backward compatibility:
20230   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
20231               FormatStyle::PAS_Left);
20232   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
20233               FormatStyle::PAS_Right);
20234   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
20235               FormatStyle::PAS_Middle);
20236 
20237   Style.Standard = FormatStyle::LS_Auto;
20238   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
20239   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
20240   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
20241   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
20242   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
20243   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
20244   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
20245   // Legacy aliases:
20246   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
20247   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
20248   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
20249   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
20250 
20251   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
20252   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
20253               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
20254   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
20255               FormatStyle::BOS_None);
20256   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
20257               FormatStyle::BOS_All);
20258   // For backward compatibility:
20259   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
20260               FormatStyle::BOS_None);
20261   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
20262               FormatStyle::BOS_All);
20263 
20264   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
20265   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
20266               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20267   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
20268               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
20269   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
20270               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
20271   // For backward compatibility:
20272   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
20273               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20274 
20275   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
20276   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
20277               FormatStyle::BILS_AfterComma);
20278   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
20279               FormatStyle::BILS_BeforeComma);
20280   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
20281               FormatStyle::BILS_AfterColon);
20282   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
20283               FormatStyle::BILS_BeforeColon);
20284   // For backward compatibility:
20285   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
20286               FormatStyle::BILS_BeforeComma);
20287 
20288   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20289   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
20290               FormatStyle::PCIS_Never);
20291   CHECK_PARSE("PackConstructorInitializers: BinPack",
20292               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20293   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
20294               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20295   CHECK_PARSE("PackConstructorInitializers: NextLine",
20296               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20297   // For backward compatibility:
20298   CHECK_PARSE("BasedOnStyle: Google\n"
20299               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20300               "AllowAllConstructorInitializersOnNextLine: false",
20301               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20302   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20303   CHECK_PARSE("BasedOnStyle: Google\n"
20304               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
20305               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20306   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20307               "AllowAllConstructorInitializersOnNextLine: true",
20308               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20309   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20310   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20311               "AllowAllConstructorInitializersOnNextLine: false",
20312               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20313 
20314   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
20315   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
20316               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
20317   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
20318               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
20319   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
20320               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
20321   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
20322               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
20323 
20324   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20325   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
20326               FormatStyle::BAS_Align);
20327   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
20328               FormatStyle::BAS_DontAlign);
20329   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
20330               FormatStyle::BAS_AlwaysBreak);
20331   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
20332               FormatStyle::BAS_BlockIndent);
20333   // For backward compatibility:
20334   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
20335               FormatStyle::BAS_DontAlign);
20336   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
20337               FormatStyle::BAS_Align);
20338 
20339   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
20340   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
20341               FormatStyle::ENAS_DontAlign);
20342   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
20343               FormatStyle::ENAS_Left);
20344   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
20345               FormatStyle::ENAS_Right);
20346   // For backward compatibility:
20347   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
20348               FormatStyle::ENAS_Left);
20349   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
20350               FormatStyle::ENAS_Right);
20351 
20352   Style.AlignOperands = FormatStyle::OAS_Align;
20353   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
20354               FormatStyle::OAS_DontAlign);
20355   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
20356   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
20357               FormatStyle::OAS_AlignAfterOperator);
20358   // For backward compatibility:
20359   CHECK_PARSE("AlignOperands: false", AlignOperands,
20360               FormatStyle::OAS_DontAlign);
20361   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
20362 
20363   Style.UseTab = FormatStyle::UT_ForIndentation;
20364   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
20365   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
20366   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
20367   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
20368               FormatStyle::UT_ForContinuationAndIndentation);
20369   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
20370               FormatStyle::UT_AlignWithSpaces);
20371   // For backward compatibility:
20372   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
20373   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
20374 
20375   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
20376   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
20377               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20378   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
20379               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
20380   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
20381               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20382   // For backward compatibility:
20383   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
20384               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20385   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
20386               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20387 
20388   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
20389   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
20390               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20391   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
20392               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
20393   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
20394               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
20395   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
20396               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20397   // For backward compatibility:
20398   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
20399               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20400   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
20401               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20402 
20403   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
20404   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
20405               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
20406   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
20407               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
20408   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
20409               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
20410   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
20411               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
20412 
20413   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
20414   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
20415               FormatStyle::SBPO_Never);
20416   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
20417               FormatStyle::SBPO_Always);
20418   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
20419               FormatStyle::SBPO_ControlStatements);
20420   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
20421               SpaceBeforeParens,
20422               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20423   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
20424               FormatStyle::SBPO_NonEmptyParentheses);
20425   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
20426               FormatStyle::SBPO_Custom);
20427   // For backward compatibility:
20428   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
20429               FormatStyle::SBPO_Never);
20430   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
20431               FormatStyle::SBPO_ControlStatements);
20432   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
20433               SpaceBeforeParens,
20434               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20435 
20436   Style.ColumnLimit = 123;
20437   FormatStyle BaseStyle = getLLVMStyle();
20438   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
20439   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
20440 
20441   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
20442   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
20443               FormatStyle::BS_Attach);
20444   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
20445               FormatStyle::BS_Linux);
20446   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
20447               FormatStyle::BS_Mozilla);
20448   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
20449               FormatStyle::BS_Stroustrup);
20450   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
20451               FormatStyle::BS_Allman);
20452   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
20453               FormatStyle::BS_Whitesmiths);
20454   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
20455   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
20456               FormatStyle::BS_WebKit);
20457   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
20458               FormatStyle::BS_Custom);
20459 
20460   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
20461   CHECK_PARSE("BraceWrapping:\n"
20462               "  AfterControlStatement: MultiLine",
20463               BraceWrapping.AfterControlStatement,
20464               FormatStyle::BWACS_MultiLine);
20465   CHECK_PARSE("BraceWrapping:\n"
20466               "  AfterControlStatement: Always",
20467               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20468   CHECK_PARSE("BraceWrapping:\n"
20469               "  AfterControlStatement: Never",
20470               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20471   // For backward compatibility:
20472   CHECK_PARSE("BraceWrapping:\n"
20473               "  AfterControlStatement: true",
20474               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20475   CHECK_PARSE("BraceWrapping:\n"
20476               "  AfterControlStatement: false",
20477               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20478 
20479   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
20480   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
20481               FormatStyle::RTBS_None);
20482   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
20483               FormatStyle::RTBS_All);
20484   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
20485               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
20486   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
20487               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
20488   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
20489               AlwaysBreakAfterReturnType,
20490               FormatStyle::RTBS_TopLevelDefinitions);
20491 
20492   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
20493   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
20494               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
20495   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
20496               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20497   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
20498               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20499   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
20500               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20501   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
20502               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20503 
20504   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
20505   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
20506               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
20507   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
20508               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
20509   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
20510               AlwaysBreakAfterDefinitionReturnType,
20511               FormatStyle::DRTBS_TopLevel);
20512 
20513   Style.NamespaceIndentation = FormatStyle::NI_All;
20514   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
20515               FormatStyle::NI_None);
20516   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
20517               FormatStyle::NI_Inner);
20518   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
20519               FormatStyle::NI_All);
20520 
20521   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
20522   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
20523               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20524   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
20525               AllowShortIfStatementsOnASingleLine,
20526               FormatStyle::SIS_WithoutElse);
20527   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
20528               AllowShortIfStatementsOnASingleLine,
20529               FormatStyle::SIS_OnlyFirstIf);
20530   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
20531               AllowShortIfStatementsOnASingleLine,
20532               FormatStyle::SIS_AllIfsAndElse);
20533   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
20534               AllowShortIfStatementsOnASingleLine,
20535               FormatStyle::SIS_OnlyFirstIf);
20536   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
20537               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20538   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
20539               AllowShortIfStatementsOnASingleLine,
20540               FormatStyle::SIS_WithoutElse);
20541 
20542   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
20543   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
20544               FormatStyle::IEBS_AfterExternBlock);
20545   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
20546               FormatStyle::IEBS_Indent);
20547   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
20548               FormatStyle::IEBS_NoIndent);
20549   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
20550               FormatStyle::IEBS_Indent);
20551   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
20552               FormatStyle::IEBS_NoIndent);
20553 
20554   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
20555   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
20556               FormatStyle::BFCS_Both);
20557   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
20558               FormatStyle::BFCS_None);
20559   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
20560               FormatStyle::BFCS_Before);
20561   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
20562               FormatStyle::BFCS_After);
20563 
20564   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
20565   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
20566               FormatStyle::SJSIO_After);
20567   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
20568               FormatStyle::SJSIO_Before);
20569 
20570   // FIXME: This is required because parsing a configuration simply overwrites
20571   // the first N elements of the list instead of resetting it.
20572   Style.ForEachMacros.clear();
20573   std::vector<std::string> BoostForeach;
20574   BoostForeach.push_back("BOOST_FOREACH");
20575   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20576   std::vector<std::string> BoostAndQForeach;
20577   BoostAndQForeach.push_back("BOOST_FOREACH");
20578   BoostAndQForeach.push_back("Q_FOREACH");
20579   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20580               BoostAndQForeach);
20581 
20582   Style.IfMacros.clear();
20583   std::vector<std::string> CustomIfs;
20584   CustomIfs.push_back("MYIF");
20585   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20586 
20587   Style.AttributeMacros.clear();
20588   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20589               std::vector<std::string>{"__capability"});
20590   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20591               std::vector<std::string>({"attr1", "attr2"}));
20592 
20593   Style.StatementAttributeLikeMacros.clear();
20594   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20595               StatementAttributeLikeMacros,
20596               std::vector<std::string>({"emit", "Q_EMIT"}));
20597 
20598   Style.StatementMacros.clear();
20599   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20600               std::vector<std::string>{"QUNUSED"});
20601   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20602               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20603 
20604   Style.NamespaceMacros.clear();
20605   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20606               std::vector<std::string>{"TESTSUITE"});
20607   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20608               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20609 
20610   Style.WhitespaceSensitiveMacros.clear();
20611   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20612               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20613   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20614               WhitespaceSensitiveMacros,
20615               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20616   Style.WhitespaceSensitiveMacros.clear();
20617   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
20618               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20619   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
20620               WhitespaceSensitiveMacros,
20621               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20622 
20623   Style.IncludeStyle.IncludeCategories.clear();
20624   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20625       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20626   CHECK_PARSE("IncludeCategories:\n"
20627               "  - Regex: abc/.*\n"
20628               "    Priority: 2\n"
20629               "  - Regex: .*\n"
20630               "    Priority: 1\n"
20631               "    CaseSensitive: true\n",
20632               IncludeStyle.IncludeCategories, ExpectedCategories);
20633   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20634               "abc$");
20635   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20636               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20637 
20638   Style.SortIncludes = FormatStyle::SI_Never;
20639   CHECK_PARSE("SortIncludes: true", SortIncludes,
20640               FormatStyle::SI_CaseSensitive);
20641   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20642   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20643               FormatStyle::SI_CaseInsensitive);
20644   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20645               FormatStyle::SI_CaseSensitive);
20646   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20647 
20648   Style.RawStringFormats.clear();
20649   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20650       {
20651           FormatStyle::LK_TextProto,
20652           {"pb", "proto"},
20653           {"PARSE_TEXT_PROTO"},
20654           /*CanonicalDelimiter=*/"",
20655           "llvm",
20656       },
20657       {
20658           FormatStyle::LK_Cpp,
20659           {"cc", "cpp"},
20660           {"C_CODEBLOCK", "CPPEVAL"},
20661           /*CanonicalDelimiter=*/"cc",
20662           /*BasedOnStyle=*/"",
20663       },
20664   };
20665 
20666   CHECK_PARSE("RawStringFormats:\n"
20667               "  - Language: TextProto\n"
20668               "    Delimiters:\n"
20669               "      - 'pb'\n"
20670               "      - 'proto'\n"
20671               "    EnclosingFunctions:\n"
20672               "      - 'PARSE_TEXT_PROTO'\n"
20673               "    BasedOnStyle: llvm\n"
20674               "  - Language: Cpp\n"
20675               "    Delimiters:\n"
20676               "      - 'cc'\n"
20677               "      - 'cpp'\n"
20678               "    EnclosingFunctions:\n"
20679               "      - 'C_CODEBLOCK'\n"
20680               "      - 'CPPEVAL'\n"
20681               "    CanonicalDelimiter: 'cc'",
20682               RawStringFormats, ExpectedRawStringFormats);
20683 
20684   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20685               "  Minimum: 0\n"
20686               "  Maximum: 0",
20687               SpacesInLineCommentPrefix.Minimum, 0u);
20688   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20689   Style.SpacesInLineCommentPrefix.Minimum = 1;
20690   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20691               "  Minimum: 2",
20692               SpacesInLineCommentPrefix.Minimum, 0u);
20693   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20694               "  Maximum: -1",
20695               SpacesInLineCommentPrefix.Maximum, -1u);
20696   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20697               "  Minimum: 2",
20698               SpacesInLineCommentPrefix.Minimum, 2u);
20699   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20700               "  Maximum: 1",
20701               SpacesInLineCommentPrefix.Maximum, 1u);
20702   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20703 
20704   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20705   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20706   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20707               FormatStyle::SIAS_Always);
20708   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20709   // For backward compatibility:
20710   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20711   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20712 
20713   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20714               FormatStyle::RCPS_WithPreceding);
20715   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20716               FormatStyle::RCPS_WithFollowing);
20717   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20718               FormatStyle::RCPS_SingleLine);
20719   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20720               FormatStyle::RCPS_OwnLine);
20721 
20722   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20723               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20724   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20725               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20726   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20727               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20728   // For backward compatibility:
20729   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20730               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20731   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20732               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20733 }
20734 
20735 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20736   FormatStyle Style = {};
20737   Style.Language = FormatStyle::LK_Cpp;
20738   CHECK_PARSE("Language: Cpp\n"
20739               "IndentWidth: 12",
20740               IndentWidth, 12u);
20741   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20742                                "IndentWidth: 34",
20743                                &Style),
20744             ParseError::Unsuitable);
20745   FormatStyle BinPackedTCS = {};
20746   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20747   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20748                                "InsertTrailingCommas: Wrapped",
20749                                &BinPackedTCS),
20750             ParseError::BinPackTrailingCommaConflict);
20751   EXPECT_EQ(12u, Style.IndentWidth);
20752   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20753   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20754 
20755   Style.Language = FormatStyle::LK_JavaScript;
20756   CHECK_PARSE("Language: JavaScript\n"
20757               "IndentWidth: 12",
20758               IndentWidth, 12u);
20759   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20760   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20761                                "IndentWidth: 34",
20762                                &Style),
20763             ParseError::Unsuitable);
20764   EXPECT_EQ(23u, Style.IndentWidth);
20765   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20766   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20767 
20768   CHECK_PARSE("BasedOnStyle: LLVM\n"
20769               "IndentWidth: 67",
20770               IndentWidth, 67u);
20771 
20772   CHECK_PARSE("---\n"
20773               "Language: JavaScript\n"
20774               "IndentWidth: 12\n"
20775               "---\n"
20776               "Language: Cpp\n"
20777               "IndentWidth: 34\n"
20778               "...\n",
20779               IndentWidth, 12u);
20780 
20781   Style.Language = FormatStyle::LK_Cpp;
20782   CHECK_PARSE("---\n"
20783               "Language: JavaScript\n"
20784               "IndentWidth: 12\n"
20785               "---\n"
20786               "Language: Cpp\n"
20787               "IndentWidth: 34\n"
20788               "...\n",
20789               IndentWidth, 34u);
20790   CHECK_PARSE("---\n"
20791               "IndentWidth: 78\n"
20792               "---\n"
20793               "Language: JavaScript\n"
20794               "IndentWidth: 56\n"
20795               "...\n",
20796               IndentWidth, 78u);
20797 
20798   Style.ColumnLimit = 123;
20799   Style.IndentWidth = 234;
20800   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20801   Style.TabWidth = 345;
20802   EXPECT_FALSE(parseConfiguration("---\n"
20803                                   "IndentWidth: 456\n"
20804                                   "BreakBeforeBraces: Allman\n"
20805                                   "---\n"
20806                                   "Language: JavaScript\n"
20807                                   "IndentWidth: 111\n"
20808                                   "TabWidth: 111\n"
20809                                   "---\n"
20810                                   "Language: Cpp\n"
20811                                   "BreakBeforeBraces: Stroustrup\n"
20812                                   "TabWidth: 789\n"
20813                                   "...\n",
20814                                   &Style));
20815   EXPECT_EQ(123u, Style.ColumnLimit);
20816   EXPECT_EQ(456u, Style.IndentWidth);
20817   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20818   EXPECT_EQ(789u, Style.TabWidth);
20819 
20820   EXPECT_EQ(parseConfiguration("---\n"
20821                                "Language: JavaScript\n"
20822                                "IndentWidth: 56\n"
20823                                "---\n"
20824                                "IndentWidth: 78\n"
20825                                "...\n",
20826                                &Style),
20827             ParseError::Error);
20828   EXPECT_EQ(parseConfiguration("---\n"
20829                                "Language: JavaScript\n"
20830                                "IndentWidth: 56\n"
20831                                "---\n"
20832                                "Language: JavaScript\n"
20833                                "IndentWidth: 78\n"
20834                                "...\n",
20835                                &Style),
20836             ParseError::Error);
20837 
20838   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20839 }
20840 
20841 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20842   FormatStyle Style = {};
20843   Style.Language = FormatStyle::LK_JavaScript;
20844   Style.BreakBeforeTernaryOperators = true;
20845   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20846   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20847 
20848   Style.BreakBeforeTernaryOperators = true;
20849   EXPECT_EQ(0, parseConfiguration("---\n"
20850                                   "BasedOnStyle: Google\n"
20851                                   "---\n"
20852                                   "Language: JavaScript\n"
20853                                   "IndentWidth: 76\n"
20854                                   "...\n",
20855                                   &Style)
20856                    .value());
20857   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20858   EXPECT_EQ(76u, Style.IndentWidth);
20859   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20860 }
20861 
20862 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20863   FormatStyle Style = getLLVMStyle();
20864   std::string YAML = configurationAsText(Style);
20865   FormatStyle ParsedStyle = {};
20866   ParsedStyle.Language = FormatStyle::LK_Cpp;
20867   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20868   EXPECT_EQ(Style, ParsedStyle);
20869 }
20870 
20871 TEST_F(FormatTest, WorksFor8bitEncodings) {
20872   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20873             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20874             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20875             "\"\xef\xee\xf0\xf3...\"",
20876             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20877                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20878                    "\xef\xee\xf0\xf3...\"",
20879                    getLLVMStyleWithColumns(12)));
20880 }
20881 
20882 TEST_F(FormatTest, HandlesUTF8BOM) {
20883   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20884   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20885             format("\xef\xbb\xbf#include <iostream>"));
20886   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20887             format("\xef\xbb\xbf\n#include <iostream>"));
20888 }
20889 
20890 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20891 #if !defined(_MSC_VER)
20892 
20893 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20894   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20895                getLLVMStyleWithColumns(35));
20896   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20897                getLLVMStyleWithColumns(31));
20898   verifyFormat("// Однажды в студёную зимнюю пору...",
20899                getLLVMStyleWithColumns(36));
20900   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20901   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20902                getLLVMStyleWithColumns(39));
20903   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20904                getLLVMStyleWithColumns(35));
20905 }
20906 
20907 TEST_F(FormatTest, SplitsUTF8Strings) {
20908   // Non-printable characters' width is currently considered to be the length in
20909   // bytes in UTF8. The characters can be displayed in very different manner
20910   // (zero-width, single width with a substitution glyph, expanded to their code
20911   // (e.g. "<8d>"), so there's no single correct way to handle them.
20912   EXPECT_EQ("\"aaaaÄ\"\n"
20913             "\"\xc2\x8d\";",
20914             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20915   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20916             "\"\xc2\x8d\";",
20917             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20918   EXPECT_EQ("\"Однажды, в \"\n"
20919             "\"студёную \"\n"
20920             "\"зимнюю \"\n"
20921             "\"пору,\"",
20922             format("\"Однажды, в студёную зимнюю пору,\"",
20923                    getLLVMStyleWithColumns(13)));
20924   EXPECT_EQ(
20925       "\"一 二 三 \"\n"
20926       "\"四 五六 \"\n"
20927       "\"七 八 九 \"\n"
20928       "\"十\"",
20929       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20930   EXPECT_EQ("\"一\t\"\n"
20931             "\"二 \t\"\n"
20932             "\"三 四 \"\n"
20933             "\"五\t\"\n"
20934             "\"六 \t\"\n"
20935             "\"七 \"\n"
20936             "\"八九十\tqq\"",
20937             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20938                    getLLVMStyleWithColumns(11)));
20939 
20940   // UTF8 character in an escape sequence.
20941   EXPECT_EQ("\"aaaaaa\"\n"
20942             "\"\\\xC2\x8D\"",
20943             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20944 }
20945 
20946 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20947   EXPECT_EQ("const char *sssss =\n"
20948             "    \"一二三四五六七八\\\n"
20949             " 九 十\";",
20950             format("const char *sssss = \"一二三四五六七八\\\n"
20951                    " 九 十\";",
20952                    getLLVMStyleWithColumns(30)));
20953 }
20954 
20955 TEST_F(FormatTest, SplitsUTF8LineComments) {
20956   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20957             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20958   EXPECT_EQ("// Я из лесу\n"
20959             "// вышел; был\n"
20960             "// сильный\n"
20961             "// мороз.",
20962             format("// Я из лесу вышел; был сильный мороз.",
20963                    getLLVMStyleWithColumns(13)));
20964   EXPECT_EQ("// 一二三\n"
20965             "// 四五六七\n"
20966             "// 八  九\n"
20967             "// 十",
20968             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20969 }
20970 
20971 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20972   EXPECT_EQ("/* Гляжу,\n"
20973             " * поднимается\n"
20974             " * медленно в\n"
20975             " * гору\n"
20976             " * Лошадка,\n"
20977             " * везущая\n"
20978             " * хворосту\n"
20979             " * воз. */",
20980             format("/* Гляжу, поднимается медленно в гору\n"
20981                    " * Лошадка, везущая хворосту воз. */",
20982                    getLLVMStyleWithColumns(13)));
20983   EXPECT_EQ(
20984       "/* 一二三\n"
20985       " * 四五六七\n"
20986       " * 八  九\n"
20987       " * 十  */",
20988       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20989   EXPECT_EQ("/* �������� ��������\n"
20990             " * ��������\n"
20991             " * ������-�� */",
20992             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20993 }
20994 
20995 #endif // _MSC_VER
20996 
20997 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
20998   FormatStyle Style = getLLVMStyle();
20999 
21000   Style.ConstructorInitializerIndentWidth = 4;
21001   verifyFormat(
21002       "SomeClass::Constructor()\n"
21003       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
21004       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
21005       Style);
21006 
21007   Style.ConstructorInitializerIndentWidth = 2;
21008   verifyFormat(
21009       "SomeClass::Constructor()\n"
21010       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
21011       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
21012       Style);
21013 
21014   Style.ConstructorInitializerIndentWidth = 0;
21015   verifyFormat(
21016       "SomeClass::Constructor()\n"
21017       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
21018       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
21019       Style);
21020   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
21021   verifyFormat(
21022       "SomeLongTemplateVariableName<\n"
21023       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
21024       Style);
21025   verifyFormat("bool smaller = 1 < "
21026                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
21027                "                       "
21028                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
21029                Style);
21030 
21031   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
21032   verifyFormat("SomeClass::Constructor() :\n"
21033                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
21034                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
21035                Style);
21036 }
21037 
21038 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
21039   FormatStyle Style = getLLVMStyle();
21040   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
21041   Style.ConstructorInitializerIndentWidth = 4;
21042   verifyFormat("SomeClass::Constructor()\n"
21043                "    : a(a)\n"
21044                "    , b(b)\n"
21045                "    , c(c) {}",
21046                Style);
21047   verifyFormat("SomeClass::Constructor()\n"
21048                "    : a(a) {}",
21049                Style);
21050 
21051   Style.ColumnLimit = 0;
21052   verifyFormat("SomeClass::Constructor()\n"
21053                "    : a(a) {}",
21054                Style);
21055   verifyFormat("SomeClass::Constructor() noexcept\n"
21056                "    : a(a) {}",
21057                Style);
21058   verifyFormat("SomeClass::Constructor()\n"
21059                "    : a(a)\n"
21060                "    , b(b)\n"
21061                "    , c(c) {}",
21062                Style);
21063   verifyFormat("SomeClass::Constructor()\n"
21064                "    : a(a) {\n"
21065                "  foo();\n"
21066                "  bar();\n"
21067                "}",
21068                Style);
21069 
21070   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
21071   verifyFormat("SomeClass::Constructor()\n"
21072                "    : a(a)\n"
21073                "    , b(b)\n"
21074                "    , c(c) {\n}",
21075                Style);
21076   verifyFormat("SomeClass::Constructor()\n"
21077                "    : a(a) {\n}",
21078                Style);
21079 
21080   Style.ColumnLimit = 80;
21081   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
21082   Style.ConstructorInitializerIndentWidth = 2;
21083   verifyFormat("SomeClass::Constructor()\n"
21084                "  : a(a)\n"
21085                "  , b(b)\n"
21086                "  , c(c) {}",
21087                Style);
21088 
21089   Style.ConstructorInitializerIndentWidth = 0;
21090   verifyFormat("SomeClass::Constructor()\n"
21091                ": a(a)\n"
21092                ", b(b)\n"
21093                ", c(c) {}",
21094                Style);
21095 
21096   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
21097   Style.ConstructorInitializerIndentWidth = 4;
21098   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
21099   verifyFormat(
21100       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
21101       Style);
21102   verifyFormat(
21103       "SomeClass::Constructor()\n"
21104       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
21105       Style);
21106   Style.ConstructorInitializerIndentWidth = 4;
21107   Style.ColumnLimit = 60;
21108   verifyFormat("SomeClass::Constructor()\n"
21109                "    : aaaaaaaa(aaaaaaaa)\n"
21110                "    , aaaaaaaa(aaaaaaaa)\n"
21111                "    , aaaaaaaa(aaaaaaaa) {}",
21112                Style);
21113 }
21114 
21115 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
21116   FormatStyle Style = getLLVMStyle();
21117   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
21118   Style.ConstructorInitializerIndentWidth = 4;
21119   verifyFormat("SomeClass::Constructor()\n"
21120                "    : a{a}\n"
21121                "    , b{b} {}",
21122                Style);
21123   verifyFormat("SomeClass::Constructor()\n"
21124                "    : a{a}\n"
21125                "#if CONDITION\n"
21126                "    , b{b}\n"
21127                "#endif\n"
21128                "{\n}",
21129                Style);
21130   Style.ConstructorInitializerIndentWidth = 2;
21131   verifyFormat("SomeClass::Constructor()\n"
21132                "#if CONDITION\n"
21133                "  : a{a}\n"
21134                "#endif\n"
21135                "  , b{b}\n"
21136                "  , c{c} {\n}",
21137                Style);
21138   Style.ConstructorInitializerIndentWidth = 0;
21139   verifyFormat("SomeClass::Constructor()\n"
21140                ": a{a}\n"
21141                "#ifdef CONDITION\n"
21142                ", b{b}\n"
21143                "#else\n"
21144                ", c{c}\n"
21145                "#endif\n"
21146                ", d{d} {\n}",
21147                Style);
21148   Style.ConstructorInitializerIndentWidth = 4;
21149   verifyFormat("SomeClass::Constructor()\n"
21150                "    : a{a}\n"
21151                "#if WINDOWS\n"
21152                "#if DEBUG\n"
21153                "    , b{0}\n"
21154                "#else\n"
21155                "    , b{1}\n"
21156                "#endif\n"
21157                "#else\n"
21158                "#if DEBUG\n"
21159                "    , b{2}\n"
21160                "#else\n"
21161                "    , b{3}\n"
21162                "#endif\n"
21163                "#endif\n"
21164                "{\n}",
21165                Style);
21166   verifyFormat("SomeClass::Constructor()\n"
21167                "    : a{a}\n"
21168                "#if WINDOWS\n"
21169                "    , b{0}\n"
21170                "#if DEBUG\n"
21171                "    , c{0}\n"
21172                "#else\n"
21173                "    , c{1}\n"
21174                "#endif\n"
21175                "#else\n"
21176                "#if DEBUG\n"
21177                "    , c{2}\n"
21178                "#else\n"
21179                "    , c{3}\n"
21180                "#endif\n"
21181                "    , b{1}\n"
21182                "#endif\n"
21183                "{\n}",
21184                Style);
21185 }
21186 
21187 TEST_F(FormatTest, Destructors) {
21188   verifyFormat("void F(int &i) { i.~int(); }");
21189   verifyFormat("void F(int &i) { i->~int(); }");
21190 }
21191 
21192 TEST_F(FormatTest, FormatsWithWebKitStyle) {
21193   FormatStyle Style = getWebKitStyle();
21194 
21195   // Don't indent in outer namespaces.
21196   verifyFormat("namespace outer {\n"
21197                "int i;\n"
21198                "namespace inner {\n"
21199                "    int i;\n"
21200                "} // namespace inner\n"
21201                "} // namespace outer\n"
21202                "namespace other_outer {\n"
21203                "int i;\n"
21204                "}",
21205                Style);
21206 
21207   // Don't indent case labels.
21208   verifyFormat("switch (variable) {\n"
21209                "case 1:\n"
21210                "case 2:\n"
21211                "    doSomething();\n"
21212                "    break;\n"
21213                "default:\n"
21214                "    ++variable;\n"
21215                "}",
21216                Style);
21217 
21218   // Wrap before binary operators.
21219   EXPECT_EQ("void f()\n"
21220             "{\n"
21221             "    if (aaaaaaaaaaaaaaaa\n"
21222             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
21223             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21224             "        return;\n"
21225             "}",
21226             format("void f() {\n"
21227                    "if (aaaaaaaaaaaaaaaa\n"
21228                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
21229                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21230                    "return;\n"
21231                    "}",
21232                    Style));
21233 
21234   // Allow functions on a single line.
21235   verifyFormat("void f() { return; }", Style);
21236 
21237   // Allow empty blocks on a single line and insert a space in empty blocks.
21238   EXPECT_EQ("void f() { }", format("void f() {}", Style));
21239   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
21240   // However, don't merge non-empty short loops.
21241   EXPECT_EQ("while (true) {\n"
21242             "    continue;\n"
21243             "}",
21244             format("while (true) { continue; }", Style));
21245 
21246   // Constructor initializers are formatted one per line with the "," on the
21247   // new line.
21248   verifyFormat("Constructor()\n"
21249                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
21250                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
21251                "          aaaaaaaaaaaaaa)\n"
21252                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
21253                "{\n"
21254                "}",
21255                Style);
21256   verifyFormat("SomeClass::Constructor()\n"
21257                "    : a(a)\n"
21258                "{\n"
21259                "}",
21260                Style);
21261   EXPECT_EQ("SomeClass::Constructor()\n"
21262             "    : a(a)\n"
21263             "{\n"
21264             "}",
21265             format("SomeClass::Constructor():a(a){}", Style));
21266   verifyFormat("SomeClass::Constructor()\n"
21267                "    : a(a)\n"
21268                "    , b(b)\n"
21269                "    , c(c)\n"
21270                "{\n"
21271                "}",
21272                Style);
21273   verifyFormat("SomeClass::Constructor()\n"
21274                "    : a(a)\n"
21275                "{\n"
21276                "    foo();\n"
21277                "    bar();\n"
21278                "}",
21279                Style);
21280 
21281   // Access specifiers should be aligned left.
21282   verifyFormat("class C {\n"
21283                "public:\n"
21284                "    int i;\n"
21285                "};",
21286                Style);
21287 
21288   // Do not align comments.
21289   verifyFormat("int a; // Do not\n"
21290                "double b; // align comments.",
21291                Style);
21292 
21293   // Do not align operands.
21294   EXPECT_EQ("ASSERT(aaaa\n"
21295             "    || bbbb);",
21296             format("ASSERT ( aaaa\n||bbbb);", Style));
21297 
21298   // Accept input's line breaks.
21299   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
21300             "    || bbbbbbbbbbbbbbb) {\n"
21301             "    i++;\n"
21302             "}",
21303             format("if (aaaaaaaaaaaaaaa\n"
21304                    "|| bbbbbbbbbbbbbbb) { i++; }",
21305                    Style));
21306   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
21307             "    i++;\n"
21308             "}",
21309             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
21310 
21311   // Don't automatically break all macro definitions (llvm.org/PR17842).
21312   verifyFormat("#define aNumber 10", Style);
21313   // However, generally keep the line breaks that the user authored.
21314   EXPECT_EQ("#define aNumber \\\n"
21315             "    10",
21316             format("#define aNumber \\\n"
21317                    " 10",
21318                    Style));
21319 
21320   // Keep empty and one-element array literals on a single line.
21321   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
21322             "                                  copyItems:YES];",
21323             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
21324                    "copyItems:YES];",
21325                    Style));
21326   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
21327             "                                  copyItems:YES];",
21328             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
21329                    "             copyItems:YES];",
21330                    Style));
21331   // FIXME: This does not seem right, there should be more indentation before
21332   // the array literal's entries. Nested blocks have the same problem.
21333   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21334             "    @\"a\",\n"
21335             "    @\"a\"\n"
21336             "]\n"
21337             "                                  copyItems:YES];",
21338             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21339                    "     @\"a\",\n"
21340                    "     @\"a\"\n"
21341                    "     ]\n"
21342                    "       copyItems:YES];",
21343                    Style));
21344   EXPECT_EQ(
21345       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21346       "                                  copyItems:YES];",
21347       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21348              "   copyItems:YES];",
21349              Style));
21350 
21351   verifyFormat("[self.a b:c c:d];", Style);
21352   EXPECT_EQ("[self.a b:c\n"
21353             "        c:d];",
21354             format("[self.a b:c\n"
21355                    "c:d];",
21356                    Style));
21357 }
21358 
21359 TEST_F(FormatTest, FormatsLambdas) {
21360   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
21361   verifyFormat(
21362       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
21363   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
21364   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
21365   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
21366   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
21367   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
21368   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
21369   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
21370   verifyFormat("int x = f(*+[] {});");
21371   verifyFormat("void f() {\n"
21372                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
21373                "}\n");
21374   verifyFormat("void f() {\n"
21375                "  other(x.begin(), //\n"
21376                "        x.end(),   //\n"
21377                "        [&](int, int) { return 1; });\n"
21378                "}\n");
21379   verifyFormat("void f() {\n"
21380                "  other.other.other.other.other(\n"
21381                "      x.begin(), x.end(),\n"
21382                "      [something, rather](int, int, int, int, int, int, int) { "
21383                "return 1; });\n"
21384                "}\n");
21385   verifyFormat(
21386       "void f() {\n"
21387       "  other.other.other.other.other(\n"
21388       "      x.begin(), x.end(),\n"
21389       "      [something, rather](int, int, int, int, int, int, int) {\n"
21390       "        //\n"
21391       "      });\n"
21392       "}\n");
21393   verifyFormat("SomeFunction([]() { // A cool function...\n"
21394                "  return 43;\n"
21395                "});");
21396   EXPECT_EQ("SomeFunction([]() {\n"
21397             "#define A a\n"
21398             "  return 43;\n"
21399             "});",
21400             format("SomeFunction([](){\n"
21401                    "#define A a\n"
21402                    "return 43;\n"
21403                    "});"));
21404   verifyFormat("void f() {\n"
21405                "  SomeFunction([](decltype(x), A *a) {});\n"
21406                "  SomeFunction([](typeof(x), A *a) {});\n"
21407                "  SomeFunction([](_Atomic(x), A *a) {});\n"
21408                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
21409                "}");
21410   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21411                "    [](const aaaaaaaaaa &a) { return a; });");
21412   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
21413                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
21414                "});");
21415   verifyFormat("Constructor()\n"
21416                "    : Field([] { // comment\n"
21417                "        int i;\n"
21418                "      }) {}");
21419   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
21420                "  return some_parameter.size();\n"
21421                "};");
21422   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
21423                "    [](const string &s) { return s; };");
21424   verifyFormat("int i = aaaaaa ? 1 //\n"
21425                "               : [] {\n"
21426                "                   return 2; //\n"
21427                "                 }();");
21428   verifyFormat("llvm::errs() << \"number of twos is \"\n"
21429                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
21430                "                  return x == 2; // force break\n"
21431                "                });");
21432   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21433                "    [=](int iiiiiiiiiiii) {\n"
21434                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
21435                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
21436                "    });",
21437                getLLVMStyleWithColumns(60));
21438 
21439   verifyFormat("SomeFunction({[&] {\n"
21440                "                // comment\n"
21441                "              },\n"
21442                "              [&] {\n"
21443                "                // comment\n"
21444                "              }});");
21445   verifyFormat("SomeFunction({[&] {\n"
21446                "  // comment\n"
21447                "}});");
21448   verifyFormat(
21449       "virtual aaaaaaaaaaaaaaaa(\n"
21450       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
21451       "    aaaaa aaaaaaaaa);");
21452 
21453   // Lambdas with return types.
21454   verifyFormat("int c = []() -> int { return 2; }();\n");
21455   verifyFormat("int c = []() -> int * { return 2; }();\n");
21456   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
21457   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
21458   verifyFormat("foo([]() noexcept -> int {});");
21459   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
21460   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
21461   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
21462   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
21463   verifyFormat("[a, a]() -> a<1> {};");
21464   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
21465   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
21466   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
21467   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
21468   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
21469   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
21470   verifyFormat("[]() -> foo<!5> { return {}; };");
21471   verifyFormat("[]() -> foo<~5> { return {}; };");
21472   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
21473   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
21474   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
21475   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
21476   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
21477   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
21478   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
21479   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
21480   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
21481   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
21482   verifyFormat("namespace bar {\n"
21483                "// broken:\n"
21484                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
21485                "} // namespace bar");
21486   verifyFormat("namespace bar {\n"
21487                "// broken:\n"
21488                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
21489                "} // namespace bar");
21490   verifyFormat("namespace bar {\n"
21491                "// broken:\n"
21492                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
21493                "} // namespace bar");
21494   verifyFormat("namespace bar {\n"
21495                "// broken:\n"
21496                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
21497                "} // namespace bar");
21498   verifyFormat("namespace bar {\n"
21499                "// broken:\n"
21500                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
21501                "} // namespace bar");
21502   verifyFormat("namespace bar {\n"
21503                "// broken:\n"
21504                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
21505                "} // namespace bar");
21506   verifyFormat("namespace bar {\n"
21507                "// broken:\n"
21508                "auto foo{[]() -> foo<!5> { return {}; }};\n"
21509                "} // namespace bar");
21510   verifyFormat("namespace bar {\n"
21511                "// broken:\n"
21512                "auto foo{[]() -> foo<~5> { return {}; }};\n"
21513                "} // namespace bar");
21514   verifyFormat("namespace bar {\n"
21515                "// broken:\n"
21516                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
21517                "} // namespace bar");
21518   verifyFormat("namespace bar {\n"
21519                "// broken:\n"
21520                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
21521                "} // namespace bar");
21522   verifyFormat("namespace bar {\n"
21523                "// broken:\n"
21524                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
21525                "} // namespace bar");
21526   verifyFormat("namespace bar {\n"
21527                "// broken:\n"
21528                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
21529                "} // namespace bar");
21530   verifyFormat("namespace bar {\n"
21531                "// broken:\n"
21532                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
21533                "} // namespace bar");
21534   verifyFormat("namespace bar {\n"
21535                "// broken:\n"
21536                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
21537                "} // namespace bar");
21538   verifyFormat("namespace bar {\n"
21539                "// broken:\n"
21540                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
21541                "} // namespace bar");
21542   verifyFormat("namespace bar {\n"
21543                "// broken:\n"
21544                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
21545                "} // namespace bar");
21546   verifyFormat("namespace bar {\n"
21547                "// broken:\n"
21548                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
21549                "} // namespace bar");
21550   verifyFormat("namespace bar {\n"
21551                "// broken:\n"
21552                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
21553                "} // namespace bar");
21554   verifyFormat("[]() -> a<1> {};");
21555   verifyFormat("[]() -> a<1> { ; };");
21556   verifyFormat("[]() -> a<1> { ; }();");
21557   verifyFormat("[a, a]() -> a<true> {};");
21558   verifyFormat("[]() -> a<true> {};");
21559   verifyFormat("[]() -> a<true> { ; };");
21560   verifyFormat("[]() -> a<true> { ; }();");
21561   verifyFormat("[a, a]() -> a<false> {};");
21562   verifyFormat("[]() -> a<false> {};");
21563   verifyFormat("[]() -> a<false> { ; };");
21564   verifyFormat("[]() -> a<false> { ; }();");
21565   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
21566   verifyFormat("namespace bar {\n"
21567                "auto foo{[]() -> foo<false> { ; }};\n"
21568                "} // namespace bar");
21569   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
21570                "                   int j) -> int {\n"
21571                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21572                "};");
21573   verifyFormat(
21574       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21575       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21576       "      return aaaaaaaaaaaaaaaaa;\n"
21577       "    });",
21578       getLLVMStyleWithColumns(70));
21579   verifyFormat("[]() //\n"
21580                "    -> int {\n"
21581                "  return 1; //\n"
21582                "};");
21583   verifyFormat("[]() -> Void<T...> {};");
21584   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21585   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21586   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21587   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21588   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21589   verifyFormat("return int{[x = x]() { return x; }()};");
21590 
21591   // Lambdas with explicit template argument lists.
21592   verifyFormat(
21593       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21594   verifyFormat("auto L = []<class T>(T) {\n"
21595                "  {\n"
21596                "    f();\n"
21597                "    g();\n"
21598                "  }\n"
21599                "};\n");
21600   verifyFormat("auto L = []<class... T>(T...) {\n"
21601                "  {\n"
21602                "    f();\n"
21603                "    g();\n"
21604                "  }\n"
21605                "};\n");
21606   verifyFormat("auto L = []<typename... T>(T...) {\n"
21607                "  {\n"
21608                "    f();\n"
21609                "    g();\n"
21610                "  }\n"
21611                "};\n");
21612   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21613                "  {\n"
21614                "    f();\n"
21615                "    g();\n"
21616                "  }\n"
21617                "};\n");
21618   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21619                "  {\n"
21620                "    f();\n"
21621                "    g();\n"
21622                "  }\n"
21623                "};\n");
21624 
21625   // Multiple lambdas in the same parentheses change indentation rules. These
21626   // lambdas are forced to start on new lines.
21627   verifyFormat("SomeFunction(\n"
21628                "    []() {\n"
21629                "      //\n"
21630                "    },\n"
21631                "    []() {\n"
21632                "      //\n"
21633                "    });");
21634 
21635   // A lambda passed as arg0 is always pushed to the next line.
21636   verifyFormat("SomeFunction(\n"
21637                "    [this] {\n"
21638                "      //\n"
21639                "    },\n"
21640                "    1);\n");
21641 
21642   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21643   // the arg0 case above.
21644   auto Style = getGoogleStyle();
21645   Style.BinPackArguments = false;
21646   verifyFormat("SomeFunction(\n"
21647                "    a,\n"
21648                "    [this] {\n"
21649                "      //\n"
21650                "    },\n"
21651                "    b);\n",
21652                Style);
21653   verifyFormat("SomeFunction(\n"
21654                "    a,\n"
21655                "    [this] {\n"
21656                "      //\n"
21657                "    },\n"
21658                "    b);\n");
21659 
21660   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21661   // the BinPackArguments value (as long as the code is wide enough).
21662   verifyFormat(
21663       "something->SomeFunction(\n"
21664       "    a,\n"
21665       "    [this] {\n"
21666       "      "
21667       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21668       "    },\n"
21669       "    b);\n");
21670 
21671   // A multi-line lambda is pulled up as long as the introducer fits on the
21672   // previous line and there are no further args.
21673   verifyFormat("function(1, [this, that] {\n"
21674                "  //\n"
21675                "});\n");
21676   verifyFormat("function([this, that] {\n"
21677                "  //\n"
21678                "});\n");
21679   // FIXME: this format is not ideal and we should consider forcing the first
21680   // arg onto its own line.
21681   verifyFormat("function(a, b, c, //\n"
21682                "         d, [this, that] {\n"
21683                "           //\n"
21684                "         });\n");
21685 
21686   // Multiple lambdas are treated correctly even when there is a short arg0.
21687   verifyFormat("SomeFunction(\n"
21688                "    1,\n"
21689                "    [this] {\n"
21690                "      //\n"
21691                "    },\n"
21692                "    [this] {\n"
21693                "      //\n"
21694                "    },\n"
21695                "    1);\n");
21696 
21697   // More complex introducers.
21698   verifyFormat("return [i, args...] {};");
21699 
21700   // Not lambdas.
21701   verifyFormat("constexpr char hello[]{\"hello\"};");
21702   verifyFormat("double &operator[](int i) { return 0; }\n"
21703                "int i;");
21704   verifyFormat("std::unique_ptr<int[]> foo() {}");
21705   verifyFormat("int i = a[a][a]->f();");
21706   verifyFormat("int i = (*b)[a]->f();");
21707 
21708   // Other corner cases.
21709   verifyFormat("void f() {\n"
21710                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21711                "  );\n"
21712                "}");
21713   verifyFormat("auto k = *[](int *j) { return j; }(&i);");
21714 
21715   // Lambdas created through weird macros.
21716   verifyFormat("void f() {\n"
21717                "  MACRO((const AA &a) { return 1; });\n"
21718                "  MACRO((AA &a) { return 1; });\n"
21719                "}");
21720 
21721   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21722                "      doo_dah();\n"
21723                "      doo_dah();\n"
21724                "    })) {\n"
21725                "}");
21726   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21727                "                doo_dah();\n"
21728                "                doo_dah();\n"
21729                "              })) {\n"
21730                "}");
21731   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21732                "                doo_dah();\n"
21733                "                doo_dah();\n"
21734                "              })) {\n"
21735                "}");
21736   verifyFormat("auto lambda = []() {\n"
21737                "  int a = 2\n"
21738                "#if A\n"
21739                "          + 2\n"
21740                "#endif\n"
21741                "      ;\n"
21742                "};");
21743 
21744   // Lambdas with complex multiline introducers.
21745   verifyFormat(
21746       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21747       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21748       "        -> ::std::unordered_set<\n"
21749       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21750       "      //\n"
21751       "    });");
21752 
21753   FormatStyle DoNotMerge = getLLVMStyle();
21754   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21755   verifyFormat("auto c = []() {\n"
21756                "  return b;\n"
21757                "};",
21758                "auto c = []() { return b; };", DoNotMerge);
21759   verifyFormat("auto c = []() {\n"
21760                "};",
21761                " auto c = []() {};", DoNotMerge);
21762 
21763   FormatStyle MergeEmptyOnly = getLLVMStyle();
21764   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21765   verifyFormat("auto c = []() {\n"
21766                "  return b;\n"
21767                "};",
21768                "auto c = []() {\n"
21769                "  return b;\n"
21770                " };",
21771                MergeEmptyOnly);
21772   verifyFormat("auto c = []() {};",
21773                "auto c = []() {\n"
21774                "};",
21775                MergeEmptyOnly);
21776 
21777   FormatStyle MergeInline = getLLVMStyle();
21778   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21779   verifyFormat("auto c = []() {\n"
21780                "  return b;\n"
21781                "};",
21782                "auto c = []() { return b; };", MergeInline);
21783   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21784                MergeInline);
21785   verifyFormat("function([]() { return b; }, a)",
21786                "function([]() { return b; }, a)", MergeInline);
21787   verifyFormat("function(a, []() { return b; })",
21788                "function(a, []() { return b; })", MergeInline);
21789 
21790   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21791   // AllowShortLambdasOnASingleLine
21792   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21793   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21794   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21795   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21796       FormatStyle::ShortLambdaStyle::SLS_None;
21797   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21798                "    []()\n"
21799                "    {\n"
21800                "      return 17;\n"
21801                "    });",
21802                LLVMWithBeforeLambdaBody);
21803   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21804                "    []()\n"
21805                "    {\n"
21806                "    });",
21807                LLVMWithBeforeLambdaBody);
21808   verifyFormat("auto fct_SLS_None = []()\n"
21809                "{\n"
21810                "  return 17;\n"
21811                "};",
21812                LLVMWithBeforeLambdaBody);
21813   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21814                "    []()\n"
21815                "    {\n"
21816                "      return Call(\n"
21817                "          []()\n"
21818                "          {\n"
21819                "            return 17;\n"
21820                "          });\n"
21821                "    });",
21822                LLVMWithBeforeLambdaBody);
21823   verifyFormat("void Fct() {\n"
21824                "  return {[]()\n"
21825                "          {\n"
21826                "            return 17;\n"
21827                "          }};\n"
21828                "}",
21829                LLVMWithBeforeLambdaBody);
21830 
21831   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21832       FormatStyle::ShortLambdaStyle::SLS_Empty;
21833   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21834                "    []()\n"
21835                "    {\n"
21836                "      return 17;\n"
21837                "    });",
21838                LLVMWithBeforeLambdaBody);
21839   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21840                LLVMWithBeforeLambdaBody);
21841   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21842                "ongFunctionName_SLS_Empty(\n"
21843                "    []() {});",
21844                LLVMWithBeforeLambdaBody);
21845   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21846                "                                []()\n"
21847                "                                {\n"
21848                "                                  return 17;\n"
21849                "                                });",
21850                LLVMWithBeforeLambdaBody);
21851   verifyFormat("auto fct_SLS_Empty = []()\n"
21852                "{\n"
21853                "  return 17;\n"
21854                "};",
21855                LLVMWithBeforeLambdaBody);
21856   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21857                "    []()\n"
21858                "    {\n"
21859                "      return Call([]() {});\n"
21860                "    });",
21861                LLVMWithBeforeLambdaBody);
21862   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21863                "                           []()\n"
21864                "                           {\n"
21865                "                             return Call([]() {});\n"
21866                "                           });",
21867                LLVMWithBeforeLambdaBody);
21868   verifyFormat(
21869       "FctWithLongLineInLambda_SLS_Empty(\n"
21870       "    []()\n"
21871       "    {\n"
21872       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21873       "                               AndShouldNotBeConsiderAsInline,\n"
21874       "                               LambdaBodyMustBeBreak);\n"
21875       "    });",
21876       LLVMWithBeforeLambdaBody);
21877 
21878   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21879       FormatStyle::ShortLambdaStyle::SLS_Inline;
21880   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21881                LLVMWithBeforeLambdaBody);
21882   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21883                LLVMWithBeforeLambdaBody);
21884   verifyFormat("auto fct_SLS_Inline = []()\n"
21885                "{\n"
21886                "  return 17;\n"
21887                "};",
21888                LLVMWithBeforeLambdaBody);
21889   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21890                "17; }); });",
21891                LLVMWithBeforeLambdaBody);
21892   verifyFormat(
21893       "FctWithLongLineInLambda_SLS_Inline(\n"
21894       "    []()\n"
21895       "    {\n"
21896       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21897       "                               AndShouldNotBeConsiderAsInline,\n"
21898       "                               LambdaBodyMustBeBreak);\n"
21899       "    });",
21900       LLVMWithBeforeLambdaBody);
21901   verifyFormat("FctWithMultipleParams_SLS_Inline("
21902                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21903                "                                 []() { return 17; });",
21904                LLVMWithBeforeLambdaBody);
21905   verifyFormat(
21906       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21907       LLVMWithBeforeLambdaBody);
21908 
21909   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21910       FormatStyle::ShortLambdaStyle::SLS_All;
21911   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21912                LLVMWithBeforeLambdaBody);
21913   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21914                LLVMWithBeforeLambdaBody);
21915   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21916                LLVMWithBeforeLambdaBody);
21917   verifyFormat("FctWithOneParam_SLS_All(\n"
21918                "    []()\n"
21919                "    {\n"
21920                "      // A cool function...\n"
21921                "      return 43;\n"
21922                "    });",
21923                LLVMWithBeforeLambdaBody);
21924   verifyFormat("FctWithMultipleParams_SLS_All("
21925                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21926                "                              []() { return 17; });",
21927                LLVMWithBeforeLambdaBody);
21928   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21929                LLVMWithBeforeLambdaBody);
21930   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21931                LLVMWithBeforeLambdaBody);
21932   verifyFormat(
21933       "FctWithLongLineInLambda_SLS_All(\n"
21934       "    []()\n"
21935       "    {\n"
21936       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21937       "                               AndShouldNotBeConsiderAsInline,\n"
21938       "                               LambdaBodyMustBeBreak);\n"
21939       "    });",
21940       LLVMWithBeforeLambdaBody);
21941   verifyFormat(
21942       "auto fct_SLS_All = []()\n"
21943       "{\n"
21944       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21945       "                           AndShouldNotBeConsiderAsInline,\n"
21946       "                           LambdaBodyMustBeBreak);\n"
21947       "};",
21948       LLVMWithBeforeLambdaBody);
21949   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21950   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21951                LLVMWithBeforeLambdaBody);
21952   verifyFormat(
21953       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21954       "                                FirstParam,\n"
21955       "                                SecondParam,\n"
21956       "                                ThirdParam,\n"
21957       "                                FourthParam);",
21958       LLVMWithBeforeLambdaBody);
21959   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21960                "    []() { return "
21961                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21962                "    FirstParam,\n"
21963                "    SecondParam,\n"
21964                "    ThirdParam,\n"
21965                "    FourthParam);",
21966                LLVMWithBeforeLambdaBody);
21967   verifyFormat(
21968       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21969       "                                SecondParam,\n"
21970       "                                ThirdParam,\n"
21971       "                                FourthParam,\n"
21972       "                                []() { return SomeValueNotSoLong; });",
21973       LLVMWithBeforeLambdaBody);
21974   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21975                "    []()\n"
21976                "    {\n"
21977                "      return "
21978                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21979                "eConsiderAsInline;\n"
21980                "    });",
21981                LLVMWithBeforeLambdaBody);
21982   verifyFormat(
21983       "FctWithLongLineInLambda_SLS_All(\n"
21984       "    []()\n"
21985       "    {\n"
21986       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21987       "                               AndShouldNotBeConsiderAsInline,\n"
21988       "                               LambdaBodyMustBeBreak);\n"
21989       "    });",
21990       LLVMWithBeforeLambdaBody);
21991   verifyFormat("FctWithTwoParams_SLS_All(\n"
21992                "    []()\n"
21993                "    {\n"
21994                "      // A cool function...\n"
21995                "      return 43;\n"
21996                "    },\n"
21997                "    87);",
21998                LLVMWithBeforeLambdaBody);
21999   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
22000                LLVMWithBeforeLambdaBody);
22001   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
22002                LLVMWithBeforeLambdaBody);
22003   verifyFormat(
22004       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
22005       LLVMWithBeforeLambdaBody);
22006   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
22007                "}); }, x);",
22008                LLVMWithBeforeLambdaBody);
22009   verifyFormat("TwoNestedLambdas_SLS_All(\n"
22010                "    []()\n"
22011                "    {\n"
22012                "      // A cool function...\n"
22013                "      return Call([]() { return 17; });\n"
22014                "    });",
22015                LLVMWithBeforeLambdaBody);
22016   verifyFormat("TwoNestedLambdas_SLS_All(\n"
22017                "    []()\n"
22018                "    {\n"
22019                "      return Call(\n"
22020                "          []()\n"
22021                "          {\n"
22022                "            // A cool function...\n"
22023                "            return 17;\n"
22024                "          });\n"
22025                "    });",
22026                LLVMWithBeforeLambdaBody);
22027 
22028   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
22029       FormatStyle::ShortLambdaStyle::SLS_None;
22030 
22031   verifyFormat("auto select = [this]() -> const Library::Object *\n"
22032                "{\n"
22033                "  return MyAssignment::SelectFromList(this);\n"
22034                "};\n",
22035                LLVMWithBeforeLambdaBody);
22036 
22037   verifyFormat("auto select = [this]() -> const Library::Object &\n"
22038                "{\n"
22039                "  return MyAssignment::SelectFromList(this);\n"
22040                "};\n",
22041                LLVMWithBeforeLambdaBody);
22042 
22043   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
22044                "{\n"
22045                "  return MyAssignment::SelectFromList(this);\n"
22046                "};\n",
22047                LLVMWithBeforeLambdaBody);
22048 
22049   verifyFormat("namespace test {\n"
22050                "class Test {\n"
22051                "public:\n"
22052                "  Test() = default;\n"
22053                "};\n"
22054                "} // namespace test",
22055                LLVMWithBeforeLambdaBody);
22056 
22057   // Lambdas with different indentation styles.
22058   Style = getLLVMStyleWithColumns(100);
22059   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
22060             "  return promise.then(\n"
22061             "      [this, &someVariable, someObject = "
22062             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22063             "        return someObject.startAsyncAction().then(\n"
22064             "            [this, &someVariable](AsyncActionResult result) "
22065             "mutable { result.processMore(); });\n"
22066             "      });\n"
22067             "}\n",
22068             format("SomeResult doSomething(SomeObject promise) {\n"
22069                    "  return promise.then([this, &someVariable, someObject = "
22070                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22071                    "    return someObject.startAsyncAction().then([this, "
22072                    "&someVariable](AsyncActionResult result) mutable {\n"
22073                    "      result.processMore();\n"
22074                    "    });\n"
22075                    "  });\n"
22076                    "}\n",
22077                    Style));
22078   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
22079   verifyFormat("test() {\n"
22080                "  ([]() -> {\n"
22081                "    int b = 32;\n"
22082                "    return 3;\n"
22083                "  }).foo();\n"
22084                "}",
22085                Style);
22086   verifyFormat("test() {\n"
22087                "  []() -> {\n"
22088                "    int b = 32;\n"
22089                "    return 3;\n"
22090                "  }\n"
22091                "}",
22092                Style);
22093   verifyFormat("std::sort(v.begin(), v.end(),\n"
22094                "          [](const auto &someLongArgumentName, const auto "
22095                "&someOtherLongArgumentName) {\n"
22096                "  return someLongArgumentName.someMemberVariable < "
22097                "someOtherLongArgumentName.someMemberVariable;\n"
22098                "});",
22099                Style);
22100   verifyFormat("test() {\n"
22101                "  (\n"
22102                "      []() -> {\n"
22103                "        int b = 32;\n"
22104                "        return 3;\n"
22105                "      },\n"
22106                "      foo, bar)\n"
22107                "      .foo();\n"
22108                "}",
22109                Style);
22110   verifyFormat("test() {\n"
22111                "  ([]() -> {\n"
22112                "    int b = 32;\n"
22113                "    return 3;\n"
22114                "  })\n"
22115                "      .foo()\n"
22116                "      .bar();\n"
22117                "}",
22118                Style);
22119   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
22120             "  return promise.then(\n"
22121             "      [this, &someVariable, someObject = "
22122             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22123             "    return someObject.startAsyncAction().then(\n"
22124             "        [this, &someVariable](AsyncActionResult result) mutable { "
22125             "result.processMore(); });\n"
22126             "  });\n"
22127             "}\n",
22128             format("SomeResult doSomething(SomeObject promise) {\n"
22129                    "  return promise.then([this, &someVariable, someObject = "
22130                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22131                    "    return someObject.startAsyncAction().then([this, "
22132                    "&someVariable](AsyncActionResult result) mutable {\n"
22133                    "      result.processMore();\n"
22134                    "    });\n"
22135                    "  });\n"
22136                    "}\n",
22137                    Style));
22138   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
22139             "  return promise.then([this, &someVariable] {\n"
22140             "    return someObject.startAsyncAction().then(\n"
22141             "        [this, &someVariable](AsyncActionResult result) mutable { "
22142             "result.processMore(); });\n"
22143             "  });\n"
22144             "}\n",
22145             format("SomeResult doSomething(SomeObject promise) {\n"
22146                    "  return promise.then([this, &someVariable] {\n"
22147                    "    return someObject.startAsyncAction().then([this, "
22148                    "&someVariable](AsyncActionResult result) mutable {\n"
22149                    "      result.processMore();\n"
22150                    "    });\n"
22151                    "  });\n"
22152                    "}\n",
22153                    Style));
22154   Style = getGoogleStyle();
22155   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
22156   EXPECT_EQ("#define A                                       \\\n"
22157             "  [] {                                          \\\n"
22158             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
22159             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
22160             "      }",
22161             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
22162                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
22163                    Style));
22164   // TODO: The current formatting has a minor issue that's not worth fixing
22165   // right now whereby the closing brace is indented relative to the signature
22166   // instead of being aligned. This only happens with macros.
22167 }
22168 
22169 TEST_F(FormatTest, LambdaWithLineComments) {
22170   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
22171   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
22172   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
22173   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
22174       FormatStyle::ShortLambdaStyle::SLS_All;
22175 
22176   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
22177   verifyFormat("auto k = []() // comment\n"
22178                "{ return; }",
22179                LLVMWithBeforeLambdaBody);
22180   verifyFormat("auto k = []() /* comment */ { return; }",
22181                LLVMWithBeforeLambdaBody);
22182   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
22183                LLVMWithBeforeLambdaBody);
22184   verifyFormat("auto k = []() // X\n"
22185                "{ return; }",
22186                LLVMWithBeforeLambdaBody);
22187   verifyFormat(
22188       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
22189       "{ return; }",
22190       LLVMWithBeforeLambdaBody);
22191 
22192   LLVMWithBeforeLambdaBody.ColumnLimit = 0;
22193 
22194   verifyFormat("foo([]()\n"
22195                "    {\n"
22196                "      bar();    //\n"
22197                "      return 1; // comment\n"
22198                "    }());",
22199                "foo([]() {\n"
22200                "  bar(); //\n"
22201                "  return 1; // comment\n"
22202                "}());",
22203                LLVMWithBeforeLambdaBody);
22204   verifyFormat("foo(\n"
22205                "    1, MACRO {\n"
22206                "      baz();\n"
22207                "      bar(); // comment\n"
22208                "    },\n"
22209                "    []() {});",
22210                "foo(\n"
22211                "  1, MACRO { baz(); bar(); // comment\n"
22212                "  }, []() {}\n"
22213                ");",
22214                LLVMWithBeforeLambdaBody);
22215 }
22216 
22217 TEST_F(FormatTest, EmptyLinesInLambdas) {
22218   verifyFormat("auto lambda = []() {\n"
22219                "  x(); //\n"
22220                "};",
22221                "auto lambda = []() {\n"
22222                "\n"
22223                "  x(); //\n"
22224                "\n"
22225                "};");
22226 }
22227 
22228 TEST_F(FormatTest, FormatsBlocks) {
22229   FormatStyle ShortBlocks = getLLVMStyle();
22230   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22231   verifyFormat("int (^Block)(int, int);", ShortBlocks);
22232   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
22233   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
22234   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
22235   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
22236   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
22237 
22238   verifyFormat("foo(^{ bar(); });", ShortBlocks);
22239   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
22240   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
22241 
22242   verifyFormat("[operation setCompletionBlock:^{\n"
22243                "  [self onOperationDone];\n"
22244                "}];");
22245   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
22246                "  [self onOperationDone];\n"
22247                "}]};");
22248   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
22249                "  f();\n"
22250                "}];");
22251   verifyFormat("int a = [operation block:^int(int *i) {\n"
22252                "  return 1;\n"
22253                "}];");
22254   verifyFormat("[myObject doSomethingWith:arg1\n"
22255                "                      aaa:^int(int *a) {\n"
22256                "                        return 1;\n"
22257                "                      }\n"
22258                "                      bbb:f(a * bbbbbbbb)];");
22259 
22260   verifyFormat("[operation setCompletionBlock:^{\n"
22261                "  [self.delegate newDataAvailable];\n"
22262                "}];",
22263                getLLVMStyleWithColumns(60));
22264   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
22265                "  NSString *path = [self sessionFilePath];\n"
22266                "  if (path) {\n"
22267                "    // ...\n"
22268                "  }\n"
22269                "});");
22270   verifyFormat("[[SessionService sharedService]\n"
22271                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22272                "      if (window) {\n"
22273                "        [self windowDidLoad:window];\n"
22274                "      } else {\n"
22275                "        [self errorLoadingWindow];\n"
22276                "      }\n"
22277                "    }];");
22278   verifyFormat("void (^largeBlock)(void) = ^{\n"
22279                "  // ...\n"
22280                "};\n",
22281                getLLVMStyleWithColumns(40));
22282   verifyFormat("[[SessionService sharedService]\n"
22283                "    loadWindowWithCompletionBlock: //\n"
22284                "        ^(SessionWindow *window) {\n"
22285                "          if (window) {\n"
22286                "            [self windowDidLoad:window];\n"
22287                "          } else {\n"
22288                "            [self errorLoadingWindow];\n"
22289                "          }\n"
22290                "        }];",
22291                getLLVMStyleWithColumns(60));
22292   verifyFormat("[myObject doSomethingWith:arg1\n"
22293                "    firstBlock:^(Foo *a) {\n"
22294                "      // ...\n"
22295                "      int i;\n"
22296                "    }\n"
22297                "    secondBlock:^(Bar *b) {\n"
22298                "      // ...\n"
22299                "      int i;\n"
22300                "    }\n"
22301                "    thirdBlock:^Foo(Bar *b) {\n"
22302                "      // ...\n"
22303                "      int i;\n"
22304                "    }];");
22305   verifyFormat("[myObject doSomethingWith:arg1\n"
22306                "               firstBlock:-1\n"
22307                "              secondBlock:^(Bar *b) {\n"
22308                "                // ...\n"
22309                "                int i;\n"
22310                "              }];");
22311 
22312   verifyFormat("f(^{\n"
22313                "  @autoreleasepool {\n"
22314                "    if (a) {\n"
22315                "      g();\n"
22316                "    }\n"
22317                "  }\n"
22318                "});");
22319   verifyFormat("Block b = ^int *(A *a, B *b) {}");
22320   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
22321                "};");
22322 
22323   FormatStyle FourIndent = getLLVMStyle();
22324   FourIndent.ObjCBlockIndentWidth = 4;
22325   verifyFormat("[operation setCompletionBlock:^{\n"
22326                "    [self onOperationDone];\n"
22327                "}];",
22328                FourIndent);
22329 }
22330 
22331 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
22332   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
22333 
22334   verifyFormat("[[SessionService sharedService] "
22335                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22336                "  if (window) {\n"
22337                "    [self windowDidLoad:window];\n"
22338                "  } else {\n"
22339                "    [self errorLoadingWindow];\n"
22340                "  }\n"
22341                "}];",
22342                ZeroColumn);
22343   EXPECT_EQ("[[SessionService sharedService]\n"
22344             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22345             "      if (window) {\n"
22346             "        [self windowDidLoad:window];\n"
22347             "      } else {\n"
22348             "        [self errorLoadingWindow];\n"
22349             "      }\n"
22350             "    }];",
22351             format("[[SessionService sharedService]\n"
22352                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22353                    "                if (window) {\n"
22354                    "    [self windowDidLoad:window];\n"
22355                    "  } else {\n"
22356                    "    [self errorLoadingWindow];\n"
22357                    "  }\n"
22358                    "}];",
22359                    ZeroColumn));
22360   verifyFormat("[myObject doSomethingWith:arg1\n"
22361                "    firstBlock:^(Foo *a) {\n"
22362                "      // ...\n"
22363                "      int i;\n"
22364                "    }\n"
22365                "    secondBlock:^(Bar *b) {\n"
22366                "      // ...\n"
22367                "      int i;\n"
22368                "    }\n"
22369                "    thirdBlock:^Foo(Bar *b) {\n"
22370                "      // ...\n"
22371                "      int i;\n"
22372                "    }];",
22373                ZeroColumn);
22374   verifyFormat("f(^{\n"
22375                "  @autoreleasepool {\n"
22376                "    if (a) {\n"
22377                "      g();\n"
22378                "    }\n"
22379                "  }\n"
22380                "});",
22381                ZeroColumn);
22382   verifyFormat("void (^largeBlock)(void) = ^{\n"
22383                "  // ...\n"
22384                "};",
22385                ZeroColumn);
22386 
22387   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22388   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
22389             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22390   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
22391   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
22392             "  int i;\n"
22393             "};",
22394             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22395 }
22396 
22397 TEST_F(FormatTest, SupportsCRLF) {
22398   EXPECT_EQ("int a;\r\n"
22399             "int b;\r\n"
22400             "int c;\r\n",
22401             format("int a;\r\n"
22402                    "  int b;\r\n"
22403                    "    int c;\r\n",
22404                    getLLVMStyle()));
22405   EXPECT_EQ("int a;\r\n"
22406             "int b;\r\n"
22407             "int c;\r\n",
22408             format("int a;\r\n"
22409                    "  int b;\n"
22410                    "    int c;\r\n",
22411                    getLLVMStyle()));
22412   EXPECT_EQ("int a;\n"
22413             "int b;\n"
22414             "int c;\n",
22415             format("int a;\r\n"
22416                    "  int b;\n"
22417                    "    int c;\n",
22418                    getLLVMStyle()));
22419   EXPECT_EQ("\"aaaaaaa \"\r\n"
22420             "\"bbbbbbb\";\r\n",
22421             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
22422   EXPECT_EQ("#define A \\\r\n"
22423             "  b;      \\\r\n"
22424             "  c;      \\\r\n"
22425             "  d;\r\n",
22426             format("#define A \\\r\n"
22427                    "  b; \\\r\n"
22428                    "  c; d; \r\n",
22429                    getGoogleStyle()));
22430 
22431   EXPECT_EQ("/*\r\n"
22432             "multi line block comments\r\n"
22433             "should not introduce\r\n"
22434             "an extra carriage return\r\n"
22435             "*/\r\n",
22436             format("/*\r\n"
22437                    "multi line block comments\r\n"
22438                    "should not introduce\r\n"
22439                    "an extra carriage return\r\n"
22440                    "*/\r\n"));
22441   EXPECT_EQ("/*\r\n"
22442             "\r\n"
22443             "*/",
22444             format("/*\r\n"
22445                    "    \r\r\r\n"
22446                    "*/"));
22447 
22448   FormatStyle style = getLLVMStyle();
22449 
22450   style.DeriveLineEnding = true;
22451   style.UseCRLF = false;
22452   EXPECT_EQ("union FooBarBazQux {\n"
22453             "  int foo;\n"
22454             "  int bar;\n"
22455             "  int baz;\n"
22456             "};",
22457             format("union FooBarBazQux {\r\n"
22458                    "  int foo;\n"
22459                    "  int bar;\r\n"
22460                    "  int baz;\n"
22461                    "};",
22462                    style));
22463   style.UseCRLF = true;
22464   EXPECT_EQ("union FooBarBazQux {\r\n"
22465             "  int foo;\r\n"
22466             "  int bar;\r\n"
22467             "  int baz;\r\n"
22468             "};",
22469             format("union FooBarBazQux {\r\n"
22470                    "  int foo;\n"
22471                    "  int bar;\r\n"
22472                    "  int baz;\n"
22473                    "};",
22474                    style));
22475 
22476   style.DeriveLineEnding = false;
22477   style.UseCRLF = false;
22478   EXPECT_EQ("union FooBarBazQux {\n"
22479             "  int foo;\n"
22480             "  int bar;\n"
22481             "  int baz;\n"
22482             "  int qux;\n"
22483             "};",
22484             format("union FooBarBazQux {\r\n"
22485                    "  int foo;\n"
22486                    "  int bar;\r\n"
22487                    "  int baz;\n"
22488                    "  int qux;\r\n"
22489                    "};",
22490                    style));
22491   style.UseCRLF = true;
22492   EXPECT_EQ("union FooBarBazQux {\r\n"
22493             "  int foo;\r\n"
22494             "  int bar;\r\n"
22495             "  int baz;\r\n"
22496             "  int qux;\r\n"
22497             "};",
22498             format("union FooBarBazQux {\r\n"
22499                    "  int foo;\n"
22500                    "  int bar;\r\n"
22501                    "  int baz;\n"
22502                    "  int qux;\n"
22503                    "};",
22504                    style));
22505 
22506   style.DeriveLineEnding = true;
22507   style.UseCRLF = false;
22508   EXPECT_EQ("union FooBarBazQux {\r\n"
22509             "  int foo;\r\n"
22510             "  int bar;\r\n"
22511             "  int baz;\r\n"
22512             "  int qux;\r\n"
22513             "};",
22514             format("union FooBarBazQux {\r\n"
22515                    "  int foo;\n"
22516                    "  int bar;\r\n"
22517                    "  int baz;\n"
22518                    "  int qux;\r\n"
22519                    "};",
22520                    style));
22521   style.UseCRLF = true;
22522   EXPECT_EQ("union FooBarBazQux {\n"
22523             "  int foo;\n"
22524             "  int bar;\n"
22525             "  int baz;\n"
22526             "  int qux;\n"
22527             "};",
22528             format("union FooBarBazQux {\r\n"
22529                    "  int foo;\n"
22530                    "  int bar;\r\n"
22531                    "  int baz;\n"
22532                    "  int qux;\n"
22533                    "};",
22534                    style));
22535 }
22536 
22537 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
22538   verifyFormat("MY_CLASS(C) {\n"
22539                "  int i;\n"
22540                "  int j;\n"
22541                "};");
22542 }
22543 
22544 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
22545   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
22546   TwoIndent.ContinuationIndentWidth = 2;
22547 
22548   EXPECT_EQ("int i =\n"
22549             "  longFunction(\n"
22550             "    arg);",
22551             format("int i = longFunction(arg);", TwoIndent));
22552 
22553   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
22554   SixIndent.ContinuationIndentWidth = 6;
22555 
22556   EXPECT_EQ("int i =\n"
22557             "      longFunction(\n"
22558             "            arg);",
22559             format("int i = longFunction(arg);", SixIndent));
22560 }
22561 
22562 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
22563   FormatStyle Style = getLLVMStyle();
22564   verifyFormat("int Foo::getter(\n"
22565                "    //\n"
22566                ") const {\n"
22567                "  return foo;\n"
22568                "}",
22569                Style);
22570   verifyFormat("void Foo::setter(\n"
22571                "    //\n"
22572                ") {\n"
22573                "  foo = 1;\n"
22574                "}",
22575                Style);
22576 }
22577 
22578 TEST_F(FormatTest, SpacesInAngles) {
22579   FormatStyle Spaces = getLLVMStyle();
22580   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22581 
22582   verifyFormat("vector< ::std::string > x1;", Spaces);
22583   verifyFormat("Foo< int, Bar > x2;", Spaces);
22584   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
22585 
22586   verifyFormat("static_cast< int >(arg);", Spaces);
22587   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
22588   verifyFormat("f< int, float >();", Spaces);
22589   verifyFormat("template <> g() {}", Spaces);
22590   verifyFormat("template < std::vector< int > > f() {}", Spaces);
22591   verifyFormat("std::function< void(int, int) > fct;", Spaces);
22592   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
22593                Spaces);
22594 
22595   Spaces.Standard = FormatStyle::LS_Cpp03;
22596   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22597   verifyFormat("A< A< int > >();", Spaces);
22598 
22599   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22600   verifyFormat("A<A<int> >();", Spaces);
22601 
22602   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22603   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22604                Spaces);
22605   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22606                Spaces);
22607 
22608   verifyFormat("A<A<int> >();", Spaces);
22609   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22610   verifyFormat("A< A< int > >();", Spaces);
22611 
22612   Spaces.Standard = FormatStyle::LS_Cpp11;
22613   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22614   verifyFormat("A< A< int > >();", Spaces);
22615 
22616   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22617   verifyFormat("vector<::std::string> x4;", Spaces);
22618   verifyFormat("vector<int> x5;", Spaces);
22619   verifyFormat("Foo<int, Bar> x6;", Spaces);
22620   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22621 
22622   verifyFormat("A<A<int>>();", Spaces);
22623 
22624   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22625   verifyFormat("vector<::std::string> x4;", Spaces);
22626   verifyFormat("vector< ::std::string > x4;", Spaces);
22627   verifyFormat("vector<int> x5;", Spaces);
22628   verifyFormat("vector< int > x5;", Spaces);
22629   verifyFormat("Foo<int, Bar> x6;", Spaces);
22630   verifyFormat("Foo< int, Bar > x6;", Spaces);
22631   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22632   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22633 
22634   verifyFormat("A<A<int>>();", Spaces);
22635   verifyFormat("A< A< int > >();", Spaces);
22636   verifyFormat("A<A<int > >();", Spaces);
22637   verifyFormat("A< A< int>>();", Spaces);
22638 
22639   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22640   verifyFormat("// clang-format off\n"
22641                "foo<<<1, 1>>>();\n"
22642                "// clang-format on\n",
22643                Spaces);
22644   verifyFormat("// clang-format off\n"
22645                "foo< < <1, 1> > >();\n"
22646                "// clang-format on\n",
22647                Spaces);
22648 }
22649 
22650 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22651   FormatStyle Style = getLLVMStyle();
22652   Style.SpaceAfterTemplateKeyword = false;
22653   verifyFormat("template<int> void foo();", Style);
22654 }
22655 
22656 TEST_F(FormatTest, TripleAngleBrackets) {
22657   verifyFormat("f<<<1, 1>>>();");
22658   verifyFormat("f<<<1, 1, 1, s>>>();");
22659   verifyFormat("f<<<a, b, c, d>>>();");
22660   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22661   verifyFormat("f<param><<<1, 1>>>();");
22662   verifyFormat("f<1><<<1, 1>>>();");
22663   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22664   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22665                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22666   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22667                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22668 }
22669 
22670 TEST_F(FormatTest, MergeLessLessAtEnd) {
22671   verifyFormat("<<");
22672   EXPECT_EQ("< < <", format("\\\n<<<"));
22673   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22674                "aaallvm::outs() <<");
22675   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22676                "aaaallvm::outs()\n    <<");
22677 }
22678 
22679 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22680   std::string code = "#if A\n"
22681                      "#if B\n"
22682                      "a.\n"
22683                      "#endif\n"
22684                      "    a = 1;\n"
22685                      "#else\n"
22686                      "#endif\n"
22687                      "#if C\n"
22688                      "#else\n"
22689                      "#endif\n";
22690   EXPECT_EQ(code, format(code));
22691 }
22692 
22693 TEST_F(FormatTest, HandleConflictMarkers) {
22694   // Git/SVN conflict markers.
22695   EXPECT_EQ("int a;\n"
22696             "void f() {\n"
22697             "  callme(some(parameter1,\n"
22698             "<<<<<<< text by the vcs\n"
22699             "              parameter2),\n"
22700             "||||||| text by the vcs\n"
22701             "              parameter2),\n"
22702             "         parameter3,\n"
22703             "======= text by the vcs\n"
22704             "              parameter2, parameter3),\n"
22705             ">>>>>>> text by the vcs\n"
22706             "         otherparameter);\n",
22707             format("int a;\n"
22708                    "void f() {\n"
22709                    "  callme(some(parameter1,\n"
22710                    "<<<<<<< text by the vcs\n"
22711                    "  parameter2),\n"
22712                    "||||||| text by the vcs\n"
22713                    "  parameter2),\n"
22714                    "  parameter3,\n"
22715                    "======= text by the vcs\n"
22716                    "  parameter2,\n"
22717                    "  parameter3),\n"
22718                    ">>>>>>> text by the vcs\n"
22719                    "  otherparameter);\n"));
22720 
22721   // Perforce markers.
22722   EXPECT_EQ("void f() {\n"
22723             "  function(\n"
22724             ">>>> text by the vcs\n"
22725             "      parameter,\n"
22726             "==== text by the vcs\n"
22727             "      parameter,\n"
22728             "==== text by the vcs\n"
22729             "      parameter,\n"
22730             "<<<< text by the vcs\n"
22731             "      parameter);\n",
22732             format("void f() {\n"
22733                    "  function(\n"
22734                    ">>>> text by the vcs\n"
22735                    "  parameter,\n"
22736                    "==== text by the vcs\n"
22737                    "  parameter,\n"
22738                    "==== text by the vcs\n"
22739                    "  parameter,\n"
22740                    "<<<< text by the vcs\n"
22741                    "  parameter);\n"));
22742 
22743   EXPECT_EQ("<<<<<<<\n"
22744             "|||||||\n"
22745             "=======\n"
22746             ">>>>>>>",
22747             format("<<<<<<<\n"
22748                    "|||||||\n"
22749                    "=======\n"
22750                    ">>>>>>>"));
22751 
22752   EXPECT_EQ("<<<<<<<\n"
22753             "|||||||\n"
22754             "int i;\n"
22755             "=======\n"
22756             ">>>>>>>",
22757             format("<<<<<<<\n"
22758                    "|||||||\n"
22759                    "int i;\n"
22760                    "=======\n"
22761                    ">>>>>>>"));
22762 
22763   // FIXME: Handle parsing of macros around conflict markers correctly:
22764   EXPECT_EQ("#define Macro \\\n"
22765             "<<<<<<<\n"
22766             "Something \\\n"
22767             "|||||||\n"
22768             "Else \\\n"
22769             "=======\n"
22770             "Other \\\n"
22771             ">>>>>>>\n"
22772             "    End int i;\n",
22773             format("#define Macro \\\n"
22774                    "<<<<<<<\n"
22775                    "  Something \\\n"
22776                    "|||||||\n"
22777                    "  Else \\\n"
22778                    "=======\n"
22779                    "  Other \\\n"
22780                    ">>>>>>>\n"
22781                    "  End\n"
22782                    "int i;\n"));
22783 
22784   verifyFormat(R"(====
22785 #ifdef A
22786 a
22787 #else
22788 b
22789 #endif
22790 )");
22791 }
22792 
22793 TEST_F(FormatTest, DisableRegions) {
22794   EXPECT_EQ("int i;\n"
22795             "// clang-format off\n"
22796             "  int j;\n"
22797             "// clang-format on\n"
22798             "int k;",
22799             format(" int  i;\n"
22800                    "   // clang-format off\n"
22801                    "  int j;\n"
22802                    " // clang-format on\n"
22803                    "   int   k;"));
22804   EXPECT_EQ("int i;\n"
22805             "/* clang-format off */\n"
22806             "  int j;\n"
22807             "/* clang-format on */\n"
22808             "int k;",
22809             format(" int  i;\n"
22810                    "   /* clang-format off */\n"
22811                    "  int j;\n"
22812                    " /* clang-format on */\n"
22813                    "   int   k;"));
22814 
22815   // Don't reflow comments within disabled regions.
22816   EXPECT_EQ("// clang-format off\n"
22817             "// long long long long long long line\n"
22818             "/* clang-format on */\n"
22819             "/* long long long\n"
22820             " * long long long\n"
22821             " * line */\n"
22822             "int i;\n"
22823             "/* clang-format off */\n"
22824             "/* long long long long long long line */\n",
22825             format("// clang-format off\n"
22826                    "// long long long long long long line\n"
22827                    "/* clang-format on */\n"
22828                    "/* long long long long long long line */\n"
22829                    "int i;\n"
22830                    "/* clang-format off */\n"
22831                    "/* long long long long long long line */\n",
22832                    getLLVMStyleWithColumns(20)));
22833 }
22834 
22835 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22836   format("? ) =");
22837   verifyNoCrash("#define a\\\n /**/}");
22838 }
22839 
22840 TEST_F(FormatTest, FormatsTableGenCode) {
22841   FormatStyle Style = getLLVMStyle();
22842   Style.Language = FormatStyle::LK_TableGen;
22843   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22844 }
22845 
22846 TEST_F(FormatTest, ArrayOfTemplates) {
22847   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22848             format("auto a = new unique_ptr<int > [ 10];"));
22849 
22850   FormatStyle Spaces = getLLVMStyle();
22851   Spaces.SpacesInSquareBrackets = true;
22852   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22853             format("auto a = new unique_ptr<int > [10];", Spaces));
22854 }
22855 
22856 TEST_F(FormatTest, ArrayAsTemplateType) {
22857   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22858             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22859 
22860   FormatStyle Spaces = getLLVMStyle();
22861   Spaces.SpacesInSquareBrackets = true;
22862   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22863             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22864 }
22865 
22866 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22867 
22868 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22869   llvm::vfs::InMemoryFileSystem FS;
22870   auto Style1 = getStyle("file", "", "Google", "", &FS);
22871   ASSERT_TRUE((bool)Style1);
22872   ASSERT_EQ(*Style1, getGoogleStyle());
22873 }
22874 
22875 TEST(FormatStyle, GetStyleOfFile) {
22876   llvm::vfs::InMemoryFileSystem FS;
22877   // Test 1: format file in the same directory.
22878   ASSERT_TRUE(
22879       FS.addFile("/a/.clang-format", 0,
22880                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22881   ASSERT_TRUE(
22882       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22883   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22884   ASSERT_TRUE((bool)Style1);
22885   ASSERT_EQ(*Style1, getLLVMStyle());
22886 
22887   // Test 2.1: fallback to default.
22888   ASSERT_TRUE(
22889       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22890   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22891   ASSERT_TRUE((bool)Style2);
22892   ASSERT_EQ(*Style2, getMozillaStyle());
22893 
22894   // Test 2.2: no format on 'none' fallback style.
22895   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22896   ASSERT_TRUE((bool)Style2);
22897   ASSERT_EQ(*Style2, getNoStyle());
22898 
22899   // Test 2.3: format if config is found with no based style while fallback is
22900   // 'none'.
22901   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22902                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22903   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22904   ASSERT_TRUE((bool)Style2);
22905   ASSERT_EQ(*Style2, getLLVMStyle());
22906 
22907   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22908   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22909   ASSERT_TRUE((bool)Style2);
22910   ASSERT_EQ(*Style2, getLLVMStyle());
22911 
22912   // Test 3: format file in parent directory.
22913   ASSERT_TRUE(
22914       FS.addFile("/c/.clang-format", 0,
22915                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22916   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22917                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22918   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22919   ASSERT_TRUE((bool)Style3);
22920   ASSERT_EQ(*Style3, getGoogleStyle());
22921 
22922   // Test 4: error on invalid fallback style
22923   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22924   ASSERT_FALSE((bool)Style4);
22925   llvm::consumeError(Style4.takeError());
22926 
22927   // Test 5: error on invalid yaml on command line
22928   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22929   ASSERT_FALSE((bool)Style5);
22930   llvm::consumeError(Style5.takeError());
22931 
22932   // Test 6: error on invalid style
22933   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22934   ASSERT_FALSE((bool)Style6);
22935   llvm::consumeError(Style6.takeError());
22936 
22937   // Test 7: found config file, error on parsing it
22938   ASSERT_TRUE(
22939       FS.addFile("/d/.clang-format", 0,
22940                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22941                                                   "InvalidKey: InvalidValue")));
22942   ASSERT_TRUE(
22943       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22944   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22945   ASSERT_FALSE((bool)Style7a);
22946   llvm::consumeError(Style7a.takeError());
22947 
22948   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22949   ASSERT_TRUE((bool)Style7b);
22950 
22951   // Test 8: inferred per-language defaults apply.
22952   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22953   ASSERT_TRUE((bool)StyleTd);
22954   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22955 
22956   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22957   // fallback style.
22958   ASSERT_TRUE(FS.addFile(
22959       "/e/sub/.clang-format", 0,
22960       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22961                                        "ColumnLimit: 20")));
22962   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22963                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22964   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22965   ASSERT_TRUE(static_cast<bool>(Style9));
22966   ASSERT_EQ(*Style9, [] {
22967     auto Style = getNoStyle();
22968     Style.ColumnLimit = 20;
22969     return Style;
22970   }());
22971 
22972   // Test 9.1.2: propagate more than one level with no parent file.
22973   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22974                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22975   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22976                          llvm::MemoryBuffer::getMemBuffer(
22977                              "BasedOnStyle: InheritParentConfig\n"
22978                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22979   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22980 
22981   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22982   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22983   ASSERT_TRUE(static_cast<bool>(Style9));
22984   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22985     auto Style = getNoStyle();
22986     Style.ColumnLimit = 20;
22987     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22988     return Style;
22989   }());
22990 
22991   // Test 9.2: with LLVM fallback style
22992   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22993   ASSERT_TRUE(static_cast<bool>(Style9));
22994   ASSERT_EQ(*Style9, [] {
22995     auto Style = getLLVMStyle();
22996     Style.ColumnLimit = 20;
22997     return Style;
22998   }());
22999 
23000   // Test 9.3: with a parent file
23001   ASSERT_TRUE(
23002       FS.addFile("/e/.clang-format", 0,
23003                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
23004                                                   "UseTab: Always")));
23005   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
23006   ASSERT_TRUE(static_cast<bool>(Style9));
23007   ASSERT_EQ(*Style9, [] {
23008     auto Style = getGoogleStyle();
23009     Style.ColumnLimit = 20;
23010     Style.UseTab = FormatStyle::UT_Always;
23011     return Style;
23012   }());
23013 
23014   // Test 9.4: propagate more than one level with a parent file.
23015   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
23016     auto Style = getGoogleStyle();
23017     Style.ColumnLimit = 20;
23018     Style.UseTab = FormatStyle::UT_Always;
23019     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
23020     return Style;
23021   }();
23022 
23023   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
23024   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
23025   ASSERT_TRUE(static_cast<bool>(Style9));
23026   ASSERT_EQ(*Style9, SubSubStyle);
23027 
23028   // Test 9.5: use InheritParentConfig as style name
23029   Style9 =
23030       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
23031   ASSERT_TRUE(static_cast<bool>(Style9));
23032   ASSERT_EQ(*Style9, SubSubStyle);
23033 
23034   // Test 9.6: use command line style with inheritance
23035   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
23036                     "none", "", &FS);
23037   ASSERT_TRUE(static_cast<bool>(Style9));
23038   ASSERT_EQ(*Style9, SubSubStyle);
23039 
23040   // Test 9.7: use command line style with inheritance and own config
23041   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
23042                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
23043                     "/e/sub/code.cpp", "none", "", &FS);
23044   ASSERT_TRUE(static_cast<bool>(Style9));
23045   ASSERT_EQ(*Style9, SubSubStyle);
23046 
23047   // Test 9.8: use inheritance from a file without BasedOnStyle
23048   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
23049                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
23050   ASSERT_TRUE(
23051       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
23052                  llvm::MemoryBuffer::getMemBuffer(
23053                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
23054   // Make sure we do not use the fallback style
23055   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
23056   ASSERT_TRUE(static_cast<bool>(Style9));
23057   ASSERT_EQ(*Style9, [] {
23058     auto Style = getLLVMStyle();
23059     Style.ColumnLimit = 123;
23060     return Style;
23061   }());
23062 
23063   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
23064   ASSERT_TRUE(static_cast<bool>(Style9));
23065   ASSERT_EQ(*Style9, [] {
23066     auto Style = getLLVMStyle();
23067     Style.ColumnLimit = 123;
23068     Style.IndentWidth = 7;
23069     return Style;
23070   }());
23071 
23072   // Test 9.9: use inheritance from a specific config file.
23073   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
23074                     "none", "", &FS);
23075   ASSERT_TRUE(static_cast<bool>(Style9));
23076   ASSERT_EQ(*Style9, SubSubStyle);
23077 }
23078 
23079 TEST(FormatStyle, GetStyleOfSpecificFile) {
23080   llvm::vfs::InMemoryFileSystem FS;
23081   // Specify absolute path to a format file in a parent directory.
23082   ASSERT_TRUE(
23083       FS.addFile("/e/.clang-format", 0,
23084                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
23085   ASSERT_TRUE(
23086       FS.addFile("/e/explicit.clang-format", 0,
23087                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
23088   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
23089                          llvm::MemoryBuffer::getMemBuffer("int i;")));
23090   auto Style = getStyle("file:/e/explicit.clang-format",
23091                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
23092   ASSERT_TRUE(static_cast<bool>(Style));
23093   ASSERT_EQ(*Style, getGoogleStyle());
23094 
23095   // Specify relative path to a format file.
23096   ASSERT_TRUE(
23097       FS.addFile("../../e/explicit.clang-format", 0,
23098                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
23099   Style = getStyle("file:../../e/explicit.clang-format",
23100                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
23101   ASSERT_TRUE(static_cast<bool>(Style));
23102   ASSERT_EQ(*Style, getGoogleStyle());
23103 
23104   // Specify path to a format file that does not exist.
23105   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
23106                    "LLVM", "", &FS);
23107   ASSERT_FALSE(static_cast<bool>(Style));
23108   llvm::consumeError(Style.takeError());
23109 
23110   // Specify path to a file on the filesystem.
23111   SmallString<128> FormatFilePath;
23112   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
23113       "FormatFileTest", "tpl", FormatFilePath);
23114   EXPECT_FALSE((bool)ECF);
23115   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
23116   EXPECT_FALSE((bool)ECF);
23117   FormatFileTest << "BasedOnStyle: Google\n";
23118   FormatFileTest.close();
23119 
23120   SmallString<128> TestFilePath;
23121   std::error_code ECT =
23122       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
23123   EXPECT_FALSE((bool)ECT);
23124   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
23125   CodeFileTest << "int i;\n";
23126   CodeFileTest.close();
23127 
23128   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
23129   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
23130 
23131   llvm::sys::fs::remove(FormatFilePath.c_str());
23132   llvm::sys::fs::remove(TestFilePath.c_str());
23133   ASSERT_TRUE(static_cast<bool>(Style));
23134   ASSERT_EQ(*Style, getGoogleStyle());
23135 }
23136 
23137 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
23138   // Column limit is 20.
23139   std::string Code = "Type *a =\n"
23140                      "    new Type();\n"
23141                      "g(iiiii, 0, jjjjj,\n"
23142                      "  0, kkkkk, 0, mm);\n"
23143                      "int  bad     = format   ;";
23144   std::string Expected = "auto a = new Type();\n"
23145                          "g(iiiii, nullptr,\n"
23146                          "  jjjjj, nullptr,\n"
23147                          "  kkkkk, nullptr,\n"
23148                          "  mm);\n"
23149                          "int  bad     = format   ;";
23150   FileID ID = Context.createInMemoryFile("format.cpp", Code);
23151   tooling::Replacements Replaces = toReplacements(
23152       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
23153                             "auto "),
23154        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
23155                             "nullptr"),
23156        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
23157                             "nullptr"),
23158        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
23159                             "nullptr")});
23160 
23161   FormatStyle Style = getLLVMStyle();
23162   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
23163   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
23164   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
23165       << llvm::toString(FormattedReplaces.takeError()) << "\n";
23166   auto Result = applyAllReplacements(Code, *FormattedReplaces);
23167   EXPECT_TRUE(static_cast<bool>(Result));
23168   EXPECT_EQ(Expected, *Result);
23169 }
23170 
23171 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
23172   std::string Code = "#include \"a.h\"\n"
23173                      "#include \"c.h\"\n"
23174                      "\n"
23175                      "int main() {\n"
23176                      "  return 0;\n"
23177                      "}";
23178   std::string Expected = "#include \"a.h\"\n"
23179                          "#include \"b.h\"\n"
23180                          "#include \"c.h\"\n"
23181                          "\n"
23182                          "int main() {\n"
23183                          "  return 0;\n"
23184                          "}";
23185   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
23186   tooling::Replacements Replaces = toReplacements(
23187       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
23188                             "#include \"b.h\"\n")});
23189 
23190   FormatStyle Style = getLLVMStyle();
23191   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
23192   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
23193   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
23194       << llvm::toString(FormattedReplaces.takeError()) << "\n";
23195   auto Result = applyAllReplacements(Code, *FormattedReplaces);
23196   EXPECT_TRUE(static_cast<bool>(Result));
23197   EXPECT_EQ(Expected, *Result);
23198 }
23199 
23200 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
23201   EXPECT_EQ("using std::cin;\n"
23202             "using std::cout;",
23203             format("using std::cout;\n"
23204                    "using std::cin;",
23205                    getGoogleStyle()));
23206 }
23207 
23208 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
23209   FormatStyle Style = getLLVMStyle();
23210   Style.Standard = FormatStyle::LS_Cpp03;
23211   // cpp03 recognize this string as identifier u8 and literal character 'a'
23212   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
23213 }
23214 
23215 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
23216   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
23217   // all modes, including C++11, C++14 and C++17
23218   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
23219 }
23220 
23221 TEST_F(FormatTest, DoNotFormatLikelyXml) {
23222   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
23223   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
23224 }
23225 
23226 TEST_F(FormatTest, StructuredBindings) {
23227   // Structured bindings is a C++17 feature.
23228   // all modes, including C++11, C++14 and C++17
23229   verifyFormat("auto [a, b] = f();");
23230   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
23231   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
23232   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
23233   EXPECT_EQ("auto const volatile [a, b] = f();",
23234             format("auto  const   volatile[a, b] = f();"));
23235   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
23236   EXPECT_EQ("auto &[a, b, c] = f();",
23237             format("auto   &[  a  ,  b,c   ] = f();"));
23238   EXPECT_EQ("auto &&[a, b, c] = f();",
23239             format("auto   &&[  a  ,  b,c   ] = f();"));
23240   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
23241   EXPECT_EQ("auto const volatile &&[a, b] = f();",
23242             format("auto  const  volatile  &&[a, b] = f();"));
23243   EXPECT_EQ("auto const &&[a, b] = f();",
23244             format("auto  const   &&  [a, b] = f();"));
23245   EXPECT_EQ("const auto &[a, b] = f();",
23246             format("const  auto  &  [a, b] = f();"));
23247   EXPECT_EQ("const auto volatile &&[a, b] = f();",
23248             format("const  auto   volatile  &&[a, b] = f();"));
23249   EXPECT_EQ("volatile const auto &&[a, b] = f();",
23250             format("volatile  const  auto   &&[a, b] = f();"));
23251   EXPECT_EQ("const auto &&[a, b] = f();",
23252             format("const  auto  &&  [a, b] = f();"));
23253 
23254   // Make sure we don't mistake structured bindings for lambdas.
23255   FormatStyle PointerMiddle = getLLVMStyle();
23256   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
23257   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
23258   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
23259   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
23260   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
23261   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
23262   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
23263   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
23264   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
23265   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
23266   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
23267   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
23268   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
23269 
23270   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
23271             format("for (const auto   &&   [a, b] : some_range) {\n}"));
23272   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
23273             format("for (const auto   &   [a, b] : some_range) {\n}"));
23274   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
23275             format("for (const auto[a, b] : some_range) {\n}"));
23276   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
23277   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
23278   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
23279   EXPECT_EQ("auto const &[x, y](expr);",
23280             format("auto  const  &  [x,y]  (expr);"));
23281   EXPECT_EQ("auto const &&[x, y](expr);",
23282             format("auto  const  &&  [x,y]  (expr);"));
23283   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
23284   EXPECT_EQ("auto const &[x, y]{expr};",
23285             format("auto  const  &  [x,y]  {expr};"));
23286   EXPECT_EQ("auto const &&[x, y]{expr};",
23287             format("auto  const  &&  [x,y]  {expr};"));
23288 
23289   FormatStyle Spaces = getLLVMStyle();
23290   Spaces.SpacesInSquareBrackets = true;
23291   verifyFormat("auto [ a, b ] = f();", Spaces);
23292   verifyFormat("auto &&[ a, b ] = f();", Spaces);
23293   verifyFormat("auto &[ a, b ] = f();", Spaces);
23294   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
23295   verifyFormat("auto const &[ a, b ] = f();", Spaces);
23296 }
23297 
23298 TEST_F(FormatTest, FileAndCode) {
23299   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
23300   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
23301   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
23302   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
23303   EXPECT_EQ(FormatStyle::LK_ObjC,
23304             guessLanguage("foo.h", "@interface Foo\n@end\n"));
23305   EXPECT_EQ(
23306       FormatStyle::LK_ObjC,
23307       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
23308   EXPECT_EQ(FormatStyle::LK_ObjC,
23309             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
23310   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
23311   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
23312   EXPECT_EQ(FormatStyle::LK_ObjC,
23313             guessLanguage("foo", "@interface Foo\n@end\n"));
23314   EXPECT_EQ(FormatStyle::LK_ObjC,
23315             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
23316   EXPECT_EQ(
23317       FormatStyle::LK_ObjC,
23318       guessLanguage("foo.h",
23319                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
23320   EXPECT_EQ(
23321       FormatStyle::LK_Cpp,
23322       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
23323   // Only one of the two preprocessor regions has ObjC-like code.
23324   EXPECT_EQ(FormatStyle::LK_ObjC,
23325             guessLanguage("foo.h", "#if A\n"
23326                                    "#define B() C\n"
23327                                    "#else\n"
23328                                    "#define B() [NSString a:@\"\"]\n"
23329                                    "#endif\n"));
23330 }
23331 
23332 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
23333   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
23334   EXPECT_EQ(FormatStyle::LK_ObjC,
23335             guessLanguage("foo.h", "array[[calculator getIndex]];"));
23336   EXPECT_EQ(FormatStyle::LK_Cpp,
23337             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
23338   EXPECT_EQ(
23339       FormatStyle::LK_Cpp,
23340       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
23341   EXPECT_EQ(FormatStyle::LK_ObjC,
23342             guessLanguage("foo.h", "[[noreturn foo] bar];"));
23343   EXPECT_EQ(FormatStyle::LK_Cpp,
23344             guessLanguage("foo.h", "[[clang::fallthrough]];"));
23345   EXPECT_EQ(FormatStyle::LK_ObjC,
23346             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
23347   EXPECT_EQ(FormatStyle::LK_Cpp,
23348             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
23349   EXPECT_EQ(FormatStyle::LK_Cpp,
23350             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
23351   EXPECT_EQ(FormatStyle::LK_ObjC,
23352             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
23353   EXPECT_EQ(FormatStyle::LK_Cpp,
23354             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
23355   EXPECT_EQ(
23356       FormatStyle::LK_Cpp,
23357       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
23358   EXPECT_EQ(
23359       FormatStyle::LK_Cpp,
23360       guessLanguage("foo.h",
23361                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
23362   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
23363 }
23364 
23365 TEST_F(FormatTest, GuessLanguageWithCaret) {
23366   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
23367   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
23368   EXPECT_EQ(FormatStyle::LK_ObjC,
23369             guessLanguage("foo.h", "int(^)(char, float);"));
23370   EXPECT_EQ(FormatStyle::LK_ObjC,
23371             guessLanguage("foo.h", "int(^foo)(char, float);"));
23372   EXPECT_EQ(FormatStyle::LK_ObjC,
23373             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
23374   EXPECT_EQ(FormatStyle::LK_ObjC,
23375             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
23376   EXPECT_EQ(
23377       FormatStyle::LK_ObjC,
23378       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
23379 }
23380 
23381 TEST_F(FormatTest, GuessLanguageWithPragmas) {
23382   EXPECT_EQ(FormatStyle::LK_Cpp,
23383             guessLanguage("foo.h", "__pragma(warning(disable:))"));
23384   EXPECT_EQ(FormatStyle::LK_Cpp,
23385             guessLanguage("foo.h", "#pragma(warning(disable:))"));
23386   EXPECT_EQ(FormatStyle::LK_Cpp,
23387             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
23388 }
23389 
23390 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
23391   // ASM symbolic names are identifiers that must be surrounded by [] without
23392   // space in between:
23393   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
23394 
23395   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
23396   verifyFormat(R"(//
23397 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
23398 )");
23399 
23400   // A list of several ASM symbolic names.
23401   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
23402 
23403   // ASM symbolic names in inline ASM with inputs and outputs.
23404   verifyFormat(R"(//
23405 asm("cmoveq %1, %2, %[result]"
23406     : [result] "=r"(result)
23407     : "r"(test), "r"(new), "[result]"(old));
23408 )");
23409 
23410   // ASM symbolic names in inline ASM with no outputs.
23411   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
23412 }
23413 
23414 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
23415   EXPECT_EQ(FormatStyle::LK_Cpp,
23416             guessLanguage("foo.h", "void f() {\n"
23417                                    "  asm (\"mov %[e], %[d]\"\n"
23418                                    "     : [d] \"=rm\" (d)\n"
23419                                    "       [e] \"rm\" (*e));\n"
23420                                    "}"));
23421   EXPECT_EQ(FormatStyle::LK_Cpp,
23422             guessLanguage("foo.h", "void f() {\n"
23423                                    "  _asm (\"mov %[e], %[d]\"\n"
23424                                    "     : [d] \"=rm\" (d)\n"
23425                                    "       [e] \"rm\" (*e));\n"
23426                                    "}"));
23427   EXPECT_EQ(FormatStyle::LK_Cpp,
23428             guessLanguage("foo.h", "void f() {\n"
23429                                    "  __asm (\"mov %[e], %[d]\"\n"
23430                                    "     : [d] \"=rm\" (d)\n"
23431                                    "       [e] \"rm\" (*e));\n"
23432                                    "}"));
23433   EXPECT_EQ(FormatStyle::LK_Cpp,
23434             guessLanguage("foo.h", "void f() {\n"
23435                                    "  __asm__ (\"mov %[e], %[d]\"\n"
23436                                    "     : [d] \"=rm\" (d)\n"
23437                                    "       [e] \"rm\" (*e));\n"
23438                                    "}"));
23439   EXPECT_EQ(FormatStyle::LK_Cpp,
23440             guessLanguage("foo.h", "void f() {\n"
23441                                    "  asm (\"mov %[e], %[d]\"\n"
23442                                    "     : [d] \"=rm\" (d),\n"
23443                                    "       [e] \"rm\" (*e));\n"
23444                                    "}"));
23445   EXPECT_EQ(FormatStyle::LK_Cpp,
23446             guessLanguage("foo.h", "void f() {\n"
23447                                    "  asm volatile (\"mov %[e], %[d]\"\n"
23448                                    "     : [d] \"=rm\" (d)\n"
23449                                    "       [e] \"rm\" (*e));\n"
23450                                    "}"));
23451 }
23452 
23453 TEST_F(FormatTest, GuessLanguageWithChildLines) {
23454   EXPECT_EQ(FormatStyle::LK_Cpp,
23455             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
23456   EXPECT_EQ(FormatStyle::LK_ObjC,
23457             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
23458   EXPECT_EQ(
23459       FormatStyle::LK_Cpp,
23460       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
23461   EXPECT_EQ(
23462       FormatStyle::LK_ObjC,
23463       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
23464 }
23465 
23466 TEST_F(FormatTest, TypenameMacros) {
23467   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
23468 
23469   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
23470   FormatStyle Google = getGoogleStyleWithColumns(0);
23471   Google.TypenameMacros = TypenameMacros;
23472   verifyFormat("struct foo {\n"
23473                "  int bar;\n"
23474                "  TAILQ_ENTRY(a) bleh;\n"
23475                "};",
23476                Google);
23477 
23478   FormatStyle Macros = getLLVMStyle();
23479   Macros.TypenameMacros = TypenameMacros;
23480 
23481   verifyFormat("STACK_OF(int) a;", Macros);
23482   verifyFormat("STACK_OF(int) *a;", Macros);
23483   verifyFormat("STACK_OF(int const *) *a;", Macros);
23484   verifyFormat("STACK_OF(int *const) *a;", Macros);
23485   verifyFormat("STACK_OF(int, string) a;", Macros);
23486   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
23487   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
23488   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
23489   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
23490   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
23491   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
23492 
23493   Macros.PointerAlignment = FormatStyle::PAS_Left;
23494   verifyFormat("STACK_OF(int)* a;", Macros);
23495   verifyFormat("STACK_OF(int*)* a;", Macros);
23496   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
23497   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
23498   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
23499 }
23500 
23501 TEST_F(FormatTest, AtomicQualifier) {
23502   // Check that we treate _Atomic as a type and not a function call
23503   FormatStyle Google = getGoogleStyleWithColumns(0);
23504   verifyFormat("struct foo {\n"
23505                "  int a1;\n"
23506                "  _Atomic(a) a2;\n"
23507                "  _Atomic(_Atomic(int) *const) a3;\n"
23508                "};",
23509                Google);
23510   verifyFormat("_Atomic(uint64_t) a;");
23511   verifyFormat("_Atomic(uint64_t) *a;");
23512   verifyFormat("_Atomic(uint64_t const *) *a;");
23513   verifyFormat("_Atomic(uint64_t *const) *a;");
23514   verifyFormat("_Atomic(const uint64_t *) *a;");
23515   verifyFormat("_Atomic(uint64_t) a;");
23516   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
23517   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
23518   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
23519   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
23520 
23521   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
23522   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
23523   FormatStyle Style = getLLVMStyle();
23524   Style.PointerAlignment = FormatStyle::PAS_Left;
23525   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
23526   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
23527   verifyFormat("_Atomic(int)* a;", Style);
23528   verifyFormat("_Atomic(int*)* a;", Style);
23529   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
23530 
23531   Style.SpacesInCStyleCastParentheses = true;
23532   Style.SpacesInParentheses = false;
23533   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
23534   Style.SpacesInCStyleCastParentheses = false;
23535   Style.SpacesInParentheses = true;
23536   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
23537   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
23538 }
23539 
23540 TEST_F(FormatTest, AmbersandInLamda) {
23541   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
23542   FormatStyle AlignStyle = getLLVMStyle();
23543   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
23544   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23545   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
23546   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23547 }
23548 
23549 TEST_F(FormatTest, SpacesInConditionalStatement) {
23550   FormatStyle Spaces = getLLVMStyle();
23551   Spaces.IfMacros.clear();
23552   Spaces.IfMacros.push_back("MYIF");
23553   Spaces.SpacesInConditionalStatement = true;
23554   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
23555   verifyFormat("if ( !a )\n  return;", Spaces);
23556   verifyFormat("if ( a )\n  return;", Spaces);
23557   verifyFormat("if constexpr ( a )\n  return;", Spaces);
23558   verifyFormat("MYIF ( a )\n  return;", Spaces);
23559   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
23560   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
23561   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
23562   verifyFormat("while ( a )\n  return;", Spaces);
23563   verifyFormat("while ( (a && b) )\n  return;", Spaces);
23564   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
23565   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
23566   // Check that space on the left of "::" is inserted as expected at beginning
23567   // of condition.
23568   verifyFormat("while ( ::func() )\n  return;", Spaces);
23569 
23570   // Check impact of ControlStatementsExceptControlMacros is honored.
23571   Spaces.SpaceBeforeParens =
23572       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
23573   verifyFormat("MYIF( a )\n  return;", Spaces);
23574   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
23575   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
23576 }
23577 
23578 TEST_F(FormatTest, AlternativeOperators) {
23579   // Test case for ensuring alternate operators are not
23580   // combined with their right most neighbour.
23581   verifyFormat("int a and b;");
23582   verifyFormat("int a and_eq b;");
23583   verifyFormat("int a bitand b;");
23584   verifyFormat("int a bitor b;");
23585   verifyFormat("int a compl b;");
23586   verifyFormat("int a not b;");
23587   verifyFormat("int a not_eq b;");
23588   verifyFormat("int a or b;");
23589   verifyFormat("int a xor b;");
23590   verifyFormat("int a xor_eq b;");
23591   verifyFormat("return this not_eq bitand other;");
23592   verifyFormat("bool operator not_eq(const X bitand other)");
23593 
23594   verifyFormat("int a and 5;");
23595   verifyFormat("int a and_eq 5;");
23596   verifyFormat("int a bitand 5;");
23597   verifyFormat("int a bitor 5;");
23598   verifyFormat("int a compl 5;");
23599   verifyFormat("int a not 5;");
23600   verifyFormat("int a not_eq 5;");
23601   verifyFormat("int a or 5;");
23602   verifyFormat("int a xor 5;");
23603   verifyFormat("int a xor_eq 5;");
23604 
23605   verifyFormat("int a compl(5);");
23606   verifyFormat("int a not(5);");
23607 
23608   /* FIXME handle alternate tokens
23609    * https://en.cppreference.com/w/cpp/language/operator_alternative
23610   // alternative tokens
23611   verifyFormat("compl foo();");     //  ~foo();
23612   verifyFormat("foo() <%%>;");      // foo();
23613   verifyFormat("void foo() <%%>;"); // void foo(){}
23614   verifyFormat("int a <:1:>;");     // int a[1];[
23615   verifyFormat("%:define ABC abc"); // #define ABC abc
23616   verifyFormat("%:%:");             // ##
23617   */
23618 }
23619 
23620 TEST_F(FormatTest, STLWhileNotDefineChed) {
23621   verifyFormat("#if defined(while)\n"
23622                "#define while EMIT WARNING C4005\n"
23623                "#endif // while");
23624 }
23625 
23626 TEST_F(FormatTest, OperatorSpacing) {
23627   FormatStyle Style = getLLVMStyle();
23628   Style.PointerAlignment = FormatStyle::PAS_Right;
23629   verifyFormat("Foo::operator*();", Style);
23630   verifyFormat("Foo::operator void *();", Style);
23631   verifyFormat("Foo::operator void **();", Style);
23632   verifyFormat("Foo::operator void *&();", Style);
23633   verifyFormat("Foo::operator void *&&();", Style);
23634   verifyFormat("Foo::operator void const *();", Style);
23635   verifyFormat("Foo::operator void const **();", Style);
23636   verifyFormat("Foo::operator void const *&();", Style);
23637   verifyFormat("Foo::operator void const *&&();", Style);
23638   verifyFormat("Foo::operator()(void *);", Style);
23639   verifyFormat("Foo::operator*(void *);", Style);
23640   verifyFormat("Foo::operator*();", Style);
23641   verifyFormat("Foo::operator**();", Style);
23642   verifyFormat("Foo::operator&();", Style);
23643   verifyFormat("Foo::operator<int> *();", Style);
23644   verifyFormat("Foo::operator<Foo> *();", Style);
23645   verifyFormat("Foo::operator<int> **();", Style);
23646   verifyFormat("Foo::operator<Foo> **();", Style);
23647   verifyFormat("Foo::operator<int> &();", Style);
23648   verifyFormat("Foo::operator<Foo> &();", Style);
23649   verifyFormat("Foo::operator<int> &&();", Style);
23650   verifyFormat("Foo::operator<Foo> &&();", Style);
23651   verifyFormat("Foo::operator<int> *&();", Style);
23652   verifyFormat("Foo::operator<Foo> *&();", Style);
23653   verifyFormat("Foo::operator<int> *&&();", Style);
23654   verifyFormat("Foo::operator<Foo> *&&();", Style);
23655   verifyFormat("operator*(int (*)(), class Foo);", Style);
23656 
23657   verifyFormat("Foo::operator&();", Style);
23658   verifyFormat("Foo::operator void &();", Style);
23659   verifyFormat("Foo::operator void const &();", Style);
23660   verifyFormat("Foo::operator()(void &);", Style);
23661   verifyFormat("Foo::operator&(void &);", Style);
23662   verifyFormat("Foo::operator&();", Style);
23663   verifyFormat("operator&(int (&)(), class Foo);", Style);
23664   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23665 
23666   verifyFormat("Foo::operator&&();", Style);
23667   verifyFormat("Foo::operator**();", Style);
23668   verifyFormat("Foo::operator void &&();", Style);
23669   verifyFormat("Foo::operator void const &&();", Style);
23670   verifyFormat("Foo::operator()(void &&);", Style);
23671   verifyFormat("Foo::operator&&(void &&);", Style);
23672   verifyFormat("Foo::operator&&();", Style);
23673   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23674   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23675   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23676                Style);
23677   verifyFormat("operator void **()", Style);
23678   verifyFormat("operator const FooRight<Object> &()", Style);
23679   verifyFormat("operator const FooRight<Object> *()", Style);
23680   verifyFormat("operator const FooRight<Object> **()", Style);
23681   verifyFormat("operator const FooRight<Object> *&()", Style);
23682   verifyFormat("operator const FooRight<Object> *&&()", Style);
23683 
23684   Style.PointerAlignment = FormatStyle::PAS_Left;
23685   verifyFormat("Foo::operator*();", Style);
23686   verifyFormat("Foo::operator**();", Style);
23687   verifyFormat("Foo::operator void*();", Style);
23688   verifyFormat("Foo::operator void**();", Style);
23689   verifyFormat("Foo::operator void*&();", Style);
23690   verifyFormat("Foo::operator void*&&();", Style);
23691   verifyFormat("Foo::operator void const*();", Style);
23692   verifyFormat("Foo::operator void const**();", Style);
23693   verifyFormat("Foo::operator void const*&();", Style);
23694   verifyFormat("Foo::operator void const*&&();", Style);
23695   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23696   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23697   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23698   verifyFormat("Foo::operator()(void*);", Style);
23699   verifyFormat("Foo::operator*(void*);", Style);
23700   verifyFormat("Foo::operator*();", Style);
23701   verifyFormat("Foo::operator<int>*();", Style);
23702   verifyFormat("Foo::operator<Foo>*();", Style);
23703   verifyFormat("Foo::operator<int>**();", Style);
23704   verifyFormat("Foo::operator<Foo>**();", Style);
23705   verifyFormat("Foo::operator<Foo>*&();", Style);
23706   verifyFormat("Foo::operator<int>&();", Style);
23707   verifyFormat("Foo::operator<Foo>&();", Style);
23708   verifyFormat("Foo::operator<int>&&();", Style);
23709   verifyFormat("Foo::operator<Foo>&&();", Style);
23710   verifyFormat("Foo::operator<int>*&();", Style);
23711   verifyFormat("Foo::operator<Foo>*&();", Style);
23712   verifyFormat("operator*(int (*)(), class Foo);", Style);
23713 
23714   verifyFormat("Foo::operator&();", Style);
23715   verifyFormat("Foo::operator void&();", Style);
23716   verifyFormat("Foo::operator void const&();", Style);
23717   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23718   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23719   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
23720   verifyFormat("Foo::operator()(void&);", Style);
23721   verifyFormat("Foo::operator&(void&);", Style);
23722   verifyFormat("Foo::operator&();", Style);
23723   verifyFormat("operator&(int (&)(), class Foo);", Style);
23724   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23725   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23726 
23727   verifyFormat("Foo::operator&&();", Style);
23728   verifyFormat("Foo::operator void&&();", Style);
23729   verifyFormat("Foo::operator void const&&();", Style);
23730   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23731   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23732   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23733   verifyFormat("Foo::operator()(void&&);", Style);
23734   verifyFormat("Foo::operator&&(void&&);", Style);
23735   verifyFormat("Foo::operator&&();", Style);
23736   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23737   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23738   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23739                Style);
23740   verifyFormat("operator void**()", Style);
23741   verifyFormat("operator const FooLeft<Object>&()", Style);
23742   verifyFormat("operator const FooLeft<Object>*()", Style);
23743   verifyFormat("operator const FooLeft<Object>**()", Style);
23744   verifyFormat("operator const FooLeft<Object>*&()", Style);
23745   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23746 
23747   // PR45107
23748   verifyFormat("operator Vector<String>&();", Style);
23749   verifyFormat("operator const Vector<String>&();", Style);
23750   verifyFormat("operator foo::Bar*();", Style);
23751   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23752   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23753                Style);
23754 
23755   Style.PointerAlignment = FormatStyle::PAS_Middle;
23756   verifyFormat("Foo::operator*();", Style);
23757   verifyFormat("Foo::operator void *();", Style);
23758   verifyFormat("Foo::operator()(void *);", Style);
23759   verifyFormat("Foo::operator*(void *);", Style);
23760   verifyFormat("Foo::operator*();", Style);
23761   verifyFormat("operator*(int (*)(), class Foo);", Style);
23762 
23763   verifyFormat("Foo::operator&();", Style);
23764   verifyFormat("Foo::operator void &();", Style);
23765   verifyFormat("Foo::operator void const &();", Style);
23766   verifyFormat("Foo::operator()(void &);", Style);
23767   verifyFormat("Foo::operator&(void &);", Style);
23768   verifyFormat("Foo::operator&();", Style);
23769   verifyFormat("operator&(int (&)(), class Foo);", Style);
23770 
23771   verifyFormat("Foo::operator&&();", Style);
23772   verifyFormat("Foo::operator void &&();", Style);
23773   verifyFormat("Foo::operator void const &&();", Style);
23774   verifyFormat("Foo::operator()(void &&);", Style);
23775   verifyFormat("Foo::operator&&(void &&);", Style);
23776   verifyFormat("Foo::operator&&();", Style);
23777   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23778 }
23779 
23780 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23781   FormatStyle Style = getLLVMStyle();
23782   // PR46157
23783   verifyFormat("foo(operator+, -42);", Style);
23784   verifyFormat("foo(operator++, -42);", Style);
23785   verifyFormat("foo(operator--, -42);", Style);
23786   verifyFormat("foo(-42, operator--);", Style);
23787   verifyFormat("foo(-42, operator, );", Style);
23788   verifyFormat("foo(operator, , -42);", Style);
23789 }
23790 
23791 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23792   FormatStyle Style = getLLVMStyle();
23793   Style.WhitespaceSensitiveMacros.push_back("FOO");
23794 
23795   // Don't use the helpers here, since 'mess up' will change the whitespace
23796   // and these are all whitespace sensitive by definition
23797   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23798             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23799   EXPECT_EQ(
23800       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23801       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23802   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23803             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23804   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23805             "       Still=Intentional);",
23806             format("FOO(String-ized&Messy+But,: :\n"
23807                    "       Still=Intentional);",
23808                    Style));
23809   Style.AlignConsecutiveAssignments.Enabled = true;
23810   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
23811             "       Still=Intentional);",
23812             format("FOO(String-ized=&Messy+But,: :\n"
23813                    "       Still=Intentional);",
23814                    Style));
23815 
23816   Style.ColumnLimit = 21;
23817   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23818             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23819 }
23820 
23821 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23822   // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
23823   // test its interaction with line wrapping
23824   FormatStyle Style = getLLVMStyleWithColumns(80);
23825   verifyFormat("namespace {\n"
23826                "int i;\n"
23827                "int j;\n"
23828                "} // namespace",
23829                Style);
23830 
23831   verifyFormat("namespace AAA {\n"
23832                "int i;\n"
23833                "int j;\n"
23834                "} // namespace AAA",
23835                Style);
23836 
23837   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23838             "int i;\n"
23839             "int j;\n"
23840             "} // namespace Averyveryveryverylongnamespace",
23841             format("namespace Averyveryveryverylongnamespace {\n"
23842                    "int i;\n"
23843                    "int j;\n"
23844                    "}",
23845                    Style));
23846 
23847   EXPECT_EQ(
23848       "namespace "
23849       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23850       "    went::mad::now {\n"
23851       "int i;\n"
23852       "int j;\n"
23853       "} // namespace\n"
23854       "  // "
23855       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23856       "went::mad::now",
23857       format("namespace "
23858              "would::it::save::you::a::lot::of::time::if_::i::"
23859              "just::gave::up::and_::went::mad::now {\n"
23860              "int i;\n"
23861              "int j;\n"
23862              "}",
23863              Style));
23864 
23865   // This used to duplicate the comment again and again on subsequent runs
23866   EXPECT_EQ(
23867       "namespace "
23868       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23869       "    went::mad::now {\n"
23870       "int i;\n"
23871       "int j;\n"
23872       "} // namespace\n"
23873       "  // "
23874       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23875       "went::mad::now",
23876       format("namespace "
23877              "would::it::save::you::a::lot::of::time::if_::i::"
23878              "just::gave::up::and_::went::mad::now {\n"
23879              "int i;\n"
23880              "int j;\n"
23881              "} // namespace\n"
23882              "  // "
23883              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23884              "and_::went::mad::now",
23885              Style));
23886 }
23887 
23888 TEST_F(FormatTest, LikelyUnlikely) {
23889   FormatStyle Style = getLLVMStyle();
23890 
23891   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23892                "  return 29;\n"
23893                "}",
23894                Style);
23895 
23896   verifyFormat("if (argc > 5) [[likely]] {\n"
23897                "  return 29;\n"
23898                "}",
23899                Style);
23900 
23901   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23902                "  return 29;\n"
23903                "} else [[likely]] {\n"
23904                "  return 42;\n"
23905                "}\n",
23906                Style);
23907 
23908   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23909                "  return 29;\n"
23910                "} else if (argc > 10) [[likely]] {\n"
23911                "  return 99;\n"
23912                "} else {\n"
23913                "  return 42;\n"
23914                "}\n",
23915                Style);
23916 
23917   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23918                "  return 29;\n"
23919                "}",
23920                Style);
23921 
23922   verifyFormat("if (argc > 5) [[unlikely]]\n"
23923                "  return 29;\n",
23924                Style);
23925   verifyFormat("if (argc > 5) [[likely]]\n"
23926                "  return 29;\n",
23927                Style);
23928 
23929   verifyFormat("while (limit > 0) [[unlikely]] {\n"
23930                "  --limit;\n"
23931                "}",
23932                Style);
23933   verifyFormat("for (auto &limit : limits) [[likely]] {\n"
23934                "  --limit;\n"
23935                "}",
23936                Style);
23937 
23938   verifyFormat("for (auto &limit : limits) [[unlikely]]\n"
23939                "  --limit;",
23940                Style);
23941   verifyFormat("while (limit > 0) [[likely]]\n"
23942                "  --limit;",
23943                Style);
23944 
23945   Style.AttributeMacros.push_back("UNLIKELY");
23946   Style.AttributeMacros.push_back("LIKELY");
23947   verifyFormat("if (argc > 5) UNLIKELY\n"
23948                "  return 29;\n",
23949                Style);
23950 
23951   verifyFormat("if (argc > 5) UNLIKELY {\n"
23952                "  return 29;\n"
23953                "}",
23954                Style);
23955   verifyFormat("if (argc > 5) UNLIKELY {\n"
23956                "  return 29;\n"
23957                "} else [[likely]] {\n"
23958                "  return 42;\n"
23959                "}\n",
23960                Style);
23961   verifyFormat("if (argc > 5) UNLIKELY {\n"
23962                "  return 29;\n"
23963                "} else LIKELY {\n"
23964                "  return 42;\n"
23965                "}\n",
23966                Style);
23967   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23968                "  return 29;\n"
23969                "} else LIKELY {\n"
23970                "  return 42;\n"
23971                "}\n",
23972                Style);
23973 
23974   verifyFormat("for (auto &limit : limits) UNLIKELY {\n"
23975                "  --limit;\n"
23976                "}",
23977                Style);
23978   verifyFormat("while (limit > 0) LIKELY {\n"
23979                "  --limit;\n"
23980                "}",
23981                Style);
23982 
23983   verifyFormat("while (limit > 0) UNLIKELY\n"
23984                "  --limit;",
23985                Style);
23986   verifyFormat("for (auto &limit : limits) LIKELY\n"
23987                "  --limit;",
23988                Style);
23989 }
23990 
23991 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23992   verifyFormat("Constructor()\n"
23993                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23994                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
23995                "aaaaaaaaaaaaaaaaaat))");
23996   verifyFormat("Constructor()\n"
23997                "    : aaaaaaaaaaaaa(aaaaaa), "
23998                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
23999 
24000   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
24001   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
24002   verifyFormat("Constructor()\n"
24003                "    : aaaaaa(aaaaaa),\n"
24004                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
24005                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
24006                StyleWithWhitespacePenalty);
24007   verifyFormat("Constructor()\n"
24008                "    : aaaaaaaaaaaaa(aaaaaa), "
24009                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
24010                StyleWithWhitespacePenalty);
24011 }
24012 
24013 TEST_F(FormatTest, LLVMDefaultStyle) {
24014   FormatStyle Style = getLLVMStyle();
24015   verifyFormat("extern \"C\" {\n"
24016                "int foo();\n"
24017                "}",
24018                Style);
24019 }
24020 TEST_F(FormatTest, GNUDefaultStyle) {
24021   FormatStyle Style = getGNUStyle();
24022   verifyFormat("extern \"C\"\n"
24023                "{\n"
24024                "  int foo ();\n"
24025                "}",
24026                Style);
24027 }
24028 TEST_F(FormatTest, MozillaDefaultStyle) {
24029   FormatStyle Style = getMozillaStyle();
24030   verifyFormat("extern \"C\"\n"
24031                "{\n"
24032                "  int foo();\n"
24033                "}",
24034                Style);
24035 }
24036 TEST_F(FormatTest, GoogleDefaultStyle) {
24037   FormatStyle Style = getGoogleStyle();
24038   verifyFormat("extern \"C\" {\n"
24039                "int foo();\n"
24040                "}",
24041                Style);
24042 }
24043 TEST_F(FormatTest, ChromiumDefaultStyle) {
24044   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
24045   verifyFormat("extern \"C\" {\n"
24046                "int foo();\n"
24047                "}",
24048                Style);
24049 }
24050 TEST_F(FormatTest, MicrosoftDefaultStyle) {
24051   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
24052   verifyFormat("extern \"C\"\n"
24053                "{\n"
24054                "    int foo();\n"
24055                "}",
24056                Style);
24057 }
24058 TEST_F(FormatTest, WebKitDefaultStyle) {
24059   FormatStyle Style = getWebKitStyle();
24060   verifyFormat("extern \"C\" {\n"
24061                "int foo();\n"
24062                "}",
24063                Style);
24064 }
24065 
24066 TEST_F(FormatTest, Concepts) {
24067   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
24068             FormatStyle::BBCDS_Always);
24069   verifyFormat("template <typename T>\n"
24070                "concept True = true;");
24071 
24072   verifyFormat("template <typename T>\n"
24073                "concept C = ((false || foo()) && C2<T>) ||\n"
24074                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
24075                getLLVMStyleWithColumns(60));
24076 
24077   verifyFormat("template <typename T>\n"
24078                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
24079                "sizeof(T) <= 8;");
24080 
24081   verifyFormat("template <typename T>\n"
24082                "concept DelayedCheck = true && requires(T t) {\n"
24083                "                                 t.bar();\n"
24084                "                                 t.baz();\n"
24085                "                               } && sizeof(T) <= 8;");
24086 
24087   verifyFormat("template <typename T>\n"
24088                "concept DelayedCheck = true && requires(T t) { // Comment\n"
24089                "                                 t.bar();\n"
24090                "                                 t.baz();\n"
24091                "                               } && sizeof(T) <= 8;");
24092 
24093   verifyFormat("template <typename T>\n"
24094                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
24095                "sizeof(T) <= 8;");
24096 
24097   verifyFormat("template <typename T>\n"
24098                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
24099                "&& sizeof(T) <= 8;");
24100 
24101   verifyFormat(
24102       "template <typename T>\n"
24103       "concept DelayedCheck = static_cast<bool>(0) ||\n"
24104       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24105 
24106   verifyFormat("template <typename T>\n"
24107                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
24108                "&& sizeof(T) <= 8;");
24109 
24110   verifyFormat(
24111       "template <typename T>\n"
24112       "concept DelayedCheck = (bool)(0) ||\n"
24113       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24114 
24115   verifyFormat("template <typename T>\n"
24116                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
24117                "&& sizeof(T) <= 8;");
24118 
24119   verifyFormat("template <typename T>\n"
24120                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
24121                "sizeof(T) <= 8;");
24122 
24123   verifyFormat("template <typename T>\n"
24124                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
24125                "               requires(T t) {\n"
24126                "                 t.bar();\n"
24127                "                 t.baz();\n"
24128                "               } && sizeof(T) <= 8 && !(4 < 3);",
24129                getLLVMStyleWithColumns(60));
24130 
24131   verifyFormat("template <typename T>\n"
24132                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
24133 
24134   verifyFormat("template <typename T>\n"
24135                "concept C = foo();");
24136 
24137   verifyFormat("template <typename T>\n"
24138                "concept C = foo(T());");
24139 
24140   verifyFormat("template <typename T>\n"
24141                "concept C = foo(T{});");
24142 
24143   verifyFormat("template <typename T>\n"
24144                "concept Size = V<sizeof(T)>::Value > 5;");
24145 
24146   verifyFormat("template <typename T>\n"
24147                "concept True = S<T>::Value;");
24148 
24149   verifyFormat(
24150       "template <typename T>\n"
24151       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
24152       "            sizeof(T) <= 8;");
24153 
24154   // FIXME: This is misformatted because the fake l paren starts at bool, not at
24155   // the lambda l square.
24156   verifyFormat("template <typename T>\n"
24157                "concept C = [] -> bool { return true; }() && requires(T t) { "
24158                "t.bar(); } &&\n"
24159                "                      sizeof(T) <= 8;");
24160 
24161   verifyFormat(
24162       "template <typename T>\n"
24163       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
24164       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24165 
24166   verifyFormat("template <typename T>\n"
24167                "concept C = decltype([]() { return std::true_type{}; "
24168                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24169                getLLVMStyleWithColumns(120));
24170 
24171   verifyFormat("template <typename T>\n"
24172                "concept C = decltype([]() -> std::true_type { return {}; "
24173                "}())::value &&\n"
24174                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24175 
24176   verifyFormat("template <typename T>\n"
24177                "concept C = true;\n"
24178                "Foo Bar;");
24179 
24180   verifyFormat("template <typename T>\n"
24181                "concept Hashable = requires(T a) {\n"
24182                "                     { std::hash<T>{}(a) } -> "
24183                "std::convertible_to<std::size_t>;\n"
24184                "                   };");
24185 
24186   verifyFormat(
24187       "template <typename T>\n"
24188       "concept EqualityComparable = requires(T a, T b) {\n"
24189       "                               { a == b } -> std::same_as<bool>;\n"
24190       "                             };");
24191 
24192   verifyFormat(
24193       "template <typename T>\n"
24194       "concept EqualityComparable = requires(T a, T b) {\n"
24195       "                               { a == b } -> std::same_as<bool>;\n"
24196       "                               { a != b } -> std::same_as<bool>;\n"
24197       "                             };");
24198 
24199   verifyFormat("template <typename T>\n"
24200                "concept WeakEqualityComparable = requires(T a, T b) {\n"
24201                "                                   { a == b };\n"
24202                "                                   { a != b };\n"
24203                "                                 };");
24204 
24205   verifyFormat("template <typename T>\n"
24206                "concept HasSizeT = requires { typename T::size_t; };");
24207 
24208   verifyFormat("template <typename T>\n"
24209                "concept Semiregular =\n"
24210                "    DefaultConstructible<T> && CopyConstructible<T> && "
24211                "CopyAssignable<T> &&\n"
24212                "    requires(T a, std::size_t n) {\n"
24213                "      requires Same<T *, decltype(&a)>;\n"
24214                "      { a.~T() } noexcept;\n"
24215                "      requires Same<T *, decltype(new T)>;\n"
24216                "      requires Same<T *, decltype(new T[n])>;\n"
24217                "      { delete new T; };\n"
24218                "      { delete new T[n]; };\n"
24219                "    };");
24220 
24221   verifyFormat("template <typename T>\n"
24222                "concept Semiregular =\n"
24223                "    requires(T a, std::size_t n) {\n"
24224                "      requires Same<T *, decltype(&a)>;\n"
24225                "      { a.~T() } noexcept;\n"
24226                "      requires Same<T *, decltype(new T)>;\n"
24227                "      requires Same<T *, decltype(new T[n])>;\n"
24228                "      { delete new T; };\n"
24229                "      { delete new T[n]; };\n"
24230                "      { new T } -> std::same_as<T *>;\n"
24231                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
24232                "CopyAssignable<T>;");
24233 
24234   verifyFormat(
24235       "template <typename T>\n"
24236       "concept Semiregular =\n"
24237       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
24238       "                                 requires Same<T *, decltype(&a)>;\n"
24239       "                                 { a.~T() } noexcept;\n"
24240       "                                 requires Same<T *, decltype(new T)>;\n"
24241       "                                 requires Same<T *, decltype(new "
24242       "T[n])>;\n"
24243       "                                 { delete new T; };\n"
24244       "                                 { delete new T[n]; };\n"
24245       "                               } && CopyConstructible<T> && "
24246       "CopyAssignable<T>;");
24247 
24248   verifyFormat("template <typename T>\n"
24249                "concept Two = requires(T t) {\n"
24250                "                { t.foo() } -> std::same_as<Bar>;\n"
24251                "              } && requires(T &&t) {\n"
24252                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
24253                "                   };");
24254 
24255   verifyFormat(
24256       "template <typename T>\n"
24257       "concept C = requires(T x) {\n"
24258       "              { *x } -> std::convertible_to<typename T::inner>;\n"
24259       "              { x + 1 } noexcept -> std::same_as<int>;\n"
24260       "              { x * 1 } -> std::convertible_to<T>;\n"
24261       "            };");
24262 
24263   verifyFormat(
24264       "template <typename T, typename U = T>\n"
24265       "concept Swappable = requires(T &&t, U &&u) {\n"
24266       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
24267       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
24268       "                    };");
24269 
24270   verifyFormat("template <typename T, typename U>\n"
24271                "concept Common = requires(T &&t, U &&u) {\n"
24272                "                   typename CommonType<T, U>;\n"
24273                "                   { CommonType<T, U>(std::forward<T>(t)) };\n"
24274                "                 };");
24275 
24276   verifyFormat("template <typename T, typename U>\n"
24277                "concept Common = requires(T &&t, U &&u) {\n"
24278                "                   typename CommonType<T, U>;\n"
24279                "                   { CommonType<T, U>{std::forward<T>(t)} };\n"
24280                "                 };");
24281 
24282   verifyFormat(
24283       "template <typename T>\n"
24284       "concept C = requires(T t) {\n"
24285       "              requires Bar<T> && Foo<T>;\n"
24286       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24287       "            };");
24288 
24289   verifyFormat("template <typename T>\n"
24290                "concept HasFoo = requires(T t) {\n"
24291                "                   { t.foo() };\n"
24292                "                   t.foo();\n"
24293                "                 };\n"
24294                "template <typename T>\n"
24295                "concept HasBar = requires(T t) {\n"
24296                "                   { t.bar() };\n"
24297                "                   t.bar();\n"
24298                "                 };");
24299 
24300   verifyFormat("template <typename T>\n"
24301                "concept Large = sizeof(T) > 10;");
24302 
24303   verifyFormat("template <typename T, typename U>\n"
24304                "concept FooableWith = requires(T t, U u) {\n"
24305                "                        typename T::foo_type;\n"
24306                "                        { t.foo(u) } -> typename T::foo_type;\n"
24307                "                        t++;\n"
24308                "                      };\n"
24309                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
24310 
24311   verifyFormat("template <typename T>\n"
24312                "concept Context = is_specialization_of_v<context, T>;");
24313 
24314   verifyFormat("template <typename T>\n"
24315                "concept Node = std::is_object_v<T>;");
24316 
24317   verifyFormat("template <class T>\n"
24318                "concept integral = __is_integral(T);");
24319 
24320   verifyFormat("template <class T>\n"
24321                "concept is2D = __array_extent(T, 1) == 2;");
24322 
24323   verifyFormat("template <class T>\n"
24324                "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
24325 
24326   verifyFormat("template <class T, class T2>\n"
24327                "concept Same = __is_same_as<T, T2>;");
24328 
24329   verifyFormat(
24330       "template <class _InIt, class _OutIt>\n"
24331       "concept _Can_reread_dest =\n"
24332       "    std::forward_iterator<_OutIt> &&\n"
24333       "    std::same_as<std::iter_value_t<_InIt>, std::iter_value_t<_OutIt>>;");
24334 
24335   auto Style = getLLVMStyle();
24336   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
24337 
24338   verifyFormat(
24339       "template <typename T>\n"
24340       "concept C = requires(T t) {\n"
24341       "              requires Bar<T> && Foo<T>;\n"
24342       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24343       "            };",
24344       Style);
24345 
24346   verifyFormat("template <typename T>\n"
24347                "concept HasFoo = requires(T t) {\n"
24348                "                   { t.foo() };\n"
24349                "                   t.foo();\n"
24350                "                 };\n"
24351                "template <typename T>\n"
24352                "concept HasBar = requires(T t) {\n"
24353                "                   { t.bar() };\n"
24354                "                   t.bar();\n"
24355                "                 };",
24356                Style);
24357 
24358   verifyFormat("template <typename T> concept True = true;", Style);
24359 
24360   verifyFormat("template <typename T>\n"
24361                "concept C = decltype([]() -> std::true_type { return {}; "
24362                "}())::value &&\n"
24363                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24364                Style);
24365 
24366   verifyFormat("template <typename T>\n"
24367                "concept Semiregular =\n"
24368                "    DefaultConstructible<T> && CopyConstructible<T> && "
24369                "CopyAssignable<T> &&\n"
24370                "    requires(T a, std::size_t n) {\n"
24371                "      requires Same<T *, decltype(&a)>;\n"
24372                "      { a.~T() } noexcept;\n"
24373                "      requires Same<T *, decltype(new T)>;\n"
24374                "      requires Same<T *, decltype(new T[n])>;\n"
24375                "      { delete new T; };\n"
24376                "      { delete new T[n]; };\n"
24377                "    };",
24378                Style);
24379 
24380   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
24381 
24382   verifyFormat("template <typename T> concept C =\n"
24383                "    requires(T t) {\n"
24384                "      requires Bar<T> && Foo<T>;\n"
24385                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24386                "    };",
24387                Style);
24388 
24389   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
24390                "                                         { t.foo() };\n"
24391                "                                         t.foo();\n"
24392                "                                       };\n"
24393                "template <typename T> concept HasBar = requires(T t) {\n"
24394                "                                         { t.bar() };\n"
24395                "                                         t.bar();\n"
24396                "                                       };",
24397                Style);
24398 
24399   verifyFormat("template <typename T> concept True = true;", Style);
24400 
24401   verifyFormat(
24402       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
24403       "                                    return {};\n"
24404       "                                  }())::value &&\n"
24405       "                                  requires(T t) { t.bar(); } && "
24406       "sizeof(T) <= 8;",
24407       Style);
24408 
24409   verifyFormat("template <typename T> concept Semiregular =\n"
24410                "    DefaultConstructible<T> && CopyConstructible<T> && "
24411                "CopyAssignable<T> &&\n"
24412                "    requires(T a, std::size_t n) {\n"
24413                "      requires Same<T *, decltype(&a)>;\n"
24414                "      { a.~T() } noexcept;\n"
24415                "      requires Same<T *, decltype(new T)>;\n"
24416                "      requires Same<T *, decltype(new T[n])>;\n"
24417                "      { delete new T; };\n"
24418                "      { delete new T[n]; };\n"
24419                "    };",
24420                Style);
24421 
24422   // The following tests are invalid C++, we just want to make sure we don't
24423   // assert.
24424   verifyFormat("template <typename T>\n"
24425                "concept C = requires C2<T>;");
24426 
24427   verifyFormat("template <typename T>\n"
24428                "concept C = 5 + 4;");
24429 
24430   verifyFormat("template <typename T>\n"
24431                "concept C =\n"
24432                "class X;");
24433 
24434   verifyFormat("template <typename T>\n"
24435                "concept C = [] && true;");
24436 
24437   verifyFormat("template <typename T>\n"
24438                "concept C = [] && requires(T t) { typename T::size_type; };");
24439 }
24440 
24441 TEST_F(FormatTest, RequiresClausesPositions) {
24442   auto Style = getLLVMStyle();
24443   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
24444   EXPECT_EQ(Style.IndentRequiresClause, true);
24445 
24446   verifyFormat("template <typename T>\n"
24447                "  requires(Foo<T> && std::trait<T>)\n"
24448                "struct Bar;",
24449                Style);
24450 
24451   verifyFormat("template <typename T>\n"
24452                "  requires(Foo<T> && std::trait<T>)\n"
24453                "class Bar {\n"
24454                "public:\n"
24455                "  Bar(T t);\n"
24456                "  bool baz();\n"
24457                "};",
24458                Style);
24459 
24460   verifyFormat(
24461       "template <typename T>\n"
24462       "  requires requires(T &&t) {\n"
24463       "             typename T::I;\n"
24464       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
24465       "           }\n"
24466       "Bar(T) -> Bar<typename T::I>;",
24467       Style);
24468 
24469   verifyFormat("template <typename T>\n"
24470                "  requires(Foo<T> && std::trait<T>)\n"
24471                "constexpr T MyGlobal;",
24472                Style);
24473 
24474   verifyFormat("template <typename T>\n"
24475                "  requires Foo<T> && requires(T t) {\n"
24476                "                       { t.baz() } -> std::same_as<bool>;\n"
24477                "                       requires std::same_as<T::Factor, int>;\n"
24478                "                     }\n"
24479                "inline int bar(T t) {\n"
24480                "  return t.baz() ? T::Factor : 5;\n"
24481                "}",
24482                Style);
24483 
24484   verifyFormat("template <typename T>\n"
24485                "inline int bar(T t)\n"
24486                "  requires Foo<T> && requires(T t) {\n"
24487                "                       { t.baz() } -> std::same_as<bool>;\n"
24488                "                       requires std::same_as<T::Factor, int>;\n"
24489                "                     }\n"
24490                "{\n"
24491                "  return t.baz() ? T::Factor : 5;\n"
24492                "}",
24493                Style);
24494 
24495   verifyFormat("template <typename T>\n"
24496                "  requires F<T>\n"
24497                "int bar(T t) {\n"
24498                "  return 5;\n"
24499                "}",
24500                Style);
24501 
24502   verifyFormat("template <typename T>\n"
24503                "int bar(T t)\n"
24504                "  requires F<T>\n"
24505                "{\n"
24506                "  return 5;\n"
24507                "}",
24508                Style);
24509 
24510   verifyFormat("template <typename T>\n"
24511                "int bar(T t)\n"
24512                "  requires F<T>;",
24513                Style);
24514 
24515   Style.IndentRequiresClause = false;
24516   verifyFormat("template <typename T>\n"
24517                "requires F<T>\n"
24518                "int bar(T t) {\n"
24519                "  return 5;\n"
24520                "}",
24521                Style);
24522 
24523   verifyFormat("template <typename T>\n"
24524                "int bar(T t)\n"
24525                "requires F<T>\n"
24526                "{\n"
24527                "  return 5;\n"
24528                "}",
24529                Style);
24530 
24531   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
24532   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
24533                "template <typename T> requires Foo<T> void bar() {}\n"
24534                "template <typename T> void bar() requires Foo<T> {}\n"
24535                "template <typename T> void bar() requires Foo<T>;\n"
24536                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
24537                Style);
24538 
24539   auto ColumnStyle = Style;
24540   ColumnStyle.ColumnLimit = 40;
24541   verifyFormat("template <typename AAAAAAA>\n"
24542                "requires Foo<T> struct Bar {};\n"
24543                "template <typename AAAAAAA>\n"
24544                "requires Foo<T> void bar() {}\n"
24545                "template <typename AAAAAAA>\n"
24546                "void bar() requires Foo<T> {}\n"
24547                "template <typename AAAAAAA>\n"
24548                "requires Foo<T> Baz(T) -> Baz<T>;",
24549                ColumnStyle);
24550 
24551   verifyFormat("template <typename T>\n"
24552                "requires Foo<AAAAAAA> struct Bar {};\n"
24553                "template <typename T>\n"
24554                "requires Foo<AAAAAAA> void bar() {}\n"
24555                "template <typename T>\n"
24556                "void bar() requires Foo<AAAAAAA> {}\n"
24557                "template <typename T>\n"
24558                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
24559                ColumnStyle);
24560 
24561   verifyFormat("template <typename AAAAAAA>\n"
24562                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24563                "struct Bar {};\n"
24564                "template <typename AAAAAAA>\n"
24565                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24566                "void bar() {}\n"
24567                "template <typename AAAAAAA>\n"
24568                "void bar()\n"
24569                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24570                "template <typename AAAAAAA>\n"
24571                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24572                "template <typename AAAAAAA>\n"
24573                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24574                "Bar(T) -> Bar<T>;",
24575                ColumnStyle);
24576 
24577   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24578   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24579 
24580   verifyFormat("template <typename T>\n"
24581                "requires Foo<T> struct Bar {};\n"
24582                "template <typename T>\n"
24583                "requires Foo<T> void bar() {}\n"
24584                "template <typename T>\n"
24585                "void bar()\n"
24586                "requires Foo<T> {}\n"
24587                "template <typename T>\n"
24588                "void bar()\n"
24589                "requires Foo<T>;\n"
24590                "template <typename T>\n"
24591                "requires Foo<T> Bar(T) -> Bar<T>;",
24592                Style);
24593 
24594   verifyFormat("template <typename AAAAAAA>\n"
24595                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24596                "struct Bar {};\n"
24597                "template <typename AAAAAAA>\n"
24598                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24599                "void bar() {}\n"
24600                "template <typename AAAAAAA>\n"
24601                "void bar()\n"
24602                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24603                "template <typename AAAAAAA>\n"
24604                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24605                "template <typename AAAAAAA>\n"
24606                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24607                "Bar(T) -> Bar<T>;",
24608                ColumnStyle);
24609 
24610   Style.IndentRequiresClause = true;
24611   ColumnStyle.IndentRequiresClause = true;
24612 
24613   verifyFormat("template <typename T>\n"
24614                "  requires Foo<T> struct Bar {};\n"
24615                "template <typename T>\n"
24616                "  requires Foo<T> void bar() {}\n"
24617                "template <typename T>\n"
24618                "void bar()\n"
24619                "  requires Foo<T> {}\n"
24620                "template <typename T>\n"
24621                "  requires Foo<T> Bar(T) -> Bar<T>;",
24622                Style);
24623 
24624   verifyFormat("template <typename AAAAAAA>\n"
24625                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24626                "struct Bar {};\n"
24627                "template <typename AAAAAAA>\n"
24628                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24629                "void bar() {}\n"
24630                "template <typename AAAAAAA>\n"
24631                "void bar()\n"
24632                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24633                "template <typename AAAAAAA>\n"
24634                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
24635                "template <typename AAAAAAA>\n"
24636                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24637                "Bar(T) -> Bar<T>;",
24638                ColumnStyle);
24639 
24640   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24641   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24642 
24643   verifyFormat("template <typename T> requires Foo<T>\n"
24644                "struct Bar {};\n"
24645                "template <typename T> requires Foo<T>\n"
24646                "void bar() {}\n"
24647                "template <typename T>\n"
24648                "void bar() requires Foo<T>\n"
24649                "{}\n"
24650                "template <typename T> void bar() requires Foo<T>;\n"
24651                "template <typename T> requires Foo<T>\n"
24652                "Bar(T) -> Bar<T>;",
24653                Style);
24654 
24655   verifyFormat("template <typename AAAAAAA>\n"
24656                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24657                "struct Bar {};\n"
24658                "template <typename AAAAAAA>\n"
24659                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24660                "void bar() {}\n"
24661                "template <typename AAAAAAA>\n"
24662                "void bar()\n"
24663                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24664                "{}\n"
24665                "template <typename AAAAAAA>\n"
24666                "requires Foo<AAAAAAAA>\n"
24667                "Bar(T) -> Bar<T>;\n"
24668                "template <typename AAAAAAA>\n"
24669                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24670                "Bar(T) -> Bar<T>;",
24671                ColumnStyle);
24672 }
24673 
24674 TEST_F(FormatTest, RequiresClauses) {
24675   verifyFormat("struct [[nodiscard]] zero_t {\n"
24676                "  template <class T>\n"
24677                "    requires requires { number_zero_v<T>; }\n"
24678                "  [[nodiscard]] constexpr operator T() const {\n"
24679                "    return number_zero_v<T>;\n"
24680                "  }\n"
24681                "};");
24682 
24683   auto Style = getLLVMStyle();
24684 
24685   verifyFormat(
24686       "template <typename T>\n"
24687       "  requires is_default_constructible_v<hash<T>> and\n"
24688       "           is_copy_constructible_v<hash<T>> and\n"
24689       "           is_move_constructible_v<hash<T>> and\n"
24690       "           is_copy_assignable_v<hash<T>> and "
24691       "is_move_assignable_v<hash<T>> and\n"
24692       "           is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
24693       "           is_callable_v<hash<T>(T)> and\n"
24694       "           is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n"
24695       "           is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n"
24696       "           is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
24697       "struct S {};",
24698       Style);
24699 
24700   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
24701   verifyFormat(
24702       "template <typename T>\n"
24703       "  requires is_default_constructible_v<hash<T>>\n"
24704       "           and is_copy_constructible_v<hash<T>>\n"
24705       "           and is_move_constructible_v<hash<T>>\n"
24706       "           and is_copy_assignable_v<hash<T>> and "
24707       "is_move_assignable_v<hash<T>>\n"
24708       "           and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
24709       "           and is_callable_v<hash<T>(T)>\n"
24710       "           and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n"
24711       "           and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n"
24712       "           and is_same_v<size_t, decltype(hash<T>(declval<const T "
24713       "&>()))>\n"
24714       "struct S {};",
24715       Style);
24716 
24717   // Not a clause, but we once hit an assert.
24718   verifyFormat("#if 0\n"
24719                "#else\n"
24720                "foo();\n"
24721                "#endif\n"
24722                "bar(requires);");
24723 }
24724 
24725 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24726   FormatStyle Style = getLLVMStyle();
24727   StringRef Source = "void Foo::slot() {\n"
24728                      "  unsigned char MyChar = 'x';\n"
24729                      "  emit signal(MyChar);\n"
24730                      "  Q_EMIT signal(MyChar);\n"
24731                      "}";
24732 
24733   EXPECT_EQ(Source, format(Source, Style));
24734 
24735   Style.AlignConsecutiveDeclarations.Enabled = true;
24736   EXPECT_EQ("void Foo::slot() {\n"
24737             "  unsigned char MyChar = 'x';\n"
24738             "  emit          signal(MyChar);\n"
24739             "  Q_EMIT signal(MyChar);\n"
24740             "}",
24741             format(Source, Style));
24742 
24743   Style.StatementAttributeLikeMacros.push_back("emit");
24744   EXPECT_EQ(Source, format(Source, Style));
24745 
24746   Style.StatementAttributeLikeMacros = {};
24747   EXPECT_EQ("void Foo::slot() {\n"
24748             "  unsigned char MyChar = 'x';\n"
24749             "  emit          signal(MyChar);\n"
24750             "  Q_EMIT        signal(MyChar);\n"
24751             "}",
24752             format(Source, Style));
24753 }
24754 
24755 TEST_F(FormatTest, IndentAccessModifiers) {
24756   FormatStyle Style = getLLVMStyle();
24757   Style.IndentAccessModifiers = true;
24758   // Members are *two* levels below the record;
24759   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24760   verifyFormat("class C {\n"
24761                "    int i;\n"
24762                "};\n",
24763                Style);
24764   verifyFormat("union C {\n"
24765                "    int i;\n"
24766                "    unsigned u;\n"
24767                "};\n",
24768                Style);
24769   // Access modifiers should be indented one level below the record.
24770   verifyFormat("class C {\n"
24771                "  public:\n"
24772                "    int i;\n"
24773                "};\n",
24774                Style);
24775   verifyFormat("struct S {\n"
24776                "  private:\n"
24777                "    class C {\n"
24778                "        int j;\n"
24779                "\n"
24780                "      public:\n"
24781                "        C();\n"
24782                "    };\n"
24783                "\n"
24784                "  public:\n"
24785                "    int i;\n"
24786                "};\n",
24787                Style);
24788   // Enumerations are not records and should be unaffected.
24789   Style.AllowShortEnumsOnASingleLine = false;
24790   verifyFormat("enum class E {\n"
24791                "  A,\n"
24792                "  B\n"
24793                "};\n",
24794                Style);
24795   // Test with a different indentation width;
24796   // also proves that the result is Style.AccessModifierOffset agnostic.
24797   Style.IndentWidth = 3;
24798   verifyFormat("class C {\n"
24799                "   public:\n"
24800                "      int i;\n"
24801                "};\n",
24802                Style);
24803 }
24804 
24805 TEST_F(FormatTest, LimitlessStringsAndComments) {
24806   auto Style = getLLVMStyleWithColumns(0);
24807   constexpr StringRef Code =
24808       "/**\n"
24809       " * This is a multiline comment with quite some long lines, at least for "
24810       "the LLVM Style.\n"
24811       " * We will redo this with strings and line comments. Just to  check if "
24812       "everything is working.\n"
24813       " */\n"
24814       "bool foo() {\n"
24815       "  /* Single line multi line comment. */\n"
24816       "  const std::string String = \"This is a multiline string with quite "
24817       "some long lines, at least for the LLVM Style.\"\n"
24818       "                             \"We already did it with multi line "
24819       "comments, and we will do it with line comments. Just to check if "
24820       "everything is working.\";\n"
24821       "  // This is a line comment (block) with quite some long lines, at "
24822       "least for the LLVM Style.\n"
24823       "  // We already did this with multi line comments and strings. Just to "
24824       "check if everything is working.\n"
24825       "  const std::string SmallString = \"Hello World\";\n"
24826       "  // Small line comment\n"
24827       "  return String.size() > SmallString.size();\n"
24828       "}";
24829   EXPECT_EQ(Code, format(Code, Style));
24830 }
24831 
24832 TEST_F(FormatTest, FormatDecayCopy) {
24833   // error cases from unit tests
24834   verifyFormat("foo(auto())");
24835   verifyFormat("foo(auto{})");
24836   verifyFormat("foo(auto({}))");
24837   verifyFormat("foo(auto{{}})");
24838 
24839   verifyFormat("foo(auto(1))");
24840   verifyFormat("foo(auto{1})");
24841   verifyFormat("foo(new auto(1))");
24842   verifyFormat("foo(new auto{1})");
24843   verifyFormat("decltype(auto(1)) x;");
24844   verifyFormat("decltype(auto{1}) x;");
24845   verifyFormat("auto(x);");
24846   verifyFormat("auto{x};");
24847   verifyFormat("new auto{x};");
24848   verifyFormat("auto{x} = y;");
24849   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24850                                 // the user's own fault
24851   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24852                                          // clearly the user's own fault
24853   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24854 }
24855 
24856 TEST_F(FormatTest, Cpp20ModulesSupport) {
24857   FormatStyle Style = getLLVMStyle();
24858   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24859   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24860 
24861   verifyFormat("export import foo;", Style);
24862   verifyFormat("export import foo:bar;", Style);
24863   verifyFormat("export import foo.bar;", Style);
24864   verifyFormat("export import foo.bar:baz;", Style);
24865   verifyFormat("export import :bar;", Style);
24866   verifyFormat("export module foo:bar;", Style);
24867   verifyFormat("export module foo;", Style);
24868   verifyFormat("export module foo.bar;", Style);
24869   verifyFormat("export module foo.bar:baz;", Style);
24870   verifyFormat("export import <string_view>;", Style);
24871 
24872   verifyFormat("export type_name var;", Style);
24873   verifyFormat("template <class T> export using A = B<T>;", Style);
24874   verifyFormat("export using A = B;", Style);
24875   verifyFormat("export int func() {\n"
24876                "  foo();\n"
24877                "}",
24878                Style);
24879   verifyFormat("export struct {\n"
24880                "  int foo;\n"
24881                "};",
24882                Style);
24883   verifyFormat("export {\n"
24884                "  int foo;\n"
24885                "};",
24886                Style);
24887   verifyFormat("export export char const *hello() { return \"hello\"; }");
24888 
24889   verifyFormat("import bar;", Style);
24890   verifyFormat("import foo.bar;", Style);
24891   verifyFormat("import foo:bar;", Style);
24892   verifyFormat("import :bar;", Style);
24893   verifyFormat("import <ctime>;", Style);
24894   verifyFormat("import \"header\";", Style);
24895 
24896   verifyFormat("module foo;", Style);
24897   verifyFormat("module foo:bar;", Style);
24898   verifyFormat("module foo.bar;", Style);
24899   verifyFormat("module;", Style);
24900 
24901   verifyFormat("export namespace hi {\n"
24902                "const char *sayhi();\n"
24903                "}",
24904                Style);
24905 
24906   verifyFormat("module :private;", Style);
24907   verifyFormat("import <foo/bar.h>;", Style);
24908   verifyFormat("import foo...bar;", Style);
24909   verifyFormat("import ..........;", Style);
24910   verifyFormat("module foo:private;", Style);
24911   verifyFormat("import a", Style);
24912   verifyFormat("module a", Style);
24913   verifyFormat("export import a", Style);
24914   verifyFormat("export module a", Style);
24915 
24916   verifyFormat("import", Style);
24917   verifyFormat("module", Style);
24918   verifyFormat("export", Style);
24919 }
24920 
24921 TEST_F(FormatTest, CoroutineForCoawait) {
24922   FormatStyle Style = getLLVMStyle();
24923   verifyFormat("for co_await (auto x : range())\n  ;");
24924   verifyFormat("for (auto i : arr) {\n"
24925                "}",
24926                Style);
24927   verifyFormat("for co_await (auto i : arr) {\n"
24928                "}",
24929                Style);
24930   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24931                "}",
24932                Style);
24933 }
24934 
24935 TEST_F(FormatTest, CoroutineCoAwait) {
24936   verifyFormat("int x = co_await foo();");
24937   verifyFormat("int x = (co_await foo());");
24938   verifyFormat("co_await (42);");
24939   verifyFormat("void operator co_await(int);");
24940   verifyFormat("void operator co_await(a);");
24941   verifyFormat("co_await a;");
24942   verifyFormat("co_await missing_await_resume{};");
24943   verifyFormat("co_await a; // comment");
24944   verifyFormat("void test0() { co_await a; }");
24945   verifyFormat("co_await co_await co_await foo();");
24946   verifyFormat("co_await foo().bar();");
24947   verifyFormat("co_await [this]() -> Task { co_return x; }");
24948   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24949                "foo(); }(x, y);");
24950 
24951   FormatStyle Style = getLLVMStyleWithColumns(40);
24952   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24953                "  co_return co_await foo();\n"
24954                "}(x, y);",
24955                Style);
24956   verifyFormat("co_await;");
24957 }
24958 
24959 TEST_F(FormatTest, CoroutineCoYield) {
24960   verifyFormat("int x = co_yield foo();");
24961   verifyFormat("int x = (co_yield foo());");
24962   verifyFormat("co_yield (42);");
24963   verifyFormat("co_yield {42};");
24964   verifyFormat("co_yield 42;");
24965   verifyFormat("co_yield n++;");
24966   verifyFormat("co_yield ++n;");
24967   verifyFormat("co_yield;");
24968 }
24969 
24970 TEST_F(FormatTest, CoroutineCoReturn) {
24971   verifyFormat("co_return (42);");
24972   verifyFormat("co_return;");
24973   verifyFormat("co_return {};");
24974   verifyFormat("co_return x;");
24975   verifyFormat("co_return co_await foo();");
24976   verifyFormat("co_return co_yield foo();");
24977 }
24978 
24979 TEST_F(FormatTest, EmptyShortBlock) {
24980   auto Style = getLLVMStyle();
24981   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24982 
24983   verifyFormat("try {\n"
24984                "  doA();\n"
24985                "} catch (Exception &e) {\n"
24986                "  e.printStackTrace();\n"
24987                "}\n",
24988                Style);
24989 
24990   verifyFormat("try {\n"
24991                "  doA();\n"
24992                "} catch (Exception &e) {}\n",
24993                Style);
24994 }
24995 
24996 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
24997   auto Style = getLLVMStyle();
24998 
24999   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
25000   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
25001   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
25002   verifyFormat("struct Y<[] { return 0; }> {};", Style);
25003 
25004   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
25005   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
25006 }
25007 
25008 TEST_F(FormatTest, InsertBraces) {
25009   FormatStyle Style = getLLVMStyle();
25010   Style.InsertBraces = true;
25011 
25012   verifyFormat("// clang-format off\n"
25013                "// comment\n"
25014                "if (a) f();\n"
25015                "// clang-format on\n"
25016                "if (b) {\n"
25017                "  g();\n"
25018                "}",
25019                "// clang-format off\n"
25020                "// comment\n"
25021                "if (a) f();\n"
25022                "// clang-format on\n"
25023                "if (b) g();",
25024                Style);
25025 
25026   verifyFormat("if (a) {\n"
25027                "  switch (b) {\n"
25028                "  case 1:\n"
25029                "    c = 0;\n"
25030                "    break;\n"
25031                "  default:\n"
25032                "    c = 1;\n"
25033                "  }\n"
25034                "}",
25035                "if (a)\n"
25036                "  switch (b) {\n"
25037                "  case 1:\n"
25038                "    c = 0;\n"
25039                "    break;\n"
25040                "  default:\n"
25041                "    c = 1;\n"
25042                "  }",
25043                Style);
25044 
25045   verifyFormat("for (auto node : nodes) {\n"
25046                "  if (node) {\n"
25047                "    break;\n"
25048                "  }\n"
25049                "}",
25050                "for (auto node : nodes)\n"
25051                "  if (node)\n"
25052                "    break;",
25053                Style);
25054 
25055   verifyFormat("for (auto node : nodes) {\n"
25056                "  if (node)\n"
25057                "}",
25058                "for (auto node : nodes)\n"
25059                "  if (node)",
25060                Style);
25061 
25062   verifyFormat("do {\n"
25063                "  --a;\n"
25064                "} while (a);",
25065                "do\n"
25066                "  --a;\n"
25067                "while (a);",
25068                Style);
25069 
25070   verifyFormat("if (i) {\n"
25071                "  ++i;\n"
25072                "} else {\n"
25073                "  --i;\n"
25074                "}",
25075                "if (i)\n"
25076                "  ++i;\n"
25077                "else {\n"
25078                "  --i;\n"
25079                "}",
25080                Style);
25081 
25082   verifyFormat("void f() {\n"
25083                "  while (j--) {\n"
25084                "    while (i) {\n"
25085                "      --i;\n"
25086                "    }\n"
25087                "  }\n"
25088                "}",
25089                "void f() {\n"
25090                "  while (j--)\n"
25091                "    while (i)\n"
25092                "      --i;\n"
25093                "}",
25094                Style);
25095 
25096   verifyFormat("f({\n"
25097                "  if (a) {\n"
25098                "    g();\n"
25099                "  }\n"
25100                "});",
25101                "f({\n"
25102                "  if (a)\n"
25103                "    g();\n"
25104                "});",
25105                Style);
25106 
25107   verifyFormat("if (a) {\n"
25108                "  f();\n"
25109                "} else if (b) {\n"
25110                "  g();\n"
25111                "} else {\n"
25112                "  h();\n"
25113                "}",
25114                "if (a)\n"
25115                "  f();\n"
25116                "else if (b)\n"
25117                "  g();\n"
25118                "else\n"
25119                "  h();",
25120                Style);
25121 
25122   verifyFormat("if (a) {\n"
25123                "  f();\n"
25124                "}\n"
25125                "// comment\n"
25126                "/* comment */",
25127                "if (a)\n"
25128                "  f();\n"
25129                "// comment\n"
25130                "/* comment */",
25131                Style);
25132 
25133   verifyFormat("if (a) {\n"
25134                "  // foo\n"
25135                "  // bar\n"
25136                "  f();\n"
25137                "}",
25138                "if (a)\n"
25139                "  // foo\n"
25140                "  // bar\n"
25141                "  f();",
25142                Style);
25143 
25144   verifyFormat("if (a) { // comment\n"
25145                "  // comment\n"
25146                "  f();\n"
25147                "}",
25148                "if (a) // comment\n"
25149                "  // comment\n"
25150                "  f();",
25151                Style);
25152 
25153   verifyFormat("if (a) {\n"
25154                "  f(); // comment\n"
25155                "}",
25156                "if (a)\n"
25157                "  f(); // comment",
25158                Style);
25159 
25160   verifyFormat("if (a) {\n"
25161                "  f();\n"
25162                "}\n"
25163                "#undef A\n"
25164                "#undef B",
25165                "if (a)\n"
25166                "  f();\n"
25167                "#undef A\n"
25168                "#undef B",
25169                Style);
25170 
25171   verifyFormat("if (a)\n"
25172                "#ifdef A\n"
25173                "  f();\n"
25174                "#else\n"
25175                "  g();\n"
25176                "#endif",
25177                Style);
25178 
25179   verifyFormat("#if 0\n"
25180                "#elif 1\n"
25181                "#endif\n"
25182                "void f() {\n"
25183                "  if (a) {\n"
25184                "    g();\n"
25185                "  }\n"
25186                "}",
25187                "#if 0\n"
25188                "#elif 1\n"
25189                "#endif\n"
25190                "void f() {\n"
25191                "  if (a) g();\n"
25192                "}",
25193                Style);
25194 
25195   Style.ColumnLimit = 15;
25196 
25197   verifyFormat("#define A     \\\n"
25198                "  if (a)      \\\n"
25199                "    f();",
25200                Style);
25201 
25202   verifyFormat("if (a + b >\n"
25203                "    c) {\n"
25204                "  f();\n"
25205                "}",
25206                "if (a + b > c)\n"
25207                "  f();",
25208                Style);
25209 }
25210 
25211 TEST_F(FormatTest, RemoveBraces) {
25212   FormatStyle Style = getLLVMStyle();
25213   Style.RemoveBracesLLVM = true;
25214 
25215   // The following test cases are fully-braced versions of the examples at
25216   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
25217   // statement-bodies-of-if-else-loop-statements".
25218 
25219   // Omit the braces since the body is simple and clearly associated with the
25220   // `if`.
25221   verifyFormat("if (isa<FunctionDecl>(D))\n"
25222                "  handleFunctionDecl(D);\n"
25223                "else if (isa<VarDecl>(D))\n"
25224                "  handleVarDecl(D);",
25225                "if (isa<FunctionDecl>(D)) {\n"
25226                "  handleFunctionDecl(D);\n"
25227                "} else if (isa<VarDecl>(D)) {\n"
25228                "  handleVarDecl(D);\n"
25229                "}",
25230                Style);
25231 
25232   // Here we document the condition itself and not the body.
25233   verifyFormat("if (isa<VarDecl>(D)) {\n"
25234                "  // It is necessary that we explain the situation with this\n"
25235                "  // surprisingly long comment, so it would be unclear\n"
25236                "  // without the braces whether the following statement is in\n"
25237                "  // the scope of the `if`.\n"
25238                "  // Because the condition is documented, we can't really\n"
25239                "  // hoist this comment that applies to the body above the\n"
25240                "  // `if`.\n"
25241                "  handleOtherDecl(D);\n"
25242                "}",
25243                Style);
25244 
25245   // Use braces on the outer `if` to avoid a potential dangling `else`
25246   // situation.
25247   verifyFormat("if (isa<VarDecl>(D)) {\n"
25248                "  if (shouldProcessAttr(A))\n"
25249                "    handleAttr(A);\n"
25250                "}",
25251                "if (isa<VarDecl>(D)) {\n"
25252                "  if (shouldProcessAttr(A)) {\n"
25253                "    handleAttr(A);\n"
25254                "  }\n"
25255                "}",
25256                Style);
25257 
25258   // Use braces for the `if` block to keep it uniform with the `else` block.
25259   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25260                "  handleFunctionDecl(D);\n"
25261                "} else {\n"
25262                "  // In this `else` case, it is necessary that we explain the\n"
25263                "  // situation with this surprisingly long comment, so it\n"
25264                "  // would be unclear without the braces whether the\n"
25265                "  // following statement is in the scope of the `if`.\n"
25266                "  handleOtherDecl(D);\n"
25267                "}",
25268                Style);
25269 
25270   // This should also omit braces. The `for` loop contains only a single
25271   // statement, so it shouldn't have braces.  The `if` also only contains a
25272   // single simple statement (the `for` loop), so it also should omit braces.
25273   verifyFormat("if (isa<FunctionDecl>(D))\n"
25274                "  for (auto *A : D.attrs())\n"
25275                "    handleAttr(A);",
25276                "if (isa<FunctionDecl>(D)) {\n"
25277                "  for (auto *A : D.attrs()) {\n"
25278                "    handleAttr(A);\n"
25279                "  }\n"
25280                "}",
25281                Style);
25282 
25283   // Use braces for a `do-while` loop and its enclosing statement.
25284   verifyFormat("if (Tok->is(tok::l_brace)) {\n"
25285                "  do {\n"
25286                "    Tok = Tok->Next;\n"
25287                "  } while (Tok);\n"
25288                "}",
25289                Style);
25290 
25291   // Use braces for the outer `if` since the nested `for` is braced.
25292   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25293                "  for (auto *A : D.attrs()) {\n"
25294                "    // In this `for` loop body, it is necessary that we\n"
25295                "    // explain the situation with this surprisingly long\n"
25296                "    // comment, forcing braces on the `for` block.\n"
25297                "    handleAttr(A);\n"
25298                "  }\n"
25299                "}",
25300                Style);
25301 
25302   // Use braces on the outer block because there are more than two levels of
25303   // nesting.
25304   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25305                "  for (auto *A : D.attrs())\n"
25306                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
25307                "      handleAttrOnDecl(D, A, i);\n"
25308                "}",
25309                "if (isa<FunctionDecl>(D)) {\n"
25310                "  for (auto *A : D.attrs()) {\n"
25311                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
25312                "      handleAttrOnDecl(D, A, i);\n"
25313                "    }\n"
25314                "  }\n"
25315                "}",
25316                Style);
25317 
25318   // Use braces on the outer block because of a nested `if`; otherwise the
25319   // compiler would warn: `add explicit braces to avoid dangling else`
25320   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25321                "  if (shouldProcess(D))\n"
25322                "    handleVarDecl(D);\n"
25323                "  else\n"
25324                "    markAsIgnored(D);\n"
25325                "}",
25326                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25327                "  if (shouldProcess(D)) {\n"
25328                "    handleVarDecl(D);\n"
25329                "  } else {\n"
25330                "    markAsIgnored(D);\n"
25331                "  }\n"
25332                "}",
25333                Style);
25334 
25335   verifyFormat("// clang-format off\n"
25336                "// comment\n"
25337                "while (i > 0) { --i; }\n"
25338                "// clang-format on\n"
25339                "while (j < 0)\n"
25340                "  ++j;",
25341                "// clang-format off\n"
25342                "// comment\n"
25343                "while (i > 0) { --i; }\n"
25344                "// clang-format on\n"
25345                "while (j < 0) { ++j; }",
25346                Style);
25347 
25348   verifyFormat("if (a)\n"
25349                "  b; // comment\n"
25350                "else if (c)\n"
25351                "  d; /* comment */\n"
25352                "else\n"
25353                "  e;",
25354                "if (a) {\n"
25355                "  b; // comment\n"
25356                "} else if (c) {\n"
25357                "  d; /* comment */\n"
25358                "} else {\n"
25359                "  e;\n"
25360                "}",
25361                Style);
25362 
25363   verifyFormat("if (a) {\n"
25364                "  b;\n"
25365                "  c;\n"
25366                "} else if (d) {\n"
25367                "  e;\n"
25368                "}",
25369                Style);
25370 
25371   verifyFormat("if (a) {\n"
25372                "#undef NDEBUG\n"
25373                "  b;\n"
25374                "} else {\n"
25375                "  c;\n"
25376                "}",
25377                Style);
25378 
25379   verifyFormat("if (a) {\n"
25380                "  // comment\n"
25381                "} else if (b) {\n"
25382                "  c;\n"
25383                "}",
25384                Style);
25385 
25386   verifyFormat("if (a) {\n"
25387                "  b;\n"
25388                "} else {\n"
25389                "  { c; }\n"
25390                "}",
25391                Style);
25392 
25393   verifyFormat("if (a) {\n"
25394                "  if (b) // comment\n"
25395                "    c;\n"
25396                "} else if (d) {\n"
25397                "  e;\n"
25398                "}",
25399                "if (a) {\n"
25400                "  if (b) { // comment\n"
25401                "    c;\n"
25402                "  }\n"
25403                "} else if (d) {\n"
25404                "  e;\n"
25405                "}",
25406                Style);
25407 
25408   verifyFormat("if (a) {\n"
25409                "  if (b) {\n"
25410                "    c;\n"
25411                "    // comment\n"
25412                "  } else if (d) {\n"
25413                "    e;\n"
25414                "  }\n"
25415                "}",
25416                Style);
25417 
25418   verifyFormat("if (a) {\n"
25419                "  if (b)\n"
25420                "    c;\n"
25421                "}",
25422                "if (a) {\n"
25423                "  if (b) {\n"
25424                "    c;\n"
25425                "  }\n"
25426                "}",
25427                Style);
25428 
25429   verifyFormat("if (a)\n"
25430                "  if (b)\n"
25431                "    c;\n"
25432                "  else\n"
25433                "    d;\n"
25434                "else\n"
25435                "  e;",
25436                "if (a) {\n"
25437                "  if (b) {\n"
25438                "    c;\n"
25439                "  } else {\n"
25440                "    d;\n"
25441                "  }\n"
25442                "} else {\n"
25443                "  e;\n"
25444                "}",
25445                Style);
25446 
25447   verifyFormat("if (a) {\n"
25448                "  // comment\n"
25449                "  if (b)\n"
25450                "    c;\n"
25451                "  else if (d)\n"
25452                "    e;\n"
25453                "} else {\n"
25454                "  g;\n"
25455                "}",
25456                "if (a) {\n"
25457                "  // comment\n"
25458                "  if (b) {\n"
25459                "    c;\n"
25460                "  } else if (d) {\n"
25461                "    e;\n"
25462                "  }\n"
25463                "} else {\n"
25464                "  g;\n"
25465                "}",
25466                Style);
25467 
25468   verifyFormat("if (a)\n"
25469                "  b;\n"
25470                "else if (c)\n"
25471                "  d;\n"
25472                "else\n"
25473                "  e;",
25474                "if (a) {\n"
25475                "  b;\n"
25476                "} else {\n"
25477                "  if (c) {\n"
25478                "    d;\n"
25479                "  } else {\n"
25480                "    e;\n"
25481                "  }\n"
25482                "}",
25483                Style);
25484 
25485   verifyFormat("if (a) {\n"
25486                "  if (b)\n"
25487                "    c;\n"
25488                "  else if (d)\n"
25489                "    e;\n"
25490                "} else {\n"
25491                "  g;\n"
25492                "}",
25493                "if (a) {\n"
25494                "  if (b)\n"
25495                "    c;\n"
25496                "  else {\n"
25497                "    if (d)\n"
25498                "      e;\n"
25499                "  }\n"
25500                "} else {\n"
25501                "  g;\n"
25502                "}",
25503                Style);
25504 
25505   verifyFormat("if (isa<VarDecl>(D)) {\n"
25506                "  for (auto *A : D.attrs())\n"
25507                "    if (shouldProcessAttr(A))\n"
25508                "      handleAttr(A);\n"
25509                "}",
25510                "if (isa<VarDecl>(D)) {\n"
25511                "  for (auto *A : D.attrs()) {\n"
25512                "    if (shouldProcessAttr(A)) {\n"
25513                "      handleAttr(A);\n"
25514                "    }\n"
25515                "  }\n"
25516                "}",
25517                Style);
25518 
25519   verifyFormat("do {\n"
25520                "  ++I;\n"
25521                "} while (hasMore() && Filter(*I));",
25522                "do { ++I; } while (hasMore() && Filter(*I));", Style);
25523 
25524   verifyFormat("if (a)\n"
25525                "  if (b)\n"
25526                "    c;\n"
25527                "  else {\n"
25528                "    if (d)\n"
25529                "      e;\n"
25530                "  }\n"
25531                "else\n"
25532                "  f;",
25533                Style);
25534 
25535   verifyFormat("if (a)\n"
25536                "  if (b)\n"
25537                "    c;\n"
25538                "  else {\n"
25539                "    if (d)\n"
25540                "      e;\n"
25541                "    else if (f)\n"
25542                "      g;\n"
25543                "  }\n"
25544                "else\n"
25545                "  h;",
25546                Style);
25547 
25548   verifyFormat("if (a) {\n"
25549                "  b;\n"
25550                "} else if (c) {\n"
25551                "  d;\n"
25552                "  e;\n"
25553                "}",
25554                "if (a) {\n"
25555                "  b;\n"
25556                "} else {\n"
25557                "  if (c) {\n"
25558                "    d;\n"
25559                "    e;\n"
25560                "  }\n"
25561                "}",
25562                Style);
25563 
25564   verifyFormat("if (a) {\n"
25565                "  b;\n"
25566                "  c;\n"
25567                "} else if (d) {\n"
25568                "  e;\n"
25569                "  f;\n"
25570                "}",
25571                "if (a) {\n"
25572                "  b;\n"
25573                "  c;\n"
25574                "} else {\n"
25575                "  if (d) {\n"
25576                "    e;\n"
25577                "    f;\n"
25578                "  }\n"
25579                "}",
25580                Style);
25581 
25582   verifyFormat("if (a) {\n"
25583                "  b;\n"
25584                "} else if (c) {\n"
25585                "  d;\n"
25586                "} else {\n"
25587                "  e;\n"
25588                "  f;\n"
25589                "}",
25590                "if (a) {\n"
25591                "  b;\n"
25592                "} else {\n"
25593                "  if (c) {\n"
25594                "    d;\n"
25595                "  } else {\n"
25596                "    e;\n"
25597                "    f;\n"
25598                "  }\n"
25599                "}",
25600                Style);
25601 
25602   verifyFormat("if (a) {\n"
25603                "  b;\n"
25604                "} else if (c) {\n"
25605                "  d;\n"
25606                "} else if (e) {\n"
25607                "  f;\n"
25608                "  g;\n"
25609                "}",
25610                "if (a) {\n"
25611                "  b;\n"
25612                "} else {\n"
25613                "  if (c) {\n"
25614                "    d;\n"
25615                "  } else if (e) {\n"
25616                "    f;\n"
25617                "    g;\n"
25618                "  }\n"
25619                "}",
25620                Style);
25621 
25622   verifyFormat("if (a) {\n"
25623                "  if (b)\n"
25624                "    c;\n"
25625                "  else if (d) {\n"
25626                "    e;\n"
25627                "    f;\n"
25628                "  }\n"
25629                "} else {\n"
25630                "  g;\n"
25631                "}",
25632                "if (a) {\n"
25633                "  if (b)\n"
25634                "    c;\n"
25635                "  else {\n"
25636                "    if (d) {\n"
25637                "      e;\n"
25638                "      f;\n"
25639                "    }\n"
25640                "  }\n"
25641                "} else {\n"
25642                "  g;\n"
25643                "}",
25644                Style);
25645 
25646   verifyFormat("if (a)\n"
25647                "  if (b)\n"
25648                "    c;\n"
25649                "  else {\n"
25650                "    if (d) {\n"
25651                "      e;\n"
25652                "      f;\n"
25653                "    }\n"
25654                "  }\n"
25655                "else\n"
25656                "  g;",
25657                Style);
25658 
25659   verifyFormat("if (a) {\n"
25660                "  b;\n"
25661                "  c;\n"
25662                "} else { // comment\n"
25663                "  if (d) {\n"
25664                "    e;\n"
25665                "    f;\n"
25666                "  }\n"
25667                "}",
25668                Style);
25669 
25670   verifyFormat("if (a)\n"
25671                "  b;\n"
25672                "else if (c)\n"
25673                "  while (d)\n"
25674                "    e;\n"
25675                "// comment",
25676                "if (a)\n"
25677                "{\n"
25678                "  b;\n"
25679                "} else if (c) {\n"
25680                "  while (d) {\n"
25681                "    e;\n"
25682                "  }\n"
25683                "}\n"
25684                "// comment",
25685                Style);
25686 
25687   verifyFormat("if (a) {\n"
25688                "  b;\n"
25689                "} else if (c) {\n"
25690                "  d;\n"
25691                "} else {\n"
25692                "  e;\n"
25693                "  g;\n"
25694                "}",
25695                Style);
25696 
25697   verifyFormat("if (a) {\n"
25698                "  b;\n"
25699                "} else if (c) {\n"
25700                "  d;\n"
25701                "} else {\n"
25702                "  e;\n"
25703                "} // comment",
25704                Style);
25705 
25706   verifyFormat("int abs = [](int i) {\n"
25707                "  if (i >= 0)\n"
25708                "    return i;\n"
25709                "  return -i;\n"
25710                "};",
25711                "int abs = [](int i) {\n"
25712                "  if (i >= 0) {\n"
25713                "    return i;\n"
25714                "  }\n"
25715                "  return -i;\n"
25716                "};",
25717                Style);
25718 
25719   verifyFormat("if (a)\n"
25720                "  foo();\n"
25721                "else\n"
25722                "  bar();",
25723                "if (a)\n"
25724                "{\n"
25725                "  foo();\n"
25726                "}\n"
25727                "else\n"
25728                "{\n"
25729                "  bar();\n"
25730                "}",
25731                Style);
25732 
25733   verifyFormat("if (a)\n"
25734                "  foo();\n"
25735                "// comment\n"
25736                "else\n"
25737                "  bar();",
25738                "if (a) {\n"
25739                "  foo();\n"
25740                "}\n"
25741                "// comment\n"
25742                "else {\n"
25743                "  bar();\n"
25744                "}",
25745                Style);
25746 
25747   verifyFormat("if (a) {\n"
25748                "  if (b)\n"
25749                "    c = 1; // comment\n"
25750                "}",
25751                "if (a) {\n"
25752                "  if (b) {\n"
25753                "    c = 1; // comment\n"
25754                "  }\n"
25755                "}",
25756                Style);
25757 
25758   verifyFormat("if (a) {\n"
25759                "Label:\n"
25760                "}",
25761                Style);
25762 
25763   verifyFormat("if (a) {\n"
25764                "Label:\n"
25765                "  f();\n"
25766                "}",
25767                Style);
25768 
25769   verifyFormat("if (a) {\n"
25770                "  f();\n"
25771                "Label:\n"
25772                "}",
25773                Style);
25774 
25775   verifyFormat("if consteval {\n"
25776                "  f();\n"
25777                "} else {\n"
25778                "  g();\n"
25779                "}",
25780                Style);
25781 
25782   verifyFormat("if not consteval {\n"
25783                "  f();\n"
25784                "} else if (a) {\n"
25785                "  g();\n"
25786                "}",
25787                Style);
25788 
25789   verifyFormat("if !consteval {\n"
25790                "  g();\n"
25791                "}",
25792                Style);
25793 
25794   Style.ColumnLimit = 65;
25795   verifyFormat("if (condition) {\n"
25796                "  ff(Indices,\n"
25797                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25798                "} else {\n"
25799                "  ff(Indices,\n"
25800                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25801                "}",
25802                Style);
25803 
25804   Style.ColumnLimit = 20;
25805 
25806   verifyFormat("int ab = [](int i) {\n"
25807                "  if (i > 0) {\n"
25808                "    i = 12345678 -\n"
25809                "        i;\n"
25810                "  }\n"
25811                "  return i;\n"
25812                "};",
25813                Style);
25814 
25815   verifyFormat("if (a) {\n"
25816                "  b = c + // 1 -\n"
25817                "      d;\n"
25818                "}",
25819                Style);
25820 
25821   verifyFormat("if (a) {\n"
25822                "  b = c >= 0 ? d\n"
25823                "             : e;\n"
25824                "}",
25825                "if (a) {\n"
25826                "  b = c >= 0 ? d : e;\n"
25827                "}",
25828                Style);
25829 
25830   verifyFormat("if (a)\n"
25831                "  b = c > 0 ? d : e;",
25832                "if (a) {\n"
25833                "  b = c > 0 ? d : e;\n"
25834                "}",
25835                Style);
25836 
25837   verifyFormat("if (-b >=\n"
25838                "    c) { // Keep.\n"
25839                "  foo();\n"
25840                "} else {\n"
25841                "  bar();\n"
25842                "}",
25843                "if (-b >= c) { // Keep.\n"
25844                "  foo();\n"
25845                "} else {\n"
25846                "  bar();\n"
25847                "}",
25848                Style);
25849 
25850   verifyFormat("if (a) /* Remove. */\n"
25851                "  f();\n"
25852                "else\n"
25853                "  g();",
25854                "if (a) <% /* Remove. */\n"
25855                "  f();\n"
25856                "%> else <%\n"
25857                "  g();\n"
25858                "%>",
25859                Style);
25860 
25861   verifyFormat("while (\n"
25862                "    !i--) <% // Keep.\n"
25863                "  foo();\n"
25864                "%>",
25865                "while (!i--) <% // Keep.\n"
25866                "  foo();\n"
25867                "%>",
25868                Style);
25869 
25870   verifyFormat("for (int &i : chars)\n"
25871                "  ++i;",
25872                "for (int &i :\n"
25873                "     chars) {\n"
25874                "  ++i;\n"
25875                "}",
25876                Style);
25877 
25878   verifyFormat("if (a)\n"
25879                "  b;\n"
25880                "else if (c) {\n"
25881                "  d;\n"
25882                "  e;\n"
25883                "} else\n"
25884                "  f = g(foo, bar,\n"
25885                "        baz);",
25886                "if (a)\n"
25887                "  b;\n"
25888                "else {\n"
25889                "  if (c) {\n"
25890                "    d;\n"
25891                "    e;\n"
25892                "  } else\n"
25893                "    f = g(foo, bar, baz);\n"
25894                "}",
25895                Style);
25896 
25897   Style.ColumnLimit = 0;
25898   verifyFormat("if (a)\n"
25899                "  b234567890223456789032345678904234567890 = "
25900                "c234567890223456789032345678904234567890;",
25901                "if (a) {\n"
25902                "  b234567890223456789032345678904234567890 = "
25903                "c234567890223456789032345678904234567890;\n"
25904                "}",
25905                Style);
25906 
25907   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
25908   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
25909   Style.BraceWrapping.BeforeElse = true;
25910 
25911   Style.ColumnLimit = 65;
25912 
25913   verifyFormat("if (condition)\n"
25914                "{\n"
25915                "  ff(Indices,\n"
25916                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25917                "}\n"
25918                "else\n"
25919                "{\n"
25920                "  ff(Indices,\n"
25921                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25922                "}",
25923                "if (condition) {\n"
25924                "  ff(Indices,\n"
25925                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25926                "} else {\n"
25927                "  ff(Indices,\n"
25928                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25929                "}",
25930                Style);
25931 
25932   verifyFormat("if (a)\n"
25933                "{ //\n"
25934                "  foo();\n"
25935                "}",
25936                "if (a) { //\n"
25937                "  foo();\n"
25938                "}",
25939                Style);
25940 
25941   Style.ColumnLimit = 20;
25942 
25943   verifyFormat("int ab = [](int i) {\n"
25944                "  if (i > 0)\n"
25945                "  {\n"
25946                "    i = 12345678 -\n"
25947                "        i;\n"
25948                "  }\n"
25949                "  return i;\n"
25950                "};",
25951                "int ab = [](int i) {\n"
25952                "  if (i > 0) {\n"
25953                "    i = 12345678 -\n"
25954                "        i;\n"
25955                "  }\n"
25956                "  return i;\n"
25957                "};",
25958                Style);
25959 
25960   verifyFormat("if (a)\n"
25961                "{\n"
25962                "  b = c + // 1 -\n"
25963                "      d;\n"
25964                "}",
25965                "if (a) {\n"
25966                "  b = c + // 1 -\n"
25967                "      d;\n"
25968                "}",
25969                Style);
25970 
25971   verifyFormat("if (a)\n"
25972                "{\n"
25973                "  b = c >= 0 ? d\n"
25974                "             : e;\n"
25975                "}",
25976                "if (a) {\n"
25977                "  b = c >= 0 ? d : e;\n"
25978                "}",
25979                Style);
25980 
25981   verifyFormat("if (a)\n"
25982                "  b = c > 0 ? d : e;",
25983                "if (a)\n"
25984                "{\n"
25985                "  b = c > 0 ? d : e;\n"
25986                "}",
25987                Style);
25988 
25989   verifyFormat("if (foo + bar <=\n"
25990                "    baz)\n"
25991                "{\n"
25992                "  func(arg1, arg2);\n"
25993                "}",
25994                "if (foo + bar <= baz) {\n"
25995                "  func(arg1, arg2);\n"
25996                "}",
25997                Style);
25998 
25999   verifyFormat("if (foo + bar < baz)\n"
26000                "  func(arg1, arg2);\n"
26001                "else\n"
26002                "  func();",
26003                "if (foo + bar < baz)\n"
26004                "<%\n"
26005                "  func(arg1, arg2);\n"
26006                "%>\n"
26007                "else\n"
26008                "<%\n"
26009                "  func();\n"
26010                "%>",
26011                Style);
26012 
26013   verifyFormat("while (i--)\n"
26014                "<% // Keep.\n"
26015                "  foo();\n"
26016                "%>",
26017                "while (i--) <% // Keep.\n"
26018                "  foo();\n"
26019                "%>",
26020                Style);
26021 
26022   verifyFormat("for (int &i : chars)\n"
26023                "  ++i;",
26024                "for (int &i : chars)\n"
26025                "{\n"
26026                "  ++i;\n"
26027                "}",
26028                Style);
26029 }
26030 
26031 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
26032   auto Style = getLLVMStyle();
26033 
26034   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
26035                     "void functionDecl(int a, int b, int c);";
26036 
26037   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
26038                      "paramF, paramG, paramH, paramI);\n"
26039                      "void functionDecl(int argumentA, int argumentB, int "
26040                      "argumentC, int argumentD, int argumentE);";
26041 
26042   verifyFormat(Short, Style);
26043 
26044   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
26045                       "paramF, paramG, paramH,\n"
26046                       "             paramI);\n"
26047                       "void functionDecl(int argumentA, int argumentB, int "
26048                       "argumentC, int argumentD,\n"
26049                       "                  int argumentE);";
26050 
26051   verifyFormat(NoBreak, Medium, Style);
26052   verifyFormat(NoBreak,
26053                "functionCall(\n"
26054                "    paramA,\n"
26055                "    paramB,\n"
26056                "    paramC,\n"
26057                "    paramD,\n"
26058                "    paramE,\n"
26059                "    paramF,\n"
26060                "    paramG,\n"
26061                "    paramH,\n"
26062                "    paramI\n"
26063                ");\n"
26064                "void functionDecl(\n"
26065                "    int argumentA,\n"
26066                "    int argumentB,\n"
26067                "    int argumentC,\n"
26068                "    int argumentD,\n"
26069                "    int argumentE\n"
26070                ");",
26071                Style);
26072 
26073   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
26074                "                  nestedLongFunctionCall(argument1, "
26075                "argument2, argument3,\n"
26076                "                                         argument4, "
26077                "argument5));",
26078                Style);
26079 
26080   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
26081 
26082   verifyFormat(Short, Style);
26083   verifyFormat(
26084       "functionCall(\n"
26085       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
26086       "paramI\n"
26087       ");\n"
26088       "void functionDecl(\n"
26089       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
26090       "argumentE\n"
26091       ");",
26092       Medium, Style);
26093 
26094   Style.AllowAllArgumentsOnNextLine = false;
26095   Style.AllowAllParametersOfDeclarationOnNextLine = false;
26096 
26097   verifyFormat(Short, Style);
26098   verifyFormat(
26099       "functionCall(\n"
26100       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
26101       "paramI\n"
26102       ");\n"
26103       "void functionDecl(\n"
26104       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
26105       "argumentE\n"
26106       ");",
26107       Medium, Style);
26108 
26109   Style.BinPackArguments = false;
26110   Style.BinPackParameters = false;
26111 
26112   verifyFormat(Short, Style);
26113 
26114   verifyFormat("functionCall(\n"
26115                "    paramA,\n"
26116                "    paramB,\n"
26117                "    paramC,\n"
26118                "    paramD,\n"
26119                "    paramE,\n"
26120                "    paramF,\n"
26121                "    paramG,\n"
26122                "    paramH,\n"
26123                "    paramI\n"
26124                ");\n"
26125                "void functionDecl(\n"
26126                "    int argumentA,\n"
26127                "    int argumentB,\n"
26128                "    int argumentC,\n"
26129                "    int argumentD,\n"
26130                "    int argumentE\n"
26131                ");",
26132                Medium, Style);
26133 
26134   verifyFormat("outerFunctionCall(\n"
26135                "    nestedFunctionCall(argument1),\n"
26136                "    nestedLongFunctionCall(\n"
26137                "        argument1,\n"
26138                "        argument2,\n"
26139                "        argument3,\n"
26140                "        argument4,\n"
26141                "        argument5\n"
26142                "    )\n"
26143                ");",
26144                Style);
26145 
26146   verifyFormat("int a = (int)b;", Style);
26147   verifyFormat("int a = (int)b;",
26148                "int a = (\n"
26149                "    int\n"
26150                ") b;",
26151                Style);
26152 
26153   verifyFormat("return (true);", Style);
26154   verifyFormat("return (true);",
26155                "return (\n"
26156                "    true\n"
26157                ");",
26158                Style);
26159 
26160   verifyFormat("void foo();", Style);
26161   verifyFormat("void foo();",
26162                "void foo(\n"
26163                ");",
26164                Style);
26165 
26166   verifyFormat("void foo() {}", Style);
26167   verifyFormat("void foo() {}",
26168                "void foo(\n"
26169                ") {\n"
26170                "}",
26171                Style);
26172 
26173   verifyFormat("auto string = std::string();", Style);
26174   verifyFormat("auto string = std::string();",
26175                "auto string = std::string(\n"
26176                ");",
26177                Style);
26178 
26179   verifyFormat("void (*functionPointer)() = nullptr;", Style);
26180   verifyFormat("void (*functionPointer)() = nullptr;",
26181                "void (\n"
26182                "    *functionPointer\n"
26183                ")\n"
26184                "(\n"
26185                ") = nullptr;",
26186                Style);
26187 }
26188 
26189 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
26190   auto Style = getLLVMStyle();
26191 
26192   verifyFormat("if (foo()) {\n"
26193                "  return;\n"
26194                "}",
26195                Style);
26196 
26197   verifyFormat("if (quitelongarg !=\n"
26198                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
26199                "comment\n"
26200                "  return;\n"
26201                "}",
26202                Style);
26203 
26204   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
26205 
26206   verifyFormat("if (foo()) {\n"
26207                "  return;\n"
26208                "}",
26209                Style);
26210 
26211   verifyFormat("if (quitelongarg !=\n"
26212                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
26213                "comment\n"
26214                "  return;\n"
26215                "}",
26216                Style);
26217 }
26218 
26219 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
26220   auto Style = getLLVMStyle();
26221 
26222   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
26223                "  doSomething();\n"
26224                "}",
26225                Style);
26226 
26227   verifyFormat("for (int myReallyLongCountVariable = 0; "
26228                "myReallyLongCountVariable < count;\n"
26229                "     myReallyLongCountVariable++) {\n"
26230                "  doSomething();\n"
26231                "}",
26232                Style);
26233 
26234   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
26235 
26236   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
26237                "  doSomething();\n"
26238                "}",
26239                Style);
26240 
26241   verifyFormat("for (int myReallyLongCountVariable = 0; "
26242                "myReallyLongCountVariable < count;\n"
26243                "     myReallyLongCountVariable++) {\n"
26244                "  doSomething();\n"
26245                "}",
26246                Style);
26247 }
26248 
26249 TEST_F(FormatTest, UnderstandsDigraphs) {
26250   verifyFormat("int arr<:5:> = {};");
26251   verifyFormat("int arr[5] = <%%>;");
26252   verifyFormat("int arr<:::qualified_variable:> = {};");
26253   verifyFormat("int arr[::qualified_variable] = <%%>;");
26254   verifyFormat("%:include <header>");
26255   verifyFormat("%:define A x##y");
26256   verifyFormat("#define A x%:%:y");
26257 }
26258 
26259 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
26260   auto Style = getLLVMStyle();
26261   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
26262   Style.AlignConsecutiveAssignments.Enabled = true;
26263   Style.AlignConsecutiveDeclarations.Enabled = true;
26264 
26265   // The AlignArray code is incorrect for non square Arrays and can cause
26266   // crashes, these tests assert that the array is not changed but will
26267   // also act as regression tests for when it is properly fixed
26268   verifyFormat("struct test demo[] = {\n"
26269                "    {1, 2},\n"
26270                "    {3, 4, 5},\n"
26271                "    {6, 7, 8}\n"
26272                "};",
26273                Style);
26274   verifyFormat("struct test demo[] = {\n"
26275                "    {1, 2, 3, 4, 5},\n"
26276                "    {3, 4, 5},\n"
26277                "    {6, 7, 8}\n"
26278                "};",
26279                Style);
26280   verifyFormat("struct test demo[] = {\n"
26281                "    {1, 2, 3, 4, 5},\n"
26282                "    {3, 4, 5},\n"
26283                "    {6, 7, 8, 9, 10, 11, 12}\n"
26284                "};",
26285                Style);
26286   verifyFormat("struct test demo[] = {\n"
26287                "    {1, 2, 3},\n"
26288                "    {3, 4, 5},\n"
26289                "    {6, 7, 8, 9, 10, 11, 12}\n"
26290                "};",
26291                Style);
26292 
26293   verifyFormat("S{\n"
26294                "    {},\n"
26295                "    {},\n"
26296                "    {a, b}\n"
26297                "};",
26298                Style);
26299   verifyFormat("S{\n"
26300                "    {},\n"
26301                "    {},\n"
26302                "    {a, b},\n"
26303                "};",
26304                Style);
26305   verifyFormat("void foo() {\n"
26306                "  auto thing = test{\n"
26307                "      {\n"
26308                "       {13}, {something}, // A\n"
26309                "      }\n"
26310                "  };\n"
26311                "}",
26312                "void foo() {\n"
26313                "  auto thing = test{\n"
26314                "      {\n"
26315                "       {13},\n"
26316                "       {something}, // A\n"
26317                "      }\n"
26318                "  };\n"
26319                "}",
26320                Style);
26321 }
26322 
26323 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
26324   auto Style = getLLVMStyle();
26325   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
26326   Style.AlignConsecutiveAssignments.Enabled = true;
26327   Style.AlignConsecutiveDeclarations.Enabled = true;
26328 
26329   // The AlignArray code is incorrect for non square Arrays and can cause
26330   // crashes, these tests assert that the array is not changed but will
26331   // also act as regression tests for when it is properly fixed
26332   verifyFormat("struct test demo[] = {\n"
26333                "    {1, 2},\n"
26334                "    {3, 4, 5},\n"
26335                "    {6, 7, 8}\n"
26336                "};",
26337                Style);
26338   verifyFormat("struct test demo[] = {\n"
26339                "    {1, 2, 3, 4, 5},\n"
26340                "    {3, 4, 5},\n"
26341                "    {6, 7, 8}\n"
26342                "};",
26343                Style);
26344   verifyFormat("struct test demo[] = {\n"
26345                "    {1, 2, 3, 4, 5},\n"
26346                "    {3, 4, 5},\n"
26347                "    {6, 7, 8, 9, 10, 11, 12}\n"
26348                "};",
26349                Style);
26350   verifyFormat("struct test demo[] = {\n"
26351                "    {1, 2, 3},\n"
26352                "    {3, 4, 5},\n"
26353                "    {6, 7, 8, 9, 10, 11, 12}\n"
26354                "};",
26355                Style);
26356 
26357   verifyFormat("S{\n"
26358                "    {},\n"
26359                "    {},\n"
26360                "    {a, b}\n"
26361                "};",
26362                Style);
26363   verifyFormat("S{\n"
26364                "    {},\n"
26365                "    {},\n"
26366                "    {a, b},\n"
26367                "};",
26368                Style);
26369   verifyFormat("void foo() {\n"
26370                "  auto thing = test{\n"
26371                "      {\n"
26372                "       {13}, {something}, // A\n"
26373                "      }\n"
26374                "  };\n"
26375                "}",
26376                "void foo() {\n"
26377                "  auto thing = test{\n"
26378                "      {\n"
26379                "       {13},\n"
26380                "       {something}, // A\n"
26381                "      }\n"
26382                "  };\n"
26383                "}",
26384                Style);
26385 }
26386 
26387 TEST_F(FormatTest, FormatsVariableTemplates) {
26388   verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
26389   verifyFormat("template <typename T> "
26390                "inline bool var = is_integral_v<T> && is_signed_v<T>;");
26391 }
26392 
26393 } // namespace
26394 } // namespace format
26395 } // namespace clang
26396