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   EXPECT_EQ("if (foo && bar &&\n"
3100             "    baz)\n"
3101             "{\n"
3102             "  quux();\n"
3103             "}",
3104             format("if(foo&&bar&&baz){quux();}", Style));
3105   EXPECT_EQ("if (foo && bar &&\n"
3106             "    baz)\n"
3107             "{\n"
3108             "  quux();\n"
3109             "}",
3110             format("if (foo && bar &&\n"
3111                    "    baz) {\n"
3112                    "  quux();\n"
3113                    "}",
3114                    Style));
3115   EXPECT_EQ("if (foo) {\n"
3116             "  bar();\n"
3117             "} else if (baz ||\n"
3118             "           quux)\n"
3119             "{\n"
3120             "  foobar();\n"
3121             "}",
3122             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
3123   EXPECT_EQ(
3124       "if (foo) {\n"
3125       "  bar();\n"
3126       "} else if (baz ||\n"
3127       "           quux)\n"
3128       "{\n"
3129       "  foobar();\n"
3130       "} else {\n"
3131       "  barbaz();\n"
3132       "}",
3133       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3134              Style));
3135   EXPECT_EQ("for (int i = 0;\n"
3136             "     i < 10; ++i)\n"
3137             "{\n"
3138             "  foo();\n"
3139             "}",
3140             format("for(int i=0;i<10;++i){foo();}", Style));
3141   EXPECT_EQ("foreach (int i,\n"
3142             "         list)\n"
3143             "{\n"
3144             "  foo();\n"
3145             "}",
3146             format("foreach(int i, list){foo();}", Style));
3147   Style.ColumnLimit =
3148       40; // to concentrate at brace wrapping, not line wrap due to column limit
3149   EXPECT_EQ("foreach (int i, list) {\n"
3150             "  foo();\n"
3151             "}",
3152             format("foreach(int i, list){foo();}", Style));
3153   Style.ColumnLimit =
3154       20; // to concentrate at brace wrapping, not line wrap due to column limit
3155   EXPECT_EQ("while (foo || bar ||\n"
3156             "       baz)\n"
3157             "{\n"
3158             "  quux();\n"
3159             "}",
3160             format("while(foo||bar||baz){quux();}", Style));
3161   EXPECT_EQ("switch (\n"
3162             "    foo = barbaz)\n"
3163             "{\n"
3164             "case quux:\n"
3165             "  return;\n"
3166             "}",
3167             format("switch(foo=barbaz){case quux:return;}", Style));
3168   EXPECT_EQ("try {\n"
3169             "  foo();\n"
3170             "} catch (\n"
3171             "    Exception &bar)\n"
3172             "{\n"
3173             "  baz();\n"
3174             "}",
3175             format("try{foo();}catch(Exception&bar){baz();}", Style));
3176   Style.ColumnLimit =
3177       40; // to concentrate at brace wrapping, not line wrap due to column limit
3178   EXPECT_EQ("try {\n"
3179             "  foo();\n"
3180             "} catch (Exception &bar) {\n"
3181             "  baz();\n"
3182             "}",
3183             format("try{foo();}catch(Exception&bar){baz();}", Style));
3184   Style.ColumnLimit =
3185       20; // to concentrate at brace wrapping, not line wrap due to column limit
3186 
3187   Style.BraceWrapping.BeforeElse = true;
3188   EXPECT_EQ(
3189       "if (foo) {\n"
3190       "  bar();\n"
3191       "}\n"
3192       "else if (baz ||\n"
3193       "         quux)\n"
3194       "{\n"
3195       "  foobar();\n"
3196       "}\n"
3197       "else {\n"
3198       "  barbaz();\n"
3199       "}",
3200       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3201              Style));
3202 
3203   Style.BraceWrapping.BeforeCatch = true;
3204   EXPECT_EQ("try {\n"
3205             "  foo();\n"
3206             "}\n"
3207             "catch (...) {\n"
3208             "  baz();\n"
3209             "}",
3210             format("try{foo();}catch(...){baz();}", Style));
3211 
3212   Style.BraceWrapping.AfterFunction = true;
3213   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3214   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
3215   Style.ColumnLimit = 80;
3216   verifyFormat("void shortfunction() { bar(); }", Style);
3217 
3218   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
3219   verifyFormat("void shortfunction()\n"
3220                "{\n"
3221                "  bar();\n"
3222                "}",
3223                Style);
3224 }
3225 
3226 TEST_F(FormatTest, BeforeWhile) {
3227   FormatStyle Style = getLLVMStyle();
3228   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3229 
3230   verifyFormat("do {\n"
3231                "  foo();\n"
3232                "} while (1);",
3233                Style);
3234   Style.BraceWrapping.BeforeWhile = true;
3235   verifyFormat("do {\n"
3236                "  foo();\n"
3237                "}\n"
3238                "while (1);",
3239                Style);
3240 }
3241 
3242 //===----------------------------------------------------------------------===//
3243 // Tests for classes, namespaces, etc.
3244 //===----------------------------------------------------------------------===//
3245 
3246 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
3247   verifyFormat("class A {};");
3248 }
3249 
3250 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
3251   verifyFormat("class A {\n"
3252                "public:\n"
3253                "public: // comment\n"
3254                "protected:\n"
3255                "private:\n"
3256                "  void f() {}\n"
3257                "};");
3258   verifyFormat("export class A {\n"
3259                "public:\n"
3260                "public: // comment\n"
3261                "protected:\n"
3262                "private:\n"
3263                "  void f() {}\n"
3264                "};");
3265   verifyGoogleFormat("class A {\n"
3266                      " public:\n"
3267                      " protected:\n"
3268                      " private:\n"
3269                      "  void f() {}\n"
3270                      "};");
3271   verifyGoogleFormat("export class A {\n"
3272                      " public:\n"
3273                      " protected:\n"
3274                      " private:\n"
3275                      "  void f() {}\n"
3276                      "};");
3277   verifyFormat("class A {\n"
3278                "public slots:\n"
3279                "  void f1() {}\n"
3280                "public Q_SLOTS:\n"
3281                "  void f2() {}\n"
3282                "protected slots:\n"
3283                "  void f3() {}\n"
3284                "protected Q_SLOTS:\n"
3285                "  void f4() {}\n"
3286                "private slots:\n"
3287                "  void f5() {}\n"
3288                "private Q_SLOTS:\n"
3289                "  void f6() {}\n"
3290                "signals:\n"
3291                "  void g1();\n"
3292                "Q_SIGNALS:\n"
3293                "  void g2();\n"
3294                "};");
3295 
3296   // Don't interpret 'signals' the wrong way.
3297   verifyFormat("signals.set();");
3298   verifyFormat("for (Signals signals : f()) {\n}");
3299   verifyFormat("{\n"
3300                "  signals.set(); // This needs indentation.\n"
3301                "}");
3302   verifyFormat("void f() {\n"
3303                "label:\n"
3304                "  signals.baz();\n"
3305                "}");
3306   verifyFormat("private[1];");
3307   verifyFormat("testArray[public] = 1;");
3308   verifyFormat("public();");
3309   verifyFormat("myFunc(public);");
3310   verifyFormat("std::vector<int> testVec = {private};");
3311   verifyFormat("private.p = 1;");
3312   verifyFormat("void function(private...){};");
3313   verifyFormat("if (private && public)\n");
3314   verifyFormat("private &= true;");
3315   verifyFormat("int x = private * public;");
3316   verifyFormat("public *= private;");
3317   verifyFormat("int x = public + private;");
3318   verifyFormat("private++;");
3319   verifyFormat("++private;");
3320   verifyFormat("public += private;");
3321   verifyFormat("public = public - private;");
3322   verifyFormat("public->foo();");
3323   verifyFormat("private--;");
3324   verifyFormat("--private;");
3325   verifyFormat("public -= 1;");
3326   verifyFormat("if (!private && !public)\n");
3327   verifyFormat("public != private;");
3328   verifyFormat("int x = public / private;");
3329   verifyFormat("public /= 2;");
3330   verifyFormat("public = public % 2;");
3331   verifyFormat("public %= 2;");
3332   verifyFormat("if (public < private)\n");
3333   verifyFormat("public << private;");
3334   verifyFormat("public <<= private;");
3335   verifyFormat("if (public > private)\n");
3336   verifyFormat("public >> private;");
3337   verifyFormat("public >>= private;");
3338   verifyFormat("public ^ private;");
3339   verifyFormat("public ^= private;");
3340   verifyFormat("public | private;");
3341   verifyFormat("public |= private;");
3342   verifyFormat("auto x = private ? 1 : 2;");
3343   verifyFormat("if (public == private)\n");
3344   verifyFormat("void foo(public, private)");
3345   verifyFormat("public::foo();");
3346 
3347   verifyFormat("class A {\n"
3348                "public:\n"
3349                "  std::unique_ptr<int *[]> b() { return nullptr; }\n"
3350                "\n"
3351                "private:\n"
3352                "  int c;\n"
3353                "};");
3354 }
3355 
3356 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3357   EXPECT_EQ("class A {\n"
3358             "public:\n"
3359             "  void f();\n"
3360             "\n"
3361             "private:\n"
3362             "  void g() {}\n"
3363             "  // test\n"
3364             "protected:\n"
3365             "  int h;\n"
3366             "};",
3367             format("class A {\n"
3368                    "public:\n"
3369                    "void f();\n"
3370                    "private:\n"
3371                    "void g() {}\n"
3372                    "// test\n"
3373                    "protected:\n"
3374                    "int h;\n"
3375                    "};"));
3376   EXPECT_EQ("class A {\n"
3377             "protected:\n"
3378             "public:\n"
3379             "  void f();\n"
3380             "};",
3381             format("class A {\n"
3382                    "protected:\n"
3383                    "\n"
3384                    "public:\n"
3385                    "\n"
3386                    "  void f();\n"
3387                    "};"));
3388 
3389   // Even ensure proper spacing inside macros.
3390   EXPECT_EQ("#define B     \\\n"
3391             "  class A {   \\\n"
3392             "   protected: \\\n"
3393             "   public:    \\\n"
3394             "    void f(); \\\n"
3395             "  };",
3396             format("#define B     \\\n"
3397                    "  class A {   \\\n"
3398                    "   protected: \\\n"
3399                    "              \\\n"
3400                    "   public:    \\\n"
3401                    "              \\\n"
3402                    "    void f(); \\\n"
3403                    "  };",
3404                    getGoogleStyle()));
3405   // But don't remove empty lines after macros ending in access specifiers.
3406   EXPECT_EQ("#define A private:\n"
3407             "\n"
3408             "int i;",
3409             format("#define A         private:\n"
3410                    "\n"
3411                    "int              i;"));
3412 }
3413 
3414 TEST_F(FormatTest, FormatsClasses) {
3415   verifyFormat("class A : public B {};");
3416   verifyFormat("class A : public ::B {};");
3417 
3418   verifyFormat(
3419       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3420       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3421   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3422                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3423                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3424   verifyFormat(
3425       "class A : public B, public C, public D, public E, public F {};");
3426   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3427                "                     public C,\n"
3428                "                     public D,\n"
3429                "                     public E,\n"
3430                "                     public F,\n"
3431                "                     public G {};");
3432 
3433   verifyFormat("class\n"
3434                "    ReallyReallyLongClassName {\n"
3435                "  int i;\n"
3436                "};",
3437                getLLVMStyleWithColumns(32));
3438   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3439                "                           aaaaaaaaaaaaaaaa> {};");
3440   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3441                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3442                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3443   verifyFormat("template <class R, class C>\n"
3444                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3445                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3446   verifyFormat("class ::A::B {};");
3447 }
3448 
3449 TEST_F(FormatTest, BreakInheritanceStyle) {
3450   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3451   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3452       FormatStyle::BILS_BeforeComma;
3453   verifyFormat("class MyClass : public X {};",
3454                StyleWithInheritanceBreakBeforeComma);
3455   verifyFormat("class MyClass\n"
3456                "    : public X\n"
3457                "    , public Y {};",
3458                StyleWithInheritanceBreakBeforeComma);
3459   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3460                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3461                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3462                StyleWithInheritanceBreakBeforeComma);
3463   verifyFormat("struct aaaaaaaaaaaaa\n"
3464                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3465                "          aaaaaaaaaaaaaaaa> {};",
3466                StyleWithInheritanceBreakBeforeComma);
3467 
3468   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3469   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3470       FormatStyle::BILS_AfterColon;
3471   verifyFormat("class MyClass : public X {};",
3472                StyleWithInheritanceBreakAfterColon);
3473   verifyFormat("class MyClass : public X, public Y {};",
3474                StyleWithInheritanceBreakAfterColon);
3475   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3476                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3477                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3478                StyleWithInheritanceBreakAfterColon);
3479   verifyFormat("struct aaaaaaaaaaaaa :\n"
3480                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3481                "        aaaaaaaaaaaaaaaa> {};",
3482                StyleWithInheritanceBreakAfterColon);
3483 
3484   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3485   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3486       FormatStyle::BILS_AfterComma;
3487   verifyFormat("class MyClass : public X {};",
3488                StyleWithInheritanceBreakAfterComma);
3489   verifyFormat("class MyClass : public X,\n"
3490                "                public Y {};",
3491                StyleWithInheritanceBreakAfterComma);
3492   verifyFormat(
3493       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3494       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3495       "{};",
3496       StyleWithInheritanceBreakAfterComma);
3497   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3498                "                           aaaaaaaaaaaaaaaa> {};",
3499                StyleWithInheritanceBreakAfterComma);
3500   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3501                "    : public OnceBreak,\n"
3502                "      public AlwaysBreak,\n"
3503                "      EvenBasesFitInOneLine {};",
3504                StyleWithInheritanceBreakAfterComma);
3505 }
3506 
3507 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) {
3508   verifyFormat("class A {\n} a, b;");
3509   verifyFormat("struct A {\n} a, b;");
3510   verifyFormat("union A {\n} a, b;");
3511 
3512   verifyFormat("constexpr class A {\n} a, b;");
3513   verifyFormat("constexpr struct A {\n} a, b;");
3514   verifyFormat("constexpr union A {\n} a, b;");
3515 
3516   verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace");
3517   verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace");
3518   verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace");
3519 
3520   verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace");
3521   verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace");
3522   verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace");
3523 
3524   verifyFormat("namespace ns {\n"
3525                "class {\n"
3526                "} a, b;\n"
3527                "} // namespace ns");
3528   verifyFormat("namespace ns {\n"
3529                "const class {\n"
3530                "} a, b;\n"
3531                "} // namespace ns");
3532   verifyFormat("namespace ns {\n"
3533                "constexpr class C {\n"
3534                "} a, b;\n"
3535                "} // namespace ns");
3536   verifyFormat("namespace ns {\n"
3537                "class { /* comment */\n"
3538                "} a, b;\n"
3539                "} // namespace ns");
3540   verifyFormat("namespace ns {\n"
3541                "const class { /* comment */\n"
3542                "} a, b;\n"
3543                "} // namespace ns");
3544 }
3545 
3546 TEST_F(FormatTest, FormatsEnum) {
3547   verifyFormat("enum {\n"
3548                "  Zero,\n"
3549                "  One = 1,\n"
3550                "  Two = One + 1,\n"
3551                "  Three = (One + Two),\n"
3552                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3553                "  Five = (One, Two, Three, Four, 5)\n"
3554                "};");
3555   verifyGoogleFormat("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   verifyFormat("enum Enum {};");
3564   verifyFormat("enum {};");
3565   verifyFormat("enum X E {} d;");
3566   verifyFormat("enum __attribute__((...)) E {} d;");
3567   verifyFormat("enum __declspec__((...)) E {} d;");
3568   verifyFormat("enum {\n"
3569                "  Bar = Foo<int, int>::value\n"
3570                "};",
3571                getLLVMStyleWithColumns(30));
3572 
3573   verifyFormat("enum ShortEnum { A, B, C };");
3574   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3575 
3576   EXPECT_EQ("enum KeepEmptyLines {\n"
3577             "  ONE,\n"
3578             "\n"
3579             "  TWO,\n"
3580             "\n"
3581             "  THREE\n"
3582             "}",
3583             format("enum KeepEmptyLines {\n"
3584                    "  ONE,\n"
3585                    "\n"
3586                    "  TWO,\n"
3587                    "\n"
3588                    "\n"
3589                    "  THREE\n"
3590                    "}"));
3591   verifyFormat("enum E { // comment\n"
3592                "  ONE,\n"
3593                "  TWO\n"
3594                "};\n"
3595                "int i;");
3596 
3597   FormatStyle EightIndent = getLLVMStyle();
3598   EightIndent.IndentWidth = 8;
3599   verifyFormat("enum {\n"
3600                "        VOID,\n"
3601                "        CHAR,\n"
3602                "        SHORT,\n"
3603                "        INT,\n"
3604                "        LONG,\n"
3605                "        SIGNED,\n"
3606                "        UNSIGNED,\n"
3607                "        BOOL,\n"
3608                "        FLOAT,\n"
3609                "        DOUBLE,\n"
3610                "        COMPLEX\n"
3611                "};",
3612                EightIndent);
3613 
3614   // Not enums.
3615   verifyFormat("enum X f() {\n"
3616                "  a();\n"
3617                "  return 42;\n"
3618                "}");
3619   verifyFormat("enum X Type::f() {\n"
3620                "  a();\n"
3621                "  return 42;\n"
3622                "}");
3623   verifyFormat("enum ::X f() {\n"
3624                "  a();\n"
3625                "  return 42;\n"
3626                "}");
3627   verifyFormat("enum ns::X f() {\n"
3628                "  a();\n"
3629                "  return 42;\n"
3630                "}");
3631 }
3632 
3633 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3634   verifyFormat("enum Type {\n"
3635                "  One = 0; // These semicolons should be commas.\n"
3636                "  Two = 1;\n"
3637                "};");
3638   verifyFormat("namespace n {\n"
3639                "enum Type {\n"
3640                "  One,\n"
3641                "  Two, // missing };\n"
3642                "  int i;\n"
3643                "}\n"
3644                "void g() {}");
3645 }
3646 
3647 TEST_F(FormatTest, FormatsEnumStruct) {
3648   verifyFormat("enum struct {\n"
3649                "  Zero,\n"
3650                "  One = 1,\n"
3651                "  Two = One + 1,\n"
3652                "  Three = (One + Two),\n"
3653                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3654                "  Five = (One, Two, Three, Four, 5)\n"
3655                "};");
3656   verifyFormat("enum struct Enum {};");
3657   verifyFormat("enum struct {};");
3658   verifyFormat("enum struct X E {} d;");
3659   verifyFormat("enum struct __attribute__((...)) E {} d;");
3660   verifyFormat("enum struct __declspec__((...)) E {} d;");
3661   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3662 }
3663 
3664 TEST_F(FormatTest, FormatsEnumClass) {
3665   verifyFormat("enum class {\n"
3666                "  Zero,\n"
3667                "  One = 1,\n"
3668                "  Two = One + 1,\n"
3669                "  Three = (One + Two),\n"
3670                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3671                "  Five = (One, Two, Three, Four, 5)\n"
3672                "};");
3673   verifyFormat("enum class Enum {};");
3674   verifyFormat("enum class {};");
3675   verifyFormat("enum class X E {} d;");
3676   verifyFormat("enum class __attribute__((...)) E {} d;");
3677   verifyFormat("enum class __declspec__((...)) E {} d;");
3678   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3679 }
3680 
3681 TEST_F(FormatTest, FormatsEnumTypes) {
3682   verifyFormat("enum X : int {\n"
3683                "  A, // Force multiple lines.\n"
3684                "  B\n"
3685                "};");
3686   verifyFormat("enum X : int { A, B };");
3687   verifyFormat("enum X : std::uint32_t { A, B };");
3688 }
3689 
3690 TEST_F(FormatTest, FormatsTypedefEnum) {
3691   FormatStyle Style = getLLVMStyleWithColumns(40);
3692   verifyFormat("typedef enum {} EmptyEnum;");
3693   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3694   verifyFormat("typedef enum {\n"
3695                "  ZERO = 0,\n"
3696                "  ONE = 1,\n"
3697                "  TWO = 2,\n"
3698                "  THREE = 3\n"
3699                "} LongEnum;",
3700                Style);
3701   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3702   Style.BraceWrapping.AfterEnum = true;
3703   verifyFormat("typedef enum {} EmptyEnum;");
3704   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3705   verifyFormat("typedef enum\n"
3706                "{\n"
3707                "  ZERO = 0,\n"
3708                "  ONE = 1,\n"
3709                "  TWO = 2,\n"
3710                "  THREE = 3\n"
3711                "} LongEnum;",
3712                Style);
3713 }
3714 
3715 TEST_F(FormatTest, FormatsNSEnums) {
3716   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3717   verifyGoogleFormat(
3718       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3719   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3720                      "  // Information about someDecentlyLongValue.\n"
3721                      "  someDecentlyLongValue,\n"
3722                      "  // Information about anotherDecentlyLongValue.\n"
3723                      "  anotherDecentlyLongValue,\n"
3724                      "  // Information about aThirdDecentlyLongValue.\n"
3725                      "  aThirdDecentlyLongValue\n"
3726                      "};");
3727   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3728                      "  // Information about someDecentlyLongValue.\n"
3729                      "  someDecentlyLongValue,\n"
3730                      "  // Information about anotherDecentlyLongValue.\n"
3731                      "  anotherDecentlyLongValue,\n"
3732                      "  // Information about aThirdDecentlyLongValue.\n"
3733                      "  aThirdDecentlyLongValue\n"
3734                      "};");
3735   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3736                      "  a = 1,\n"
3737                      "  b = 2,\n"
3738                      "  c = 3,\n"
3739                      "};");
3740   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3741                      "  a = 1,\n"
3742                      "  b = 2,\n"
3743                      "  c = 3,\n"
3744                      "};");
3745   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3746                      "  a = 1,\n"
3747                      "  b = 2,\n"
3748                      "  c = 3,\n"
3749                      "};");
3750   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3751                      "  a = 1,\n"
3752                      "  b = 2,\n"
3753                      "  c = 3,\n"
3754                      "};");
3755 }
3756 
3757 TEST_F(FormatTest, FormatsBitfields) {
3758   verifyFormat("struct Bitfields {\n"
3759                "  unsigned sClass : 8;\n"
3760                "  unsigned ValueKind : 2;\n"
3761                "};");
3762   verifyFormat("struct A {\n"
3763                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3764                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3765                "};");
3766   verifyFormat("struct MyStruct {\n"
3767                "  uchar data;\n"
3768                "  uchar : 8;\n"
3769                "  uchar : 8;\n"
3770                "  uchar other;\n"
3771                "};");
3772   FormatStyle Style = getLLVMStyle();
3773   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3774   verifyFormat("struct Bitfields {\n"
3775                "  unsigned sClass:8;\n"
3776                "  unsigned ValueKind:2;\n"
3777                "  uchar other;\n"
3778                "};",
3779                Style);
3780   verifyFormat("struct A {\n"
3781                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3782                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3783                "};",
3784                Style);
3785   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3786   verifyFormat("struct Bitfields {\n"
3787                "  unsigned sClass :8;\n"
3788                "  unsigned ValueKind :2;\n"
3789                "  uchar other;\n"
3790                "};",
3791                Style);
3792   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3793   verifyFormat("struct Bitfields {\n"
3794                "  unsigned sClass: 8;\n"
3795                "  unsigned ValueKind: 2;\n"
3796                "  uchar other;\n"
3797                "};",
3798                Style);
3799 }
3800 
3801 TEST_F(FormatTest, FormatsNamespaces) {
3802   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3803   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3804 
3805   verifyFormat("namespace some_namespace {\n"
3806                "class A {};\n"
3807                "void f() { f(); }\n"
3808                "}",
3809                LLVMWithNoNamespaceFix);
3810   verifyFormat("#define M(x) x##x\n"
3811                "namespace M(x) {\n"
3812                "class A {};\n"
3813                "void f() { f(); }\n"
3814                "}",
3815                LLVMWithNoNamespaceFix);
3816   verifyFormat("#define M(x) x##x\n"
3817                "namespace N::inline M(x) {\n"
3818                "class A {};\n"
3819                "void f() { f(); }\n"
3820                "}",
3821                LLVMWithNoNamespaceFix);
3822   verifyFormat("#define M(x) x##x\n"
3823                "namespace M(x)::inline N {\n"
3824                "class A {};\n"
3825                "void f() { f(); }\n"
3826                "}",
3827                LLVMWithNoNamespaceFix);
3828   verifyFormat("#define M(x) x##x\n"
3829                "namespace N::M(x) {\n"
3830                "class A {};\n"
3831                "void f() { f(); }\n"
3832                "}",
3833                LLVMWithNoNamespaceFix);
3834   verifyFormat("#define M(x) x##x\n"
3835                "namespace M::N(x) {\n"
3836                "class A {};\n"
3837                "void f() { f(); }\n"
3838                "}",
3839                LLVMWithNoNamespaceFix);
3840   verifyFormat("namespace N::inline D {\n"
3841                "class A {};\n"
3842                "void f() { f(); }\n"
3843                "}",
3844                LLVMWithNoNamespaceFix);
3845   verifyFormat("namespace N::inline D::E {\n"
3846                "class A {};\n"
3847                "void f() { f(); }\n"
3848                "}",
3849                LLVMWithNoNamespaceFix);
3850   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3851                "class A {};\n"
3852                "void f() { f(); }\n"
3853                "}",
3854                LLVMWithNoNamespaceFix);
3855   verifyFormat("/* something */ namespace some_namespace {\n"
3856                "class A {};\n"
3857                "void f() { f(); }\n"
3858                "}",
3859                LLVMWithNoNamespaceFix);
3860   verifyFormat("namespace {\n"
3861                "class A {};\n"
3862                "void f() { f(); }\n"
3863                "}",
3864                LLVMWithNoNamespaceFix);
3865   verifyFormat("/* something */ namespace {\n"
3866                "class A {};\n"
3867                "void f() { f(); }\n"
3868                "}",
3869                LLVMWithNoNamespaceFix);
3870   verifyFormat("inline namespace X {\n"
3871                "class A {};\n"
3872                "void f() { f(); }\n"
3873                "}",
3874                LLVMWithNoNamespaceFix);
3875   verifyFormat("/* something */ inline namespace X {\n"
3876                "class A {};\n"
3877                "void f() { f(); }\n"
3878                "}",
3879                LLVMWithNoNamespaceFix);
3880   verifyFormat("export namespace X {\n"
3881                "class A {};\n"
3882                "void f() { f(); }\n"
3883                "}",
3884                LLVMWithNoNamespaceFix);
3885   verifyFormat("using namespace some_namespace;\n"
3886                "class A {};\n"
3887                "void f() { f(); }",
3888                LLVMWithNoNamespaceFix);
3889 
3890   // This code is more common than we thought; if we
3891   // layout this correctly the semicolon will go into
3892   // its own line, which is undesirable.
3893   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3894   verifyFormat("namespace {\n"
3895                "class A {};\n"
3896                "};",
3897                LLVMWithNoNamespaceFix);
3898 
3899   verifyFormat("namespace {\n"
3900                "int SomeVariable = 0; // comment\n"
3901                "} // namespace",
3902                LLVMWithNoNamespaceFix);
3903   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3904             "#define HEADER_GUARD\n"
3905             "namespace my_namespace {\n"
3906             "int i;\n"
3907             "} // my_namespace\n"
3908             "#endif // HEADER_GUARD",
3909             format("#ifndef HEADER_GUARD\n"
3910                    " #define HEADER_GUARD\n"
3911                    "   namespace my_namespace {\n"
3912                    "int i;\n"
3913                    "}    // my_namespace\n"
3914                    "#endif    // HEADER_GUARD",
3915                    LLVMWithNoNamespaceFix));
3916 
3917   EXPECT_EQ("namespace A::B {\n"
3918             "class C {};\n"
3919             "}",
3920             format("namespace A::B {\n"
3921                    "class C {};\n"
3922                    "}",
3923                    LLVMWithNoNamespaceFix));
3924 
3925   FormatStyle Style = getLLVMStyle();
3926   Style.NamespaceIndentation = FormatStyle::NI_All;
3927   EXPECT_EQ("namespace out {\n"
3928             "  int i;\n"
3929             "  namespace in {\n"
3930             "    int i;\n"
3931             "  } // namespace in\n"
3932             "} // namespace out",
3933             format("namespace out {\n"
3934                    "int i;\n"
3935                    "namespace in {\n"
3936                    "int i;\n"
3937                    "} // namespace in\n"
3938                    "} // namespace out",
3939                    Style));
3940 
3941   FormatStyle ShortInlineFunctions = getLLVMStyle();
3942   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3943   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3944       FormatStyle::SFS_Inline;
3945   verifyFormat("namespace {\n"
3946                "  void f() {\n"
3947                "    return;\n"
3948                "  }\n"
3949                "} // namespace\n",
3950                ShortInlineFunctions);
3951   verifyFormat("namespace { /* comment */\n"
3952                "  void f() {\n"
3953                "    return;\n"
3954                "  }\n"
3955                "} // namespace\n",
3956                ShortInlineFunctions);
3957   verifyFormat("namespace { // comment\n"
3958                "  void f() {\n"
3959                "    return;\n"
3960                "  }\n"
3961                "} // namespace\n",
3962                ShortInlineFunctions);
3963   verifyFormat("namespace {\n"
3964                "  int some_int;\n"
3965                "  void f() {\n"
3966                "    return;\n"
3967                "  }\n"
3968                "} // namespace\n",
3969                ShortInlineFunctions);
3970   verifyFormat("namespace interface {\n"
3971                "  void f() {\n"
3972                "    return;\n"
3973                "  }\n"
3974                "} // namespace interface\n",
3975                ShortInlineFunctions);
3976   verifyFormat("namespace {\n"
3977                "  class X {\n"
3978                "    void f() { return; }\n"
3979                "  };\n"
3980                "} // namespace\n",
3981                ShortInlineFunctions);
3982   verifyFormat("namespace {\n"
3983                "  class X { /* comment */\n"
3984                "    void f() { return; }\n"
3985                "  };\n"
3986                "} // namespace\n",
3987                ShortInlineFunctions);
3988   verifyFormat("namespace {\n"
3989                "  class X { // comment\n"
3990                "    void f() { return; }\n"
3991                "  };\n"
3992                "} // namespace\n",
3993                ShortInlineFunctions);
3994   verifyFormat("namespace {\n"
3995                "  struct X {\n"
3996                "    void f() { return; }\n"
3997                "  };\n"
3998                "} // namespace\n",
3999                ShortInlineFunctions);
4000   verifyFormat("namespace {\n"
4001                "  union X {\n"
4002                "    void f() { return; }\n"
4003                "  };\n"
4004                "} // namespace\n",
4005                ShortInlineFunctions);
4006   verifyFormat("extern \"C\" {\n"
4007                "void f() {\n"
4008                "  return;\n"
4009                "}\n"
4010                "} // namespace\n",
4011                ShortInlineFunctions);
4012   verifyFormat("namespace {\n"
4013                "  class X {\n"
4014                "    void f() { return; }\n"
4015                "  } x;\n"
4016                "} // namespace\n",
4017                ShortInlineFunctions);
4018   verifyFormat("namespace {\n"
4019                "  [[nodiscard]] class X {\n"
4020                "    void f() { return; }\n"
4021                "  };\n"
4022                "} // namespace\n",
4023                ShortInlineFunctions);
4024   verifyFormat("namespace {\n"
4025                "  static class X {\n"
4026                "    void f() { return; }\n"
4027                "  } x;\n"
4028                "} // namespace\n",
4029                ShortInlineFunctions);
4030   verifyFormat("namespace {\n"
4031                "  constexpr class X {\n"
4032                "    void f() { return; }\n"
4033                "  } x;\n"
4034                "} // namespace\n",
4035                ShortInlineFunctions);
4036 
4037   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
4038   verifyFormat("extern \"C\" {\n"
4039                "  void f() {\n"
4040                "    return;\n"
4041                "  }\n"
4042                "} // namespace\n",
4043                ShortInlineFunctions);
4044 
4045   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4046   EXPECT_EQ("namespace out {\n"
4047             "int i;\n"
4048             "namespace in {\n"
4049             "  int i;\n"
4050             "} // namespace in\n"
4051             "} // namespace out",
4052             format("namespace out {\n"
4053                    "int i;\n"
4054                    "namespace in {\n"
4055                    "int i;\n"
4056                    "} // namespace in\n"
4057                    "} // namespace out",
4058                    Style));
4059 
4060   Style.NamespaceIndentation = FormatStyle::NI_None;
4061   verifyFormat("template <class T>\n"
4062                "concept a_concept = X<>;\n"
4063                "namespace B {\n"
4064                "struct b_struct {};\n"
4065                "} // namespace B\n",
4066                Style);
4067   verifyFormat("template <int I>\n"
4068                "constexpr void foo()\n"
4069                "  requires(I == 42)\n"
4070                "{}\n"
4071                "namespace ns {\n"
4072                "void foo() {}\n"
4073                "} // namespace ns\n",
4074                Style);
4075 }
4076 
4077 TEST_F(FormatTest, NamespaceMacros) {
4078   FormatStyle Style = getLLVMStyle();
4079   Style.NamespaceMacros.push_back("TESTSUITE");
4080 
4081   verifyFormat("TESTSUITE(A) {\n"
4082                "int foo();\n"
4083                "} // TESTSUITE(A)",
4084                Style);
4085 
4086   verifyFormat("TESTSUITE(A, B) {\n"
4087                "int foo();\n"
4088                "} // TESTSUITE(A)",
4089                Style);
4090 
4091   // Properly indent according to NamespaceIndentation style
4092   Style.NamespaceIndentation = FormatStyle::NI_All;
4093   verifyFormat("TESTSUITE(A) {\n"
4094                "  int foo();\n"
4095                "} // TESTSUITE(A)",
4096                Style);
4097   verifyFormat("TESTSUITE(A) {\n"
4098                "  namespace B {\n"
4099                "    int foo();\n"
4100                "  } // namespace B\n"
4101                "} // TESTSUITE(A)",
4102                Style);
4103   verifyFormat("namespace A {\n"
4104                "  TESTSUITE(B) {\n"
4105                "    int foo();\n"
4106                "  } // TESTSUITE(B)\n"
4107                "} // namespace A",
4108                Style);
4109 
4110   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4111   verifyFormat("TESTSUITE(A) {\n"
4112                "TESTSUITE(B) {\n"
4113                "  int foo();\n"
4114                "} // TESTSUITE(B)\n"
4115                "} // TESTSUITE(A)",
4116                Style);
4117   verifyFormat("TESTSUITE(A) {\n"
4118                "namespace B {\n"
4119                "  int foo();\n"
4120                "} // namespace B\n"
4121                "} // TESTSUITE(A)",
4122                Style);
4123   verifyFormat("namespace A {\n"
4124                "TESTSUITE(B) {\n"
4125                "  int foo();\n"
4126                "} // TESTSUITE(B)\n"
4127                "} // namespace A",
4128                Style);
4129 
4130   // Properly merge namespace-macros blocks in CompactNamespaces mode
4131   Style.NamespaceIndentation = FormatStyle::NI_None;
4132   Style.CompactNamespaces = true;
4133   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
4134                "}} // TESTSUITE(A::B)",
4135                Style);
4136 
4137   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4138             "}} // TESTSUITE(out::in)",
4139             format("TESTSUITE(out) {\n"
4140                    "TESTSUITE(in) {\n"
4141                    "} // TESTSUITE(in)\n"
4142                    "} // TESTSUITE(out)",
4143                    Style));
4144 
4145   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4146             "}} // TESTSUITE(out::in)",
4147             format("TESTSUITE(out) {\n"
4148                    "TESTSUITE(in) {\n"
4149                    "} // TESTSUITE(in)\n"
4150                    "} // TESTSUITE(out)",
4151                    Style));
4152 
4153   // Do not merge different namespaces/macros
4154   EXPECT_EQ("namespace out {\n"
4155             "TESTSUITE(in) {\n"
4156             "} // TESTSUITE(in)\n"
4157             "} // namespace out",
4158             format("namespace out {\n"
4159                    "TESTSUITE(in) {\n"
4160                    "} // TESTSUITE(in)\n"
4161                    "} // namespace out",
4162                    Style));
4163   EXPECT_EQ("TESTSUITE(out) {\n"
4164             "namespace in {\n"
4165             "} // namespace in\n"
4166             "} // TESTSUITE(out)",
4167             format("TESTSUITE(out) {\n"
4168                    "namespace in {\n"
4169                    "} // namespace in\n"
4170                    "} // TESTSUITE(out)",
4171                    Style));
4172   Style.NamespaceMacros.push_back("FOOBAR");
4173   EXPECT_EQ("TESTSUITE(out) {\n"
4174             "FOOBAR(in) {\n"
4175             "} // FOOBAR(in)\n"
4176             "} // TESTSUITE(out)",
4177             format("TESTSUITE(out) {\n"
4178                    "FOOBAR(in) {\n"
4179                    "} // FOOBAR(in)\n"
4180                    "} // TESTSUITE(out)",
4181                    Style));
4182 }
4183 
4184 TEST_F(FormatTest, FormatsCompactNamespaces) {
4185   FormatStyle Style = getLLVMStyle();
4186   Style.CompactNamespaces = true;
4187   Style.NamespaceMacros.push_back("TESTSUITE");
4188 
4189   verifyFormat("namespace A { namespace B {\n"
4190                "}} // namespace A::B",
4191                Style);
4192 
4193   EXPECT_EQ("namespace out { namespace in {\n"
4194             "}} // namespace out::in",
4195             format("namespace out {\n"
4196                    "namespace in {\n"
4197                    "} // namespace in\n"
4198                    "} // namespace out",
4199                    Style));
4200 
4201   // Only namespaces which have both consecutive opening and end get compacted
4202   EXPECT_EQ("namespace out {\n"
4203             "namespace in1 {\n"
4204             "} // namespace in1\n"
4205             "namespace in2 {\n"
4206             "} // namespace in2\n"
4207             "} // namespace out",
4208             format("namespace out {\n"
4209                    "namespace in1 {\n"
4210                    "} // namespace in1\n"
4211                    "namespace in2 {\n"
4212                    "} // namespace in2\n"
4213                    "} // namespace out",
4214                    Style));
4215 
4216   EXPECT_EQ("namespace out {\n"
4217             "int i;\n"
4218             "namespace in {\n"
4219             "int j;\n"
4220             "} // namespace in\n"
4221             "int k;\n"
4222             "} // namespace out",
4223             format("namespace out { int i;\n"
4224                    "namespace in { int j; } // namespace in\n"
4225                    "int k; } // namespace out",
4226                    Style));
4227 
4228   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
4229             "}}} // namespace A::B::C\n",
4230             format("namespace A { namespace B {\n"
4231                    "namespace C {\n"
4232                    "}} // namespace B::C\n"
4233                    "} // namespace A\n",
4234                    Style));
4235 
4236   Style.ColumnLimit = 40;
4237   EXPECT_EQ("namespace aaaaaaaaaa {\n"
4238             "namespace bbbbbbbbbb {\n"
4239             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
4240             format("namespace aaaaaaaaaa {\n"
4241                    "namespace bbbbbbbbbb {\n"
4242                    "} // namespace bbbbbbbbbb\n"
4243                    "} // namespace aaaaaaaaaa",
4244                    Style));
4245 
4246   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
4247             "namespace cccccc {\n"
4248             "}}} // namespace aaaaaa::bbbbbb::cccccc",
4249             format("namespace aaaaaa {\n"
4250                    "namespace bbbbbb {\n"
4251                    "namespace cccccc {\n"
4252                    "} // namespace cccccc\n"
4253                    "} // namespace bbbbbb\n"
4254                    "} // namespace aaaaaa",
4255                    Style));
4256   Style.ColumnLimit = 80;
4257 
4258   // Extra semicolon after 'inner' closing brace prevents merging
4259   EXPECT_EQ("namespace out { namespace in {\n"
4260             "}; } // namespace out::in",
4261             format("namespace out {\n"
4262                    "namespace in {\n"
4263                    "}; // namespace in\n"
4264                    "} // namespace out",
4265                    Style));
4266 
4267   // Extra semicolon after 'outer' closing brace is conserved
4268   EXPECT_EQ("namespace out { namespace in {\n"
4269             "}}; // namespace out::in",
4270             format("namespace out {\n"
4271                    "namespace in {\n"
4272                    "} // namespace in\n"
4273                    "}; // namespace out",
4274                    Style));
4275 
4276   Style.NamespaceIndentation = FormatStyle::NI_All;
4277   EXPECT_EQ("namespace out { namespace in {\n"
4278             "  int i;\n"
4279             "}} // namespace out::in",
4280             format("namespace out {\n"
4281                    "namespace in {\n"
4282                    "int i;\n"
4283                    "} // namespace in\n"
4284                    "} // namespace out",
4285                    Style));
4286   EXPECT_EQ("namespace out { namespace mid {\n"
4287             "  namespace in {\n"
4288             "    int j;\n"
4289             "  } // namespace in\n"
4290             "  int k;\n"
4291             "}} // namespace out::mid",
4292             format("namespace out { namespace mid {\n"
4293                    "namespace in { int j; } // namespace in\n"
4294                    "int k; }} // namespace out::mid",
4295                    Style));
4296 
4297   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4298   EXPECT_EQ("namespace out { namespace in {\n"
4299             "  int i;\n"
4300             "}} // namespace out::in",
4301             format("namespace out {\n"
4302                    "namespace in {\n"
4303                    "int i;\n"
4304                    "} // namespace in\n"
4305                    "} // namespace out",
4306                    Style));
4307   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
4308             "  int i;\n"
4309             "}}} // namespace out::mid::in",
4310             format("namespace out {\n"
4311                    "namespace mid {\n"
4312                    "namespace in {\n"
4313                    "int i;\n"
4314                    "} // namespace in\n"
4315                    "} // namespace mid\n"
4316                    "} // namespace out",
4317                    Style));
4318 
4319   Style.CompactNamespaces = true;
4320   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
4321   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4322   Style.BraceWrapping.BeforeLambdaBody = true;
4323   verifyFormat("namespace out { namespace in {\n"
4324                "}} // namespace out::in",
4325                Style);
4326   EXPECT_EQ("namespace out { namespace in {\n"
4327             "}} // namespace out::in",
4328             format("namespace out {\n"
4329                    "namespace in {\n"
4330                    "} // namespace in\n"
4331                    "} // namespace out",
4332                    Style));
4333 }
4334 
4335 TEST_F(FormatTest, FormatsExternC) {
4336   verifyFormat("extern \"C\" {\nint a;");
4337   verifyFormat("extern \"C\" {}");
4338   verifyFormat("extern \"C\" {\n"
4339                "int foo();\n"
4340                "}");
4341   verifyFormat("extern \"C\" int foo() {}");
4342   verifyFormat("extern \"C\" int foo();");
4343   verifyFormat("extern \"C\" int foo() {\n"
4344                "  int i = 42;\n"
4345                "  return i;\n"
4346                "}");
4347 
4348   FormatStyle Style = getLLVMStyle();
4349   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4350   Style.BraceWrapping.AfterFunction = true;
4351   verifyFormat("extern \"C\" int foo() {}", Style);
4352   verifyFormat("extern \"C\" int foo();", Style);
4353   verifyFormat("extern \"C\" int foo()\n"
4354                "{\n"
4355                "  int i = 42;\n"
4356                "  return i;\n"
4357                "}",
4358                Style);
4359 
4360   Style.BraceWrapping.AfterExternBlock = true;
4361   Style.BraceWrapping.SplitEmptyRecord = false;
4362   verifyFormat("extern \"C\"\n"
4363                "{}",
4364                Style);
4365   verifyFormat("extern \"C\"\n"
4366                "{\n"
4367                "  int foo();\n"
4368                "}",
4369                Style);
4370 }
4371 
4372 TEST_F(FormatTest, IndentExternBlockStyle) {
4373   FormatStyle Style = getLLVMStyle();
4374   Style.IndentWidth = 2;
4375 
4376   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4377   verifyFormat("extern \"C\" { /*9*/\n"
4378                "}",
4379                Style);
4380   verifyFormat("extern \"C\" {\n"
4381                "  int foo10();\n"
4382                "}",
4383                Style);
4384 
4385   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4386   verifyFormat("extern \"C\" { /*11*/\n"
4387                "}",
4388                Style);
4389   verifyFormat("extern \"C\" {\n"
4390                "int foo12();\n"
4391                "}",
4392                Style);
4393 
4394   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4395   Style.BraceWrapping.AfterExternBlock = true;
4396   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4397   verifyFormat("extern \"C\"\n"
4398                "{ /*13*/\n"
4399                "}",
4400                Style);
4401   verifyFormat("extern \"C\"\n{\n"
4402                "  int foo14();\n"
4403                "}",
4404                Style);
4405 
4406   Style.BraceWrapping.AfterExternBlock = false;
4407   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4408   verifyFormat("extern \"C\" { /*15*/\n"
4409                "}",
4410                Style);
4411   verifyFormat("extern \"C\" {\n"
4412                "int foo16();\n"
4413                "}",
4414                Style);
4415 
4416   Style.BraceWrapping.AfterExternBlock = true;
4417   verifyFormat("extern \"C\"\n"
4418                "{ /*13*/\n"
4419                "}",
4420                Style);
4421   verifyFormat("extern \"C\"\n"
4422                "{\n"
4423                "int foo14();\n"
4424                "}",
4425                Style);
4426 
4427   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4428   verifyFormat("extern \"C\"\n"
4429                "{ /*13*/\n"
4430                "}",
4431                Style);
4432   verifyFormat("extern \"C\"\n"
4433                "{\n"
4434                "  int foo14();\n"
4435                "}",
4436                Style);
4437 }
4438 
4439 TEST_F(FormatTest, FormatsInlineASM) {
4440   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4441   verifyFormat("asm(\"nop\" ::: \"memory\");");
4442   verifyFormat(
4443       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4444       "    \"cpuid\\n\\t\"\n"
4445       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4446       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4447       "    : \"a\"(value));");
4448   EXPECT_EQ(
4449       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4450       "  __asm {\n"
4451       "        mov     edx,[that] // vtable in edx\n"
4452       "        mov     eax,methodIndex\n"
4453       "        call    [edx][eax*4] // stdcall\n"
4454       "  }\n"
4455       "}",
4456       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4457              "    __asm {\n"
4458              "        mov     edx,[that] // vtable in edx\n"
4459              "        mov     eax,methodIndex\n"
4460              "        call    [edx][eax*4] // stdcall\n"
4461              "    }\n"
4462              "}"));
4463   EXPECT_EQ("_asm {\n"
4464             "  xor eax, eax;\n"
4465             "  cpuid;\n"
4466             "}",
4467             format("_asm {\n"
4468                    "  xor eax, eax;\n"
4469                    "  cpuid;\n"
4470                    "}"));
4471   verifyFormat("void function() {\n"
4472                "  // comment\n"
4473                "  asm(\"\");\n"
4474                "}");
4475   EXPECT_EQ("__asm {\n"
4476             "}\n"
4477             "int i;",
4478             format("__asm   {\n"
4479                    "}\n"
4480                    "int   i;"));
4481 }
4482 
4483 TEST_F(FormatTest, FormatTryCatch) {
4484   verifyFormat("try {\n"
4485                "  throw a * b;\n"
4486                "} catch (int a) {\n"
4487                "  // Do nothing.\n"
4488                "} catch (...) {\n"
4489                "  exit(42);\n"
4490                "}");
4491 
4492   // Function-level try statements.
4493   verifyFormat("int f() try { return 4; } catch (...) {\n"
4494                "  return 5;\n"
4495                "}");
4496   verifyFormat("class A {\n"
4497                "  int a;\n"
4498                "  A() try : a(0) {\n"
4499                "  } catch (...) {\n"
4500                "    throw;\n"
4501                "  }\n"
4502                "};\n");
4503   verifyFormat("class A {\n"
4504                "  int a;\n"
4505                "  A() try : a(0), b{1} {\n"
4506                "  } catch (...) {\n"
4507                "    throw;\n"
4508                "  }\n"
4509                "};\n");
4510   verifyFormat("class A {\n"
4511                "  int a;\n"
4512                "  A() try : a(0), b{1}, c{2} {\n"
4513                "  } catch (...) {\n"
4514                "    throw;\n"
4515                "  }\n"
4516                "};\n");
4517   verifyFormat("class A {\n"
4518                "  int a;\n"
4519                "  A() try : a(0), b{1}, c{2} {\n"
4520                "    { // New scope.\n"
4521                "    }\n"
4522                "  } catch (...) {\n"
4523                "    throw;\n"
4524                "  }\n"
4525                "};\n");
4526 
4527   // Incomplete try-catch blocks.
4528   verifyIncompleteFormat("try {} catch (");
4529 }
4530 
4531 TEST_F(FormatTest, FormatTryAsAVariable) {
4532   verifyFormat("int try;");
4533   verifyFormat("int try, size;");
4534   verifyFormat("try = foo();");
4535   verifyFormat("if (try < size) {\n  return true;\n}");
4536 
4537   verifyFormat("int catch;");
4538   verifyFormat("int catch, size;");
4539   verifyFormat("catch = foo();");
4540   verifyFormat("if (catch < size) {\n  return true;\n}");
4541 
4542   FormatStyle Style = getLLVMStyle();
4543   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4544   Style.BraceWrapping.AfterFunction = true;
4545   Style.BraceWrapping.BeforeCatch = true;
4546   verifyFormat("try {\n"
4547                "  int bar = 1;\n"
4548                "}\n"
4549                "catch (...) {\n"
4550                "  int bar = 1;\n"
4551                "}",
4552                Style);
4553   verifyFormat("#if NO_EX\n"
4554                "try\n"
4555                "#endif\n"
4556                "{\n"
4557                "}\n"
4558                "#if NO_EX\n"
4559                "catch (...) {\n"
4560                "}",
4561                Style);
4562   verifyFormat("try /* abc */ {\n"
4563                "  int bar = 1;\n"
4564                "}\n"
4565                "catch (...) {\n"
4566                "  int bar = 1;\n"
4567                "}",
4568                Style);
4569   verifyFormat("try\n"
4570                "// abc\n"
4571                "{\n"
4572                "  int bar = 1;\n"
4573                "}\n"
4574                "catch (...) {\n"
4575                "  int bar = 1;\n"
4576                "}",
4577                Style);
4578 }
4579 
4580 TEST_F(FormatTest, FormatSEHTryCatch) {
4581   verifyFormat("__try {\n"
4582                "  int a = b * c;\n"
4583                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4584                "  // Do nothing.\n"
4585                "}");
4586 
4587   verifyFormat("__try {\n"
4588                "  int a = b * c;\n"
4589                "} __finally {\n"
4590                "  // Do nothing.\n"
4591                "}");
4592 
4593   verifyFormat("DEBUG({\n"
4594                "  __try {\n"
4595                "  } __finally {\n"
4596                "  }\n"
4597                "});\n");
4598 }
4599 
4600 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4601   verifyFormat("try {\n"
4602                "  f();\n"
4603                "} catch {\n"
4604                "  g();\n"
4605                "}");
4606   verifyFormat("try {\n"
4607                "  f();\n"
4608                "} catch (A a) MACRO(x) {\n"
4609                "  g();\n"
4610                "} catch (B b) MACRO(x) {\n"
4611                "  g();\n"
4612                "}");
4613 }
4614 
4615 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4616   FormatStyle Style = getLLVMStyle();
4617   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4618                           FormatStyle::BS_WebKit}) {
4619     Style.BreakBeforeBraces = BraceStyle;
4620     verifyFormat("try {\n"
4621                  "  // something\n"
4622                  "} catch (...) {\n"
4623                  "  // something\n"
4624                  "}",
4625                  Style);
4626   }
4627   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4628   verifyFormat("try {\n"
4629                "  // something\n"
4630                "}\n"
4631                "catch (...) {\n"
4632                "  // something\n"
4633                "}",
4634                Style);
4635   verifyFormat("__try {\n"
4636                "  // something\n"
4637                "}\n"
4638                "__finally {\n"
4639                "  // something\n"
4640                "}",
4641                Style);
4642   verifyFormat("@try {\n"
4643                "  // something\n"
4644                "}\n"
4645                "@finally {\n"
4646                "  // something\n"
4647                "}",
4648                Style);
4649   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4650   verifyFormat("try\n"
4651                "{\n"
4652                "  // something\n"
4653                "}\n"
4654                "catch (...)\n"
4655                "{\n"
4656                "  // something\n"
4657                "}",
4658                Style);
4659   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4660   verifyFormat("try\n"
4661                "  {\n"
4662                "  // something white\n"
4663                "  }\n"
4664                "catch (...)\n"
4665                "  {\n"
4666                "  // something white\n"
4667                "  }",
4668                Style);
4669   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4670   verifyFormat("try\n"
4671                "  {\n"
4672                "    // something\n"
4673                "  }\n"
4674                "catch (...)\n"
4675                "  {\n"
4676                "    // something\n"
4677                "  }",
4678                Style);
4679   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4680   Style.BraceWrapping.BeforeCatch = true;
4681   verifyFormat("try {\n"
4682                "  // something\n"
4683                "}\n"
4684                "catch (...) {\n"
4685                "  // something\n"
4686                "}",
4687                Style);
4688 }
4689 
4690 TEST_F(FormatTest, StaticInitializers) {
4691   verifyFormat("static SomeClass SC = {1, 'a'};");
4692 
4693   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4694                "    100000000, "
4695                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4696 
4697   // Here, everything other than the "}" would fit on a line.
4698   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4699                "    10000000000000000000000000};");
4700   EXPECT_EQ("S s = {a,\n"
4701             "\n"
4702             "       b};",
4703             format("S s = {\n"
4704                    "  a,\n"
4705                    "\n"
4706                    "  b\n"
4707                    "};"));
4708 
4709   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4710   // line. However, the formatting looks a bit off and this probably doesn't
4711   // happen often in practice.
4712   verifyFormat("static int Variable[1] = {\n"
4713                "    {1000000000000000000000000000000000000}};",
4714                getLLVMStyleWithColumns(40));
4715 }
4716 
4717 TEST_F(FormatTest, DesignatedInitializers) {
4718   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4719   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4720                "                    .bbbbbbbbbb = 2,\n"
4721                "                    .cccccccccc = 3,\n"
4722                "                    .dddddddddd = 4,\n"
4723                "                    .eeeeeeeeee = 5};");
4724   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4725                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4726                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4727                "    .ccccccccccccccccccccccccccc = 3,\n"
4728                "    .ddddddddddddddddddddddddddd = 4,\n"
4729                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4730 
4731   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4732 
4733   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4734   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4735                "                    [2] = bbbbbbbbbb,\n"
4736                "                    [3] = cccccccccc,\n"
4737                "                    [4] = dddddddddd,\n"
4738                "                    [5] = eeeeeeeeee};");
4739   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4740                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4741                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4742                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4743                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4744                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4745 }
4746 
4747 TEST_F(FormatTest, NestedStaticInitializers) {
4748   verifyFormat("static A x = {{{}}};\n");
4749   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4750                "               {init1, init2, init3, init4}}};",
4751                getLLVMStyleWithColumns(50));
4752 
4753   verifyFormat("somes Status::global_reps[3] = {\n"
4754                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4755                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4756                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4757                getLLVMStyleWithColumns(60));
4758   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4759                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4760                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4761                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4762   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4763                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4764                "rect.fTop}};");
4765 
4766   verifyFormat(
4767       "SomeArrayOfSomeType a = {\n"
4768       "    {{1, 2, 3},\n"
4769       "     {1, 2, 3},\n"
4770       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4771       "      333333333333333333333333333333},\n"
4772       "     {1, 2, 3},\n"
4773       "     {1, 2, 3}}};");
4774   verifyFormat(
4775       "SomeArrayOfSomeType a = {\n"
4776       "    {{1, 2, 3}},\n"
4777       "    {{1, 2, 3}},\n"
4778       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4779       "      333333333333333333333333333333}},\n"
4780       "    {{1, 2, 3}},\n"
4781       "    {{1, 2, 3}}};");
4782 
4783   verifyFormat("struct {\n"
4784                "  unsigned bit;\n"
4785                "  const char *const name;\n"
4786                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4787                "                 {kOsWin, \"Windows\"},\n"
4788                "                 {kOsLinux, \"Linux\"},\n"
4789                "                 {kOsCrOS, \"Chrome OS\"}};");
4790   verifyFormat("struct {\n"
4791                "  unsigned bit;\n"
4792                "  const char *const name;\n"
4793                "} kBitsToOs[] = {\n"
4794                "    {kOsMac, \"Mac\"},\n"
4795                "    {kOsWin, \"Windows\"},\n"
4796                "    {kOsLinux, \"Linux\"},\n"
4797                "    {kOsCrOS, \"Chrome OS\"},\n"
4798                "};");
4799 }
4800 
4801 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4802   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4803                "                      \\\n"
4804                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4805 }
4806 
4807 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4808   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4809                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4810 
4811   // Do break defaulted and deleted functions.
4812   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4813                "    default;",
4814                getLLVMStyleWithColumns(40));
4815   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4816                "    delete;",
4817                getLLVMStyleWithColumns(40));
4818 }
4819 
4820 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4821   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4822                getLLVMStyleWithColumns(40));
4823   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4824                getLLVMStyleWithColumns(40));
4825   EXPECT_EQ("#define Q                              \\\n"
4826             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4827             "  \"aaaaaaaa.cpp\"",
4828             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4829                    getLLVMStyleWithColumns(40)));
4830 }
4831 
4832 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4833   EXPECT_EQ("# 123 \"A string literal\"",
4834             format("   #     123    \"A string literal\""));
4835 }
4836 
4837 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4838   EXPECT_EQ("#;", format("#;"));
4839   verifyFormat("#\n;\n;\n;");
4840 }
4841 
4842 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4843   EXPECT_EQ("#line 42 \"test\"\n",
4844             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4845   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4846                                     getLLVMStyleWithColumns(12)));
4847 }
4848 
4849 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4850   EXPECT_EQ("#line 42 \"test\"",
4851             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4852   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4853 }
4854 
4855 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4856   verifyFormat("#define A \\x20");
4857   verifyFormat("#define A \\ x20");
4858   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4859   verifyFormat("#define A ''");
4860   verifyFormat("#define A ''qqq");
4861   verifyFormat("#define A `qqq");
4862   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4863   EXPECT_EQ("const char *c = STRINGIFY(\n"
4864             "\\na : b);",
4865             format("const char * c = STRINGIFY(\n"
4866                    "\\na : b);"));
4867 
4868   verifyFormat("a\r\\");
4869   verifyFormat("a\v\\");
4870   verifyFormat("a\f\\");
4871 }
4872 
4873 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4874   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4875   style.IndentWidth = 4;
4876   style.PPIndentWidth = 1;
4877 
4878   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4879   verifyFormat("#ifdef __linux__\n"
4880                "void foo() {\n"
4881                "    int x = 0;\n"
4882                "}\n"
4883                "#define FOO\n"
4884                "#endif\n"
4885                "void bar() {\n"
4886                "    int y = 0;\n"
4887                "}\n",
4888                style);
4889 
4890   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4891   verifyFormat("#ifdef __linux__\n"
4892                "void foo() {\n"
4893                "    int x = 0;\n"
4894                "}\n"
4895                "# define FOO foo\n"
4896                "#endif\n"
4897                "void bar() {\n"
4898                "    int y = 0;\n"
4899                "}\n",
4900                style);
4901 
4902   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4903   verifyFormat("#ifdef __linux__\n"
4904                "void foo() {\n"
4905                "    int x = 0;\n"
4906                "}\n"
4907                " #define FOO foo\n"
4908                "#endif\n"
4909                "void bar() {\n"
4910                "    int y = 0;\n"
4911                "}\n",
4912                style);
4913 }
4914 
4915 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4916   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4917   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4918   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4919   // FIXME: We never break before the macro name.
4920   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4921 
4922   verifyFormat("#define A A\n#define A A");
4923   verifyFormat("#define A(X) A\n#define A A");
4924 
4925   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4926   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4927 }
4928 
4929 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4930   EXPECT_EQ("// somecomment\n"
4931             "#include \"a.h\"\n"
4932             "#define A(  \\\n"
4933             "    A, B)\n"
4934             "#include \"b.h\"\n"
4935             "// somecomment\n",
4936             format("  // somecomment\n"
4937                    "  #include \"a.h\"\n"
4938                    "#define A(A,\\\n"
4939                    "    B)\n"
4940                    "    #include \"b.h\"\n"
4941                    " // somecomment\n",
4942                    getLLVMStyleWithColumns(13)));
4943 }
4944 
4945 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4946 
4947 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4948   EXPECT_EQ("#define A    \\\n"
4949             "  c;         \\\n"
4950             "  e;\n"
4951             "f;",
4952             format("#define A c; e;\n"
4953                    "f;",
4954                    getLLVMStyleWithColumns(14)));
4955 }
4956 
4957 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4958 
4959 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4960   EXPECT_EQ("int x,\n"
4961             "#define A\n"
4962             "    y;",
4963             format("int x,\n#define A\ny;"));
4964 }
4965 
4966 TEST_F(FormatTest, HashInMacroDefinition) {
4967   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4968   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4969   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4970   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4971   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4972   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4973   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4974   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4975   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4976   verifyFormat("#define A  \\\n"
4977                "  {        \\\n"
4978                "    f(#c); \\\n"
4979                "  }",
4980                getLLVMStyleWithColumns(11));
4981 
4982   verifyFormat("#define A(X)         \\\n"
4983                "  void function##X()",
4984                getLLVMStyleWithColumns(22));
4985 
4986   verifyFormat("#define A(a, b, c)   \\\n"
4987                "  void a##b##c()",
4988                getLLVMStyleWithColumns(22));
4989 
4990   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4991 }
4992 
4993 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4994   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4995   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4996 
4997   FormatStyle Style = getLLVMStyle();
4998   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4999   verifyFormat("#define true ((foo)1)", Style);
5000   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
5001   verifyFormat("#define false((foo)0)", Style);
5002 }
5003 
5004 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
5005   EXPECT_EQ("#define A b;", format("#define A \\\n"
5006                                    "          \\\n"
5007                                    "  b;",
5008                                    getLLVMStyleWithColumns(25)));
5009   EXPECT_EQ("#define A \\\n"
5010             "          \\\n"
5011             "  a;      \\\n"
5012             "  b;",
5013             format("#define A \\\n"
5014                    "          \\\n"
5015                    "  a;      \\\n"
5016                    "  b;",
5017                    getLLVMStyleWithColumns(11)));
5018   EXPECT_EQ("#define A \\\n"
5019             "  a;      \\\n"
5020             "          \\\n"
5021             "  b;",
5022             format("#define A \\\n"
5023                    "  a;      \\\n"
5024                    "          \\\n"
5025                    "  b;",
5026                    getLLVMStyleWithColumns(11)));
5027 }
5028 
5029 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
5030   verifyIncompleteFormat("#define A :");
5031   verifyFormat("#define SOMECASES  \\\n"
5032                "  case 1:          \\\n"
5033                "  case 2\n",
5034                getLLVMStyleWithColumns(20));
5035   verifyFormat("#define MACRO(a) \\\n"
5036                "  if (a)         \\\n"
5037                "    f();         \\\n"
5038                "  else           \\\n"
5039                "    g()",
5040                getLLVMStyleWithColumns(18));
5041   verifyFormat("#define A template <typename T>");
5042   verifyIncompleteFormat("#define STR(x) #x\n"
5043                          "f(STR(this_is_a_string_literal{));");
5044   verifyFormat("#pragma omp threadprivate( \\\n"
5045                "    y)), // expected-warning",
5046                getLLVMStyleWithColumns(28));
5047   verifyFormat("#d, = };");
5048   verifyFormat("#if \"a");
5049   verifyIncompleteFormat("({\n"
5050                          "#define b     \\\n"
5051                          "  }           \\\n"
5052                          "  a\n"
5053                          "a",
5054                          getLLVMStyleWithColumns(15));
5055   verifyFormat("#define A     \\\n"
5056                "  {           \\\n"
5057                "    {\n"
5058                "#define B     \\\n"
5059                "  }           \\\n"
5060                "  }",
5061                getLLVMStyleWithColumns(15));
5062   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
5063   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
5064   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
5065   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
5066 }
5067 
5068 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
5069   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
5070   EXPECT_EQ("class A : public QObject {\n"
5071             "  Q_OBJECT\n"
5072             "\n"
5073             "  A() {}\n"
5074             "};",
5075             format("class A  :  public QObject {\n"
5076                    "     Q_OBJECT\n"
5077                    "\n"
5078                    "  A() {\n}\n"
5079                    "}  ;"));
5080   EXPECT_EQ("MACRO\n"
5081             "/*static*/ int i;",
5082             format("MACRO\n"
5083                    " /*static*/ int   i;"));
5084   EXPECT_EQ("SOME_MACRO\n"
5085             "namespace {\n"
5086             "void f();\n"
5087             "} // namespace",
5088             format("SOME_MACRO\n"
5089                    "  namespace    {\n"
5090                    "void   f(  );\n"
5091                    "} // namespace"));
5092   // Only if the identifier contains at least 5 characters.
5093   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
5094   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
5095   // Only if everything is upper case.
5096   EXPECT_EQ("class A : public QObject {\n"
5097             "  Q_Object A() {}\n"
5098             "};",
5099             format("class A  :  public QObject {\n"
5100                    "     Q_Object\n"
5101                    "  A() {\n}\n"
5102                    "}  ;"));
5103 
5104   // Only if the next line can actually start an unwrapped line.
5105   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
5106             format("SOME_WEIRD_LOG_MACRO\n"
5107                    "<< SomeThing;"));
5108 
5109   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
5110                "(n, buffers))\n",
5111                getChromiumStyle(FormatStyle::LK_Cpp));
5112 
5113   // See PR41483
5114   EXPECT_EQ("/**/ FOO(a)\n"
5115             "FOO(b)",
5116             format("/**/ FOO(a)\n"
5117                    "FOO(b)"));
5118 }
5119 
5120 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
5121   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5122             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5123             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5124             "class X {};\n"
5125             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5126             "int *createScopDetectionPass() { return 0; }",
5127             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5128                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5129                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5130                    "  class X {};\n"
5131                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5132                    "  int *createScopDetectionPass() { return 0; }"));
5133   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
5134   // braces, so that inner block is indented one level more.
5135   EXPECT_EQ("int q() {\n"
5136             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5137             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5138             "  IPC_END_MESSAGE_MAP()\n"
5139             "}",
5140             format("int q() {\n"
5141                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5142                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5143                    "  IPC_END_MESSAGE_MAP()\n"
5144                    "}"));
5145 
5146   // Same inside macros.
5147   EXPECT_EQ("#define LIST(L) \\\n"
5148             "  L(A)          \\\n"
5149             "  L(B)          \\\n"
5150             "  L(C)",
5151             format("#define LIST(L) \\\n"
5152                    "  L(A) \\\n"
5153                    "  L(B) \\\n"
5154                    "  L(C)",
5155                    getGoogleStyle()));
5156 
5157   // These must not be recognized as macros.
5158   EXPECT_EQ("int q() {\n"
5159             "  f(x);\n"
5160             "  f(x) {}\n"
5161             "  f(x)->g();\n"
5162             "  f(x)->*g();\n"
5163             "  f(x).g();\n"
5164             "  f(x) = x;\n"
5165             "  f(x) += x;\n"
5166             "  f(x) -= x;\n"
5167             "  f(x) *= x;\n"
5168             "  f(x) /= x;\n"
5169             "  f(x) %= x;\n"
5170             "  f(x) &= x;\n"
5171             "  f(x) |= x;\n"
5172             "  f(x) ^= x;\n"
5173             "  f(x) >>= x;\n"
5174             "  f(x) <<= x;\n"
5175             "  f(x)[y].z();\n"
5176             "  LOG(INFO) << x;\n"
5177             "  ifstream(x) >> x;\n"
5178             "}\n",
5179             format("int q() {\n"
5180                    "  f(x)\n;\n"
5181                    "  f(x)\n {}\n"
5182                    "  f(x)\n->g();\n"
5183                    "  f(x)\n->*g();\n"
5184                    "  f(x)\n.g();\n"
5185                    "  f(x)\n = x;\n"
5186                    "  f(x)\n += x;\n"
5187                    "  f(x)\n -= x;\n"
5188                    "  f(x)\n *= x;\n"
5189                    "  f(x)\n /= x;\n"
5190                    "  f(x)\n %= x;\n"
5191                    "  f(x)\n &= x;\n"
5192                    "  f(x)\n |= x;\n"
5193                    "  f(x)\n ^= x;\n"
5194                    "  f(x)\n >>= x;\n"
5195                    "  f(x)\n <<= x;\n"
5196                    "  f(x)\n[y].z();\n"
5197                    "  LOG(INFO)\n << x;\n"
5198                    "  ifstream(x)\n >> x;\n"
5199                    "}\n"));
5200   EXPECT_EQ("int q() {\n"
5201             "  F(x)\n"
5202             "  if (1) {\n"
5203             "  }\n"
5204             "  F(x)\n"
5205             "  while (1) {\n"
5206             "  }\n"
5207             "  F(x)\n"
5208             "  G(x);\n"
5209             "  F(x)\n"
5210             "  try {\n"
5211             "    Q();\n"
5212             "  } catch (...) {\n"
5213             "  }\n"
5214             "}\n",
5215             format("int q() {\n"
5216                    "F(x)\n"
5217                    "if (1) {}\n"
5218                    "F(x)\n"
5219                    "while (1) {}\n"
5220                    "F(x)\n"
5221                    "G(x);\n"
5222                    "F(x)\n"
5223                    "try { Q(); } catch (...) {}\n"
5224                    "}\n"));
5225   EXPECT_EQ("class A {\n"
5226             "  A() : t(0) {}\n"
5227             "  A(int i) noexcept() : {}\n"
5228             "  A(X x)\n" // FIXME: function-level try blocks are broken.
5229             "  try : t(0) {\n"
5230             "  } catch (...) {\n"
5231             "  }\n"
5232             "};",
5233             format("class A {\n"
5234                    "  A()\n : t(0) {}\n"
5235                    "  A(int i)\n noexcept() : {}\n"
5236                    "  A(X x)\n"
5237                    "  try : t(0) {} catch (...) {}\n"
5238                    "};"));
5239   FormatStyle Style = getLLVMStyle();
5240   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5241   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5242   Style.BraceWrapping.AfterFunction = true;
5243   EXPECT_EQ("void f()\n"
5244             "try\n"
5245             "{\n"
5246             "}",
5247             format("void f() try {\n"
5248                    "}",
5249                    Style));
5250   EXPECT_EQ("class SomeClass {\n"
5251             "public:\n"
5252             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5253             "};",
5254             format("class SomeClass {\n"
5255                    "public:\n"
5256                    "  SomeClass()\n"
5257                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5258                    "};"));
5259   EXPECT_EQ("class SomeClass {\n"
5260             "public:\n"
5261             "  SomeClass()\n"
5262             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5263             "};",
5264             format("class SomeClass {\n"
5265                    "public:\n"
5266                    "  SomeClass()\n"
5267                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5268                    "};",
5269                    getLLVMStyleWithColumns(40)));
5270 
5271   verifyFormat("MACRO(>)");
5272 
5273   // Some macros contain an implicit semicolon.
5274   Style = getLLVMStyle();
5275   Style.StatementMacros.push_back("FOO");
5276   verifyFormat("FOO(a) int b = 0;");
5277   verifyFormat("FOO(a)\n"
5278                "int b = 0;",
5279                Style);
5280   verifyFormat("FOO(a);\n"
5281                "int b = 0;",
5282                Style);
5283   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
5284                "int b = 0;",
5285                Style);
5286   verifyFormat("FOO()\n"
5287                "int b = 0;",
5288                Style);
5289   verifyFormat("FOO\n"
5290                "int b = 0;",
5291                Style);
5292   verifyFormat("void f() {\n"
5293                "  FOO(a)\n"
5294                "  return a;\n"
5295                "}",
5296                Style);
5297   verifyFormat("FOO(a)\n"
5298                "FOO(b)",
5299                Style);
5300   verifyFormat("int a = 0;\n"
5301                "FOO(b)\n"
5302                "int c = 0;",
5303                Style);
5304   verifyFormat("int a = 0;\n"
5305                "int x = FOO(a)\n"
5306                "int b = 0;",
5307                Style);
5308   verifyFormat("void foo(int a) { FOO(a) }\n"
5309                "uint32_t bar() {}",
5310                Style);
5311 }
5312 
5313 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
5314   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
5315 
5316   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
5317                ZeroColumn);
5318 }
5319 
5320 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5321   verifyFormat("#define A \\\n"
5322                "  f({     \\\n"
5323                "    g();  \\\n"
5324                "  });",
5325                getLLVMStyleWithColumns(11));
5326 }
5327 
5328 TEST_F(FormatTest, IndentPreprocessorDirectives) {
5329   FormatStyle Style = getLLVMStyleWithColumns(40);
5330   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
5331   verifyFormat("#ifdef _WIN32\n"
5332                "#define A 0\n"
5333                "#ifdef VAR2\n"
5334                "#define B 1\n"
5335                "#include <someheader.h>\n"
5336                "#define MACRO                          \\\n"
5337                "  some_very_long_func_aaaaaaaaaa();\n"
5338                "#endif\n"
5339                "#else\n"
5340                "#define A 1\n"
5341                "#endif",
5342                Style);
5343   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
5344   verifyFormat("#ifdef _WIN32\n"
5345                "#  define A 0\n"
5346                "#  ifdef VAR2\n"
5347                "#    define B 1\n"
5348                "#    include <someheader.h>\n"
5349                "#    define MACRO                      \\\n"
5350                "      some_very_long_func_aaaaaaaaaa();\n"
5351                "#  endif\n"
5352                "#else\n"
5353                "#  define A 1\n"
5354                "#endif",
5355                Style);
5356   verifyFormat("#if A\n"
5357                "#  define MACRO                        \\\n"
5358                "    void a(int x) {                    \\\n"
5359                "      b();                             \\\n"
5360                "      c();                             \\\n"
5361                "      d();                             \\\n"
5362                "      e();                             \\\n"
5363                "      f();                             \\\n"
5364                "    }\n"
5365                "#endif",
5366                Style);
5367   // Comments before include guard.
5368   verifyFormat("// file comment\n"
5369                "// file comment\n"
5370                "#ifndef HEADER_H\n"
5371                "#define HEADER_H\n"
5372                "code();\n"
5373                "#endif",
5374                Style);
5375   // Test with include guards.
5376   verifyFormat("#ifndef HEADER_H\n"
5377                "#define HEADER_H\n"
5378                "code();\n"
5379                "#endif",
5380                Style);
5381   // Include guards must have a #define with the same variable immediately
5382   // after #ifndef.
5383   verifyFormat("#ifndef NOT_GUARD\n"
5384                "#  define FOO\n"
5385                "code();\n"
5386                "#endif",
5387                Style);
5388 
5389   // Include guards must cover the entire file.
5390   verifyFormat("code();\n"
5391                "code();\n"
5392                "#ifndef NOT_GUARD\n"
5393                "#  define NOT_GUARD\n"
5394                "code();\n"
5395                "#endif",
5396                Style);
5397   verifyFormat("#ifndef NOT_GUARD\n"
5398                "#  define NOT_GUARD\n"
5399                "code();\n"
5400                "#endif\n"
5401                "code();",
5402                Style);
5403   // Test with trailing blank lines.
5404   verifyFormat("#ifndef HEADER_H\n"
5405                "#define HEADER_H\n"
5406                "code();\n"
5407                "#endif\n",
5408                Style);
5409   // Include guards don't have #else.
5410   verifyFormat("#ifndef NOT_GUARD\n"
5411                "#  define NOT_GUARD\n"
5412                "code();\n"
5413                "#else\n"
5414                "#endif",
5415                Style);
5416   verifyFormat("#ifndef NOT_GUARD\n"
5417                "#  define NOT_GUARD\n"
5418                "code();\n"
5419                "#elif FOO\n"
5420                "#endif",
5421                Style);
5422   // Non-identifier #define after potential include guard.
5423   verifyFormat("#ifndef FOO\n"
5424                "#  define 1\n"
5425                "#endif\n",
5426                Style);
5427   // #if closes past last non-preprocessor line.
5428   verifyFormat("#ifndef FOO\n"
5429                "#define FOO\n"
5430                "#if 1\n"
5431                "int i;\n"
5432                "#  define A 0\n"
5433                "#endif\n"
5434                "#endif\n",
5435                Style);
5436   // Don't crash if there is an #elif directive without a condition.
5437   verifyFormat("#if 1\n"
5438                "int x;\n"
5439                "#elif\n"
5440                "int y;\n"
5441                "#else\n"
5442                "int z;\n"
5443                "#endif",
5444                Style);
5445   // FIXME: This doesn't handle the case where there's code between the
5446   // #ifndef and #define but all other conditions hold. This is because when
5447   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5448   // previous code line yet, so we can't detect it.
5449   EXPECT_EQ("#ifndef NOT_GUARD\n"
5450             "code();\n"
5451             "#define NOT_GUARD\n"
5452             "code();\n"
5453             "#endif",
5454             format("#ifndef NOT_GUARD\n"
5455                    "code();\n"
5456                    "#  define NOT_GUARD\n"
5457                    "code();\n"
5458                    "#endif",
5459                    Style));
5460   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5461   // be outside an include guard. Examples are #pragma once and
5462   // #pragma GCC diagnostic, or anything else that does not change the meaning
5463   // of the file if it's included multiple times.
5464   EXPECT_EQ("#ifdef WIN32\n"
5465             "#  pragma once\n"
5466             "#endif\n"
5467             "#ifndef HEADER_H\n"
5468             "#  define HEADER_H\n"
5469             "code();\n"
5470             "#endif",
5471             format("#ifdef WIN32\n"
5472                    "#  pragma once\n"
5473                    "#endif\n"
5474                    "#ifndef HEADER_H\n"
5475                    "#define HEADER_H\n"
5476                    "code();\n"
5477                    "#endif",
5478                    Style));
5479   // FIXME: This does not detect when there is a single non-preprocessor line
5480   // in front of an include-guard-like structure where other conditions hold
5481   // because ScopedLineState hides the line.
5482   EXPECT_EQ("code();\n"
5483             "#ifndef HEADER_H\n"
5484             "#define HEADER_H\n"
5485             "code();\n"
5486             "#endif",
5487             format("code();\n"
5488                    "#ifndef HEADER_H\n"
5489                    "#  define HEADER_H\n"
5490                    "code();\n"
5491                    "#endif",
5492                    Style));
5493   // Keep comments aligned with #, otherwise indent comments normally. These
5494   // tests cannot use verifyFormat because messUp manipulates leading
5495   // whitespace.
5496   {
5497     const char *Expected = ""
5498                            "void f() {\n"
5499                            "#if 1\n"
5500                            "// Preprocessor aligned.\n"
5501                            "#  define A 0\n"
5502                            "  // Code. Separated by blank line.\n"
5503                            "\n"
5504                            "#  define B 0\n"
5505                            "  // Code. Not aligned with #\n"
5506                            "#  define C 0\n"
5507                            "#endif";
5508     const char *ToFormat = ""
5509                            "void f() {\n"
5510                            "#if 1\n"
5511                            "// Preprocessor aligned.\n"
5512                            "#  define A 0\n"
5513                            "// Code. Separated by blank line.\n"
5514                            "\n"
5515                            "#  define B 0\n"
5516                            "   // Code. Not aligned with #\n"
5517                            "#  define C 0\n"
5518                            "#endif";
5519     EXPECT_EQ(Expected, format(ToFormat, Style));
5520     EXPECT_EQ(Expected, format(Expected, Style));
5521   }
5522   // Keep block quotes aligned.
5523   {
5524     const char *Expected = ""
5525                            "void f() {\n"
5526                            "#if 1\n"
5527                            "/* Preprocessor aligned. */\n"
5528                            "#  define A 0\n"
5529                            "  /* Code. Separated by blank line. */\n"
5530                            "\n"
5531                            "#  define B 0\n"
5532                            "  /* Code. Not aligned with # */\n"
5533                            "#  define C 0\n"
5534                            "#endif";
5535     const char *ToFormat = ""
5536                            "void f() {\n"
5537                            "#if 1\n"
5538                            "/* Preprocessor aligned. */\n"
5539                            "#  define A 0\n"
5540                            "/* Code. Separated by blank line. */\n"
5541                            "\n"
5542                            "#  define B 0\n"
5543                            "   /* Code. Not aligned with # */\n"
5544                            "#  define C 0\n"
5545                            "#endif";
5546     EXPECT_EQ(Expected, format(ToFormat, Style));
5547     EXPECT_EQ(Expected, format(Expected, Style));
5548   }
5549   // Keep comments aligned with un-indented directives.
5550   {
5551     const char *Expected = ""
5552                            "void f() {\n"
5553                            "// Preprocessor aligned.\n"
5554                            "#define A 0\n"
5555                            "  // Code. Separated by blank line.\n"
5556                            "\n"
5557                            "#define B 0\n"
5558                            "  // Code. Not aligned with #\n"
5559                            "#define C 0\n";
5560     const char *ToFormat = ""
5561                            "void f() {\n"
5562                            "// Preprocessor aligned.\n"
5563                            "#define A 0\n"
5564                            "// Code. Separated by blank line.\n"
5565                            "\n"
5566                            "#define B 0\n"
5567                            "   // Code. Not aligned with #\n"
5568                            "#define C 0\n";
5569     EXPECT_EQ(Expected, format(ToFormat, Style));
5570     EXPECT_EQ(Expected, format(Expected, Style));
5571   }
5572   // Test AfterHash with tabs.
5573   {
5574     FormatStyle Tabbed = Style;
5575     Tabbed.UseTab = FormatStyle::UT_Always;
5576     Tabbed.IndentWidth = 8;
5577     Tabbed.TabWidth = 8;
5578     verifyFormat("#ifdef _WIN32\n"
5579                  "#\tdefine A 0\n"
5580                  "#\tifdef VAR2\n"
5581                  "#\t\tdefine B 1\n"
5582                  "#\t\tinclude <someheader.h>\n"
5583                  "#\t\tdefine MACRO          \\\n"
5584                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5585                  "#\tendif\n"
5586                  "#else\n"
5587                  "#\tdefine A 1\n"
5588                  "#endif",
5589                  Tabbed);
5590   }
5591 
5592   // Regression test: Multiline-macro inside include guards.
5593   verifyFormat("#ifndef HEADER_H\n"
5594                "#define HEADER_H\n"
5595                "#define A()        \\\n"
5596                "  int i;           \\\n"
5597                "  int j;\n"
5598                "#endif // HEADER_H",
5599                getLLVMStyleWithColumns(20));
5600 
5601   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5602   // Basic before hash indent tests
5603   verifyFormat("#ifdef _WIN32\n"
5604                "  #define A 0\n"
5605                "  #ifdef VAR2\n"
5606                "    #define B 1\n"
5607                "    #include <someheader.h>\n"
5608                "    #define MACRO                      \\\n"
5609                "      some_very_long_func_aaaaaaaaaa();\n"
5610                "  #endif\n"
5611                "#else\n"
5612                "  #define A 1\n"
5613                "#endif",
5614                Style);
5615   verifyFormat("#if A\n"
5616                "  #define MACRO                        \\\n"
5617                "    void a(int x) {                    \\\n"
5618                "      b();                             \\\n"
5619                "      c();                             \\\n"
5620                "      d();                             \\\n"
5621                "      e();                             \\\n"
5622                "      f();                             \\\n"
5623                "    }\n"
5624                "#endif",
5625                Style);
5626   // Keep comments aligned with indented directives. These
5627   // tests cannot use verifyFormat because messUp manipulates leading
5628   // whitespace.
5629   {
5630     const char *Expected = "void f() {\n"
5631                            "// Aligned to preprocessor.\n"
5632                            "#if 1\n"
5633                            "  // Aligned to code.\n"
5634                            "  int a;\n"
5635                            "  #if 1\n"
5636                            "    // Aligned to preprocessor.\n"
5637                            "    #define A 0\n"
5638                            "  // Aligned to code.\n"
5639                            "  int b;\n"
5640                            "  #endif\n"
5641                            "#endif\n"
5642                            "}";
5643     const char *ToFormat = "void f() {\n"
5644                            "// Aligned to preprocessor.\n"
5645                            "#if 1\n"
5646                            "// Aligned to code.\n"
5647                            "int a;\n"
5648                            "#if 1\n"
5649                            "// Aligned to preprocessor.\n"
5650                            "#define A 0\n"
5651                            "// Aligned to code.\n"
5652                            "int b;\n"
5653                            "#endif\n"
5654                            "#endif\n"
5655                            "}";
5656     EXPECT_EQ(Expected, format(ToFormat, Style));
5657     EXPECT_EQ(Expected, format(Expected, Style));
5658   }
5659   {
5660     const char *Expected = "void f() {\n"
5661                            "/* Aligned to preprocessor. */\n"
5662                            "#if 1\n"
5663                            "  /* Aligned to code. */\n"
5664                            "  int a;\n"
5665                            "  #if 1\n"
5666                            "    /* Aligned to preprocessor. */\n"
5667                            "    #define A 0\n"
5668                            "  /* Aligned to code. */\n"
5669                            "  int b;\n"
5670                            "  #endif\n"
5671                            "#endif\n"
5672                            "}";
5673     const char *ToFormat = "void f() {\n"
5674                            "/* Aligned to preprocessor. */\n"
5675                            "#if 1\n"
5676                            "/* Aligned to code. */\n"
5677                            "int a;\n"
5678                            "#if 1\n"
5679                            "/* Aligned to preprocessor. */\n"
5680                            "#define A 0\n"
5681                            "/* Aligned to code. */\n"
5682                            "int b;\n"
5683                            "#endif\n"
5684                            "#endif\n"
5685                            "}";
5686     EXPECT_EQ(Expected, format(ToFormat, Style));
5687     EXPECT_EQ(Expected, format(Expected, Style));
5688   }
5689 
5690   // Test single comment before preprocessor
5691   verifyFormat("// Comment\n"
5692                "\n"
5693                "#if 1\n"
5694                "#endif",
5695                Style);
5696 }
5697 
5698 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5699   verifyFormat("{\n  { a #c; }\n}");
5700 }
5701 
5702 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5703   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5704             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5705   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5706             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5707 }
5708 
5709 TEST_F(FormatTest, EscapedNewlines) {
5710   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5711   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5712             format("#define A \\\nint i;\\\n  int j;", Narrow));
5713   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5714   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5715   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5716   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5717 
5718   FormatStyle AlignLeft = getLLVMStyle();
5719   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5720   EXPECT_EQ("#define MACRO(x) \\\n"
5721             "private:         \\\n"
5722             "  int x(int a);\n",
5723             format("#define MACRO(x) \\\n"
5724                    "private:         \\\n"
5725                    "  int x(int a);\n",
5726                    AlignLeft));
5727 
5728   // CRLF line endings
5729   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5730             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5731   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5732   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5733   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5734   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5735   EXPECT_EQ("#define MACRO(x) \\\r\n"
5736             "private:         \\\r\n"
5737             "  int x(int a);\r\n",
5738             format("#define MACRO(x) \\\r\n"
5739                    "private:         \\\r\n"
5740                    "  int x(int a);\r\n",
5741                    AlignLeft));
5742 
5743   FormatStyle DontAlign = getLLVMStyle();
5744   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5745   DontAlign.MaxEmptyLinesToKeep = 3;
5746   // FIXME: can't use verifyFormat here because the newline before
5747   // "public:" is not inserted the first time it's reformatted
5748   EXPECT_EQ("#define A \\\n"
5749             "  class Foo { \\\n"
5750             "    void bar(); \\\n"
5751             "\\\n"
5752             "\\\n"
5753             "\\\n"
5754             "  public: \\\n"
5755             "    void baz(); \\\n"
5756             "  };",
5757             format("#define A \\\n"
5758                    "  class Foo { \\\n"
5759                    "    void bar(); \\\n"
5760                    "\\\n"
5761                    "\\\n"
5762                    "\\\n"
5763                    "  public: \\\n"
5764                    "    void baz(); \\\n"
5765                    "  };",
5766                    DontAlign));
5767 }
5768 
5769 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5770   verifyFormat("#define A \\\n"
5771                "  int v(  \\\n"
5772                "      a); \\\n"
5773                "  int i;",
5774                getLLVMStyleWithColumns(11));
5775 }
5776 
5777 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5778   EXPECT_EQ(
5779       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5780       "                      \\\n"
5781       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5782       "\n"
5783       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5784       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5785       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5786              "\\\n"
5787              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5788              "  \n"
5789              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5790              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5791 }
5792 
5793 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5794   EXPECT_EQ("int\n"
5795             "#define A\n"
5796             "    a;",
5797             format("int\n#define A\na;"));
5798   verifyFormat("functionCallTo(\n"
5799                "    someOtherFunction(\n"
5800                "        withSomeParameters, whichInSequence,\n"
5801                "        areLongerThanALine(andAnotherCall,\n"
5802                "#define A B\n"
5803                "                           withMoreParamters,\n"
5804                "                           whichStronglyInfluenceTheLayout),\n"
5805                "        andMoreParameters),\n"
5806                "    trailing);",
5807                getLLVMStyleWithColumns(69));
5808   verifyFormat("Foo::Foo()\n"
5809                "#ifdef BAR\n"
5810                "    : baz(0)\n"
5811                "#endif\n"
5812                "{\n"
5813                "}");
5814   verifyFormat("void f() {\n"
5815                "  if (true)\n"
5816                "#ifdef A\n"
5817                "    f(42);\n"
5818                "  x();\n"
5819                "#else\n"
5820                "    g();\n"
5821                "  x();\n"
5822                "#endif\n"
5823                "}");
5824   verifyFormat("void f(param1, param2,\n"
5825                "       param3,\n"
5826                "#ifdef A\n"
5827                "       param4(param5,\n"
5828                "#ifdef A1\n"
5829                "              param6,\n"
5830                "#ifdef A2\n"
5831                "              param7),\n"
5832                "#else\n"
5833                "              param8),\n"
5834                "       param9,\n"
5835                "#endif\n"
5836                "       param10,\n"
5837                "#endif\n"
5838                "       param11)\n"
5839                "#else\n"
5840                "       param12)\n"
5841                "#endif\n"
5842                "{\n"
5843                "  x();\n"
5844                "}",
5845                getLLVMStyleWithColumns(28));
5846   verifyFormat("#if 1\n"
5847                "int i;");
5848   verifyFormat("#if 1\n"
5849                "#endif\n"
5850                "#if 1\n"
5851                "#else\n"
5852                "#endif\n");
5853   verifyFormat("DEBUG({\n"
5854                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5855                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5856                "});\n"
5857                "#if a\n"
5858                "#else\n"
5859                "#endif");
5860 
5861   verifyIncompleteFormat("void f(\n"
5862                          "#if A\n"
5863                          ");\n"
5864                          "#else\n"
5865                          "#endif");
5866 }
5867 
5868 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5869   verifyFormat("#endif\n"
5870                "#if B");
5871 }
5872 
5873 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5874   FormatStyle SingleLine = getLLVMStyle();
5875   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5876   verifyFormat("#if 0\n"
5877                "#elif 1\n"
5878                "#endif\n"
5879                "void foo() {\n"
5880                "  if (test) foo2();\n"
5881                "}",
5882                SingleLine);
5883 }
5884 
5885 TEST_F(FormatTest, LayoutBlockInsideParens) {
5886   verifyFormat("functionCall({ int i; });");
5887   verifyFormat("functionCall({\n"
5888                "  int i;\n"
5889                "  int j;\n"
5890                "});");
5891   verifyFormat("functionCall(\n"
5892                "    {\n"
5893                "      int i;\n"
5894                "      int j;\n"
5895                "    },\n"
5896                "    aaaa, bbbb, cccc);");
5897   verifyFormat("functionA(functionB({\n"
5898                "            int i;\n"
5899                "            int j;\n"
5900                "          }),\n"
5901                "          aaaa, bbbb, cccc);");
5902   verifyFormat("functionCall(\n"
5903                "    {\n"
5904                "      int i;\n"
5905                "      int j;\n"
5906                "    },\n"
5907                "    aaaa, bbbb, // comment\n"
5908                "    cccc);");
5909   verifyFormat("functionA(functionB({\n"
5910                "            int i;\n"
5911                "            int j;\n"
5912                "          }),\n"
5913                "          aaaa, bbbb, // comment\n"
5914                "          cccc);");
5915   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5916   verifyFormat("functionCall(aaaa, bbbb, {\n"
5917                "  int i;\n"
5918                "  int j;\n"
5919                "});");
5920   verifyFormat(
5921       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5922       "    {\n"
5923       "      int i; // break\n"
5924       "    },\n"
5925       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5926       "                                     ccccccccccccccccc));");
5927   verifyFormat("DEBUG({\n"
5928                "  if (a)\n"
5929                "    f();\n"
5930                "});");
5931 }
5932 
5933 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5934   EXPECT_EQ("SOME_MACRO { int i; }\n"
5935             "int i;",
5936             format("  SOME_MACRO  {int i;}  int i;"));
5937 }
5938 
5939 TEST_F(FormatTest, LayoutNestedBlocks) {
5940   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5941                "  struct s {\n"
5942                "    int i;\n"
5943                "  };\n"
5944                "  s kBitsToOs[] = {{10}};\n"
5945                "  for (int i = 0; i < 10; ++i)\n"
5946                "    return;\n"
5947                "}");
5948   verifyFormat("call(parameter, {\n"
5949                "  something();\n"
5950                "  // Comment using all columns.\n"
5951                "  somethingelse();\n"
5952                "});",
5953                getLLVMStyleWithColumns(40));
5954   verifyFormat("DEBUG( //\n"
5955                "    { f(); }, a);");
5956   verifyFormat("DEBUG( //\n"
5957                "    {\n"
5958                "      f(); //\n"
5959                "    },\n"
5960                "    a);");
5961 
5962   EXPECT_EQ("call(parameter, {\n"
5963             "  something();\n"
5964             "  // Comment too\n"
5965             "  // looooooooooong.\n"
5966             "  somethingElse();\n"
5967             "});",
5968             format("call(parameter, {\n"
5969                    "  something();\n"
5970                    "  // Comment too looooooooooong.\n"
5971                    "  somethingElse();\n"
5972                    "});",
5973                    getLLVMStyleWithColumns(29)));
5974   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5975   EXPECT_EQ("DEBUG({ // comment\n"
5976             "  int i;\n"
5977             "});",
5978             format("DEBUG({ // comment\n"
5979                    "int  i;\n"
5980                    "});"));
5981   EXPECT_EQ("DEBUG({\n"
5982             "  int i;\n"
5983             "\n"
5984             "  // comment\n"
5985             "  int j;\n"
5986             "});",
5987             format("DEBUG({\n"
5988                    "  int  i;\n"
5989                    "\n"
5990                    "  // comment\n"
5991                    "  int  j;\n"
5992                    "});"));
5993 
5994   verifyFormat("DEBUG({\n"
5995                "  if (a)\n"
5996                "    return;\n"
5997                "});");
5998   verifyGoogleFormat("DEBUG({\n"
5999                      "  if (a) return;\n"
6000                      "});");
6001   FormatStyle Style = getGoogleStyle();
6002   Style.ColumnLimit = 45;
6003   verifyFormat("Debug(\n"
6004                "    aaaaa,\n"
6005                "    {\n"
6006                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
6007                "    },\n"
6008                "    a);",
6009                Style);
6010 
6011   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
6012 
6013   verifyNoCrash("^{v^{a}}");
6014 }
6015 
6016 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
6017   EXPECT_EQ("#define MACRO()                     \\\n"
6018             "  Debug(aaa, /* force line break */ \\\n"
6019             "        {                           \\\n"
6020             "          int i;                    \\\n"
6021             "          int j;                    \\\n"
6022             "        })",
6023             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
6024                    "          {  int   i;  int  j;   })",
6025                    getGoogleStyle()));
6026 
6027   EXPECT_EQ("#define A                                       \\\n"
6028             "  [] {                                          \\\n"
6029             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
6030             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
6031             "  }",
6032             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
6033                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
6034                    getGoogleStyle()));
6035 }
6036 
6037 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
6038   EXPECT_EQ("{}", format("{}"));
6039   verifyFormat("enum E {};");
6040   verifyFormat("enum E {}");
6041   FormatStyle Style = getLLVMStyle();
6042   Style.SpaceInEmptyBlock = true;
6043   EXPECT_EQ("void f() { }", format("void f() {}", Style));
6044   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
6045   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
6046   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
6047   Style.BraceWrapping.BeforeElse = false;
6048   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
6049   verifyFormat("if (a)\n"
6050                "{\n"
6051                "} else if (b)\n"
6052                "{\n"
6053                "} else\n"
6054                "{ }",
6055                Style);
6056   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
6057   verifyFormat("if (a) {\n"
6058                "} else if (b) {\n"
6059                "} else {\n"
6060                "}",
6061                Style);
6062   Style.BraceWrapping.BeforeElse = true;
6063   verifyFormat("if (a) { }\n"
6064                "else if (b) { }\n"
6065                "else { }",
6066                Style);
6067 }
6068 
6069 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
6070   FormatStyle Style = getLLVMStyle();
6071   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
6072   Style.MacroBlockEnd = "^[A-Z_]+_END$";
6073   verifyFormat("FOO_BEGIN\n"
6074                "  FOO_ENTRY\n"
6075                "FOO_END",
6076                Style);
6077   verifyFormat("FOO_BEGIN\n"
6078                "  NESTED_FOO_BEGIN\n"
6079                "    NESTED_FOO_ENTRY\n"
6080                "  NESTED_FOO_END\n"
6081                "FOO_END",
6082                Style);
6083   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
6084                "  int x;\n"
6085                "  x = 1;\n"
6086                "FOO_END(Baz)",
6087                Style);
6088 }
6089 
6090 //===----------------------------------------------------------------------===//
6091 // Line break tests.
6092 //===----------------------------------------------------------------------===//
6093 
6094 TEST_F(FormatTest, PreventConfusingIndents) {
6095   verifyFormat(
6096       "void f() {\n"
6097       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
6098       "                         parameter, parameter, parameter)),\n"
6099       "                     SecondLongCall(parameter));\n"
6100       "}");
6101   verifyFormat(
6102       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6103       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6104       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6105       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
6106   verifyFormat(
6107       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6108       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
6109       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6110       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
6111   verifyFormat(
6112       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
6113       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
6114       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
6115       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
6116   verifyFormat("int a = bbbb && ccc &&\n"
6117                "        fffff(\n"
6118                "#define A Just forcing a new line\n"
6119                "            ddd);");
6120 }
6121 
6122 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
6123   verifyFormat(
6124       "bool aaaaaaa =\n"
6125       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
6126       "    bbbbbbbb();");
6127   verifyFormat(
6128       "bool aaaaaaa =\n"
6129       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
6130       "    bbbbbbbb();");
6131 
6132   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6133                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
6134                "    ccccccccc == ddddddddddd;");
6135   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6136                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
6137                "    ccccccccc == ddddddddddd;");
6138   verifyFormat(
6139       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6140       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
6141       "    ccccccccc == ddddddddddd;");
6142 
6143   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6144                "                 aaaaaa) &&\n"
6145                "         bbbbbb && cccccc;");
6146   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6147                "                 aaaaaa) >>\n"
6148                "         bbbbbb;");
6149   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
6150                "    SourceMgr.getSpellingColumnNumber(\n"
6151                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
6152                "    1);");
6153 
6154   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6155                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
6156                "    cccccc) {\n}");
6157   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6158                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6159                "              cccccc) {\n}");
6160   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6161                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6162                "              cccccc) {\n}");
6163   verifyFormat("b = a &&\n"
6164                "    // Comment\n"
6165                "    b.c && d;");
6166 
6167   // If the LHS of a comparison is not a binary expression itself, the
6168   // additional linebreak confuses many people.
6169   verifyFormat(
6170       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6171       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
6172       "}");
6173   verifyFormat(
6174       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6175       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6176       "}");
6177   verifyFormat(
6178       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
6179       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6180       "}");
6181   verifyFormat(
6182       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6183       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
6184       "}");
6185   // Even explicit parentheses stress the precedence enough to make the
6186   // additional break unnecessary.
6187   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6188                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6189                "}");
6190   // This cases is borderline, but with the indentation it is still readable.
6191   verifyFormat(
6192       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6193       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6194       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
6195       "}",
6196       getLLVMStyleWithColumns(75));
6197 
6198   // If the LHS is a binary expression, we should still use the additional break
6199   // as otherwise the formatting hides the operator precedence.
6200   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6201                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6202                "    5) {\n"
6203                "}");
6204   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6205                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
6206                "    5) {\n"
6207                "}");
6208 
6209   FormatStyle OnePerLine = getLLVMStyle();
6210   OnePerLine.BinPackParameters = false;
6211   verifyFormat(
6212       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6213       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6214       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
6215       OnePerLine);
6216 
6217   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
6218                "                .aaa(aaaaaaaaaaaaa) *\n"
6219                "            aaaaaaa +\n"
6220                "        aaaaaaa;",
6221                getLLVMStyleWithColumns(40));
6222 }
6223 
6224 TEST_F(FormatTest, ExpressionIndentation) {
6225   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6226                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6227                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6228                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6229                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6230                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
6231                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6232                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
6233                "                 ccccccccccccccccccccccccccccccccccccccccc;");
6234   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6235                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6236                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6237                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6238   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6239                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6240                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6241                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6242   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6243                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6244                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6245                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6246   verifyFormat("if () {\n"
6247                "} else if (aaaaa && bbbbb > // break\n"
6248                "                        ccccc) {\n"
6249                "}");
6250   verifyFormat("if () {\n"
6251                "} else if constexpr (aaaaa && bbbbb > // break\n"
6252                "                                  ccccc) {\n"
6253                "}");
6254   verifyFormat("if () {\n"
6255                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
6256                "                                  ccccc) {\n"
6257                "}");
6258   verifyFormat("if () {\n"
6259                "} else if (aaaaa &&\n"
6260                "           bbbbb > // break\n"
6261                "               ccccc &&\n"
6262                "           ddddd) {\n"
6263                "}");
6264 
6265   // Presence of a trailing comment used to change indentation of b.
6266   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
6267                "       b;\n"
6268                "return aaaaaaaaaaaaaaaaaaa +\n"
6269                "       b; //",
6270                getLLVMStyleWithColumns(30));
6271 }
6272 
6273 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
6274   // Not sure what the best system is here. Like this, the LHS can be found
6275   // immediately above an operator (everything with the same or a higher
6276   // indent). The RHS is aligned right of the operator and so compasses
6277   // everything until something with the same indent as the operator is found.
6278   // FIXME: Is this a good system?
6279   FormatStyle Style = getLLVMStyle();
6280   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6281   verifyFormat(
6282       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6283       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6284       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6285       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6286       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6287       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6288       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6289       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6290       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
6291       Style);
6292   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6293                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6294                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6295                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6296                Style);
6297   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6298                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6299                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6300                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6301                Style);
6302   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6303                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6304                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6305                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6306                Style);
6307   verifyFormat("if () {\n"
6308                "} else if (aaaaa\n"
6309                "           && bbbbb // break\n"
6310                "                  > ccccc) {\n"
6311                "}",
6312                Style);
6313   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6314                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6315                Style);
6316   verifyFormat("return (a)\n"
6317                "       // comment\n"
6318                "       + b;",
6319                Style);
6320   verifyFormat(
6321       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6322       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6323       "             + cc;",
6324       Style);
6325 
6326   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6327                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6328                Style);
6329 
6330   // Forced by comments.
6331   verifyFormat(
6332       "unsigned ContentSize =\n"
6333       "    sizeof(int16_t)   // DWARF ARange version number\n"
6334       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6335       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6336       "    + sizeof(int8_t); // Segment Size (in bytes)");
6337 
6338   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6339                "       == boost::fusion::at_c<1>(iiii).second;",
6340                Style);
6341 
6342   Style.ColumnLimit = 60;
6343   verifyFormat("zzzzzzzzzz\n"
6344                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6345                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6346                Style);
6347 
6348   Style.ColumnLimit = 80;
6349   Style.IndentWidth = 4;
6350   Style.TabWidth = 4;
6351   Style.UseTab = FormatStyle::UT_Always;
6352   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6353   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6354   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
6355             "\t&& (someOtherLongishConditionPart1\n"
6356             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
6357             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
6358                    "(someOtherLongishConditionPart1 || "
6359                    "someOtherEvenLongerNestedConditionPart2);",
6360                    Style));
6361 }
6362 
6363 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
6364   FormatStyle Style = getLLVMStyle();
6365   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6366   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
6367 
6368   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6369                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6370                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6371                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6372                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6373                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6374                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6375                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6376                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
6377                Style);
6378   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6379                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6380                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6381                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6382                Style);
6383   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6384                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6385                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6386                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6387                Style);
6388   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6389                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6390                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6391                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6392                Style);
6393   verifyFormat("if () {\n"
6394                "} else if (aaaaa\n"
6395                "           && bbbbb // break\n"
6396                "                  > ccccc) {\n"
6397                "}",
6398                Style);
6399   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6400                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6401                Style);
6402   verifyFormat("return (a)\n"
6403                "     // comment\n"
6404                "     + b;",
6405                Style);
6406   verifyFormat(
6407       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6408       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6409       "           + cc;",
6410       Style);
6411   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6412                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6413                "                        : 3333333333333333;",
6414                Style);
6415   verifyFormat(
6416       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6417       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6418       "                                             : eeeeeeeeeeeeeeeeee)\n"
6419       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6420       "                        : 3333333333333333;",
6421       Style);
6422   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6423                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6424                Style);
6425 
6426   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6427                "    == boost::fusion::at_c<1>(iiii).second;",
6428                Style);
6429 
6430   Style.ColumnLimit = 60;
6431   verifyFormat("zzzzzzzzzzzzz\n"
6432                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6433                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6434                Style);
6435 
6436   // Forced by comments.
6437   Style.ColumnLimit = 80;
6438   verifyFormat(
6439       "unsigned ContentSize\n"
6440       "    = sizeof(int16_t) // DWARF ARange version number\n"
6441       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6442       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6443       "    + sizeof(int8_t); // Segment Size (in bytes)",
6444       Style);
6445 
6446   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6447   verifyFormat(
6448       "unsigned ContentSize =\n"
6449       "    sizeof(int16_t)   // DWARF ARange version number\n"
6450       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6451       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6452       "    + sizeof(int8_t); // Segment Size (in bytes)",
6453       Style);
6454 
6455   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6456   verifyFormat(
6457       "unsigned ContentSize =\n"
6458       "    sizeof(int16_t)   // DWARF ARange version number\n"
6459       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6460       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6461       "    + sizeof(int8_t); // Segment Size (in bytes)",
6462       Style);
6463 }
6464 
6465 TEST_F(FormatTest, EnforcedOperatorWraps) {
6466   // Here we'd like to wrap after the || operators, but a comment is forcing an
6467   // earlier wrap.
6468   verifyFormat("bool x = aaaaa //\n"
6469                "         || bbbbb\n"
6470                "         //\n"
6471                "         || cccc;");
6472 }
6473 
6474 TEST_F(FormatTest, NoOperandAlignment) {
6475   FormatStyle Style = getLLVMStyle();
6476   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6477   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6478                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6479                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6480                Style);
6481   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6482   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6483                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6484                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6485                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6486                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6487                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6488                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6489                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6490                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6491                Style);
6492 
6493   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6494                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6495                "    + cc;",
6496                Style);
6497   verifyFormat("int a = aa\n"
6498                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6499                "        * cccccccccccccccccccccccccccccccccccc;\n",
6500                Style);
6501 
6502   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6503   verifyFormat("return (a > b\n"
6504                "    // comment1\n"
6505                "    // comment2\n"
6506                "    || c);",
6507                Style);
6508 }
6509 
6510 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6511   FormatStyle Style = getLLVMStyle();
6512   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6513   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6514                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6515                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6516                Style);
6517 }
6518 
6519 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6520   FormatStyle Style = getLLVMStyleWithColumns(40);
6521   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6522   Style.BinPackArguments = false;
6523   verifyFormat("void test() {\n"
6524                "  someFunction(\n"
6525                "      this + argument + is + quite\n"
6526                "      + long + so + it + gets + wrapped\n"
6527                "      + but + remains + bin - packed);\n"
6528                "}",
6529                Style);
6530   verifyFormat("void test() {\n"
6531                "  someFunction(arg1,\n"
6532                "               this + argument + is\n"
6533                "                   + quite + long + so\n"
6534                "                   + it + gets + wrapped\n"
6535                "                   + but + remains + bin\n"
6536                "                   - packed,\n"
6537                "               arg3);\n"
6538                "}",
6539                Style);
6540   verifyFormat("void test() {\n"
6541                "  someFunction(\n"
6542                "      arg1,\n"
6543                "      this + argument + has\n"
6544                "          + anotherFunc(nested,\n"
6545                "                        calls + whose\n"
6546                "                            + arguments\n"
6547                "                            + are + also\n"
6548                "                            + wrapped,\n"
6549                "                        in + addition)\n"
6550                "          + to + being + bin - packed,\n"
6551                "      arg3);\n"
6552                "}",
6553                Style);
6554 
6555   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6556   verifyFormat("void test() {\n"
6557                "  someFunction(\n"
6558                "      arg1,\n"
6559                "      this + argument + has +\n"
6560                "          anotherFunc(nested,\n"
6561                "                      calls + whose +\n"
6562                "                          arguments +\n"
6563                "                          are + also +\n"
6564                "                          wrapped,\n"
6565                "                      in + addition) +\n"
6566                "          to + being + bin - packed,\n"
6567                "      arg3);\n"
6568                "}",
6569                Style);
6570 }
6571 
6572 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) {
6573   auto Style = getLLVMStyleWithColumns(45);
6574   EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None);
6575   verifyFormat("bool b =\n"
6576                "    is_default_constructible_v<hash<T>> and\n"
6577                "    is_copy_constructible_v<hash<T>> and\n"
6578                "    is_move_constructible_v<hash<T>> and\n"
6579                "    is_copy_assignable_v<hash<T>> and\n"
6580                "    is_move_assignable_v<hash<T>> and\n"
6581                "    is_destructible_v<hash<T>> and\n"
6582                "    is_swappable_v<hash<T>> and\n"
6583                "    is_callable_v<hash<T>(T)>;",
6584                Style);
6585 
6586   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6587   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6588                "         and is_copy_constructible_v<hash<T>>\n"
6589                "         and is_move_constructible_v<hash<T>>\n"
6590                "         and is_copy_assignable_v<hash<T>>\n"
6591                "         and is_move_assignable_v<hash<T>>\n"
6592                "         and is_destructible_v<hash<T>>\n"
6593                "         and is_swappable_v<hash<T>>\n"
6594                "         and is_callable_v<hash<T>(T)>;",
6595                Style);
6596 
6597   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6598   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6599                "         and is_copy_constructible_v<hash<T>>\n"
6600                "         and is_move_constructible_v<hash<T>>\n"
6601                "         and is_copy_assignable_v<hash<T>>\n"
6602                "         and is_move_assignable_v<hash<T>>\n"
6603                "         and is_destructible_v<hash<T>>\n"
6604                "         and is_swappable_v<hash<T>>\n"
6605                "         and is_callable_v<hash<T>(T)>;",
6606                Style);
6607 }
6608 
6609 TEST_F(FormatTest, ConstructorInitializers) {
6610   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6611   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6612                getLLVMStyleWithColumns(45));
6613   verifyFormat("Constructor()\n"
6614                "    : Inttializer(FitsOnTheLine) {}",
6615                getLLVMStyleWithColumns(44));
6616   verifyFormat("Constructor()\n"
6617                "    : Inttializer(FitsOnTheLine) {}",
6618                getLLVMStyleWithColumns(43));
6619 
6620   verifyFormat("template <typename T>\n"
6621                "Constructor() : Initializer(FitsOnTheLine) {}",
6622                getLLVMStyleWithColumns(45));
6623 
6624   verifyFormat(
6625       "SomeClass::Constructor()\n"
6626       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6627 
6628   verifyFormat(
6629       "SomeClass::Constructor()\n"
6630       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6631       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6632   verifyFormat(
6633       "SomeClass::Constructor()\n"
6634       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6635       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6636   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6637                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6638                "    : aaaaaaaaaa(aaaaaa) {}");
6639 
6640   verifyFormat("Constructor()\n"
6641                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6642                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6643                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6644                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6645 
6646   verifyFormat("Constructor()\n"
6647                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6648                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6649 
6650   verifyFormat("Constructor(int Parameter = 0)\n"
6651                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6652                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6653   verifyFormat("Constructor()\n"
6654                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6655                "}",
6656                getLLVMStyleWithColumns(60));
6657   verifyFormat("Constructor()\n"
6658                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6659                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6660 
6661   // Here a line could be saved by splitting the second initializer onto two
6662   // lines, but that is not desirable.
6663   verifyFormat("Constructor()\n"
6664                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6665                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6666                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6667 
6668   FormatStyle OnePerLine = getLLVMStyle();
6669   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6670   verifyFormat("MyClass::MyClass()\n"
6671                "    : a(a),\n"
6672                "      b(b),\n"
6673                "      c(c) {}",
6674                OnePerLine);
6675   verifyFormat("MyClass::MyClass()\n"
6676                "    : a(a), // comment\n"
6677                "      b(b),\n"
6678                "      c(c) {}",
6679                OnePerLine);
6680   verifyFormat("MyClass::MyClass(int a)\n"
6681                "    : b(a),      // comment\n"
6682                "      c(a + 1) { // lined up\n"
6683                "}",
6684                OnePerLine);
6685   verifyFormat("Constructor()\n"
6686                "    : a(b, b, b) {}",
6687                OnePerLine);
6688   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6689   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6690   verifyFormat("SomeClass::Constructor()\n"
6691                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6692                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6693                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6694                OnePerLine);
6695   verifyFormat("SomeClass::Constructor()\n"
6696                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6697                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6698                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6699                OnePerLine);
6700   verifyFormat("MyClass::MyClass(int var)\n"
6701                "    : some_var_(var),            // 4 space indent\n"
6702                "      some_other_var_(var + 1) { // lined up\n"
6703                "}",
6704                OnePerLine);
6705   verifyFormat("Constructor()\n"
6706                "    : aaaaa(aaaaaa),\n"
6707                "      aaaaa(aaaaaa),\n"
6708                "      aaaaa(aaaaaa),\n"
6709                "      aaaaa(aaaaaa),\n"
6710                "      aaaaa(aaaaaa) {}",
6711                OnePerLine);
6712   verifyFormat("Constructor()\n"
6713                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6714                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6715                OnePerLine);
6716   OnePerLine.BinPackParameters = false;
6717   verifyFormat(
6718       "Constructor()\n"
6719       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6720       "          aaaaaaaaaaa().aaa(),\n"
6721       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6722       OnePerLine);
6723   OnePerLine.ColumnLimit = 60;
6724   verifyFormat("Constructor()\n"
6725                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6726                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6727                OnePerLine);
6728 
6729   EXPECT_EQ("Constructor()\n"
6730             "    : // Comment forcing unwanted break.\n"
6731             "      aaaa(aaaa) {}",
6732             format("Constructor() :\n"
6733                    "    // Comment forcing unwanted break.\n"
6734                    "    aaaa(aaaa) {}"));
6735 }
6736 
6737 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6738   FormatStyle Style = getLLVMStyleWithColumns(60);
6739   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6740   Style.BinPackParameters = false;
6741 
6742   for (int i = 0; i < 4; ++i) {
6743     // Test all combinations of parameters that should not have an effect.
6744     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6745     Style.AllowAllArgumentsOnNextLine = i & 2;
6746 
6747     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6748     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6749     verifyFormat("Constructor()\n"
6750                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6751                  Style);
6752     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6753 
6754     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6755     verifyFormat("Constructor()\n"
6756                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6757                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6758                  Style);
6759     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6760 
6761     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6762     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6763     verifyFormat("Constructor()\n"
6764                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6765                  Style);
6766 
6767     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6768     verifyFormat("Constructor()\n"
6769                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6770                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6771                  Style);
6772 
6773     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6774     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6775     verifyFormat("Constructor() :\n"
6776                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6777                  Style);
6778 
6779     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6780     verifyFormat("Constructor() :\n"
6781                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6782                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6783                  Style);
6784   }
6785 
6786   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6787   // AllowAllConstructorInitializersOnNextLine in all
6788   // BreakConstructorInitializers modes
6789   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6790   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6791   verifyFormat("SomeClassWithALongName::Constructor(\n"
6792                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6793                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6794                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6795                Style);
6796 
6797   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6798   verifyFormat("SomeClassWithALongName::Constructor(\n"
6799                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6800                "    int bbbbbbbbbbbbb,\n"
6801                "    int cccccccccccccccc)\n"
6802                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6803                Style);
6804 
6805   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6806   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6807   verifyFormat("SomeClassWithALongName::Constructor(\n"
6808                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6809                "    int bbbbbbbbbbbbb)\n"
6810                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6811                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6812                Style);
6813 
6814   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6815 
6816   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6817   verifyFormat("SomeClassWithALongName::Constructor(\n"
6818                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6819                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6820                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6821                Style);
6822 
6823   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6824   verifyFormat("SomeClassWithALongName::Constructor(\n"
6825                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6826                "    int bbbbbbbbbbbbb,\n"
6827                "    int cccccccccccccccc)\n"
6828                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6829                Style);
6830 
6831   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6832   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6833   verifyFormat("SomeClassWithALongName::Constructor(\n"
6834                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6835                "    int bbbbbbbbbbbbb)\n"
6836                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6837                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6838                Style);
6839 
6840   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6841   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6842   verifyFormat("SomeClassWithALongName::Constructor(\n"
6843                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6844                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6845                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6846                Style);
6847 
6848   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6849   verifyFormat("SomeClassWithALongName::Constructor(\n"
6850                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6851                "    int bbbbbbbbbbbbb,\n"
6852                "    int cccccccccccccccc) :\n"
6853                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6854                Style);
6855 
6856   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6857   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6858   verifyFormat("SomeClassWithALongName::Constructor(\n"
6859                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6860                "    int bbbbbbbbbbbbb) :\n"
6861                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6862                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6863                Style);
6864 }
6865 
6866 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6867   FormatStyle Style = getLLVMStyleWithColumns(60);
6868   Style.BinPackArguments = false;
6869   for (int i = 0; i < 4; ++i) {
6870     // Test all combinations of parameters that should not have an effect.
6871     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6872     Style.PackConstructorInitializers =
6873         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6874 
6875     Style.AllowAllArgumentsOnNextLine = true;
6876     verifyFormat("void foo() {\n"
6877                  "  FunctionCallWithReallyLongName(\n"
6878                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6879                  "}",
6880                  Style);
6881     Style.AllowAllArgumentsOnNextLine = false;
6882     verifyFormat("void foo() {\n"
6883                  "  FunctionCallWithReallyLongName(\n"
6884                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6885                  "      bbbbbbbbbbbb);\n"
6886                  "}",
6887                  Style);
6888 
6889     Style.AllowAllArgumentsOnNextLine = true;
6890     verifyFormat("void foo() {\n"
6891                  "  auto VariableWithReallyLongName = {\n"
6892                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6893                  "}",
6894                  Style);
6895     Style.AllowAllArgumentsOnNextLine = false;
6896     verifyFormat("void foo() {\n"
6897                  "  auto VariableWithReallyLongName = {\n"
6898                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6899                  "      bbbbbbbbbbbb};\n"
6900                  "}",
6901                  Style);
6902   }
6903 
6904   // This parameter should not affect declarations.
6905   Style.BinPackParameters = false;
6906   Style.AllowAllArgumentsOnNextLine = false;
6907   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6908   verifyFormat("void FunctionCallWithReallyLongName(\n"
6909                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6910                Style);
6911   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6912   verifyFormat("void FunctionCallWithReallyLongName(\n"
6913                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6914                "    int bbbbbbbbbbbb);",
6915                Style);
6916 }
6917 
6918 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6919   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6920   // and BAS_Align.
6921   FormatStyle Style = getLLVMStyleWithColumns(35);
6922   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6923                     "void functionDecl(int A, int B, int C);";
6924   Style.AllowAllArgumentsOnNextLine = false;
6925   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6926   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6927                       "    paramC);\n"
6928                       "void functionDecl(int A, int B,\n"
6929                       "    int C);"),
6930             format(Input, Style));
6931   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6932   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6933                       "             paramC);\n"
6934                       "void functionDecl(int A, int B,\n"
6935                       "                  int C);"),
6936             format(Input, Style));
6937   // However, BAS_AlwaysBreak should take precedence over
6938   // AllowAllArgumentsOnNextLine.
6939   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6940   EXPECT_EQ(StringRef("functionCall(\n"
6941                       "    paramA, paramB, paramC);\n"
6942                       "void functionDecl(\n"
6943                       "    int A, int B, int C);"),
6944             format(Input, Style));
6945 
6946   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6947   // first argument.
6948   Style.AllowAllArgumentsOnNextLine = true;
6949   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6950   EXPECT_EQ(StringRef("functionCall(\n"
6951                       "    paramA, paramB, paramC);\n"
6952                       "void functionDecl(\n"
6953                       "    int A, int B, int C);"),
6954             format(Input, Style));
6955   // It wouldn't fit on one line with aligned parameters so this setting
6956   // doesn't change anything for BAS_Align.
6957   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6958   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6959                       "             paramC);\n"
6960                       "void functionDecl(int A, int B,\n"
6961                       "                  int C);"),
6962             format(Input, Style));
6963   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6964   EXPECT_EQ(StringRef("functionCall(\n"
6965                       "    paramA, paramB, paramC);\n"
6966                       "void functionDecl(\n"
6967                       "    int A, int B, int C);"),
6968             format(Input, Style));
6969 }
6970 
6971 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6972   FormatStyle Style = getLLVMStyle();
6973   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6974 
6975   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6976   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6977                getStyleWithColumns(Style, 45));
6978   verifyFormat("Constructor() :\n"
6979                "    Initializer(FitsOnTheLine) {}",
6980                getStyleWithColumns(Style, 44));
6981   verifyFormat("Constructor() :\n"
6982                "    Initializer(FitsOnTheLine) {}",
6983                getStyleWithColumns(Style, 43));
6984 
6985   verifyFormat("template <typename T>\n"
6986                "Constructor() : Initializer(FitsOnTheLine) {}",
6987                getStyleWithColumns(Style, 50));
6988   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6989   verifyFormat(
6990       "SomeClass::Constructor() :\n"
6991       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6992       Style);
6993 
6994   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6995   verifyFormat(
6996       "SomeClass::Constructor() :\n"
6997       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6998       Style);
6999 
7000   verifyFormat(
7001       "SomeClass::Constructor() :\n"
7002       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7003       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7004       Style);
7005   verifyFormat(
7006       "SomeClass::Constructor() :\n"
7007       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7008       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
7009       Style);
7010   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7011                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7012                "    aaaaaaaaaa(aaaaaa) {}",
7013                Style);
7014 
7015   verifyFormat("Constructor() :\n"
7016                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7017                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7018                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7019                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
7020                Style);
7021 
7022   verifyFormat("Constructor() :\n"
7023                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7024                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7025                Style);
7026 
7027   verifyFormat("Constructor(int Parameter = 0) :\n"
7028                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
7029                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
7030                Style);
7031   verifyFormat("Constructor() :\n"
7032                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
7033                "}",
7034                getStyleWithColumns(Style, 60));
7035   verifyFormat("Constructor() :\n"
7036                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7037                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
7038                Style);
7039 
7040   // Here a line could be saved by splitting the second initializer onto two
7041   // lines, but that is not desirable.
7042   verifyFormat("Constructor() :\n"
7043                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
7044                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
7045                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7046                Style);
7047 
7048   FormatStyle OnePerLine = Style;
7049   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
7050   verifyFormat("SomeClass::Constructor() :\n"
7051                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7052                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7053                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7054                OnePerLine);
7055   verifyFormat("SomeClass::Constructor() :\n"
7056                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
7057                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7058                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7059                OnePerLine);
7060   verifyFormat("MyClass::MyClass(int var) :\n"
7061                "    some_var_(var),            // 4 space indent\n"
7062                "    some_other_var_(var + 1) { // lined up\n"
7063                "}",
7064                OnePerLine);
7065   verifyFormat("Constructor() :\n"
7066                "    aaaaa(aaaaaa),\n"
7067                "    aaaaa(aaaaaa),\n"
7068                "    aaaaa(aaaaaa),\n"
7069                "    aaaaa(aaaaaa),\n"
7070                "    aaaaa(aaaaaa) {}",
7071                OnePerLine);
7072   verifyFormat("Constructor() :\n"
7073                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
7074                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
7075                OnePerLine);
7076   OnePerLine.BinPackParameters = false;
7077   verifyFormat("Constructor() :\n"
7078                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7079                "        aaaaaaaaaaa().aaa(),\n"
7080                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7081                OnePerLine);
7082   OnePerLine.ColumnLimit = 60;
7083   verifyFormat("Constructor() :\n"
7084                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
7085                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
7086                OnePerLine);
7087 
7088   EXPECT_EQ("Constructor() :\n"
7089             "    // Comment forcing unwanted break.\n"
7090             "    aaaa(aaaa) {}",
7091             format("Constructor() :\n"
7092                    "    // Comment forcing unwanted break.\n"
7093                    "    aaaa(aaaa) {}",
7094                    Style));
7095 
7096   Style.ColumnLimit = 0;
7097   verifyFormat("SomeClass::Constructor() :\n"
7098                "    a(a) {}",
7099                Style);
7100   verifyFormat("SomeClass::Constructor() noexcept :\n"
7101                "    a(a) {}",
7102                Style);
7103   verifyFormat("SomeClass::Constructor() :\n"
7104                "    a(a), b(b), c(c) {}",
7105                Style);
7106   verifyFormat("SomeClass::Constructor() :\n"
7107                "    a(a) {\n"
7108                "  foo();\n"
7109                "  bar();\n"
7110                "}",
7111                Style);
7112 
7113   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
7114   verifyFormat("SomeClass::Constructor() :\n"
7115                "    a(a), b(b), c(c) {\n"
7116                "}",
7117                Style);
7118   verifyFormat("SomeClass::Constructor() :\n"
7119                "    a(a) {\n"
7120                "}",
7121                Style);
7122 
7123   Style.ColumnLimit = 80;
7124   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
7125   Style.ConstructorInitializerIndentWidth = 2;
7126   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
7127   verifyFormat("SomeClass::Constructor() :\n"
7128                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7129                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
7130                Style);
7131 
7132   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
7133   // well
7134   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
7135   verifyFormat(
7136       "class SomeClass\n"
7137       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7138       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7139       Style);
7140   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
7141   verifyFormat(
7142       "class SomeClass\n"
7143       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7144       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7145       Style);
7146   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
7147   verifyFormat(
7148       "class SomeClass :\n"
7149       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7150       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7151       Style);
7152   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
7153   verifyFormat(
7154       "class SomeClass\n"
7155       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7156       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7157       Style);
7158 }
7159 
7160 #ifndef EXPENSIVE_CHECKS
7161 // Expensive checks enables libstdc++ checking which includes validating the
7162 // state of ranges used in std::priority_queue - this blows out the
7163 // runtime/scalability of the function and makes this test unacceptably slow.
7164 TEST_F(FormatTest, MemoizationTests) {
7165   // This breaks if the memoization lookup does not take \c Indent and
7166   // \c LastSpace into account.
7167   verifyFormat(
7168       "extern CFRunLoopTimerRef\n"
7169       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
7170       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
7171       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
7172       "                     CFRunLoopTimerContext *context) {}");
7173 
7174   // Deep nesting somewhat works around our memoization.
7175   verifyFormat(
7176       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7177       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7178       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7179       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7180       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
7181       getLLVMStyleWithColumns(65));
7182   verifyFormat(
7183       "aaaaa(\n"
7184       "    aaaaa,\n"
7185       "    aaaaa(\n"
7186       "        aaaaa,\n"
7187       "        aaaaa(\n"
7188       "            aaaaa,\n"
7189       "            aaaaa(\n"
7190       "                aaaaa,\n"
7191       "                aaaaa(\n"
7192       "                    aaaaa,\n"
7193       "                    aaaaa(\n"
7194       "                        aaaaa,\n"
7195       "                        aaaaa(\n"
7196       "                            aaaaa,\n"
7197       "                            aaaaa(\n"
7198       "                                aaaaa,\n"
7199       "                                aaaaa(\n"
7200       "                                    aaaaa,\n"
7201       "                                    aaaaa(\n"
7202       "                                        aaaaa,\n"
7203       "                                        aaaaa(\n"
7204       "                                            aaaaa,\n"
7205       "                                            aaaaa(\n"
7206       "                                                aaaaa,\n"
7207       "                                                aaaaa))))))))))));",
7208       getLLVMStyleWithColumns(65));
7209   verifyFormat(
7210       "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"
7211       "                                  a),\n"
7212       "                                a),\n"
7213       "                              a),\n"
7214       "                            a),\n"
7215       "                          a),\n"
7216       "                        a),\n"
7217       "                      a),\n"
7218       "                    a),\n"
7219       "                  a),\n"
7220       "                a),\n"
7221       "              a),\n"
7222       "            a),\n"
7223       "          a),\n"
7224       "        a),\n"
7225       "      a),\n"
7226       "    a),\n"
7227       "  a)",
7228       getLLVMStyleWithColumns(65));
7229 
7230   // This test takes VERY long when memoization is broken.
7231   FormatStyle OnePerLine = getLLVMStyle();
7232   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
7233   OnePerLine.BinPackParameters = false;
7234   std::string input = "Constructor()\n"
7235                       "    : aaaa(a,\n";
7236   for (unsigned i = 0, e = 80; i != e; ++i)
7237     input += "           a,\n";
7238   input += "           a) {}";
7239   verifyFormat(input, OnePerLine);
7240 }
7241 #endif
7242 
7243 TEST_F(FormatTest, BreaksAsHighAsPossible) {
7244   verifyFormat(
7245       "void f() {\n"
7246       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
7247       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
7248       "    f();\n"
7249       "}");
7250   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
7251                "    Intervals[i - 1].getRange().getLast()) {\n}");
7252 }
7253 
7254 TEST_F(FormatTest, BreaksFunctionDeclarations) {
7255   // Principially, we break function declarations in a certain order:
7256   // 1) break amongst arguments.
7257   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
7258                "                              Cccccccccccccc cccccccccccccc);");
7259   verifyFormat("template <class TemplateIt>\n"
7260                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
7261                "                            TemplateIt *stop) {}");
7262 
7263   // 2) break after return type.
7264   verifyFormat(
7265       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7266       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
7267       getGoogleStyle());
7268 
7269   // 3) break after (.
7270   verifyFormat(
7271       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
7272       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
7273       getGoogleStyle());
7274 
7275   // 4) break before after nested name specifiers.
7276   verifyFormat(
7277       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7278       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
7279       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
7280       getGoogleStyle());
7281 
7282   // However, there are exceptions, if a sufficient amount of lines can be
7283   // saved.
7284   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
7285   // more adjusting.
7286   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7287                "                                  Cccccccccccccc cccccccccc,\n"
7288                "                                  Cccccccccccccc cccccccccc,\n"
7289                "                                  Cccccccccccccc cccccccccc,\n"
7290                "                                  Cccccccccccccc cccccccccc);");
7291   verifyFormat(
7292       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7293       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7294       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7295       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
7296       getGoogleStyle());
7297   verifyFormat(
7298       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7299       "                                          Cccccccccccccc cccccccccc,\n"
7300       "                                          Cccccccccccccc cccccccccc,\n"
7301       "                                          Cccccccccccccc cccccccccc,\n"
7302       "                                          Cccccccccccccc cccccccccc,\n"
7303       "                                          Cccccccccccccc cccccccccc,\n"
7304       "                                          Cccccccccccccc cccccccccc);");
7305   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7306                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7307                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7308                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7309                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
7310 
7311   // Break after multi-line parameters.
7312   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7313                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7314                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7315                "    bbbb bbbb);");
7316   verifyFormat("void SomeLoooooooooooongFunction(\n"
7317                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
7318                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7319                "    int bbbbbbbbbbbbb);");
7320 
7321   // Treat overloaded operators like other functions.
7322   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7323                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
7324   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7325                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
7326   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7327                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
7328   verifyGoogleFormat(
7329       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
7330       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7331   verifyGoogleFormat(
7332       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
7333       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7334   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7335                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7336   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
7337                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7338   verifyGoogleFormat(
7339       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
7340       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7341       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
7342   verifyGoogleFormat("template <typename T>\n"
7343                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7344                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
7345                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
7346 
7347   FormatStyle Style = getLLVMStyle();
7348   Style.PointerAlignment = FormatStyle::PAS_Left;
7349   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7350                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
7351                Style);
7352   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
7353                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7354                Style);
7355 }
7356 
7357 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
7358   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
7359   // Prefer keeping `::` followed by `operator` together.
7360   EXPECT_EQ("const aaaa::bbbbbbb &\n"
7361             "ccccccccc::operator++() {\n"
7362             "  stuff();\n"
7363             "}",
7364             format("const aaaa::bbbbbbb\n"
7365                    "&ccccccccc::operator++() { stuff(); }",
7366                    getLLVMStyleWithColumns(40)));
7367 }
7368 
7369 TEST_F(FormatTest, TrailingReturnType) {
7370   verifyFormat("auto foo() -> int;\n");
7371   // correct trailing return type spacing
7372   verifyFormat("auto operator->() -> int;\n");
7373   verifyFormat("auto operator++(int) -> int;\n");
7374 
7375   verifyFormat("struct S {\n"
7376                "  auto bar() const -> int;\n"
7377                "};");
7378   verifyFormat("template <size_t Order, typename T>\n"
7379                "auto load_img(const std::string &filename)\n"
7380                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
7381   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
7382                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
7383   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
7384   verifyFormat("template <typename T>\n"
7385                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
7386                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
7387 
7388   // Not trailing return types.
7389   verifyFormat("void f() { auto a = b->c(); }");
7390   verifyFormat("auto a = p->foo();");
7391   verifyFormat("int a = p->foo();");
7392   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
7393 }
7394 
7395 TEST_F(FormatTest, DeductionGuides) {
7396   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
7397   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
7398   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
7399   verifyFormat(
7400       "template <class... T>\n"
7401       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
7402   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
7403   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
7404   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
7405   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
7406   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
7407   verifyFormat("template <class T> x() -> x<1>;");
7408   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
7409 
7410   // Ensure not deduction guides.
7411   verifyFormat("c()->f<int>();");
7412   verifyFormat("x()->foo<1>;");
7413   verifyFormat("x = p->foo<3>();");
7414   verifyFormat("x()->x<1>();");
7415   verifyFormat("x()->x<1>;");
7416 }
7417 
7418 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
7419   // Avoid breaking before trailing 'const' or other trailing annotations, if
7420   // they are not function-like.
7421   FormatStyle Style = getGoogleStyleWithColumns(47);
7422   verifyFormat("void someLongFunction(\n"
7423                "    int someLoooooooooooooongParameter) const {\n}",
7424                getLLVMStyleWithColumns(47));
7425   verifyFormat("LoooooongReturnType\n"
7426                "someLoooooooongFunction() const {}",
7427                getLLVMStyleWithColumns(47));
7428   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
7429                "    const {}",
7430                Style);
7431   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7432                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
7433   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7434                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
7435   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7436                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
7437   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
7438                "                   aaaaaaaaaaa aaaaa) const override;");
7439   verifyGoogleFormat(
7440       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7441       "    const override;");
7442 
7443   // Even if the first parameter has to be wrapped.
7444   verifyFormat("void someLongFunction(\n"
7445                "    int someLongParameter) const {}",
7446                getLLVMStyleWithColumns(46));
7447   verifyFormat("void someLongFunction(\n"
7448                "    int someLongParameter) const {}",
7449                Style);
7450   verifyFormat("void someLongFunction(\n"
7451                "    int someLongParameter) override {}",
7452                Style);
7453   verifyFormat("void someLongFunction(\n"
7454                "    int someLongParameter) OVERRIDE {}",
7455                Style);
7456   verifyFormat("void someLongFunction(\n"
7457                "    int someLongParameter) final {}",
7458                Style);
7459   verifyFormat("void someLongFunction(\n"
7460                "    int someLongParameter) FINAL {}",
7461                Style);
7462   verifyFormat("void someLongFunction(\n"
7463                "    int parameter) const override {}",
7464                Style);
7465 
7466   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
7467   verifyFormat("void someLongFunction(\n"
7468                "    int someLongParameter) const\n"
7469                "{\n"
7470                "}",
7471                Style);
7472 
7473   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
7474   verifyFormat("void someLongFunction(\n"
7475                "    int someLongParameter) const\n"
7476                "  {\n"
7477                "  }",
7478                Style);
7479 
7480   // Unless these are unknown annotations.
7481   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
7482                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7483                "    LONG_AND_UGLY_ANNOTATION;");
7484 
7485   // Breaking before function-like trailing annotations is fine to keep them
7486   // close to their arguments.
7487   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7488                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7489   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7490                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7491   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7492                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
7493   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
7494                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
7495   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
7496 
7497   verifyFormat(
7498       "void aaaaaaaaaaaaaaaaaa()\n"
7499       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
7500       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
7501   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7502                "    __attribute__((unused));");
7503   verifyGoogleFormat(
7504       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7505       "    GUARDED_BY(aaaaaaaaaaaa);");
7506   verifyGoogleFormat(
7507       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7508       "    GUARDED_BY(aaaaaaaaaaaa);");
7509   verifyGoogleFormat(
7510       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7511       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7512   verifyGoogleFormat(
7513       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7514       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
7515 }
7516 
7517 TEST_F(FormatTest, FunctionAnnotations) {
7518   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7519                "int OldFunction(const string &parameter) {}");
7520   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7521                "string OldFunction(const string &parameter) {}");
7522   verifyFormat("template <typename T>\n"
7523                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7524                "string OldFunction(const string &parameter) {}");
7525 
7526   // Not function annotations.
7527   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7528                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
7529   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
7530                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
7531   verifyFormat("MACRO(abc).function() // wrap\n"
7532                "    << abc;");
7533   verifyFormat("MACRO(abc)->function() // wrap\n"
7534                "    << abc;");
7535   verifyFormat("MACRO(abc)::function() // wrap\n"
7536                "    << abc;");
7537 }
7538 
7539 TEST_F(FormatTest, BreaksDesireably) {
7540   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7541                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7542                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
7543   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7544                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
7545                "}");
7546 
7547   verifyFormat(
7548       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7549       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7550 
7551   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7552                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7553                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7554 
7555   verifyFormat(
7556       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7557       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7558       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7559       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7560       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7561 
7562   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7563                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7564 
7565   verifyFormat(
7566       "void f() {\n"
7567       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7568       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7569       "}");
7570   verifyFormat(
7571       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7572       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7573   verifyFormat(
7574       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7575       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7576   verifyFormat(
7577       "aaaaaa(aaa,\n"
7578       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7579       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7580       "       aaaa);");
7581   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7582                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7583                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7584 
7585   // Indent consistently independent of call expression and unary operator.
7586   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7587                "    dddddddddddddddddddddddddddddd));");
7588   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7589                "    dddddddddddddddddddddddddddddd));");
7590   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7591                "    dddddddddddddddddddddddddddddd));");
7592 
7593   // This test case breaks on an incorrect memoization, i.e. an optimization not
7594   // taking into account the StopAt value.
7595   verifyFormat(
7596       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7597       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7598       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7599       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7600 
7601   verifyFormat("{\n  {\n    {\n"
7602                "      Annotation.SpaceRequiredBefore =\n"
7603                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7604                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7605                "    }\n  }\n}");
7606 
7607   // Break on an outer level if there was a break on an inner level.
7608   EXPECT_EQ("f(g(h(a, // comment\n"
7609             "      b, c),\n"
7610             "    d, e),\n"
7611             "  x, y);",
7612             format("f(g(h(a, // comment\n"
7613                    "    b, c), d, e), x, y);"));
7614 
7615   // Prefer breaking similar line breaks.
7616   verifyFormat(
7617       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7618       "                             NSTrackingMouseEnteredAndExited |\n"
7619       "                             NSTrackingActiveAlways;");
7620 }
7621 
7622 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7623   FormatStyle NoBinPacking = getGoogleStyle();
7624   NoBinPacking.BinPackParameters = false;
7625   NoBinPacking.BinPackArguments = true;
7626   verifyFormat("void f() {\n"
7627                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7628                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7629                "}",
7630                NoBinPacking);
7631   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7632                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7633                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7634                NoBinPacking);
7635 
7636   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7637   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7638                "                        vector<int> bbbbbbbbbbbbbbb);",
7639                NoBinPacking);
7640   // FIXME: This behavior difference is probably not wanted. However, currently
7641   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7642   // template arguments from BreakBeforeParameter being set because of the
7643   // one-per-line formatting.
7644   verifyFormat(
7645       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7646       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7647       NoBinPacking);
7648   verifyFormat(
7649       "void fffffffffff(\n"
7650       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7651       "        aaaaaaaaaa);");
7652 }
7653 
7654 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7655   FormatStyle NoBinPacking = getGoogleStyle();
7656   NoBinPacking.BinPackParameters = false;
7657   NoBinPacking.BinPackArguments = false;
7658   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7659                "  aaaaaaaaaaaaaaaaaaaa,\n"
7660                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7661                NoBinPacking);
7662   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7663                "        aaaaaaaaaaaaa,\n"
7664                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7665                NoBinPacking);
7666   verifyFormat(
7667       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7668       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7669       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7670       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7671       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7672       NoBinPacking);
7673   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7674                "    .aaaaaaaaaaaaaaaaaa();",
7675                NoBinPacking);
7676   verifyFormat("void f() {\n"
7677                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7678                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7679                "}",
7680                NoBinPacking);
7681 
7682   verifyFormat(
7683       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7684       "             aaaaaaaaaaaa,\n"
7685       "             aaaaaaaaaaaa);",
7686       NoBinPacking);
7687   verifyFormat(
7688       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7689       "                               ddddddddddddddddddddddddddddd),\n"
7690       "             test);",
7691       NoBinPacking);
7692 
7693   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7694                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7695                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7696                "    aaaaaaaaaaaaaaaaaa;",
7697                NoBinPacking);
7698   verifyFormat("a(\"a\"\n"
7699                "  \"a\",\n"
7700                "  a);");
7701 
7702   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7703   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7704                "                aaaaaaaaa,\n"
7705                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7706                NoBinPacking);
7707   verifyFormat(
7708       "void f() {\n"
7709       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7710       "      .aaaaaaa();\n"
7711       "}",
7712       NoBinPacking);
7713   verifyFormat(
7714       "template <class SomeType, class SomeOtherType>\n"
7715       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7716       NoBinPacking);
7717 }
7718 
7719 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7720   FormatStyle Style = getLLVMStyleWithColumns(15);
7721   Style.ExperimentalAutoDetectBinPacking = true;
7722   EXPECT_EQ("aaa(aaaa,\n"
7723             "    aaaa,\n"
7724             "    aaaa);\n"
7725             "aaa(aaaa,\n"
7726             "    aaaa,\n"
7727             "    aaaa);",
7728             format("aaa(aaaa,\n" // one-per-line
7729                    "  aaaa,\n"
7730                    "    aaaa  );\n"
7731                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7732                    Style));
7733   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7734             "    aaaa);\n"
7735             "aaa(aaaa, aaaa,\n"
7736             "    aaaa);",
7737             format("aaa(aaaa,  aaaa,\n" // bin-packed
7738                    "    aaaa  );\n"
7739                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7740                    Style));
7741 }
7742 
7743 TEST_F(FormatTest, FormatsBuilderPattern) {
7744   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7745                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7746                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7747                "    .StartsWith(\".init\", ORDER_INIT)\n"
7748                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7749                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7750                "    .Default(ORDER_TEXT);\n");
7751 
7752   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7753                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7754   verifyFormat("aaaaaaa->aaaaaaa\n"
7755                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7756                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7757                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7758   verifyFormat(
7759       "aaaaaaa->aaaaaaa\n"
7760       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7761       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7762   verifyFormat(
7763       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7764       "    aaaaaaaaaaaaaa);");
7765   verifyFormat(
7766       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7767       "    aaaaaa->aaaaaaaaaaaa()\n"
7768       "        ->aaaaaaaaaaaaaaaa(\n"
7769       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7770       "        ->aaaaaaaaaaaaaaaaa();");
7771   verifyGoogleFormat(
7772       "void f() {\n"
7773       "  someo->Add((new util::filetools::Handler(dir))\n"
7774       "                 ->OnEvent1(NewPermanentCallback(\n"
7775       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7776       "                 ->OnEvent2(NewPermanentCallback(\n"
7777       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7778       "                 ->OnEvent3(NewPermanentCallback(\n"
7779       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7780       "                 ->OnEvent5(NewPermanentCallback(\n"
7781       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7782       "                 ->OnEvent6(NewPermanentCallback(\n"
7783       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7784       "}");
7785 
7786   verifyFormat(
7787       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7788   verifyFormat("aaaaaaaaaaaaaaa()\n"
7789                "    .aaaaaaaaaaaaaaa()\n"
7790                "    .aaaaaaaaaaaaaaa()\n"
7791                "    .aaaaaaaaaaaaaaa()\n"
7792                "    .aaaaaaaaaaaaaaa();");
7793   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7794                "    .aaaaaaaaaaaaaaa()\n"
7795                "    .aaaaaaaaaaaaaaa()\n"
7796                "    .aaaaaaaaaaaaaaa();");
7797   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7798                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7799                "    .aaaaaaaaaaaaaaa();");
7800   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7801                "    ->aaaaaaaaaaaaaae(0)\n"
7802                "    ->aaaaaaaaaaaaaaa();");
7803 
7804   // Don't linewrap after very short segments.
7805   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7806                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7807                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7808   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7809                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7810                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7811   verifyFormat("aaa()\n"
7812                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7813                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7814                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7815 
7816   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7817                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7818                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7819   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7820                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7821                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7822 
7823   // Prefer not to break after empty parentheses.
7824   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7825                "    First->LastNewlineOffset);");
7826 
7827   // Prefer not to create "hanging" indents.
7828   verifyFormat(
7829       "return !soooooooooooooome_map\n"
7830       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7831       "            .second;");
7832   verifyFormat(
7833       "return aaaaaaaaaaaaaaaa\n"
7834       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7835       "    .aaaa(aaaaaaaaaaaaaa);");
7836   // No hanging indent here.
7837   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7838                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7839   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7840                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7841   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7842                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7843                getLLVMStyleWithColumns(60));
7844   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7845                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7846                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7847                getLLVMStyleWithColumns(59));
7848   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7849                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7850                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7851 
7852   // Dont break if only closing statements before member call
7853   verifyFormat("test() {\n"
7854                "  ([]() -> {\n"
7855                "    int b = 32;\n"
7856                "    return 3;\n"
7857                "  }).foo();\n"
7858                "}");
7859   verifyFormat("test() {\n"
7860                "  (\n"
7861                "      []() -> {\n"
7862                "        int b = 32;\n"
7863                "        return 3;\n"
7864                "      },\n"
7865                "      foo, bar)\n"
7866                "      .foo();\n"
7867                "}");
7868   verifyFormat("test() {\n"
7869                "  ([]() -> {\n"
7870                "    int b = 32;\n"
7871                "    return 3;\n"
7872                "  })\n"
7873                "      .foo()\n"
7874                "      .bar();\n"
7875                "}");
7876   verifyFormat("test() {\n"
7877                "  ([]() -> {\n"
7878                "    int b = 32;\n"
7879                "    return 3;\n"
7880                "  })\n"
7881                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7882                "           \"bbbb\");\n"
7883                "}",
7884                getLLVMStyleWithColumns(30));
7885 }
7886 
7887 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7888   verifyFormat(
7889       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7890       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7891   verifyFormat(
7892       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7893       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7894 
7895   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7896                "    ccccccccccccccccccccccccc) {\n}");
7897   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7898                "    ccccccccccccccccccccccccc) {\n}");
7899 
7900   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7901                "    ccccccccccccccccccccccccc) {\n}");
7902   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7903                "    ccccccccccccccccccccccccc) {\n}");
7904 
7905   verifyFormat(
7906       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7907       "    ccccccccccccccccccccccccc) {\n}");
7908   verifyFormat(
7909       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7910       "    ccccccccccccccccccccccccc) {\n}");
7911 
7912   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7913                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7914                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7915                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7916   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7917                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7918                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7919                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7920 
7921   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7922                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7923                "    aaaaaaaaaaaaaaa != aa) {\n}");
7924   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7925                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7926                "    aaaaaaaaaaaaaaa != aa) {\n}");
7927 }
7928 
7929 TEST_F(FormatTest, BreaksAfterAssignments) {
7930   verifyFormat(
7931       "unsigned Cost =\n"
7932       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7933       "                        SI->getPointerAddressSpaceee());\n");
7934   verifyFormat(
7935       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7936       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7937 
7938   verifyFormat(
7939       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7940       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7941   verifyFormat("unsigned OriginalStartColumn =\n"
7942                "    SourceMgr.getSpellingColumnNumber(\n"
7943                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7944                "    1;");
7945 }
7946 
7947 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7948   FormatStyle Style = getLLVMStyle();
7949   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7950                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7951                Style);
7952 
7953   Style.PenaltyBreakAssignment = 20;
7954   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7955                "                                 cccccccccccccccccccccccccc;",
7956                Style);
7957 }
7958 
7959 TEST_F(FormatTest, AlignsAfterAssignments) {
7960   verifyFormat(
7961       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7962       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7963   verifyFormat(
7964       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7965       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7966   verifyFormat(
7967       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7968       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7969   verifyFormat(
7970       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7971       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7972   verifyFormat(
7973       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7974       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7975       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7976 }
7977 
7978 TEST_F(FormatTest, AlignsAfterReturn) {
7979   verifyFormat(
7980       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7981       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7982   verifyFormat(
7983       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7984       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7985   verifyFormat(
7986       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7987       "       aaaaaaaaaaaaaaaaaaaaaa();");
7988   verifyFormat(
7989       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7990       "        aaaaaaaaaaaaaaaaaaaaaa());");
7991   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7992                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7993   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7994                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7995                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7996   verifyFormat("return\n"
7997                "    // true if code is one of a or b.\n"
7998                "    code == a || code == b;");
7999 }
8000 
8001 TEST_F(FormatTest, AlignsAfterOpenBracket) {
8002   verifyFormat(
8003       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
8004       "                                                aaaaaaaaa aaaaaaa) {}");
8005   verifyFormat(
8006       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
8007       "                                               aaaaaaaaaaa aaaaaaaaa);");
8008   verifyFormat(
8009       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
8010       "                                             aaaaaaaaaaaaaaaaaaaaa));");
8011   FormatStyle Style = getLLVMStyle();
8012   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8013   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8014                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
8015                Style);
8016   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8017                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
8018                Style);
8019   verifyFormat("SomeLongVariableName->someFunction(\n"
8020                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
8021                Style);
8022   verifyFormat(
8023       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
8024       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8025       Style);
8026   verifyFormat(
8027       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
8028       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8029       Style);
8030   verifyFormat(
8031       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
8032       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8033       Style);
8034 
8035   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
8036                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
8037                "        b));",
8038                Style);
8039 
8040   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8041   Style.BinPackArguments = false;
8042   Style.BinPackParameters = false;
8043   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8044                "    aaaaaaaaaaa aaaaaaaa,\n"
8045                "    aaaaaaaaa aaaaaaa,\n"
8046                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8047                Style);
8048   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8049                "    aaaaaaaaaaa aaaaaaaaa,\n"
8050                "    aaaaaaaaaaa aaaaaaaaa,\n"
8051                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8052                Style);
8053   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
8054                "    aaaaaaaaaaaaaaa,\n"
8055                "    aaaaaaaaaaaaaaaaaaaaa,\n"
8056                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8057                Style);
8058   verifyFormat(
8059       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
8060       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8061       Style);
8062   verifyFormat(
8063       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
8064       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8065       Style);
8066   verifyFormat(
8067       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8068       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8069       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
8070       "    aaaaaaaaaaaaaaaa);",
8071       Style);
8072   verifyFormat(
8073       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8074       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8075       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
8076       "    aaaaaaaaaaaaaaaa);",
8077       Style);
8078 }
8079 
8080 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
8081   FormatStyle Style = getLLVMStyleWithColumns(40);
8082   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8083                "          bbbbbbbbbbbbbbbbbbbbbb);",
8084                Style);
8085   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
8086   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8087   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8088                "          bbbbbbbbbbbbbbbbbbbbbb);",
8089                Style);
8090   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8091   Style.AlignOperands = FormatStyle::OAS_Align;
8092   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8093                "          bbbbbbbbbbbbbbbbbbbbbb);",
8094                Style);
8095   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8096   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8097   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8098                "    bbbbbbbbbbbbbbbbbbbbbb);",
8099                Style);
8100 }
8101 
8102 TEST_F(FormatTest, BreaksConditionalExpressions) {
8103   verifyFormat(
8104       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8105       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8106       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8107   verifyFormat(
8108       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8109       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8110       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8111   verifyFormat(
8112       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8113       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8114   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
8115                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8116                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8117   verifyFormat(
8118       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
8119       "                                                    : aaaaaaaaaaaaa);");
8120   verifyFormat(
8121       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8122       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8123       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8124       "                   aaaaaaaaaaaaa);");
8125   verifyFormat(
8126       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8127       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8128       "                   aaaaaaaaaaaaa);");
8129   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8130                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8131                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8132                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8133                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8134   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8135                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8136                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8137                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8138                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8139                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8140                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8141   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8142                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8143                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8144                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8145                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8146   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8147                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8148                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8149   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8150                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8151                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8152                "        : aaaaaaaaaaaaaaaa;");
8153   verifyFormat(
8154       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8155       "    ? aaaaaaaaaaaaaaa\n"
8156       "    : aaaaaaaaaaaaaaa;");
8157   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8158                "          aaaaaaaaa\n"
8159                "      ? b\n"
8160                "      : c);");
8161   verifyFormat("return aaaa == bbbb\n"
8162                "           // comment\n"
8163                "           ? aaaa\n"
8164                "           : bbbb;");
8165   verifyFormat("unsigned Indent =\n"
8166                "    format(TheLine.First,\n"
8167                "           IndentForLevel[TheLine.Level] >= 0\n"
8168                "               ? IndentForLevel[TheLine.Level]\n"
8169                "               : TheLine * 2,\n"
8170                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8171                getLLVMStyleWithColumns(60));
8172   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8173                "                  ? aaaaaaaaaaaaaaa\n"
8174                "                  : bbbbbbbbbbbbbbb //\n"
8175                "                        ? ccccccccccccccc\n"
8176                "                        : ddddddddddddddd;");
8177   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8178                "                  ? aaaaaaaaaaaaaaa\n"
8179                "                  : (bbbbbbbbbbbbbbb //\n"
8180                "                         ? ccccccccccccccc\n"
8181                "                         : ddddddddddddddd);");
8182   verifyFormat(
8183       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8184       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8185       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
8186       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
8187       "                                      : aaaaaaaaaa;");
8188   verifyFormat(
8189       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8190       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
8191       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8192 
8193   FormatStyle NoBinPacking = getLLVMStyle();
8194   NoBinPacking.BinPackArguments = false;
8195   verifyFormat(
8196       "void f() {\n"
8197       "  g(aaa,\n"
8198       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8199       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8200       "        ? aaaaaaaaaaaaaaa\n"
8201       "        : aaaaaaaaaaaaaaa);\n"
8202       "}",
8203       NoBinPacking);
8204   verifyFormat(
8205       "void f() {\n"
8206       "  g(aaa,\n"
8207       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8208       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8209       "        ?: aaaaaaaaaaaaaaa);\n"
8210       "}",
8211       NoBinPacking);
8212 
8213   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
8214                "             // comment.\n"
8215                "             ccccccccccccccccccccccccccccccccccccccc\n"
8216                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8217                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
8218 
8219   // Assignments in conditional expressions. Apparently not uncommon :-(.
8220   verifyFormat("return a != b\n"
8221                "           // comment\n"
8222                "           ? a = b\n"
8223                "           : a = b;");
8224   verifyFormat("return a != b\n"
8225                "           // comment\n"
8226                "           ? a = a != b\n"
8227                "                     // comment\n"
8228                "                     ? a = b\n"
8229                "                     : a\n"
8230                "           : a;\n");
8231   verifyFormat("return a != b\n"
8232                "           // comment\n"
8233                "           ? a\n"
8234                "           : a = a != b\n"
8235                "                     // comment\n"
8236                "                     ? a = b\n"
8237                "                     : a;");
8238 
8239   // Chained conditionals
8240   FormatStyle Style = getLLVMStyleWithColumns(70);
8241   Style.AlignOperands = FormatStyle::OAS_Align;
8242   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8243                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8244                "                        : 3333333333333333;",
8245                Style);
8246   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8247                "       : bbbbbbbbbb     ? 2222222222222222\n"
8248                "                        : 3333333333333333;",
8249                Style);
8250   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
8251                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
8252                "                          : 3333333333333333;",
8253                Style);
8254   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8255                "       : bbbbbbbbbbbbbb ? 222222\n"
8256                "                        : 333333;",
8257                Style);
8258   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8259                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8260                "       : cccccccccccccc ? 3333333333333333\n"
8261                "                        : 4444444444444444;",
8262                Style);
8263   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
8264                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8265                "                        : 3333333333333333;",
8266                Style);
8267   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8268                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8269                "                        : (aaa ? bbb : ccc);",
8270                Style);
8271   verifyFormat(
8272       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8273       "                                             : cccccccccccccccccc)\n"
8274       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8275       "                        : 3333333333333333;",
8276       Style);
8277   verifyFormat(
8278       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8279       "                                             : cccccccccccccccccc)\n"
8280       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8281       "                        : 3333333333333333;",
8282       Style);
8283   verifyFormat(
8284       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8285       "                                             : dddddddddddddddddd)\n"
8286       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8287       "                        : 3333333333333333;",
8288       Style);
8289   verifyFormat(
8290       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8291       "                                             : dddddddddddddddddd)\n"
8292       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8293       "                        : 3333333333333333;",
8294       Style);
8295   verifyFormat(
8296       "return aaaaaaaaa        ? 1111111111111111\n"
8297       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8298       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8299       "                                             : dddddddddddddddddd)\n",
8300       Style);
8301   verifyFormat(
8302       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8303       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8304       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8305       "                                             : cccccccccccccccccc);",
8306       Style);
8307   verifyFormat(
8308       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8309       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8310       "                                             : eeeeeeeeeeeeeeeeee)\n"
8311       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8312       "                        : 3333333333333333;",
8313       Style);
8314   verifyFormat(
8315       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
8316       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8317       "                                             : eeeeeeeeeeeeeeeeee)\n"
8318       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8319       "                        : 3333333333333333;",
8320       Style);
8321   verifyFormat(
8322       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8323       "                           : cccccccccccc    ? dddddddddddddddddd\n"
8324       "                                             : eeeeeeeeeeeeeeeeee)\n"
8325       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8326       "                        : 3333333333333333;",
8327       Style);
8328   verifyFormat(
8329       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8330       "                                             : cccccccccccccccccc\n"
8331       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8332       "                        : 3333333333333333;",
8333       Style);
8334   verifyFormat(
8335       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8336       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
8337       "                                             : eeeeeeeeeeeeeeeeee\n"
8338       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8339       "                        : 3333333333333333;",
8340       Style);
8341   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
8342                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
8343                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
8344                "                                   : eeeeeeeeeeeeeeeeee)\n"
8345                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8346                "                             : 3333333333333333;",
8347                Style);
8348   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
8349                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8350                "             : cccccccccccccccc ? dddddddddddddddddd\n"
8351                "                                : eeeeeeeeeeeeeeeeee\n"
8352                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8353                "                                 : 3333333333333333;",
8354                Style);
8355 
8356   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8357   Style.BreakBeforeTernaryOperators = false;
8358   // FIXME: Aligning the question marks is weird given DontAlign.
8359   // Consider disabling this alignment in this case. Also check whether this
8360   // will render the adjustment from https://reviews.llvm.org/D82199
8361   // unnecessary.
8362   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
8363                "    bbbb                ? cccccccccccccccccc :\n"
8364                "                          ddddd;\n",
8365                Style);
8366 
8367   EXPECT_EQ(
8368       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8369       "    /*\n"
8370       "     */\n"
8371       "    function() {\n"
8372       "      try {\n"
8373       "        return JJJJJJJJJJJJJJ(\n"
8374       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8375       "      }\n"
8376       "    } :\n"
8377       "    function() {};",
8378       format(
8379           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8380           "     /*\n"
8381           "      */\n"
8382           "     function() {\n"
8383           "      try {\n"
8384           "        return JJJJJJJJJJJJJJ(\n"
8385           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8386           "      }\n"
8387           "    } :\n"
8388           "    function() {};",
8389           getGoogleStyle(FormatStyle::LK_JavaScript)));
8390 }
8391 
8392 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
8393   FormatStyle Style = getLLVMStyleWithColumns(70);
8394   Style.BreakBeforeTernaryOperators = false;
8395   verifyFormat(
8396       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8397       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8398       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8399       Style);
8400   verifyFormat(
8401       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8402       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8403       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8404       Style);
8405   verifyFormat(
8406       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8407       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8408       Style);
8409   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
8410                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8411                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8412                Style);
8413   verifyFormat(
8414       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
8415       "                                                      aaaaaaaaaaaaa);",
8416       Style);
8417   verifyFormat(
8418       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8419       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8420       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8421       "                   aaaaaaaaaaaaa);",
8422       Style);
8423   verifyFormat(
8424       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8425       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8426       "                   aaaaaaaaaaaaa);",
8427       Style);
8428   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8429                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8430                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8431                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8432                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8433                Style);
8434   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8435                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8436                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8437                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8438                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8439                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8440                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8441                Style);
8442   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8443                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
8444                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8445                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8446                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8447                Style);
8448   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8449                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8450                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8451                Style);
8452   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8453                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8454                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8455                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8456                Style);
8457   verifyFormat(
8458       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8459       "    aaaaaaaaaaaaaaa :\n"
8460       "    aaaaaaaaaaaaaaa;",
8461       Style);
8462   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8463                "          aaaaaaaaa ?\n"
8464                "      b :\n"
8465                "      c);",
8466                Style);
8467   verifyFormat("unsigned Indent =\n"
8468                "    format(TheLine.First,\n"
8469                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
8470                "               IndentForLevel[TheLine.Level] :\n"
8471                "               TheLine * 2,\n"
8472                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8473                Style);
8474   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8475                "                  aaaaaaaaaaaaaaa :\n"
8476                "                  bbbbbbbbbbbbbbb ? //\n"
8477                "                      ccccccccccccccc :\n"
8478                "                      ddddddddddddddd;",
8479                Style);
8480   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8481                "                  aaaaaaaaaaaaaaa :\n"
8482                "                  (bbbbbbbbbbbbbbb ? //\n"
8483                "                       ccccccccccccccc :\n"
8484                "                       ddddddddddddddd);",
8485                Style);
8486   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8487                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
8488                "            ccccccccccccccccccccccccccc;",
8489                Style);
8490   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8491                "           aaaaa :\n"
8492                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
8493                Style);
8494 
8495   // Chained conditionals
8496   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8497                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8498                "                          3333333333333333;",
8499                Style);
8500   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8501                "       bbbbbbbbbb       ? 2222222222222222 :\n"
8502                "                          3333333333333333;",
8503                Style);
8504   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
8505                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8506                "                          3333333333333333;",
8507                Style);
8508   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8509                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
8510                "                          333333;",
8511                Style);
8512   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8513                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8514                "       cccccccccccccccc ? 3333333333333333 :\n"
8515                "                          4444444444444444;",
8516                Style);
8517   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
8518                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8519                "                          3333333333333333;",
8520                Style);
8521   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8522                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8523                "                          (aaa ? bbb : ccc);",
8524                Style);
8525   verifyFormat(
8526       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8527       "                                               cccccccccccccccccc) :\n"
8528       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8529       "                          3333333333333333;",
8530       Style);
8531   verifyFormat(
8532       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8533       "                                               cccccccccccccccccc) :\n"
8534       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8535       "                          3333333333333333;",
8536       Style);
8537   verifyFormat(
8538       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8539       "                                               dddddddddddddddddd) :\n"
8540       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8541       "                          3333333333333333;",
8542       Style);
8543   verifyFormat(
8544       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8545       "                                               dddddddddddddddddd) :\n"
8546       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8547       "                          3333333333333333;",
8548       Style);
8549   verifyFormat(
8550       "return aaaaaaaaa        ? 1111111111111111 :\n"
8551       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8552       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8553       "                                               dddddddddddddddddd)\n",
8554       Style);
8555   verifyFormat(
8556       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8557       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8558       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8559       "                                               cccccccccccccccccc);",
8560       Style);
8561   verifyFormat(
8562       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8563       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8564       "                                               eeeeeeeeeeeeeeeeee) :\n"
8565       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8566       "                          3333333333333333;",
8567       Style);
8568   verifyFormat(
8569       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8570       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8571       "                                               eeeeeeeeeeeeeeeeee) :\n"
8572       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8573       "                          3333333333333333;",
8574       Style);
8575   verifyFormat(
8576       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8577       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8578       "                                               eeeeeeeeeeeeeeeeee) :\n"
8579       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8580       "                          3333333333333333;",
8581       Style);
8582   verifyFormat(
8583       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8584       "                                               cccccccccccccccccc :\n"
8585       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8586       "                          3333333333333333;",
8587       Style);
8588   verifyFormat(
8589       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8590       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8591       "                                               eeeeeeeeeeeeeeeeee :\n"
8592       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8593       "                          3333333333333333;",
8594       Style);
8595   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8596                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8597                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8598                "                                 eeeeeeeeeeeeeeeeee) :\n"
8599                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8600                "                               3333333333333333;",
8601                Style);
8602   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8603                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8604                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8605                "                                  eeeeeeeeeeeeeeeeee :\n"
8606                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8607                "                               3333333333333333;",
8608                Style);
8609 }
8610 
8611 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8612   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8613                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8614   verifyFormat("bool a = true, b = false;");
8615 
8616   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8617                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8618                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8619                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8620   verifyFormat(
8621       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8622       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8623       "     d = e && f;");
8624   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8625                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8626   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8627                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8628   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8629                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8630 
8631   FormatStyle Style = getGoogleStyle();
8632   Style.PointerAlignment = FormatStyle::PAS_Left;
8633   Style.DerivePointerAlignment = false;
8634   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8635                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8636                "    *b = bbbbbbbbbbbbbbbbbbb;",
8637                Style);
8638   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8639                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8640                Style);
8641   verifyFormat("vector<int*> a, b;", Style);
8642   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8643   verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style);
8644   verifyFormat("if (int *p, *q; p != q) {\n  p = p->next;\n}", Style);
8645   verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n  p = p->next;\n}",
8646                Style);
8647   verifyFormat("switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8648                Style);
8649   verifyFormat(
8650       "/*comment*/ switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8651       Style);
8652 
8653   verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style);
8654   verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style);
8655   verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style);
8656   verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style);
8657   verifyFormat("switch ([](int* p, int* q) {}()) {\n  default:\n    break;\n}",
8658                Style);
8659 }
8660 
8661 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8662   verifyFormat("arr[foo ? bar : baz];");
8663   verifyFormat("f()[foo ? bar : baz];");
8664   verifyFormat("(a + b)[foo ? bar : baz];");
8665   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8666 }
8667 
8668 TEST_F(FormatTest, AlignsStringLiterals) {
8669   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8670                "                                      \"short literal\");");
8671   verifyFormat(
8672       "looooooooooooooooooooooooongFunction(\n"
8673       "    \"short literal\"\n"
8674       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8675   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8676                "             \" string literals\",\n"
8677                "             and, other, parameters);");
8678   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8679             "      \"5678\";",
8680             format("fun + \"1243\" /* comment */\n"
8681                    "    \"5678\";",
8682                    getLLVMStyleWithColumns(28)));
8683   EXPECT_EQ(
8684       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8685       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8686       "         \"aaaaaaaaaaaaaaaa\";",
8687       format("aaaaaa ="
8688              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8689              "aaaaaaaaaaaaaaaaaaaaa\" "
8690              "\"aaaaaaaaaaaaaaaa\";"));
8691   verifyFormat("a = a + \"a\"\n"
8692                "        \"a\"\n"
8693                "        \"a\";");
8694   verifyFormat("f(\"a\", \"b\"\n"
8695                "       \"c\");");
8696 
8697   verifyFormat(
8698       "#define LL_FORMAT \"ll\"\n"
8699       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8700       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8701 
8702   verifyFormat("#define A(X)          \\\n"
8703                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8704                "  \"ccccc\"",
8705                getLLVMStyleWithColumns(23));
8706   verifyFormat("#define A \"def\"\n"
8707                "f(\"abc\" A \"ghi\"\n"
8708                "  \"jkl\");");
8709 
8710   verifyFormat("f(L\"a\"\n"
8711                "  L\"b\");");
8712   verifyFormat("#define A(X)            \\\n"
8713                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8714                "  L\"ccccc\"",
8715                getLLVMStyleWithColumns(25));
8716 
8717   verifyFormat("f(@\"a\"\n"
8718                "  @\"b\");");
8719   verifyFormat("NSString s = @\"a\"\n"
8720                "             @\"b\"\n"
8721                "             @\"c\";");
8722   verifyFormat("NSString s = @\"a\"\n"
8723                "              \"b\"\n"
8724                "              \"c\";");
8725 }
8726 
8727 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8728   FormatStyle Style = getLLVMStyle();
8729   // No declarations or definitions should be moved to own line.
8730   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8731   verifyFormat("class A {\n"
8732                "  int f() { return 1; }\n"
8733                "  int g();\n"
8734                "};\n"
8735                "int f() { return 1; }\n"
8736                "int g();\n",
8737                Style);
8738 
8739   // All declarations and definitions should have the return type moved to its
8740   // own line.
8741   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8742   Style.TypenameMacros = {"LIST"};
8743   verifyFormat("SomeType\n"
8744                "funcdecl(LIST(uint64_t));",
8745                Style);
8746   verifyFormat("class E {\n"
8747                "  int\n"
8748                "  f() {\n"
8749                "    return 1;\n"
8750                "  }\n"
8751                "  int\n"
8752                "  g();\n"
8753                "};\n"
8754                "int\n"
8755                "f() {\n"
8756                "  return 1;\n"
8757                "}\n"
8758                "int\n"
8759                "g();\n",
8760                Style);
8761 
8762   // Top-level definitions, and no kinds of declarations should have the
8763   // return type moved to its own line.
8764   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8765   verifyFormat("class B {\n"
8766                "  int f() { return 1; }\n"
8767                "  int g();\n"
8768                "};\n"
8769                "int\n"
8770                "f() {\n"
8771                "  return 1;\n"
8772                "}\n"
8773                "int g();\n",
8774                Style);
8775 
8776   // Top-level definitions and declarations should have the return type moved
8777   // to its own line.
8778   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8779   verifyFormat("class C {\n"
8780                "  int f() { return 1; }\n"
8781                "  int g();\n"
8782                "};\n"
8783                "int\n"
8784                "f() {\n"
8785                "  return 1;\n"
8786                "}\n"
8787                "int\n"
8788                "g();\n",
8789                Style);
8790 
8791   // All definitions should have the return type moved to its own line, but no
8792   // kinds of declarations.
8793   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8794   verifyFormat("class D {\n"
8795                "  int\n"
8796                "  f() {\n"
8797                "    return 1;\n"
8798                "  }\n"
8799                "  int g();\n"
8800                "};\n"
8801                "int\n"
8802                "f() {\n"
8803                "  return 1;\n"
8804                "}\n"
8805                "int g();\n",
8806                Style);
8807   verifyFormat("const char *\n"
8808                "f(void) {\n" // Break here.
8809                "  return \"\";\n"
8810                "}\n"
8811                "const char *bar(void);\n", // No break here.
8812                Style);
8813   verifyFormat("template <class T>\n"
8814                "T *\n"
8815                "f(T &c) {\n" // Break here.
8816                "  return NULL;\n"
8817                "}\n"
8818                "template <class T> T *f(T &c);\n", // No break here.
8819                Style);
8820   verifyFormat("class C {\n"
8821                "  int\n"
8822                "  operator+() {\n"
8823                "    return 1;\n"
8824                "  }\n"
8825                "  int\n"
8826                "  operator()() {\n"
8827                "    return 1;\n"
8828                "  }\n"
8829                "};\n",
8830                Style);
8831   verifyFormat("void\n"
8832                "A::operator()() {}\n"
8833                "void\n"
8834                "A::operator>>() {}\n"
8835                "void\n"
8836                "A::operator+() {}\n"
8837                "void\n"
8838                "A::operator*() {}\n"
8839                "void\n"
8840                "A::operator->() {}\n"
8841                "void\n"
8842                "A::operator void *() {}\n"
8843                "void\n"
8844                "A::operator void &() {}\n"
8845                "void\n"
8846                "A::operator void &&() {}\n"
8847                "void\n"
8848                "A::operator char *() {}\n"
8849                "void\n"
8850                "A::operator[]() {}\n"
8851                "void\n"
8852                "A::operator!() {}\n"
8853                "void\n"
8854                "A::operator**() {}\n"
8855                "void\n"
8856                "A::operator<Foo> *() {}\n"
8857                "void\n"
8858                "A::operator<Foo> **() {}\n"
8859                "void\n"
8860                "A::operator<Foo> &() {}\n"
8861                "void\n"
8862                "A::operator void **() {}\n",
8863                Style);
8864   verifyFormat("constexpr auto\n"
8865                "operator()() const -> reference {}\n"
8866                "constexpr auto\n"
8867                "operator>>() const -> reference {}\n"
8868                "constexpr auto\n"
8869                "operator+() const -> reference {}\n"
8870                "constexpr auto\n"
8871                "operator*() const -> reference {}\n"
8872                "constexpr auto\n"
8873                "operator->() const -> reference {}\n"
8874                "constexpr auto\n"
8875                "operator++() const -> reference {}\n"
8876                "constexpr auto\n"
8877                "operator void *() const -> reference {}\n"
8878                "constexpr auto\n"
8879                "operator void **() const -> reference {}\n"
8880                "constexpr auto\n"
8881                "operator void *() const -> reference {}\n"
8882                "constexpr auto\n"
8883                "operator void &() const -> reference {}\n"
8884                "constexpr auto\n"
8885                "operator void &&() const -> reference {}\n"
8886                "constexpr auto\n"
8887                "operator char *() const -> reference {}\n"
8888                "constexpr auto\n"
8889                "operator!() const -> reference {}\n"
8890                "constexpr auto\n"
8891                "operator[]() const -> reference {}\n",
8892                Style);
8893   verifyFormat("void *operator new(std::size_t s);", // No break here.
8894                Style);
8895   verifyFormat("void *\n"
8896                "operator new(std::size_t s) {}",
8897                Style);
8898   verifyFormat("void *\n"
8899                "operator delete[](void *ptr) {}",
8900                Style);
8901   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8902   verifyFormat("const char *\n"
8903                "f(void)\n" // Break here.
8904                "{\n"
8905                "  return \"\";\n"
8906                "}\n"
8907                "const char *bar(void);\n", // No break here.
8908                Style);
8909   verifyFormat("template <class T>\n"
8910                "T *\n"     // Problem here: no line break
8911                "f(T &c)\n" // Break here.
8912                "{\n"
8913                "  return NULL;\n"
8914                "}\n"
8915                "template <class T> T *f(T &c);\n", // No break here.
8916                Style);
8917   verifyFormat("int\n"
8918                "foo(A<bool> a)\n"
8919                "{\n"
8920                "  return a;\n"
8921                "}\n",
8922                Style);
8923   verifyFormat("int\n"
8924                "foo(A<8> a)\n"
8925                "{\n"
8926                "  return a;\n"
8927                "}\n",
8928                Style);
8929   verifyFormat("int\n"
8930                "foo(A<B<bool>, 8> a)\n"
8931                "{\n"
8932                "  return a;\n"
8933                "}\n",
8934                Style);
8935   verifyFormat("int\n"
8936                "foo(A<B<8>, bool> a)\n"
8937                "{\n"
8938                "  return a;\n"
8939                "}\n",
8940                Style);
8941   verifyFormat("int\n"
8942                "foo(A<B<bool>, bool> a)\n"
8943                "{\n"
8944                "  return a;\n"
8945                "}\n",
8946                Style);
8947   verifyFormat("int\n"
8948                "foo(A<B<8>, 8> a)\n"
8949                "{\n"
8950                "  return a;\n"
8951                "}\n",
8952                Style);
8953 
8954   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8955   Style.BraceWrapping.AfterFunction = true;
8956   verifyFormat("int f(i);\n" // No break here.
8957                "int\n"       // Break here.
8958                "f(i)\n"
8959                "{\n"
8960                "  return i + 1;\n"
8961                "}\n"
8962                "int\n" // Break here.
8963                "f(i)\n"
8964                "{\n"
8965                "  return i + 1;\n"
8966                "};",
8967                Style);
8968   verifyFormat("int f(a, b, c);\n" // No break here.
8969                "int\n"             // Break here.
8970                "f(a, b, c)\n"      // Break here.
8971                "short a, b;\n"
8972                "float c;\n"
8973                "{\n"
8974                "  return a + b < c;\n"
8975                "}\n"
8976                "int\n"        // Break here.
8977                "f(a, b, c)\n" // Break here.
8978                "short a, b;\n"
8979                "float c;\n"
8980                "{\n"
8981                "  return a + b < c;\n"
8982                "};",
8983                Style);
8984   verifyFormat("byte *\n" // Break here.
8985                "f(a)\n"   // Break here.
8986                "byte a[];\n"
8987                "{\n"
8988                "  return a;\n"
8989                "}",
8990                Style);
8991   verifyFormat("bool f(int a, int) override;\n"
8992                "Bar g(int a, Bar) final;\n"
8993                "Bar h(a, Bar) final;",
8994                Style);
8995   verifyFormat("int\n"
8996                "f(a)",
8997                Style);
8998   verifyFormat("bool\n"
8999                "f(size_t = 0, bool b = false)\n"
9000                "{\n"
9001                "  return !b;\n"
9002                "}",
9003                Style);
9004 
9005   // The return breaking style doesn't affect:
9006   // * function and object definitions with attribute-like macros
9007   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9008                "    ABSL_GUARDED_BY(mutex) = {};",
9009                getGoogleStyleWithColumns(40));
9010   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9011                "    ABSL_GUARDED_BY(mutex);  // comment",
9012                getGoogleStyleWithColumns(40));
9013   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9014                "    ABSL_GUARDED_BY(mutex1)\n"
9015                "        ABSL_GUARDED_BY(mutex2);",
9016                getGoogleStyleWithColumns(40));
9017   verifyFormat("Tttttt f(int a, int b)\n"
9018                "    ABSL_GUARDED_BY(mutex1)\n"
9019                "        ABSL_GUARDED_BY(mutex2);",
9020                getGoogleStyleWithColumns(40));
9021   // * typedefs
9022   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
9023 
9024   Style = getGNUStyle();
9025 
9026   // Test for comments at the end of function declarations.
9027   verifyFormat("void\n"
9028                "foo (int a, /*abc*/ int b) // def\n"
9029                "{\n"
9030                "}\n",
9031                Style);
9032 
9033   verifyFormat("void\n"
9034                "foo (int a, /* abc */ int b) /* def */\n"
9035                "{\n"
9036                "}\n",
9037                Style);
9038 
9039   // Definitions that should not break after return type
9040   verifyFormat("void foo (int a, int b); // def\n", Style);
9041   verifyFormat("void foo (int a, int b); /* def */\n", Style);
9042   verifyFormat("void foo (int a, int b);\n", Style);
9043 }
9044 
9045 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
9046   FormatStyle NoBreak = getLLVMStyle();
9047   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
9048   FormatStyle Break = getLLVMStyle();
9049   Break.AlwaysBreakBeforeMultilineStrings = true;
9050   verifyFormat("aaaa = \"bbbb\"\n"
9051                "       \"cccc\";",
9052                NoBreak);
9053   verifyFormat("aaaa =\n"
9054                "    \"bbbb\"\n"
9055                "    \"cccc\";",
9056                Break);
9057   verifyFormat("aaaa(\"bbbb\"\n"
9058                "     \"cccc\");",
9059                NoBreak);
9060   verifyFormat("aaaa(\n"
9061                "    \"bbbb\"\n"
9062                "    \"cccc\");",
9063                Break);
9064   verifyFormat("aaaa(qqq, \"bbbb\"\n"
9065                "          \"cccc\");",
9066                NoBreak);
9067   verifyFormat("aaaa(qqq,\n"
9068                "     \"bbbb\"\n"
9069                "     \"cccc\");",
9070                Break);
9071   verifyFormat("aaaa(qqq,\n"
9072                "     L\"bbbb\"\n"
9073                "     L\"cccc\");",
9074                Break);
9075   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
9076                "                      \"bbbb\"));",
9077                Break);
9078   verifyFormat("string s = someFunction(\n"
9079                "    \"abc\"\n"
9080                "    \"abc\");",
9081                Break);
9082 
9083   // As we break before unary operators, breaking right after them is bad.
9084   verifyFormat("string foo = abc ? \"x\"\n"
9085                "                   \"blah blah blah blah blah blah\"\n"
9086                "                 : \"y\";",
9087                Break);
9088 
9089   // Don't break if there is no column gain.
9090   verifyFormat("f(\"aaaa\"\n"
9091                "  \"bbbb\");",
9092                Break);
9093 
9094   // Treat literals with escaped newlines like multi-line string literals.
9095   EXPECT_EQ("x = \"a\\\n"
9096             "b\\\n"
9097             "c\";",
9098             format("x = \"a\\\n"
9099                    "b\\\n"
9100                    "c\";",
9101                    NoBreak));
9102   EXPECT_EQ("xxxx =\n"
9103             "    \"a\\\n"
9104             "b\\\n"
9105             "c\";",
9106             format("xxxx = \"a\\\n"
9107                    "b\\\n"
9108                    "c\";",
9109                    Break));
9110 
9111   EXPECT_EQ("NSString *const kString =\n"
9112             "    @\"aaaa\"\n"
9113             "    @\"bbbb\";",
9114             format("NSString *const kString = @\"aaaa\"\n"
9115                    "@\"bbbb\";",
9116                    Break));
9117 
9118   Break.ColumnLimit = 0;
9119   verifyFormat("const char *hello = \"hello llvm\";", Break);
9120 }
9121 
9122 TEST_F(FormatTest, AlignsPipes) {
9123   verifyFormat(
9124       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9125       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9126       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9127   verifyFormat(
9128       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
9129       "                     << aaaaaaaaaaaaaaaaaaaa;");
9130   verifyFormat(
9131       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9132       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9133   verifyFormat(
9134       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
9135       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9136   verifyFormat(
9137       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
9138       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
9139       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
9140   verifyFormat(
9141       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9142       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9143       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9144   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9145                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9146                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9147                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9148   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
9149                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
9150   verifyFormat(
9151       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9152       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9153   verifyFormat(
9154       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
9155       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
9156 
9157   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
9158                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
9159   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9160                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9161                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
9162                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
9163   verifyFormat("LOG_IF(aaa == //\n"
9164                "       bbb)\n"
9165                "    << a << b;");
9166 
9167   // But sometimes, breaking before the first "<<" is desirable.
9168   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9169                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
9170   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
9171                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9172                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9173   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
9174                "    << BEF << IsTemplate << Description << E->getType();");
9175   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9176                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9177                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9178   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9179                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9180                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9181                "    << aaa;");
9182 
9183   verifyFormat(
9184       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9185       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9186 
9187   // Incomplete string literal.
9188   EXPECT_EQ("llvm::errs() << \"\n"
9189             "             << a;",
9190             format("llvm::errs() << \"\n<<a;"));
9191 
9192   verifyFormat("void f() {\n"
9193                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
9194                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
9195                "}");
9196 
9197   // Handle 'endl'.
9198   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
9199                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9200   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9201 
9202   // Handle '\n'.
9203   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
9204                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9205   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
9206                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
9207   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
9208                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
9209   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9210 }
9211 
9212 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
9213   verifyFormat("return out << \"somepacket = {\\n\"\n"
9214                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
9215                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
9216                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
9217                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
9218                "           << \"}\";");
9219 
9220   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9221                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9222                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
9223   verifyFormat(
9224       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
9225       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
9226       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
9227       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
9228       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
9229   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
9230                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9231   verifyFormat(
9232       "void f() {\n"
9233       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
9234       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
9235       "}");
9236 
9237   // Breaking before the first "<<" is generally not desirable.
9238   verifyFormat(
9239       "llvm::errs()\n"
9240       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9241       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9242       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9243       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9244       getLLVMStyleWithColumns(70));
9245   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9246                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9247                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9248                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9249                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9250                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9251                getLLVMStyleWithColumns(70));
9252 
9253   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9254                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9255                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
9256   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9257                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9258                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
9259   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
9260                "           (aaaa + aaaa);",
9261                getLLVMStyleWithColumns(40));
9262   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
9263                "                  (aaaaaaa + aaaaa));",
9264                getLLVMStyleWithColumns(40));
9265   verifyFormat(
9266       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
9267       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
9268       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
9269 }
9270 
9271 TEST_F(FormatTest, UnderstandsEquals) {
9272   verifyFormat(
9273       "aaaaaaaaaaaaaaaaa =\n"
9274       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9275   verifyFormat(
9276       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9277       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9278   verifyFormat(
9279       "if (a) {\n"
9280       "  f();\n"
9281       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9282       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
9283       "}");
9284 
9285   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9286                "        100000000 + 10000000) {\n}");
9287 }
9288 
9289 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
9290   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9291                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
9292 
9293   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9294                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
9295 
9296   verifyFormat(
9297       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
9298       "                                                          Parameter2);");
9299 
9300   verifyFormat(
9301       "ShortObject->shortFunction(\n"
9302       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
9303       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
9304 
9305   verifyFormat("loooooooooooooongFunction(\n"
9306                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
9307 
9308   verifyFormat(
9309       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
9310       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
9311 
9312   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9313                "    .WillRepeatedly(Return(SomeValue));");
9314   verifyFormat("void f() {\n"
9315                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9316                "      .Times(2)\n"
9317                "      .WillRepeatedly(Return(SomeValue));\n"
9318                "}");
9319   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
9320                "    ccccccccccccccccccccccc);");
9321   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9322                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9323                "          .aaaaa(aaaaa),\n"
9324                "      aaaaaaaaaaaaaaaaaaaaa);");
9325   verifyFormat("void f() {\n"
9326                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9327                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
9328                "}");
9329   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9330                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9331                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9332                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9333                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9334   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9335                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9336                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9337                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
9338                "}");
9339 
9340   // Here, it is not necessary to wrap at "." or "->".
9341   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
9342                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9343   verifyFormat(
9344       "aaaaaaaaaaa->aaaaaaaaa(\n"
9345       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9346       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
9347 
9348   verifyFormat(
9349       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9350       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
9351   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
9352                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9353   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
9354                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9355 
9356   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9357                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9358                "    .a();");
9359 
9360   FormatStyle NoBinPacking = getLLVMStyle();
9361   NoBinPacking.BinPackParameters = false;
9362   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9363                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9364                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
9365                "                         aaaaaaaaaaaaaaaaaaa,\n"
9366                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
9367                NoBinPacking);
9368 
9369   // If there is a subsequent call, change to hanging indentation.
9370   verifyFormat(
9371       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9372       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
9373       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9374   verifyFormat(
9375       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9376       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
9377   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9378                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9379                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9380   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9381                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9382                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9383 }
9384 
9385 TEST_F(FormatTest, WrapsTemplateDeclarations) {
9386   verifyFormat("template <typename T>\n"
9387                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9388   verifyFormat("template <typename T>\n"
9389                "// T should be one of {A, B}.\n"
9390                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9391   verifyFormat(
9392       "template <typename T>\n"
9393       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
9394   verifyFormat("template <typename T>\n"
9395                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
9396                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
9397   verifyFormat(
9398       "template <typename T>\n"
9399       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
9400       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
9401   verifyFormat(
9402       "template <typename T>\n"
9403       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
9404       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
9405       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9406   verifyFormat("template <typename T>\n"
9407                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9408                "    int aaaaaaaaaaaaaaaaaaaaaa);");
9409   verifyFormat(
9410       "template <typename T1, typename T2 = char, typename T3 = char,\n"
9411       "          typename T4 = char>\n"
9412       "void f();");
9413   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
9414                "          template <typename> class cccccccccccccccccccccc,\n"
9415                "          typename ddddddddddddd>\n"
9416                "class C {};");
9417   verifyFormat(
9418       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
9419       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9420 
9421   verifyFormat("void f() {\n"
9422                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
9423                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
9424                "}");
9425 
9426   verifyFormat("template <typename T> class C {};");
9427   verifyFormat("template <typename T> void f();");
9428   verifyFormat("template <typename T> void f() {}");
9429   verifyFormat(
9430       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9431       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9432       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
9433       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9434       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9435       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
9436       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
9437       getLLVMStyleWithColumns(72));
9438   EXPECT_EQ("static_cast<A< //\n"
9439             "    B> *>(\n"
9440             "\n"
9441             ");",
9442             format("static_cast<A<//\n"
9443                    "    B>*>(\n"
9444                    "\n"
9445                    "    );"));
9446   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9447                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
9448 
9449   FormatStyle AlwaysBreak = getLLVMStyle();
9450   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9451   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
9452   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
9453   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
9454   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9455                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9456                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
9457   verifyFormat("template <template <typename> class Fooooooo,\n"
9458                "          template <typename> class Baaaaaaar>\n"
9459                "struct C {};",
9460                AlwaysBreak);
9461   verifyFormat("template <typename T> // T can be A, B or C.\n"
9462                "struct C {};",
9463                AlwaysBreak);
9464   verifyFormat("template <enum E> class A {\n"
9465                "public:\n"
9466                "  E *f();\n"
9467                "};");
9468 
9469   FormatStyle NeverBreak = getLLVMStyle();
9470   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
9471   verifyFormat("template <typename T> class C {};", NeverBreak);
9472   verifyFormat("template <typename T> void f();", NeverBreak);
9473   verifyFormat("template <typename T> void f() {}", NeverBreak);
9474   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9475                "bbbbbbbbbbbbbbbbbbbb) {}",
9476                NeverBreak);
9477   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9478                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9479                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
9480                NeverBreak);
9481   verifyFormat("template <template <typename> class Fooooooo,\n"
9482                "          template <typename> class Baaaaaaar>\n"
9483                "struct C {};",
9484                NeverBreak);
9485   verifyFormat("template <typename T> // T can be A, B or C.\n"
9486                "struct C {};",
9487                NeverBreak);
9488   verifyFormat("template <enum E> class A {\n"
9489                "public:\n"
9490                "  E *f();\n"
9491                "};",
9492                NeverBreak);
9493   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
9494   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9495                "bbbbbbbbbbbbbbbbbbbb) {}",
9496                NeverBreak);
9497 }
9498 
9499 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
9500   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9501   Style.ColumnLimit = 60;
9502   EXPECT_EQ("// Baseline - no comments.\n"
9503             "template <\n"
9504             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9505             "void f() {}",
9506             format("// Baseline - no comments.\n"
9507                    "template <\n"
9508                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9509                    "void f() {}",
9510                    Style));
9511 
9512   EXPECT_EQ("template <\n"
9513             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9514             "void f() {}",
9515             format("template <\n"
9516                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9517                    "void f() {}",
9518                    Style));
9519 
9520   EXPECT_EQ(
9521       "template <\n"
9522       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
9523       "void f() {}",
9524       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
9525              "void f() {}",
9526              Style));
9527 
9528   EXPECT_EQ(
9529       "template <\n"
9530       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9531       "                                               // multiline\n"
9532       "void f() {}",
9533       format("template <\n"
9534              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9535              "                                              // multiline\n"
9536              "void f() {}",
9537              Style));
9538 
9539   EXPECT_EQ(
9540       "template <typename aaaaaaaaaa<\n"
9541       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
9542       "void f() {}",
9543       format(
9544           "template <\n"
9545           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
9546           "void f() {}",
9547           Style));
9548 }
9549 
9550 TEST_F(FormatTest, WrapsTemplateParameters) {
9551   FormatStyle Style = getLLVMStyle();
9552   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9553   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9554   verifyFormat(
9555       "template <typename... a> struct q {};\n"
9556       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9557       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9558       "    y;",
9559       Style);
9560   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9561   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9562   verifyFormat(
9563       "template <typename... a> struct r {};\n"
9564       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9565       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9566       "    y;",
9567       Style);
9568   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9569   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9570   verifyFormat("template <typename... a> struct s {};\n"
9571                "extern s<\n"
9572                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9573                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9574                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9575                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9576                "    y;",
9577                Style);
9578   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9579   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9580   verifyFormat("template <typename... a> struct t {};\n"
9581                "extern t<\n"
9582                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9583                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9584                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9585                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9586                "    y;",
9587                Style);
9588 }
9589 
9590 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9591   verifyFormat(
9592       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9593       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9594   verifyFormat(
9595       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9596       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9597       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9598 
9599   // FIXME: Should we have the extra indent after the second break?
9600   verifyFormat(
9601       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9602       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9603       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9604 
9605   verifyFormat(
9606       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9607       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9608 
9609   // Breaking at nested name specifiers is generally not desirable.
9610   verifyFormat(
9611       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9612       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9613 
9614   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9615                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9616                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9617                "                   aaaaaaaaaaaaaaaaaaaaa);",
9618                getLLVMStyleWithColumns(74));
9619 
9620   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9621                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9622                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9623 }
9624 
9625 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9626   verifyFormat("A<int> a;");
9627   verifyFormat("A<A<A<int>>> a;");
9628   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9629   verifyFormat("bool x = a < 1 || 2 > a;");
9630   verifyFormat("bool x = 5 < f<int>();");
9631   verifyFormat("bool x = f<int>() > 5;");
9632   verifyFormat("bool x = 5 < a<int>::x;");
9633   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9634   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9635 
9636   verifyGoogleFormat("A<A<int>> a;");
9637   verifyGoogleFormat("A<A<A<int>>> a;");
9638   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9639   verifyGoogleFormat("A<A<int> > a;");
9640   verifyGoogleFormat("A<A<A<int> > > a;");
9641   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9642   verifyGoogleFormat("A<::A<int>> a;");
9643   verifyGoogleFormat("A<::A> a;");
9644   verifyGoogleFormat("A< ::A> a;");
9645   verifyGoogleFormat("A< ::A<int> > a;");
9646   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9647   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9648   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9649   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9650   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9651             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9652 
9653   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9654 
9655   // template closer followed by a token that starts with > or =
9656   verifyFormat("bool b = a<1> > 1;");
9657   verifyFormat("bool b = a<1> >= 1;");
9658   verifyFormat("int i = a<1> >> 1;");
9659   FormatStyle Style = getLLVMStyle();
9660   Style.SpaceBeforeAssignmentOperators = false;
9661   verifyFormat("bool b= a<1> == 1;", Style);
9662   verifyFormat("a<int> = 1;", Style);
9663   verifyFormat("a<int> >>= 1;", Style);
9664 
9665   verifyFormat("test < a | b >> c;");
9666   verifyFormat("test<test<a | b>> c;");
9667   verifyFormat("test >> a >> b;");
9668   verifyFormat("test << a >> b;");
9669 
9670   verifyFormat("f<int>();");
9671   verifyFormat("template <typename T> void f() {}");
9672   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9673   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9674                "sizeof(char)>::type>;");
9675   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9676   verifyFormat("f(a.operator()<A>());");
9677   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9678                "      .template operator()<A>());",
9679                getLLVMStyleWithColumns(35));
9680   verifyFormat("bool_constant<a && noexcept(f())>");
9681   verifyFormat("bool_constant<a || noexcept(f())>");
9682 
9683   // Not template parameters.
9684   verifyFormat("return a < b && c > d;");
9685   verifyFormat("void f() {\n"
9686                "  while (a < b && c > d) {\n"
9687                "  }\n"
9688                "}");
9689   verifyFormat("template <typename... Types>\n"
9690                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9691 
9692   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9693                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9694                getLLVMStyleWithColumns(60));
9695   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9696   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9697   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9698   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9699 }
9700 
9701 TEST_F(FormatTest, UnderstandsShiftOperators) {
9702   verifyFormat("if (i < x >> 1)");
9703   verifyFormat("while (i < x >> 1)");
9704   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9705   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9706   verifyFormat(
9707       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9708   verifyFormat("Foo.call<Bar<Function>>()");
9709   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9710   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9711                "++i, v = v >> 1)");
9712   verifyFormat("if (w<u<v<x>>, 1>::t)");
9713 }
9714 
9715 TEST_F(FormatTest, BitshiftOperatorWidth) {
9716   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9717             "                   bar */",
9718             format("int    a=1<<2;  /* foo\n"
9719                    "                   bar */"));
9720 
9721   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9722             "                     bar */",
9723             format("int  b  =256>>1 ;  /* foo\n"
9724                    "                      bar */"));
9725 }
9726 
9727 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9728   verifyFormat("COMPARE(a, ==, b);");
9729   verifyFormat("auto s = sizeof...(Ts) - 1;");
9730 }
9731 
9732 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9733   verifyFormat("int A::*x;");
9734   verifyFormat("int (S::*func)(void *);");
9735   verifyFormat("void f() { int (S::*func)(void *); }");
9736   verifyFormat("typedef bool *(Class::*Member)() const;");
9737   verifyFormat("void f() {\n"
9738                "  (a->*f)();\n"
9739                "  a->*x;\n"
9740                "  (a.*f)();\n"
9741                "  ((*a).*f)();\n"
9742                "  a.*x;\n"
9743                "}");
9744   verifyFormat("void f() {\n"
9745                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9746                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9747                "}");
9748   verifyFormat(
9749       "(aaaaaaaaaa->*bbbbbbb)(\n"
9750       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9751   FormatStyle Style = getLLVMStyle();
9752   Style.PointerAlignment = FormatStyle::PAS_Left;
9753   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9754 }
9755 
9756 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9757   verifyFormat("int a = -2;");
9758   verifyFormat("f(-1, -2, -3);");
9759   verifyFormat("a[-1] = 5;");
9760   verifyFormat("int a = 5 + -2;");
9761   verifyFormat("if (i == -1) {\n}");
9762   verifyFormat("if (i != -1) {\n}");
9763   verifyFormat("if (i > -1) {\n}");
9764   verifyFormat("if (i < -1) {\n}");
9765   verifyFormat("++(a->f());");
9766   verifyFormat("--(a->f());");
9767   verifyFormat("(a->f())++;");
9768   verifyFormat("a[42]++;");
9769   verifyFormat("if (!(a->f())) {\n}");
9770   verifyFormat("if (!+i) {\n}");
9771   verifyFormat("~&a;");
9772   verifyFormat("for (x = 0; -10 < x; --x) {\n}");
9773   verifyFormat("sizeof -x");
9774   verifyFormat("sizeof +x");
9775   verifyFormat("sizeof *x");
9776   verifyFormat("sizeof &x");
9777   verifyFormat("delete +x;");
9778   verifyFormat("co_await +x;");
9779   verifyFormat("case *x:");
9780   verifyFormat("case &x:");
9781 
9782   verifyFormat("a-- > b;");
9783   verifyFormat("b ? -a : c;");
9784   verifyFormat("n * sizeof char16;");
9785   verifyFormat("n * alignof char16;", getGoogleStyle());
9786   verifyFormat("sizeof(char);");
9787   verifyFormat("alignof(char);", getGoogleStyle());
9788 
9789   verifyFormat("return -1;");
9790   verifyFormat("throw -1;");
9791   verifyFormat("switch (a) {\n"
9792                "case -1:\n"
9793                "  break;\n"
9794                "}");
9795   verifyFormat("#define X -1");
9796   verifyFormat("#define X -kConstant");
9797 
9798   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9799   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9800 
9801   verifyFormat("int a = /* confusing comment */ -1;");
9802   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9803   verifyFormat("int a = i /* confusing comment */++;");
9804 
9805   verifyFormat("co_yield -1;");
9806   verifyFormat("co_return -1;");
9807 
9808   // Check that * is not treated as a binary operator when we set
9809   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9810   FormatStyle PASLeftStyle = getLLVMStyle();
9811   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9812   verifyFormat("co_return *a;", PASLeftStyle);
9813   verifyFormat("co_await *a;", PASLeftStyle);
9814   verifyFormat("co_yield *a", PASLeftStyle);
9815   verifyFormat("return *a;", PASLeftStyle);
9816 }
9817 
9818 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9819   verifyFormat("if (!aaaaaaaaaa( // break\n"
9820                "        aaaaa)) {\n"
9821                "}");
9822   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9823                "    aaaaa));");
9824   verifyFormat("*aaa = aaaaaaa( // break\n"
9825                "    bbbbbb);");
9826 }
9827 
9828 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9829   verifyFormat("bool operator<();");
9830   verifyFormat("bool operator>();");
9831   verifyFormat("bool operator=();");
9832   verifyFormat("bool operator==();");
9833   verifyFormat("bool operator!=();");
9834   verifyFormat("int operator+();");
9835   verifyFormat("int operator++();");
9836   verifyFormat("int operator++(int) volatile noexcept;");
9837   verifyFormat("bool operator,();");
9838   verifyFormat("bool operator();");
9839   verifyFormat("bool operator()();");
9840   verifyFormat("bool operator[]();");
9841   verifyFormat("operator bool();");
9842   verifyFormat("operator int();");
9843   verifyFormat("operator void *();");
9844   verifyFormat("operator SomeType<int>();");
9845   verifyFormat("operator SomeType<int, int>();");
9846   verifyFormat("operator SomeType<SomeType<int>>();");
9847   verifyFormat("operator< <>();");
9848   verifyFormat("operator<< <>();");
9849   verifyFormat("< <>");
9850 
9851   verifyFormat("void *operator new(std::size_t size);");
9852   verifyFormat("void *operator new[](std::size_t size);");
9853   verifyFormat("void operator delete(void *ptr);");
9854   verifyFormat("void operator delete[](void *ptr);");
9855   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9856                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9857   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9858                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9859 
9860   verifyFormat(
9861       "ostream &operator<<(ostream &OutputStream,\n"
9862       "                    SomeReallyLongType WithSomeReallyLongValue);");
9863   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9864                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9865                "  return left.group < right.group;\n"
9866                "}");
9867   verifyFormat("SomeType &operator=(const SomeType &S);");
9868   verifyFormat("f.template operator()<int>();");
9869 
9870   verifyGoogleFormat("operator void*();");
9871   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9872   verifyGoogleFormat("operator ::A();");
9873 
9874   verifyFormat("using A::operator+;");
9875   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9876                "int i;");
9877 
9878   // Calling an operator as a member function.
9879   verifyFormat("void f() { a.operator*(); }");
9880   verifyFormat("void f() { a.operator*(b & b); }");
9881   verifyFormat("void f() { a->operator&(a * b); }");
9882   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9883   // TODO: Calling an operator as a non-member function is hard to distinguish.
9884   // https://llvm.org/PR50629
9885   // verifyFormat("void f() { operator*(a & a); }");
9886   // verifyFormat("void f() { operator&(a, b * b); }");
9887 
9888   verifyFormat("::operator delete(foo);");
9889   verifyFormat("::operator new(n * sizeof(foo));");
9890   verifyFormat("foo() { ::operator delete(foo); }");
9891   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9892 }
9893 
9894 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9895   verifyFormat("void A::b() && {}");
9896   verifyFormat("void A::b() &&noexcept {}");
9897   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9898   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9899   verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
9900   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9901   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9902   verifyFormat("Deleted &operator=(const Deleted &) &;");
9903   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9904   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9905   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9906   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9907   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9908   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9909   verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
9910   verifyFormat("void Fn(T const &) const &;");
9911   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9912   verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
9913   verifyFormat("template <typename T>\n"
9914                "void F(T) && = delete;",
9915                getGoogleStyle());
9916   verifyFormat("template <typename T> void operator=(T) &;");
9917   verifyFormat("template <typename T> void operator=(T) const &;");
9918   verifyFormat("template <typename T> void operator=(T) &noexcept;");
9919   verifyFormat("template <typename T> void operator=(T) & = default;");
9920   verifyFormat("template <typename T> void operator=(T) &&;");
9921   verifyFormat("template <typename T> void operator=(T) && = delete;");
9922   verifyFormat("template <typename T> void operator=(T) & {}");
9923   verifyFormat("template <typename T> void operator=(T) && {}");
9924 
9925   FormatStyle AlignLeft = getLLVMStyle();
9926   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9927   verifyFormat("void A::b() && {}", AlignLeft);
9928   verifyFormat("void A::b() && noexcept {}", AlignLeft);
9929   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9930   verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
9931                AlignLeft);
9932   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9933                AlignLeft);
9934   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9935   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9936   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9937   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9938   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9939   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9940   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9941   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9942   verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
9943                AlignLeft);
9944   verifyFormat("template <typename T> void operator=(T) &;", AlignLeft);
9945   verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft);
9946   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9947                AlignLeft);
9948   verifyFormat("template <typename T> void operator=(T) & = default;",
9949                AlignLeft);
9950   verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft);
9951   verifyFormat("template <typename T> void operator=(T) && = delete;",
9952                AlignLeft);
9953   verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft);
9954   verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft);
9955 
9956   FormatStyle AlignMiddle = getLLVMStyle();
9957   AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9958   verifyFormat("void A::b() && {}", AlignMiddle);
9959   verifyFormat("void A::b() && noexcept {}", AlignMiddle);
9960   verifyFormat("Deleted & operator=(const Deleted &) & = default;",
9961                AlignMiddle);
9962   verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
9963                AlignMiddle);
9964   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
9965                AlignMiddle);
9966   verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
9967   verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
9968   verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
9969   verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
9970   verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
9971   verifyFormat("auto Function(T) & -> void;", AlignMiddle);
9972   verifyFormat("void Fn(T const &) const &;", AlignMiddle);
9973   verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
9974   verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
9975                AlignMiddle);
9976   verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle);
9977   verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle);
9978   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9979                AlignMiddle);
9980   verifyFormat("template <typename T> void operator=(T) & = default;",
9981                AlignMiddle);
9982   verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle);
9983   verifyFormat("template <typename T> void operator=(T) && = delete;",
9984                AlignMiddle);
9985   verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle);
9986   verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle);
9987 
9988   FormatStyle Spaces = getLLVMStyle();
9989   Spaces.SpacesInCStyleCastParentheses = true;
9990   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9991   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9992   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9993   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9994 
9995   Spaces.SpacesInCStyleCastParentheses = false;
9996   Spaces.SpacesInParentheses = true;
9997   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9998   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9999                Spaces);
10000   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
10001   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
10002 
10003   FormatStyle BreakTemplate = getLLVMStyle();
10004   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
10005 
10006   verifyFormat("struct f {\n"
10007                "  template <class T>\n"
10008                "  int &foo(const std::string &str) &noexcept {}\n"
10009                "};",
10010                BreakTemplate);
10011 
10012   verifyFormat("struct f {\n"
10013                "  template <class T>\n"
10014                "  int &foo(const std::string &str) &&noexcept {}\n"
10015                "};",
10016                BreakTemplate);
10017 
10018   verifyFormat("struct f {\n"
10019                "  template <class T>\n"
10020                "  int &foo(const std::string &str) const &noexcept {}\n"
10021                "};",
10022                BreakTemplate);
10023 
10024   verifyFormat("struct f {\n"
10025                "  template <class T>\n"
10026                "  int &foo(const std::string &str) const &noexcept {}\n"
10027                "};",
10028                BreakTemplate);
10029 
10030   verifyFormat("struct f {\n"
10031                "  template <class T>\n"
10032                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
10033                "};",
10034                BreakTemplate);
10035 
10036   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
10037   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
10038       FormatStyle::BTDS_Yes;
10039   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
10040 
10041   verifyFormat("struct f {\n"
10042                "  template <class T>\n"
10043                "  int& foo(const std::string& str) & noexcept {}\n"
10044                "};",
10045                AlignLeftBreakTemplate);
10046 
10047   verifyFormat("struct f {\n"
10048                "  template <class T>\n"
10049                "  int& foo(const std::string& str) && noexcept {}\n"
10050                "};",
10051                AlignLeftBreakTemplate);
10052 
10053   verifyFormat("struct f {\n"
10054                "  template <class T>\n"
10055                "  int& foo(const std::string& str) const& noexcept {}\n"
10056                "};",
10057                AlignLeftBreakTemplate);
10058 
10059   verifyFormat("struct f {\n"
10060                "  template <class T>\n"
10061                "  int& foo(const std::string& str) const&& noexcept {}\n"
10062                "};",
10063                AlignLeftBreakTemplate);
10064 
10065   verifyFormat("struct f {\n"
10066                "  template <class T>\n"
10067                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
10068                "};",
10069                AlignLeftBreakTemplate);
10070 
10071   // The `&` in `Type&` should not be confused with a trailing `&` of
10072   // DEPRECATED(reason) member function.
10073   verifyFormat("struct f {\n"
10074                "  template <class T>\n"
10075                "  DEPRECATED(reason)\n"
10076                "  Type &foo(arguments) {}\n"
10077                "};",
10078                BreakTemplate);
10079 
10080   verifyFormat("struct f {\n"
10081                "  template <class T>\n"
10082                "  DEPRECATED(reason)\n"
10083                "  Type& foo(arguments) {}\n"
10084                "};",
10085                AlignLeftBreakTemplate);
10086 
10087   verifyFormat("void (*foopt)(int) = &func;");
10088 
10089   FormatStyle DerivePointerAlignment = getLLVMStyle();
10090   DerivePointerAlignment.DerivePointerAlignment = true;
10091   // There's always a space between the function and its trailing qualifiers.
10092   // This isn't evidence for PAS_Right (or for PAS_Left).
10093   std::string Prefix = "void a() &;\n"
10094                        "void b() &;\n";
10095   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10096   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10097   // Same if the function is an overloaded operator, and with &&.
10098   Prefix = "void operator()() &&;\n"
10099            "void operator()() &&;\n";
10100   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10101   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10102   // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
10103   Prefix = "void a() const &;\n"
10104            "void b() const &;\n";
10105   EXPECT_EQ(Prefix + "int *x;",
10106             format(Prefix + "int* x;", DerivePointerAlignment));
10107 }
10108 
10109 TEST_F(FormatTest, UnderstandsNewAndDelete) {
10110   verifyFormat("void f() {\n"
10111                "  A *a = new A;\n"
10112                "  A *a = new (placement) A;\n"
10113                "  delete a;\n"
10114                "  delete (A *)a;\n"
10115                "}");
10116   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10117                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10118   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10119                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10120                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10121   verifyFormat("delete[] h->p;");
10122   verifyFormat("delete[] (void *)p;");
10123 
10124   verifyFormat("void operator delete(void *foo) ATTRIB;");
10125   verifyFormat("void operator new(void *foo) ATTRIB;");
10126   verifyFormat("void operator delete[](void *foo) ATTRIB;");
10127   verifyFormat("void operator delete(void *ptr) noexcept;");
10128 
10129   EXPECT_EQ("void new(link p);\n"
10130             "void delete(link p);\n",
10131             format("void new (link p);\n"
10132                    "void delete (link p);\n"));
10133 }
10134 
10135 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
10136   verifyFormat("int *f(int *a) {}");
10137   verifyFormat("int main(int argc, char **argv) {}");
10138   verifyFormat("Test::Test(int b) : a(b * b) {}");
10139   verifyIndependentOfContext("f(a, *a);");
10140   verifyFormat("void g() { f(*a); }");
10141   verifyIndependentOfContext("int a = b * 10;");
10142   verifyIndependentOfContext("int a = 10 * b;");
10143   verifyIndependentOfContext("int a = b * c;");
10144   verifyIndependentOfContext("int a += b * c;");
10145   verifyIndependentOfContext("int a -= b * c;");
10146   verifyIndependentOfContext("int a *= b * c;");
10147   verifyIndependentOfContext("int a /= b * c;");
10148   verifyIndependentOfContext("int a = *b;");
10149   verifyIndependentOfContext("int a = *b * c;");
10150   verifyIndependentOfContext("int a = b * *c;");
10151   verifyIndependentOfContext("int a = b * (10);");
10152   verifyIndependentOfContext("S << b * (10);");
10153   verifyIndependentOfContext("return 10 * b;");
10154   verifyIndependentOfContext("return *b * *c;");
10155   verifyIndependentOfContext("return a & ~b;");
10156   verifyIndependentOfContext("f(b ? *c : *d);");
10157   verifyIndependentOfContext("int a = b ? *c : *d;");
10158   verifyIndependentOfContext("*b = a;");
10159   verifyIndependentOfContext("a * ~b;");
10160   verifyIndependentOfContext("a * !b;");
10161   verifyIndependentOfContext("a * +b;");
10162   verifyIndependentOfContext("a * -b;");
10163   verifyIndependentOfContext("a * ++b;");
10164   verifyIndependentOfContext("a * --b;");
10165   verifyIndependentOfContext("a[4] * b;");
10166   verifyIndependentOfContext("a[a * a] = 1;");
10167   verifyIndependentOfContext("f() * b;");
10168   verifyIndependentOfContext("a * [self dostuff];");
10169   verifyIndependentOfContext("int x = a * (a + b);");
10170   verifyIndependentOfContext("(a *)(a + b);");
10171   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
10172   verifyIndependentOfContext("int *pa = (int *)&a;");
10173   verifyIndependentOfContext("return sizeof(int **);");
10174   verifyIndependentOfContext("return sizeof(int ******);");
10175   verifyIndependentOfContext("return (int **&)a;");
10176   verifyIndependentOfContext("f((*PointerToArray)[10]);");
10177   verifyFormat("void f(Type (*parameter)[10]) {}");
10178   verifyFormat("void f(Type (&parameter)[10]) {}");
10179   verifyGoogleFormat("return sizeof(int**);");
10180   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
10181   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
10182   verifyFormat("auto a = [](int **&, int ***) {};");
10183   verifyFormat("auto PointerBinding = [](const char *S) {};");
10184   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
10185   verifyFormat("[](const decltype(*a) &value) {}");
10186   verifyFormat("[](const typeof(*a) &value) {}");
10187   verifyFormat("[](const _Atomic(a *) &value) {}");
10188   verifyFormat("[](const __underlying_type(a) &value) {}");
10189   verifyFormat("decltype(a * b) F();");
10190   verifyFormat("typeof(a * b) F();");
10191   verifyFormat("#define MACRO() [](A *a) { return 1; }");
10192   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
10193   verifyIndependentOfContext("typedef void (*f)(int *a);");
10194   verifyIndependentOfContext("int i{a * b};");
10195   verifyIndependentOfContext("aaa && aaa->f();");
10196   verifyIndependentOfContext("int x = ~*p;");
10197   verifyFormat("Constructor() : a(a), area(width * height) {}");
10198   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
10199   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
10200   verifyFormat("void f() { f(a, c * d); }");
10201   verifyFormat("void f() { f(new a(), c * d); }");
10202   verifyFormat("void f(const MyOverride &override);");
10203   verifyFormat("void f(const MyFinal &final);");
10204   verifyIndependentOfContext("bool a = f() && override.f();");
10205   verifyIndependentOfContext("bool a = f() && final.f();");
10206 
10207   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
10208 
10209   verifyIndependentOfContext("A<int *> a;");
10210   verifyIndependentOfContext("A<int **> a;");
10211   verifyIndependentOfContext("A<int *, int *> a;");
10212   verifyIndependentOfContext("A<int *[]> a;");
10213   verifyIndependentOfContext(
10214       "const char *const p = reinterpret_cast<const char *const>(q);");
10215   verifyIndependentOfContext("A<int **, int **> a;");
10216   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
10217   verifyFormat("for (char **a = b; *a; ++a) {\n}");
10218   verifyFormat("for (; a && b;) {\n}");
10219   verifyFormat("bool foo = true && [] { return false; }();");
10220 
10221   verifyFormat(
10222       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10223       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10224 
10225   verifyGoogleFormat("int const* a = &b;");
10226   verifyGoogleFormat("**outparam = 1;");
10227   verifyGoogleFormat("*outparam = a * b;");
10228   verifyGoogleFormat("int main(int argc, char** argv) {}");
10229   verifyGoogleFormat("A<int*> a;");
10230   verifyGoogleFormat("A<int**> a;");
10231   verifyGoogleFormat("A<int*, int*> a;");
10232   verifyGoogleFormat("A<int**, int**> a;");
10233   verifyGoogleFormat("f(b ? *c : *d);");
10234   verifyGoogleFormat("int a = b ? *c : *d;");
10235   verifyGoogleFormat("Type* t = **x;");
10236   verifyGoogleFormat("Type* t = *++*x;");
10237   verifyGoogleFormat("*++*x;");
10238   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
10239   verifyGoogleFormat("Type* t = x++ * y;");
10240   verifyGoogleFormat(
10241       "const char* const p = reinterpret_cast<const char* const>(q);");
10242   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
10243   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
10244   verifyGoogleFormat("template <typename T>\n"
10245                      "void f(int i = 0, SomeType** temps = NULL);");
10246 
10247   FormatStyle Left = getLLVMStyle();
10248   Left.PointerAlignment = FormatStyle::PAS_Left;
10249   verifyFormat("x = *a(x) = *a(y);", Left);
10250   verifyFormat("for (;; *a = b) {\n}", Left);
10251   verifyFormat("return *this += 1;", Left);
10252   verifyFormat("throw *x;", Left);
10253   verifyFormat("delete *x;", Left);
10254   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
10255   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
10256   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
10257   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
10258   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
10259   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
10260   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
10261   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
10262   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
10263 
10264   verifyIndependentOfContext("a = *(x + y);");
10265   verifyIndependentOfContext("a = &(x + y);");
10266   verifyIndependentOfContext("*(x + y).call();");
10267   verifyIndependentOfContext("&(x + y)->call();");
10268   verifyFormat("void f() { &(*I).first; }");
10269 
10270   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
10271   verifyFormat("f(* /* confusing comment */ foo);");
10272   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
10273   verifyFormat("void foo(int * // this is the first paramters\n"
10274                "         ,\n"
10275                "         int second);");
10276   verifyFormat("double term = a * // first\n"
10277                "              b;");
10278   verifyFormat(
10279       "int *MyValues = {\n"
10280       "    *A, // Operator detection might be confused by the '{'\n"
10281       "    *BB // Operator detection might be confused by previous comment\n"
10282       "};");
10283 
10284   verifyIndependentOfContext("if (int *a = &b)");
10285   verifyIndependentOfContext("if (int &a = *b)");
10286   verifyIndependentOfContext("if (a & b[i])");
10287   verifyIndependentOfContext("if constexpr (a & b[i])");
10288   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
10289   verifyIndependentOfContext("if (a * (b * c))");
10290   verifyIndependentOfContext("if constexpr (a * (b * c))");
10291   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
10292   verifyIndependentOfContext("if (a::b::c::d & b[i])");
10293   verifyIndependentOfContext("if (*b[i])");
10294   verifyIndependentOfContext("if (int *a = (&b))");
10295   verifyIndependentOfContext("while (int *a = &b)");
10296   verifyIndependentOfContext("while (a * (b * c))");
10297   verifyIndependentOfContext("size = sizeof *a;");
10298   verifyIndependentOfContext("if (a && (b = c))");
10299   verifyFormat("void f() {\n"
10300                "  for (const int &v : Values) {\n"
10301                "  }\n"
10302                "}");
10303   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
10304   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
10305   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
10306 
10307   verifyFormat("#define A (!a * b)");
10308   verifyFormat("#define MACRO     \\\n"
10309                "  int *i = a * b; \\\n"
10310                "  void f(a *b);",
10311                getLLVMStyleWithColumns(19));
10312 
10313   verifyIndependentOfContext("A = new SomeType *[Length];");
10314   verifyIndependentOfContext("A = new SomeType *[Length]();");
10315   verifyIndependentOfContext("T **t = new T *;");
10316   verifyIndependentOfContext("T **t = new T *();");
10317   verifyGoogleFormat("A = new SomeType*[Length]();");
10318   verifyGoogleFormat("A = new SomeType*[Length];");
10319   verifyGoogleFormat("T** t = new T*;");
10320   verifyGoogleFormat("T** t = new T*();");
10321 
10322   verifyFormat("STATIC_ASSERT((a & b) == 0);");
10323   verifyFormat("STATIC_ASSERT(0 == (a & b));");
10324   verifyFormat("template <bool a, bool b> "
10325                "typename t::if<x && y>::type f() {}");
10326   verifyFormat("template <int *y> f() {}");
10327   verifyFormat("vector<int *> v;");
10328   verifyFormat("vector<int *const> v;");
10329   verifyFormat("vector<int *const **const *> v;");
10330   verifyFormat("vector<int *volatile> v;");
10331   verifyFormat("vector<a *_Nonnull> v;");
10332   verifyFormat("vector<a *_Nullable> v;");
10333   verifyFormat("vector<a *_Null_unspecified> v;");
10334   verifyFormat("vector<a *__ptr32> v;");
10335   verifyFormat("vector<a *__ptr64> v;");
10336   verifyFormat("vector<a *__capability> v;");
10337   FormatStyle TypeMacros = getLLVMStyle();
10338   TypeMacros.TypenameMacros = {"LIST"};
10339   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
10340   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
10341   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
10342   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
10343   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
10344 
10345   FormatStyle CustomQualifier = getLLVMStyle();
10346   // Add identifiers that should not be parsed as a qualifier by default.
10347   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10348   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
10349   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
10350   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
10351   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
10352   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
10353   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
10354   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
10355   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
10356   verifyFormat("vector<a * _NotAQualifier> v;");
10357   verifyFormat("vector<a * __not_a_qualifier> v;");
10358   verifyFormat("vector<a * b> v;");
10359   verifyFormat("foo<b && false>();");
10360   verifyFormat("foo<b & 1>();");
10361   verifyFormat("foo<b & (1)>();");
10362   verifyFormat("foo<b & (~0)>();");
10363   verifyFormat("foo<b & (true)>();");
10364   verifyFormat("foo<b & ((1))>();");
10365   verifyFormat("foo<b & (/*comment*/ 1)>();");
10366   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
10367   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
10368   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
10369   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
10370   verifyFormat(
10371       "template <class T, class = typename std::enable_if<\n"
10372       "                       std::is_integral<T>::value &&\n"
10373       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
10374       "void F();",
10375       getLLVMStyleWithColumns(70));
10376   verifyFormat("template <class T,\n"
10377                "          class = typename std::enable_if<\n"
10378                "              std::is_integral<T>::value &&\n"
10379                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
10380                "          class U>\n"
10381                "void F();",
10382                getLLVMStyleWithColumns(70));
10383   verifyFormat(
10384       "template <class T,\n"
10385       "          class = typename ::std::enable_if<\n"
10386       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
10387       "void F();",
10388       getGoogleStyleWithColumns(68));
10389 
10390   verifyIndependentOfContext("MACRO(int *i);");
10391   verifyIndependentOfContext("MACRO(auto *a);");
10392   verifyIndependentOfContext("MACRO(const A *a);");
10393   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
10394   verifyIndependentOfContext("MACRO(decltype(A) *a);");
10395   verifyIndependentOfContext("MACRO(typeof(A) *a);");
10396   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
10397   verifyIndependentOfContext("MACRO(A *const a);");
10398   verifyIndependentOfContext("MACRO(A *restrict a);");
10399   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
10400   verifyIndependentOfContext("MACRO(A *__restrict a);");
10401   verifyIndependentOfContext("MACRO(A *volatile a);");
10402   verifyIndependentOfContext("MACRO(A *__volatile a);");
10403   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
10404   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
10405   verifyIndependentOfContext("MACRO(A *_Nullable a);");
10406   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
10407   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
10408   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
10409   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
10410   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
10411   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
10412   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
10413   verifyIndependentOfContext("MACRO(A *__capability);");
10414   verifyIndependentOfContext("MACRO(A &__capability);");
10415   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
10416   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
10417   // If we add __my_qualifier to AttributeMacros it should always be parsed as
10418   // a type declaration:
10419   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
10420   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
10421   // Also check that TypenameMacros prevents parsing it as multiplication:
10422   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
10423   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
10424 
10425   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
10426   verifyFormat("void f() { f(float{1}, a * a); }");
10427   verifyFormat("void f() { f(float(1), a * a); }");
10428 
10429   verifyFormat("f((void (*)(int))g);");
10430   verifyFormat("f((void (&)(int))g);");
10431   verifyFormat("f((void (^)(int))g);");
10432 
10433   // FIXME: Is there a way to make this work?
10434   // verifyIndependentOfContext("MACRO(A *a);");
10435   verifyFormat("MACRO(A &B);");
10436   verifyFormat("MACRO(A *B);");
10437   verifyFormat("void f() { MACRO(A * B); }");
10438   verifyFormat("void f() { MACRO(A & B); }");
10439 
10440   // This lambda was mis-formatted after D88956 (treating it as a binop):
10441   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
10442   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
10443   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
10444   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
10445 
10446   verifyFormat("DatumHandle const *operator->() const { return input_; }");
10447   verifyFormat("return options != nullptr && operator==(*options);");
10448 
10449   EXPECT_EQ("#define OP(x)                                    \\\n"
10450             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
10451             "    return s << a.DebugString();                 \\\n"
10452             "  }",
10453             format("#define OP(x) \\\n"
10454                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
10455                    "    return s << a.DebugString(); \\\n"
10456                    "  }",
10457                    getLLVMStyleWithColumns(50)));
10458 
10459   // FIXME: We cannot handle this case yet; we might be able to figure out that
10460   // foo<x> d > v; doesn't make sense.
10461   verifyFormat("foo<a<b && c> d> v;");
10462 
10463   FormatStyle PointerMiddle = getLLVMStyle();
10464   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10465   verifyFormat("delete *x;", PointerMiddle);
10466   verifyFormat("int * x;", PointerMiddle);
10467   verifyFormat("int *[] x;", PointerMiddle);
10468   verifyFormat("template <int * y> f() {}", PointerMiddle);
10469   verifyFormat("int * f(int * a) {}", PointerMiddle);
10470   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
10471   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10472   verifyFormat("A<int *> a;", PointerMiddle);
10473   verifyFormat("A<int **> a;", PointerMiddle);
10474   verifyFormat("A<int *, int *> a;", PointerMiddle);
10475   verifyFormat("A<int *[]> a;", PointerMiddle);
10476   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10477   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10478   verifyFormat("T ** t = new T *;", PointerMiddle);
10479 
10480   // Member function reference qualifiers aren't binary operators.
10481   verifyFormat("string // break\n"
10482                "operator()() & {}");
10483   verifyFormat("string // break\n"
10484                "operator()() && {}");
10485   verifyGoogleFormat("template <typename T>\n"
10486                      "auto x() & -> int {}");
10487 
10488   // Should be binary operators when used as an argument expression (overloaded
10489   // operator invoked as a member function).
10490   verifyFormat("void f() { a.operator()(a * a); }");
10491   verifyFormat("void f() { a->operator()(a & a); }");
10492   verifyFormat("void f() { a.operator()(*a & *a); }");
10493   verifyFormat("void f() { a->operator()(*a * *a); }");
10494 
10495   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10496   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10497 }
10498 
10499 TEST_F(FormatTest, UnderstandsAttributes) {
10500   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10501   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10502                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10503   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10504   FormatStyle AfterType = getLLVMStyle();
10505   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10506   verifyFormat("__attribute__((nodebug)) void\n"
10507                "foo() {}\n",
10508                AfterType);
10509   verifyFormat("__unused void\n"
10510                "foo() {}",
10511                AfterType);
10512 
10513   FormatStyle CustomAttrs = getLLVMStyle();
10514   CustomAttrs.AttributeMacros.push_back("__unused");
10515   CustomAttrs.AttributeMacros.push_back("__attr1");
10516   CustomAttrs.AttributeMacros.push_back("__attr2");
10517   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10518   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10519   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10520   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10521   // Check that it is parsed as a multiplication without AttributeMacros and
10522   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10523   verifyFormat("vector<SomeType * __attr1> v;");
10524   verifyFormat("vector<SomeType __attr1 *> v;");
10525   verifyFormat("vector<SomeType __attr1 *const> v;");
10526   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10527   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10528   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10529   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10530   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10531   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10532   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10533   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10534 
10535   // Check that these are not parsed as function declarations:
10536   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10537   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10538   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10539   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10540   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10541   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10542   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10543   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10544   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10545   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10546 }
10547 
10548 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10549   // Check that qualifiers on pointers don't break parsing of casts.
10550   verifyFormat("x = (foo *const)*v;");
10551   verifyFormat("x = (foo *volatile)*v;");
10552   verifyFormat("x = (foo *restrict)*v;");
10553   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10554   verifyFormat("x = (foo *_Nonnull)*v;");
10555   verifyFormat("x = (foo *_Nullable)*v;");
10556   verifyFormat("x = (foo *_Null_unspecified)*v;");
10557   verifyFormat("x = (foo *_Nonnull)*v;");
10558   verifyFormat("x = (foo *[[clang::attr]])*v;");
10559   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10560   verifyFormat("x = (foo *__ptr32)*v;");
10561   verifyFormat("x = (foo *__ptr64)*v;");
10562   verifyFormat("x = (foo *__capability)*v;");
10563 
10564   // Check that we handle multiple trailing qualifiers and skip them all to
10565   // determine that the expression is a cast to a pointer type.
10566   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10567   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10568   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10569   StringRef AllQualifiers =
10570       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10571       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10572   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10573   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10574 
10575   // Also check that address-of is not parsed as a binary bitwise-and:
10576   verifyFormat("x = (foo *const)&v;");
10577   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10578   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10579 
10580   // Check custom qualifiers:
10581   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10582   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10583   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10584   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10585   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10586                CustomQualifier);
10587   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10588                CustomQualifier);
10589 
10590   // Check that unknown identifiers result in binary operator parsing:
10591   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10592   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10593 }
10594 
10595 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10596   verifyFormat("SomeType s [[unused]] (InitValue);");
10597   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10598   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10599   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10600   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10601   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10602                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10603   verifyFormat("[[nodiscard]] bool f() { return false; }");
10604   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10605   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10606   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10607   verifyFormat("[[nodiscard]] ::qualified_type f();");
10608 
10609   // Make sure we do not mistake attributes for array subscripts.
10610   verifyFormat("int a() {}\n"
10611                "[[unused]] int b() {}\n");
10612   verifyFormat("NSArray *arr;\n"
10613                "arr[[Foo() bar]];");
10614 
10615   // On the other hand, we still need to correctly find array subscripts.
10616   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10617 
10618   // Make sure that we do not mistake Objective-C method inside array literals
10619   // as attributes, even if those method names are also keywords.
10620   verifyFormat("@[ [foo bar] ];");
10621   verifyFormat("@[ [NSArray class] ];");
10622   verifyFormat("@[ [foo enum] ];");
10623 
10624   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10625 
10626   // Make sure we do not parse attributes as lambda introducers.
10627   FormatStyle MultiLineFunctions = getLLVMStyle();
10628   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10629   verifyFormat("[[unused]] int b() {\n"
10630                "  return 42;\n"
10631                "}\n",
10632                MultiLineFunctions);
10633 }
10634 
10635 TEST_F(FormatTest, AttributeClass) {
10636   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10637   verifyFormat("class S {\n"
10638                "  S(S&&) = default;\n"
10639                "};",
10640                Style);
10641   verifyFormat("class [[nodiscard]] S {\n"
10642                "  S(S&&) = default;\n"
10643                "};",
10644                Style);
10645   verifyFormat("class __attribute((maybeunused)) S {\n"
10646                "  S(S&&) = default;\n"
10647                "};",
10648                Style);
10649   verifyFormat("struct S {\n"
10650                "  S(S&&) = default;\n"
10651                "};",
10652                Style);
10653   verifyFormat("struct [[nodiscard]] S {\n"
10654                "  S(S&&) = default;\n"
10655                "};",
10656                Style);
10657 }
10658 
10659 TEST_F(FormatTest, AttributesAfterMacro) {
10660   FormatStyle Style = getLLVMStyle();
10661   verifyFormat("MACRO;\n"
10662                "__attribute__((maybe_unused)) int foo() {\n"
10663                "  //...\n"
10664                "}");
10665 
10666   verifyFormat("MACRO;\n"
10667                "[[nodiscard]] int foo() {\n"
10668                "  //...\n"
10669                "}");
10670 
10671   EXPECT_EQ("MACRO\n\n"
10672             "__attribute__((maybe_unused)) int foo() {\n"
10673             "  //...\n"
10674             "}",
10675             format("MACRO\n\n"
10676                    "__attribute__((maybe_unused)) int foo() {\n"
10677                    "  //...\n"
10678                    "}"));
10679 
10680   EXPECT_EQ("MACRO\n\n"
10681             "[[nodiscard]] int foo() {\n"
10682             "  //...\n"
10683             "}",
10684             format("MACRO\n\n"
10685                    "[[nodiscard]] int foo() {\n"
10686                    "  //...\n"
10687                    "}"));
10688 }
10689 
10690 TEST_F(FormatTest, AttributePenaltyBreaking) {
10691   FormatStyle Style = getLLVMStyle();
10692   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10693                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10694                Style);
10695   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10696                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10697                Style);
10698   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10699                "shared_ptr<ALongTypeName> &C d) {\n}",
10700                Style);
10701 }
10702 
10703 TEST_F(FormatTest, UnderstandsEllipsis) {
10704   FormatStyle Style = getLLVMStyle();
10705   verifyFormat("int printf(const char *fmt, ...);");
10706   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10707   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10708 
10709   verifyFormat("template <int *...PP> a;", Style);
10710 
10711   Style.PointerAlignment = FormatStyle::PAS_Left;
10712   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10713 
10714   verifyFormat("template <int*... PP> a;", Style);
10715 
10716   Style.PointerAlignment = FormatStyle::PAS_Middle;
10717   verifyFormat("template <int *... PP> a;", Style);
10718 }
10719 
10720 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10721   EXPECT_EQ("int *a;\n"
10722             "int *a;\n"
10723             "int *a;",
10724             format("int *a;\n"
10725                    "int* a;\n"
10726                    "int *a;",
10727                    getGoogleStyle()));
10728   EXPECT_EQ("int* a;\n"
10729             "int* a;\n"
10730             "int* a;",
10731             format("int* a;\n"
10732                    "int* a;\n"
10733                    "int *a;",
10734                    getGoogleStyle()));
10735   EXPECT_EQ("int *a;\n"
10736             "int *a;\n"
10737             "int *a;",
10738             format("int *a;\n"
10739                    "int * a;\n"
10740                    "int *  a;",
10741                    getGoogleStyle()));
10742   EXPECT_EQ("auto x = [] {\n"
10743             "  int *a;\n"
10744             "  int *a;\n"
10745             "  int *a;\n"
10746             "};",
10747             format("auto x=[]{int *a;\n"
10748                    "int * a;\n"
10749                    "int *  a;};",
10750                    getGoogleStyle()));
10751 }
10752 
10753 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10754   verifyFormat("int f(int &&a) {}");
10755   verifyFormat("int f(int a, char &&b) {}");
10756   verifyFormat("void f() { int &&a = b; }");
10757   verifyGoogleFormat("int f(int a, char&& b) {}");
10758   verifyGoogleFormat("void f() { int&& a = b; }");
10759 
10760   verifyIndependentOfContext("A<int &&> a;");
10761   verifyIndependentOfContext("A<int &&, int &&> a;");
10762   verifyGoogleFormat("A<int&&> a;");
10763   verifyGoogleFormat("A<int&&, int&&> a;");
10764 
10765   // Not rvalue references:
10766   verifyFormat("template <bool B, bool C> class A {\n"
10767                "  static_assert(B && C, \"Something is wrong\");\n"
10768                "};");
10769   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10770   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10771   verifyFormat("#define A(a, b) (a && b)");
10772 }
10773 
10774 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10775   verifyFormat("void f() {\n"
10776                "  x[aaaaaaaaa -\n"
10777                "    b] = 23;\n"
10778                "}",
10779                getLLVMStyleWithColumns(15));
10780 }
10781 
10782 TEST_F(FormatTest, FormatsCasts) {
10783   verifyFormat("Type *A = static_cast<Type *>(P);");
10784   verifyFormat("static_cast<Type *>(P);");
10785   verifyFormat("static_cast<Type &>(Fun)(Args);");
10786   verifyFormat("static_cast<Type &>(*Fun)(Args);");
10787   verifyFormat("if (static_cast<int>(A) + B >= 0)\n  ;");
10788   // Check that static_cast<...>(...) does not require the next token to be on
10789   // the same line.
10790   verifyFormat("some_loooong_output << something_something__ << "
10791                "static_cast<const void *>(R)\n"
10792                "                    << something;");
10793   verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
10794   verifyFormat("const_cast<Type &>(*Fun)(Args);");
10795   verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
10796   verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
10797   verifyFormat("Type *A = (Type *)P;");
10798   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10799   verifyFormat("int a = (int)(2.0f);");
10800   verifyFormat("int a = (int)2.0f;");
10801   verifyFormat("x[(int32)y];");
10802   verifyFormat("x = (int32)y;");
10803   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10804   verifyFormat("int a = (int)*b;");
10805   verifyFormat("int a = (int)2.0f;");
10806   verifyFormat("int a = (int)~0;");
10807   verifyFormat("int a = (int)++a;");
10808   verifyFormat("int a = (int)sizeof(int);");
10809   verifyFormat("int a = (int)+2;");
10810   verifyFormat("my_int a = (my_int)2.0f;");
10811   verifyFormat("my_int a = (my_int)sizeof(int);");
10812   verifyFormat("return (my_int)aaa;");
10813   verifyFormat("#define x ((int)-1)");
10814   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10815   verifyFormat("#define p(q) ((int *)&q)");
10816   verifyFormat("fn(a)(b) + 1;");
10817 
10818   verifyFormat("void f() { my_int a = (my_int)*b; }");
10819   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10820   verifyFormat("my_int a = (my_int)~0;");
10821   verifyFormat("my_int a = (my_int)++a;");
10822   verifyFormat("my_int a = (my_int)-2;");
10823   verifyFormat("my_int a = (my_int)1;");
10824   verifyFormat("my_int a = (my_int *)1;");
10825   verifyFormat("my_int a = (const my_int)-1;");
10826   verifyFormat("my_int a = (const my_int *)-1;");
10827   verifyFormat("my_int a = (my_int)(my_int)-1;");
10828   verifyFormat("my_int a = (ns::my_int)-2;");
10829   verifyFormat("case (my_int)ONE:");
10830   verifyFormat("auto x = (X)this;");
10831   // Casts in Obj-C style calls used to not be recognized as such.
10832   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10833 
10834   // FIXME: single value wrapped with paren will be treated as cast.
10835   verifyFormat("void f(int i = (kValue)*kMask) {}");
10836 
10837   verifyFormat("{ (void)F; }");
10838 
10839   // Don't break after a cast's
10840   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10841                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10842                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10843 
10844   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10845   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10846   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10847   verifyFormat("bool *y = (bool *)(void *)(x);");
10848   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10849   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10850   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10851   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10852 
10853   // These are not casts.
10854   verifyFormat("void f(int *) {}");
10855   verifyFormat("f(foo)->b;");
10856   verifyFormat("f(foo).b;");
10857   verifyFormat("f(foo)(b);");
10858   verifyFormat("f(foo)[b];");
10859   verifyFormat("[](foo) { return 4; }(bar);");
10860   verifyFormat("(*funptr)(foo)[4];");
10861   verifyFormat("funptrs[4](foo)[4];");
10862   verifyFormat("void f(int *);");
10863   verifyFormat("void f(int *) = 0;");
10864   verifyFormat("void f(SmallVector<int>) {}");
10865   verifyFormat("void f(SmallVector<int>);");
10866   verifyFormat("void f(SmallVector<int>) = 0;");
10867   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10868   verifyFormat("int a = sizeof(int) * b;");
10869   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10870   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10871   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10872   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10873 
10874   // These are not casts, but at some point were confused with casts.
10875   verifyFormat("virtual void foo(int *) override;");
10876   verifyFormat("virtual void foo(char &) const;");
10877   verifyFormat("virtual void foo(int *a, char *) const;");
10878   verifyFormat("int a = sizeof(int *) + b;");
10879   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10880   verifyFormat("bool b = f(g<int>) && c;");
10881   verifyFormat("typedef void (*f)(int i) func;");
10882   verifyFormat("void operator++(int) noexcept;");
10883   verifyFormat("void operator++(int &) noexcept;");
10884   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10885                "&) noexcept;");
10886   verifyFormat(
10887       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10888   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10889   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10890   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10891   verifyFormat("void operator delete(foo &) noexcept;");
10892   verifyFormat("void operator delete(foo) noexcept;");
10893   verifyFormat("void operator delete(int) noexcept;");
10894   verifyFormat("void operator delete(int &) noexcept;");
10895   verifyFormat("void operator delete(int &) volatile noexcept;");
10896   verifyFormat("void operator delete(int &) const");
10897   verifyFormat("void operator delete(int &) = default");
10898   verifyFormat("void operator delete(int &) = delete");
10899   verifyFormat("void operator delete(int &) [[noreturn]]");
10900   verifyFormat("void operator delete(int &) throw();");
10901   verifyFormat("void operator delete(int &) throw(int);");
10902   verifyFormat("auto operator delete(int &) -> int;");
10903   verifyFormat("auto operator delete(int &) override");
10904   verifyFormat("auto operator delete(int &) final");
10905 
10906   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10907                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10908   // FIXME: The indentation here is not ideal.
10909   verifyFormat(
10910       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10911       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10912       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10913 }
10914 
10915 TEST_F(FormatTest, FormatsFunctionTypes) {
10916   verifyFormat("A<bool()> a;");
10917   verifyFormat("A<SomeType()> a;");
10918   verifyFormat("A<void (*)(int, std::string)> a;");
10919   verifyFormat("A<void *(int)>;");
10920   verifyFormat("void *(*a)(int *, SomeType *);");
10921   verifyFormat("int (*func)(void *);");
10922   verifyFormat("void f() { int (*func)(void *); }");
10923   verifyFormat("template <class CallbackClass>\n"
10924                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10925 
10926   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10927   verifyGoogleFormat("void* (*a)(int);");
10928   verifyGoogleFormat(
10929       "template <class CallbackClass>\n"
10930       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10931 
10932   // Other constructs can look somewhat like function types:
10933   verifyFormat("A<sizeof(*x)> a;");
10934   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10935   verifyFormat("some_var = function(*some_pointer_var)[0];");
10936   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10937   verifyFormat("int x = f(&h)();");
10938   verifyFormat("returnsFunction(&param1, &param2)(param);");
10939   verifyFormat("std::function<\n"
10940                "    LooooooooooongTemplatedType<\n"
10941                "        SomeType>*(\n"
10942                "        LooooooooooooooooongType type)>\n"
10943                "    function;",
10944                getGoogleStyleWithColumns(40));
10945 }
10946 
10947 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10948   verifyFormat("A (*foo_)[6];");
10949   verifyFormat("vector<int> (*foo_)[6];");
10950 }
10951 
10952 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10953   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10954                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10955   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10956                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10957   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10958                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10959 
10960   // Different ways of ()-initializiation.
10961   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10962                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10963   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10964                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10965   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10966                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10967   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10968                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10969 
10970   // Lambdas should not confuse the variable declaration heuristic.
10971   verifyFormat("LooooooooooooooooongType\n"
10972                "    variable(nullptr, [](A *a) {});",
10973                getLLVMStyleWithColumns(40));
10974 }
10975 
10976 TEST_F(FormatTest, BreaksLongDeclarations) {
10977   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10978                "    AnotherNameForTheLongType;");
10979   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10980                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10981   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10982                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10983   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10984                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10985   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10986                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10987   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10988                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10989   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10990                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10991   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10992                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10993   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10994                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10995   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10996                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10997   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10998                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10999   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11000                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
11001   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11002                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
11003   FormatStyle Indented = getLLVMStyle();
11004   Indented.IndentWrappedFunctionNames = true;
11005   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11006                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
11007                Indented);
11008   verifyFormat(
11009       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11010       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11011       Indented);
11012   verifyFormat(
11013       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
11014       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11015       Indented);
11016   verifyFormat(
11017       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
11018       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11019       Indented);
11020 
11021   // FIXME: Without the comment, this breaks after "(".
11022   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
11023                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
11024                getGoogleStyle());
11025 
11026   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
11027                "                  int LoooooooooooooooooooongParam2) {}");
11028   verifyFormat(
11029       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
11030       "                                   SourceLocation L, IdentifierIn *II,\n"
11031       "                                   Type *T) {}");
11032   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
11033                "ReallyReaaallyLongFunctionName(\n"
11034                "    const std::string &SomeParameter,\n"
11035                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11036                "        &ReallyReallyLongParameterName,\n"
11037                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11038                "        &AnotherLongParameterName) {}");
11039   verifyFormat("template <typename A>\n"
11040                "SomeLoooooooooooooooooooooongType<\n"
11041                "    typename some_namespace::SomeOtherType<A>::Type>\n"
11042                "Function() {}");
11043 
11044   verifyGoogleFormat(
11045       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
11046       "    aaaaaaaaaaaaaaaaaaaaaaa;");
11047   verifyGoogleFormat(
11048       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
11049       "                                   SourceLocation L) {}");
11050   verifyGoogleFormat(
11051       "some_namespace::LongReturnType\n"
11052       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
11053       "    int first_long_parameter, int second_parameter) {}");
11054 
11055   verifyGoogleFormat("template <typename T>\n"
11056                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11057                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
11058   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11059                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
11060 
11061   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
11062                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11063                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11064   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11065                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11066                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
11067   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11068                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
11069                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
11070                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11071 
11072   verifyFormat("template <typename T> // Templates on own line.\n"
11073                "static int            // Some comment.\n"
11074                "MyFunction(int a);",
11075                getLLVMStyle());
11076 }
11077 
11078 TEST_F(FormatTest, FormatsAccessModifiers) {
11079   FormatStyle Style = getLLVMStyle();
11080   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
11081             FormatStyle::ELBAMS_LogicalBlock);
11082   verifyFormat("struct foo {\n"
11083                "private:\n"
11084                "  void f() {}\n"
11085                "\n"
11086                "private:\n"
11087                "  int i;\n"
11088                "\n"
11089                "protected:\n"
11090                "  int j;\n"
11091                "};\n",
11092                Style);
11093   verifyFormat("struct foo {\n"
11094                "private:\n"
11095                "  void f() {}\n"
11096                "\n"
11097                "private:\n"
11098                "  int i;\n"
11099                "\n"
11100                "protected:\n"
11101                "  int j;\n"
11102                "};\n",
11103                "struct foo {\n"
11104                "private:\n"
11105                "  void f() {}\n"
11106                "private:\n"
11107                "  int i;\n"
11108                "protected:\n"
11109                "  int j;\n"
11110                "};\n",
11111                Style);
11112   verifyFormat("struct foo { /* comment */\n"
11113                "private:\n"
11114                "  int i;\n"
11115                "  // comment\n"
11116                "private:\n"
11117                "  int j;\n"
11118                "};\n",
11119                Style);
11120   verifyFormat("struct foo {\n"
11121                "#ifdef FOO\n"
11122                "#endif\n"
11123                "private:\n"
11124                "  int i;\n"
11125                "#ifdef FOO\n"
11126                "private:\n"
11127                "#endif\n"
11128                "  int j;\n"
11129                "};\n",
11130                Style);
11131   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11132   verifyFormat("struct foo {\n"
11133                "private:\n"
11134                "  void f() {}\n"
11135                "private:\n"
11136                "  int i;\n"
11137                "protected:\n"
11138                "  int j;\n"
11139                "};\n",
11140                Style);
11141   verifyFormat("struct foo {\n"
11142                "private:\n"
11143                "  void f() {}\n"
11144                "private:\n"
11145                "  int i;\n"
11146                "protected:\n"
11147                "  int j;\n"
11148                "};\n",
11149                "struct foo {\n"
11150                "\n"
11151                "private:\n"
11152                "  void f() {}\n"
11153                "\n"
11154                "private:\n"
11155                "  int i;\n"
11156                "\n"
11157                "protected:\n"
11158                "  int j;\n"
11159                "};\n",
11160                Style);
11161   verifyFormat("struct foo { /* comment */\n"
11162                "private:\n"
11163                "  int i;\n"
11164                "  // comment\n"
11165                "private:\n"
11166                "  int j;\n"
11167                "};\n",
11168                "struct foo { /* comment */\n"
11169                "\n"
11170                "private:\n"
11171                "  int i;\n"
11172                "  // comment\n"
11173                "\n"
11174                "private:\n"
11175                "  int j;\n"
11176                "};\n",
11177                Style);
11178   verifyFormat("struct foo {\n"
11179                "#ifdef FOO\n"
11180                "#endif\n"
11181                "private:\n"
11182                "  int i;\n"
11183                "#ifdef FOO\n"
11184                "private:\n"
11185                "#endif\n"
11186                "  int j;\n"
11187                "};\n",
11188                "struct foo {\n"
11189                "#ifdef FOO\n"
11190                "#endif\n"
11191                "\n"
11192                "private:\n"
11193                "  int i;\n"
11194                "#ifdef FOO\n"
11195                "\n"
11196                "private:\n"
11197                "#endif\n"
11198                "  int j;\n"
11199                "};\n",
11200                Style);
11201   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11202   verifyFormat("struct foo {\n"
11203                "private:\n"
11204                "  void f() {}\n"
11205                "\n"
11206                "private:\n"
11207                "  int i;\n"
11208                "\n"
11209                "protected:\n"
11210                "  int j;\n"
11211                "};\n",
11212                Style);
11213   verifyFormat("struct foo {\n"
11214                "private:\n"
11215                "  void f() {}\n"
11216                "\n"
11217                "private:\n"
11218                "  int i;\n"
11219                "\n"
11220                "protected:\n"
11221                "  int j;\n"
11222                "};\n",
11223                "struct foo {\n"
11224                "private:\n"
11225                "  void f() {}\n"
11226                "private:\n"
11227                "  int i;\n"
11228                "protected:\n"
11229                "  int j;\n"
11230                "};\n",
11231                Style);
11232   verifyFormat("struct foo { /* comment */\n"
11233                "private:\n"
11234                "  int i;\n"
11235                "  // comment\n"
11236                "\n"
11237                "private:\n"
11238                "  int j;\n"
11239                "};\n",
11240                "struct foo { /* comment */\n"
11241                "private:\n"
11242                "  int i;\n"
11243                "  // comment\n"
11244                "\n"
11245                "private:\n"
11246                "  int j;\n"
11247                "};\n",
11248                Style);
11249   verifyFormat("struct foo {\n"
11250                "#ifdef FOO\n"
11251                "#endif\n"
11252                "\n"
11253                "private:\n"
11254                "  int i;\n"
11255                "#ifdef FOO\n"
11256                "\n"
11257                "private:\n"
11258                "#endif\n"
11259                "  int j;\n"
11260                "};\n",
11261                "struct foo {\n"
11262                "#ifdef FOO\n"
11263                "#endif\n"
11264                "private:\n"
11265                "  int i;\n"
11266                "#ifdef FOO\n"
11267                "private:\n"
11268                "#endif\n"
11269                "  int j;\n"
11270                "};\n",
11271                Style);
11272   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11273   EXPECT_EQ("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             format("struct foo {\n"
11285                    "\n"
11286                    "private:\n"
11287                    "  void f() {}\n"
11288                    "\n"
11289                    "private:\n"
11290                    "  int i;\n"
11291                    "\n"
11292                    "protected:\n"
11293                    "  int j;\n"
11294                    "};\n",
11295                    Style));
11296   verifyFormat("struct foo {\n"
11297                "private:\n"
11298                "  void f() {}\n"
11299                "private:\n"
11300                "  int i;\n"
11301                "protected:\n"
11302                "  int j;\n"
11303                "};\n",
11304                Style);
11305   EXPECT_EQ("struct foo { /* comment */\n"
11306             "\n"
11307             "private:\n"
11308             "  int i;\n"
11309             "  // comment\n"
11310             "\n"
11311             "private:\n"
11312             "  int j;\n"
11313             "};\n",
11314             format("struct foo { /* comment */\n"
11315                    "\n"
11316                    "private:\n"
11317                    "  int i;\n"
11318                    "  // comment\n"
11319                    "\n"
11320                    "private:\n"
11321                    "  int j;\n"
11322                    "};\n",
11323                    Style));
11324   verifyFormat("struct foo { /* comment */\n"
11325                "private:\n"
11326                "  int i;\n"
11327                "  // comment\n"
11328                "private:\n"
11329                "  int j;\n"
11330                "};\n",
11331                Style);
11332   EXPECT_EQ("struct foo {\n"
11333             "#ifdef FOO\n"
11334             "#endif\n"
11335             "\n"
11336             "private:\n"
11337             "  int i;\n"
11338             "#ifdef FOO\n"
11339             "\n"
11340             "private:\n"
11341             "#endif\n"
11342             "  int j;\n"
11343             "};\n",
11344             format("struct foo {\n"
11345                    "#ifdef FOO\n"
11346                    "#endif\n"
11347                    "\n"
11348                    "private:\n"
11349                    "  int i;\n"
11350                    "#ifdef FOO\n"
11351                    "\n"
11352                    "private:\n"
11353                    "#endif\n"
11354                    "  int j;\n"
11355                    "};\n",
11356                    Style));
11357   verifyFormat("struct foo {\n"
11358                "#ifdef FOO\n"
11359                "#endif\n"
11360                "private:\n"
11361                "  int i;\n"
11362                "#ifdef FOO\n"
11363                "private:\n"
11364                "#endif\n"
11365                "  int j;\n"
11366                "};\n",
11367                Style);
11368 
11369   FormatStyle NoEmptyLines = getLLVMStyle();
11370   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11371   verifyFormat("struct foo {\n"
11372                "private:\n"
11373                "  void f() {}\n"
11374                "\n"
11375                "private:\n"
11376                "  int i;\n"
11377                "\n"
11378                "public:\n"
11379                "protected:\n"
11380                "  int j;\n"
11381                "};\n",
11382                NoEmptyLines);
11383 
11384   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11385   verifyFormat("struct foo {\n"
11386                "private:\n"
11387                "  void f() {}\n"
11388                "private:\n"
11389                "  int i;\n"
11390                "public:\n"
11391                "protected:\n"
11392                "  int j;\n"
11393                "};\n",
11394                NoEmptyLines);
11395 
11396   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11397   verifyFormat("struct foo {\n"
11398                "private:\n"
11399                "  void f() {}\n"
11400                "\n"
11401                "private:\n"
11402                "  int i;\n"
11403                "\n"
11404                "public:\n"
11405                "\n"
11406                "protected:\n"
11407                "  int j;\n"
11408                "};\n",
11409                NoEmptyLines);
11410 }
11411 
11412 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
11413 
11414   FormatStyle Style = getLLVMStyle();
11415   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
11416   verifyFormat("struct foo {\n"
11417                "private:\n"
11418                "  void f() {}\n"
11419                "\n"
11420                "private:\n"
11421                "  int i;\n"
11422                "\n"
11423                "protected:\n"
11424                "  int j;\n"
11425                "};\n",
11426                Style);
11427 
11428   // Check if lines are removed.
11429   verifyFormat("struct foo {\n"
11430                "private:\n"
11431                "  void f() {}\n"
11432                "\n"
11433                "private:\n"
11434                "  int i;\n"
11435                "\n"
11436                "protected:\n"
11437                "  int j;\n"
11438                "};\n",
11439                "struct foo {\n"
11440                "private:\n"
11441                "\n"
11442                "  void f() {}\n"
11443                "\n"
11444                "private:\n"
11445                "\n"
11446                "  int i;\n"
11447                "\n"
11448                "protected:\n"
11449                "\n"
11450                "  int j;\n"
11451                "};\n",
11452                Style);
11453 
11454   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11455   verifyFormat("struct foo {\n"
11456                "private:\n"
11457                "\n"
11458                "  void f() {}\n"
11459                "\n"
11460                "private:\n"
11461                "\n"
11462                "  int i;\n"
11463                "\n"
11464                "protected:\n"
11465                "\n"
11466                "  int j;\n"
11467                "};\n",
11468                Style);
11469 
11470   // Check if lines are added.
11471   verifyFormat("struct foo {\n"
11472                "private:\n"
11473                "\n"
11474                "  void f() {}\n"
11475                "\n"
11476                "private:\n"
11477                "\n"
11478                "  int i;\n"
11479                "\n"
11480                "protected:\n"
11481                "\n"
11482                "  int j;\n"
11483                "};\n",
11484                "struct foo {\n"
11485                "private:\n"
11486                "  void f() {}\n"
11487                "\n"
11488                "private:\n"
11489                "  int i;\n"
11490                "\n"
11491                "protected:\n"
11492                "  int j;\n"
11493                "};\n",
11494                Style);
11495 
11496   // Leave tests rely on the code layout, test::messUp can not be used.
11497   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11498   Style.MaxEmptyLinesToKeep = 0u;
11499   verifyFormat("struct foo {\n"
11500                "private:\n"
11501                "  void f() {}\n"
11502                "\n"
11503                "private:\n"
11504                "  int i;\n"
11505                "\n"
11506                "protected:\n"
11507                "  int j;\n"
11508                "};\n",
11509                Style);
11510 
11511   // Check if MaxEmptyLinesToKeep is respected.
11512   EXPECT_EQ("struct foo {\n"
11513             "private:\n"
11514             "  void f() {}\n"
11515             "\n"
11516             "private:\n"
11517             "  int i;\n"
11518             "\n"
11519             "protected:\n"
11520             "  int j;\n"
11521             "};\n",
11522             format("struct foo {\n"
11523                    "private:\n"
11524                    "\n\n\n"
11525                    "  void f() {}\n"
11526                    "\n"
11527                    "private:\n"
11528                    "\n\n\n"
11529                    "  int i;\n"
11530                    "\n"
11531                    "protected:\n"
11532                    "\n\n\n"
11533                    "  int j;\n"
11534                    "};\n",
11535                    Style));
11536 
11537   Style.MaxEmptyLinesToKeep = 1u;
11538   EXPECT_EQ("struct foo {\n"
11539             "private:\n"
11540             "\n"
11541             "  void f() {}\n"
11542             "\n"
11543             "private:\n"
11544             "\n"
11545             "  int i;\n"
11546             "\n"
11547             "protected:\n"
11548             "\n"
11549             "  int j;\n"
11550             "};\n",
11551             format("struct foo {\n"
11552                    "private:\n"
11553                    "\n"
11554                    "  void f() {}\n"
11555                    "\n"
11556                    "private:\n"
11557                    "\n"
11558                    "  int i;\n"
11559                    "\n"
11560                    "protected:\n"
11561                    "\n"
11562                    "  int j;\n"
11563                    "};\n",
11564                    Style));
11565   // Check if no lines are kept.
11566   EXPECT_EQ("struct foo {\n"
11567             "private:\n"
11568             "  void f() {}\n"
11569             "\n"
11570             "private:\n"
11571             "  int i;\n"
11572             "\n"
11573             "protected:\n"
11574             "  int j;\n"
11575             "};\n",
11576             format("struct foo {\n"
11577                    "private:\n"
11578                    "  void f() {}\n"
11579                    "\n"
11580                    "private:\n"
11581                    "  int i;\n"
11582                    "\n"
11583                    "protected:\n"
11584                    "  int j;\n"
11585                    "};\n",
11586                    Style));
11587   // Check if MaxEmptyLinesToKeep is respected.
11588   EXPECT_EQ("struct foo {\n"
11589             "private:\n"
11590             "\n"
11591             "  void f() {}\n"
11592             "\n"
11593             "private:\n"
11594             "\n"
11595             "  int i;\n"
11596             "\n"
11597             "protected:\n"
11598             "\n"
11599             "  int j;\n"
11600             "};\n",
11601             format("struct foo {\n"
11602                    "private:\n"
11603                    "\n\n\n"
11604                    "  void f() {}\n"
11605                    "\n"
11606                    "private:\n"
11607                    "\n\n\n"
11608                    "  int i;\n"
11609                    "\n"
11610                    "protected:\n"
11611                    "\n\n\n"
11612                    "  int j;\n"
11613                    "};\n",
11614                    Style));
11615 
11616   Style.MaxEmptyLinesToKeep = 10u;
11617   EXPECT_EQ("struct foo {\n"
11618             "private:\n"
11619             "\n\n\n"
11620             "  void f() {}\n"
11621             "\n"
11622             "private:\n"
11623             "\n\n\n"
11624             "  int i;\n"
11625             "\n"
11626             "protected:\n"
11627             "\n\n\n"
11628             "  int j;\n"
11629             "};\n",
11630             format("struct foo {\n"
11631                    "private:\n"
11632                    "\n\n\n"
11633                    "  void f() {}\n"
11634                    "\n"
11635                    "private:\n"
11636                    "\n\n\n"
11637                    "  int i;\n"
11638                    "\n"
11639                    "protected:\n"
11640                    "\n\n\n"
11641                    "  int j;\n"
11642                    "};\n",
11643                    Style));
11644 
11645   // Test with comments.
11646   Style = getLLVMStyle();
11647   verifyFormat("struct foo {\n"
11648                "private:\n"
11649                "  // comment\n"
11650                "  void f() {}\n"
11651                "\n"
11652                "private: /* comment */\n"
11653                "  int i;\n"
11654                "};\n",
11655                Style);
11656   verifyFormat("struct foo {\n"
11657                "private:\n"
11658                "  // comment\n"
11659                "  void f() {}\n"
11660                "\n"
11661                "private: /* comment */\n"
11662                "  int i;\n"
11663                "};\n",
11664                "struct foo {\n"
11665                "private:\n"
11666                "\n"
11667                "  // comment\n"
11668                "  void f() {}\n"
11669                "\n"
11670                "private: /* comment */\n"
11671                "\n"
11672                "  int i;\n"
11673                "};\n",
11674                Style);
11675 
11676   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11677   verifyFormat("struct foo {\n"
11678                "private:\n"
11679                "\n"
11680                "  // comment\n"
11681                "  void f() {}\n"
11682                "\n"
11683                "private: /* comment */\n"
11684                "\n"
11685                "  int i;\n"
11686                "};\n",
11687                "struct foo {\n"
11688                "private:\n"
11689                "  // comment\n"
11690                "  void f() {}\n"
11691                "\n"
11692                "private: /* comment */\n"
11693                "  int i;\n"
11694                "};\n",
11695                Style);
11696   verifyFormat("struct foo {\n"
11697                "private:\n"
11698                "\n"
11699                "  // comment\n"
11700                "  void f() {}\n"
11701                "\n"
11702                "private: /* comment */\n"
11703                "\n"
11704                "  int i;\n"
11705                "};\n",
11706                Style);
11707 
11708   // Test with preprocessor defines.
11709   Style = getLLVMStyle();
11710   verifyFormat("struct foo {\n"
11711                "private:\n"
11712                "#ifdef FOO\n"
11713                "#endif\n"
11714                "  void f() {}\n"
11715                "};\n",
11716                Style);
11717   verifyFormat("struct foo {\n"
11718                "private:\n"
11719                "#ifdef FOO\n"
11720                "#endif\n"
11721                "  void f() {}\n"
11722                "};\n",
11723                "struct foo {\n"
11724                "private:\n"
11725                "\n"
11726                "#ifdef FOO\n"
11727                "#endif\n"
11728                "  void f() {}\n"
11729                "};\n",
11730                Style);
11731 
11732   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11733   verifyFormat("struct foo {\n"
11734                "private:\n"
11735                "\n"
11736                "#ifdef FOO\n"
11737                "#endif\n"
11738                "  void f() {}\n"
11739                "};\n",
11740                "struct foo {\n"
11741                "private:\n"
11742                "#ifdef FOO\n"
11743                "#endif\n"
11744                "  void f() {}\n"
11745                "};\n",
11746                Style);
11747   verifyFormat("struct foo {\n"
11748                "private:\n"
11749                "\n"
11750                "#ifdef FOO\n"
11751                "#endif\n"
11752                "  void f() {}\n"
11753                "};\n",
11754                Style);
11755 }
11756 
11757 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11758   // Combined tests of EmptyLineAfterAccessModifier and
11759   // EmptyLineBeforeAccessModifier.
11760   FormatStyle Style = getLLVMStyle();
11761   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11762   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11763   verifyFormat("struct foo {\n"
11764                "private:\n"
11765                "\n"
11766                "protected:\n"
11767                "};\n",
11768                Style);
11769 
11770   Style.MaxEmptyLinesToKeep = 10u;
11771   // Both remove all new lines.
11772   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11773   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11774   verifyFormat("struct foo {\n"
11775                "private:\n"
11776                "protected:\n"
11777                "};\n",
11778                "struct foo {\n"
11779                "private:\n"
11780                "\n\n\n"
11781                "protected:\n"
11782                "};\n",
11783                Style);
11784 
11785   // Leave tests rely on the code layout, test::messUp can not be used.
11786   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11787   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11788   Style.MaxEmptyLinesToKeep = 10u;
11789   EXPECT_EQ("struct foo {\n"
11790             "private:\n"
11791             "\n\n\n"
11792             "protected:\n"
11793             "};\n",
11794             format("struct foo {\n"
11795                    "private:\n"
11796                    "\n\n\n"
11797                    "protected:\n"
11798                    "};\n",
11799                    Style));
11800   Style.MaxEmptyLinesToKeep = 3u;
11801   EXPECT_EQ("struct foo {\n"
11802             "private:\n"
11803             "\n\n\n"
11804             "protected:\n"
11805             "};\n",
11806             format("struct foo {\n"
11807                    "private:\n"
11808                    "\n\n\n"
11809                    "protected:\n"
11810                    "};\n",
11811                    Style));
11812   Style.MaxEmptyLinesToKeep = 1u;
11813   EXPECT_EQ("struct foo {\n"
11814             "private:\n"
11815             "\n\n\n"
11816             "protected:\n"
11817             "};\n",
11818             format("struct foo {\n"
11819                    "private:\n"
11820                    "\n\n\n"
11821                    "protected:\n"
11822                    "};\n",
11823                    Style)); // Based on new lines in original document and not
11824                             // on the setting.
11825 
11826   Style.MaxEmptyLinesToKeep = 10u;
11827   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11828   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11829   // Newlines are kept if they are greater than zero,
11830   // test::messUp removes all new lines which changes the logic
11831   EXPECT_EQ("struct foo {\n"
11832             "private:\n"
11833             "\n\n\n"
11834             "protected:\n"
11835             "};\n",
11836             format("struct foo {\n"
11837                    "private:\n"
11838                    "\n\n\n"
11839                    "protected:\n"
11840                    "};\n",
11841                    Style));
11842 
11843   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11844   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11845   // test::messUp removes all new lines which changes the logic
11846   EXPECT_EQ("struct foo {\n"
11847             "private:\n"
11848             "\n\n\n"
11849             "protected:\n"
11850             "};\n",
11851             format("struct foo {\n"
11852                    "private:\n"
11853                    "\n\n\n"
11854                    "protected:\n"
11855                    "};\n",
11856                    Style));
11857 
11858   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11859   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11860   EXPECT_EQ("struct foo {\n"
11861             "private:\n"
11862             "\n\n\n"
11863             "protected:\n"
11864             "};\n",
11865             format("struct foo {\n"
11866                    "private:\n"
11867                    "\n\n\n"
11868                    "protected:\n"
11869                    "};\n",
11870                    Style)); // test::messUp removes all new lines which changes
11871                             // the logic.
11872 
11873   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11874   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11875   verifyFormat("struct foo {\n"
11876                "private:\n"
11877                "protected:\n"
11878                "};\n",
11879                "struct foo {\n"
11880                "private:\n"
11881                "\n\n\n"
11882                "protected:\n"
11883                "};\n",
11884                Style);
11885 
11886   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11887   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11888   EXPECT_EQ("struct foo {\n"
11889             "private:\n"
11890             "\n\n\n"
11891             "protected:\n"
11892             "};\n",
11893             format("struct foo {\n"
11894                    "private:\n"
11895                    "\n\n\n"
11896                    "protected:\n"
11897                    "};\n",
11898                    Style)); // test::messUp removes all new lines which changes
11899                             // the logic.
11900 
11901   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11902   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11903   verifyFormat("struct foo {\n"
11904                "private:\n"
11905                "protected:\n"
11906                "};\n",
11907                "struct foo {\n"
11908                "private:\n"
11909                "\n\n\n"
11910                "protected:\n"
11911                "};\n",
11912                Style);
11913 
11914   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11915   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11916   verifyFormat("struct foo {\n"
11917                "private:\n"
11918                "protected:\n"
11919                "};\n",
11920                "struct foo {\n"
11921                "private:\n"
11922                "\n\n\n"
11923                "protected:\n"
11924                "};\n",
11925                Style);
11926 
11927   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11928   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11929   verifyFormat("struct foo {\n"
11930                "private:\n"
11931                "protected:\n"
11932                "};\n",
11933                "struct foo {\n"
11934                "private:\n"
11935                "\n\n\n"
11936                "protected:\n"
11937                "};\n",
11938                Style);
11939 
11940   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11941   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11942   verifyFormat("struct foo {\n"
11943                "private:\n"
11944                "protected:\n"
11945                "};\n",
11946                "struct foo {\n"
11947                "private:\n"
11948                "\n\n\n"
11949                "protected:\n"
11950                "};\n",
11951                Style);
11952 }
11953 
11954 TEST_F(FormatTest, FormatsArrays) {
11955   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11956                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11957   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11958                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11959   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11960                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11961   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11962                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11963   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11964                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11965   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11966                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11967                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11968   verifyFormat(
11969       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11970       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11971       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11972   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11973                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11974 
11975   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11976                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11977   verifyFormat(
11978       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11979       "                                  .aaaaaaa[0]\n"
11980       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11981   verifyFormat("a[::b::c];");
11982 
11983   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11984 
11985   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11986   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11987 }
11988 
11989 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11990   verifyFormat("(a)->b();");
11991   verifyFormat("--a;");
11992 }
11993 
11994 TEST_F(FormatTest, HandlesIncludeDirectives) {
11995   verifyFormat("#include <string>\n"
11996                "#include <a/b/c.h>\n"
11997                "#include \"a/b/string\"\n"
11998                "#include \"string.h\"\n"
11999                "#include \"string.h\"\n"
12000                "#include <a-a>\n"
12001                "#include < path with space >\n"
12002                "#include_next <test.h>"
12003                "#include \"abc.h\" // this is included for ABC\n"
12004                "#include \"some long include\" // with a comment\n"
12005                "#include \"some very long include path\"\n"
12006                "#include <some/very/long/include/path>\n",
12007                getLLVMStyleWithColumns(35));
12008   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
12009   EXPECT_EQ("#include <a>", format("#include<a>"));
12010 
12011   verifyFormat("#import <string>");
12012   verifyFormat("#import <a/b/c.h>");
12013   verifyFormat("#import \"a/b/string\"");
12014   verifyFormat("#import \"string.h\"");
12015   verifyFormat("#import \"string.h\"");
12016   verifyFormat("#if __has_include(<strstream>)\n"
12017                "#include <strstream>\n"
12018                "#endif");
12019 
12020   verifyFormat("#define MY_IMPORT <a/b>");
12021 
12022   verifyFormat("#if __has_include(<a/b>)");
12023   verifyFormat("#if __has_include_next(<a/b>)");
12024   verifyFormat("#define F __has_include(<a/b>)");
12025   verifyFormat("#define F __has_include_next(<a/b>)");
12026 
12027   // Protocol buffer definition or missing "#".
12028   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
12029                getLLVMStyleWithColumns(30));
12030 
12031   FormatStyle Style = getLLVMStyle();
12032   Style.AlwaysBreakBeforeMultilineStrings = true;
12033   Style.ColumnLimit = 0;
12034   verifyFormat("#import \"abc.h\"", Style);
12035 
12036   // But 'import' might also be a regular C++ namespace.
12037   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12038                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
12039 }
12040 
12041 //===----------------------------------------------------------------------===//
12042 // Error recovery tests.
12043 //===----------------------------------------------------------------------===//
12044 
12045 TEST_F(FormatTest, IncompleteParameterLists) {
12046   FormatStyle NoBinPacking = getLLVMStyle();
12047   NoBinPacking.BinPackParameters = false;
12048   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
12049                "                        double *min_x,\n"
12050                "                        double *max_x,\n"
12051                "                        double *min_y,\n"
12052                "                        double *max_y,\n"
12053                "                        double *min_z,\n"
12054                "                        double *max_z, ) {}",
12055                NoBinPacking);
12056 }
12057 
12058 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
12059   verifyFormat("void f() { return; }\n42");
12060   verifyFormat("void f() {\n"
12061                "  if (0)\n"
12062                "    return;\n"
12063                "}\n"
12064                "42");
12065   verifyFormat("void f() { return }\n42");
12066   verifyFormat("void f() {\n"
12067                "  if (0)\n"
12068                "    return\n"
12069                "}\n"
12070                "42");
12071 }
12072 
12073 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
12074   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
12075   EXPECT_EQ("void f() {\n"
12076             "  if (a)\n"
12077             "    return\n"
12078             "}",
12079             format("void  f  (  )  {  if  ( a )  return  }"));
12080   EXPECT_EQ("namespace N {\n"
12081             "void f()\n"
12082             "}",
12083             format("namespace  N  {  void f()  }"));
12084   EXPECT_EQ("namespace N {\n"
12085             "void f() {}\n"
12086             "void g()\n"
12087             "} // namespace N",
12088             format("namespace N  { void f( ) { } void g( ) }"));
12089 }
12090 
12091 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
12092   verifyFormat("int aaaaaaaa =\n"
12093                "    // Overlylongcomment\n"
12094                "    b;",
12095                getLLVMStyleWithColumns(20));
12096   verifyFormat("function(\n"
12097                "    ShortArgument,\n"
12098                "    LoooooooooooongArgument);\n",
12099                getLLVMStyleWithColumns(20));
12100 }
12101 
12102 TEST_F(FormatTest, IncorrectAccessSpecifier) {
12103   verifyFormat("public:");
12104   verifyFormat("class A {\n"
12105                "public\n"
12106                "  void f() {}\n"
12107                "};");
12108   verifyFormat("public\n"
12109                "int qwerty;");
12110   verifyFormat("public\n"
12111                "B {}");
12112   verifyFormat("public\n"
12113                "{}");
12114   verifyFormat("public\n"
12115                "B { int x; }");
12116 }
12117 
12118 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
12119   verifyFormat("{");
12120   verifyFormat("#})");
12121   verifyNoCrash("(/**/[:!] ?[).");
12122 }
12123 
12124 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
12125   // Found by oss-fuzz:
12126   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
12127   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
12128   Style.ColumnLimit = 60;
12129   verifyNoCrash(
12130       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
12131       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
12132       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
12133       Style);
12134 }
12135 
12136 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
12137   verifyFormat("do {\n}");
12138   verifyFormat("do {\n}\n"
12139                "f();");
12140   verifyFormat("do {\n}\n"
12141                "wheeee(fun);");
12142   verifyFormat("do {\n"
12143                "  f();\n"
12144                "}");
12145 }
12146 
12147 TEST_F(FormatTest, IncorrectCodeMissingParens) {
12148   verifyFormat("if {\n  foo;\n  foo();\n}");
12149   verifyFormat("switch {\n  foo;\n  foo();\n}");
12150   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
12151   verifyIncompleteFormat("ERROR: for target;");
12152   verifyFormat("while {\n  foo;\n  foo();\n}");
12153   verifyFormat("do {\n  foo;\n  foo();\n} while;");
12154 }
12155 
12156 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
12157   verifyIncompleteFormat("namespace {\n"
12158                          "class Foo { Foo (\n"
12159                          "};\n"
12160                          "} // namespace");
12161 }
12162 
12163 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
12164   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
12165   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
12166   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
12167   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
12168 
12169   EXPECT_EQ("{\n"
12170             "  {\n"
12171             "    breakme(\n"
12172             "        qwe);\n"
12173             "  }\n",
12174             format("{\n"
12175                    "    {\n"
12176                    " breakme(qwe);\n"
12177                    "}\n",
12178                    getLLVMStyleWithColumns(10)));
12179 }
12180 
12181 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
12182   verifyFormat("int x = {\n"
12183                "    avariable,\n"
12184                "    b(alongervariable)};",
12185                getLLVMStyleWithColumns(25));
12186 }
12187 
12188 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
12189   verifyFormat("return (a)(b){1, 2, 3};");
12190 }
12191 
12192 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
12193   verifyFormat("vector<int> x{1, 2, 3, 4};");
12194   verifyFormat("vector<int> x{\n"
12195                "    1,\n"
12196                "    2,\n"
12197                "    3,\n"
12198                "    4,\n"
12199                "};");
12200   verifyFormat("vector<T> x{{}, {}, {}, {}};");
12201   verifyFormat("f({1, 2});");
12202   verifyFormat("auto v = Foo{-1};");
12203   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
12204   verifyFormat("Class::Class : member{1, 2, 3} {}");
12205   verifyFormat("new vector<int>{1, 2, 3};");
12206   verifyFormat("new int[3]{1, 2, 3};");
12207   verifyFormat("new int{1};");
12208   verifyFormat("return {arg1, arg2};");
12209   verifyFormat("return {arg1, SomeType{parameter}};");
12210   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
12211   verifyFormat("new T{arg1, arg2};");
12212   verifyFormat("f(MyMap[{composite, key}]);");
12213   verifyFormat("class Class {\n"
12214                "  T member = {arg1, arg2};\n"
12215                "};");
12216   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
12217   verifyFormat("const struct A a = {.a = 1, .b = 2};");
12218   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
12219   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
12220   verifyFormat("int a = std::is_integral<int>{} + 0;");
12221 
12222   verifyFormat("int foo(int i) { return fo1{}(i); }");
12223   verifyFormat("int foo(int i) { return fo1{}(i); }");
12224   verifyFormat("auto i = decltype(x){};");
12225   verifyFormat("auto i = typeof(x){};");
12226   verifyFormat("auto i = _Atomic(x){};");
12227   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
12228   verifyFormat("Node n{1, Node{1000}, //\n"
12229                "       2};");
12230   verifyFormat("Aaaa aaaaaaa{\n"
12231                "    {\n"
12232                "        aaaa,\n"
12233                "    },\n"
12234                "};");
12235   verifyFormat("class C : public D {\n"
12236                "  SomeClass SC{2};\n"
12237                "};");
12238   verifyFormat("class C : public A {\n"
12239                "  class D : public B {\n"
12240                "    void f() { int i{2}; }\n"
12241                "  };\n"
12242                "};");
12243   verifyFormat("#define A {a, a},");
12244   // Don't confuse braced list initializers with compound statements.
12245   verifyFormat(
12246       "class A {\n"
12247       "  A() : a{} {}\n"
12248       "  A(int b) : b(b) {}\n"
12249       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
12250       "  int a, b;\n"
12251       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
12252       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
12253       "{}\n"
12254       "};");
12255 
12256   // Avoid breaking between equal sign and opening brace
12257   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
12258   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
12259   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
12260                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
12261                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
12262                "     {\"ccccccccccccccccccccc\", 2}};",
12263                AvoidBreakingFirstArgument);
12264 
12265   // Binpacking only if there is no trailing comma
12266   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
12267                "                      cccccccccc, dddddddddd};",
12268                getLLVMStyleWithColumns(50));
12269   verifyFormat("const Aaaaaa aaaaa = {\n"
12270                "    aaaaaaaaaaa,\n"
12271                "    bbbbbbbbbbb,\n"
12272                "    ccccccccccc,\n"
12273                "    ddddddddddd,\n"
12274                "};",
12275                getLLVMStyleWithColumns(50));
12276 
12277   // Cases where distinguising braced lists and blocks is hard.
12278   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
12279   verifyFormat("void f() {\n"
12280                "  return; // comment\n"
12281                "}\n"
12282                "SomeType t;");
12283   verifyFormat("void f() {\n"
12284                "  if (a) {\n"
12285                "    f();\n"
12286                "  }\n"
12287                "}\n"
12288                "SomeType t;");
12289 
12290   // In combination with BinPackArguments = false.
12291   FormatStyle NoBinPacking = getLLVMStyle();
12292   NoBinPacking.BinPackArguments = false;
12293   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
12294                "                      bbbbb,\n"
12295                "                      ccccc,\n"
12296                "                      ddddd,\n"
12297                "                      eeeee,\n"
12298                "                      ffffff,\n"
12299                "                      ggggg,\n"
12300                "                      hhhhhh,\n"
12301                "                      iiiiii,\n"
12302                "                      jjjjjj,\n"
12303                "                      kkkkkk};",
12304                NoBinPacking);
12305   verifyFormat("const Aaaaaa aaaaa = {\n"
12306                "    aaaaa,\n"
12307                "    bbbbb,\n"
12308                "    ccccc,\n"
12309                "    ddddd,\n"
12310                "    eeeee,\n"
12311                "    ffffff,\n"
12312                "    ggggg,\n"
12313                "    hhhhhh,\n"
12314                "    iiiiii,\n"
12315                "    jjjjjj,\n"
12316                "    kkkkkk,\n"
12317                "};",
12318                NoBinPacking);
12319   verifyFormat(
12320       "const Aaaaaa aaaaa = {\n"
12321       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
12322       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
12323       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
12324       "};",
12325       NoBinPacking);
12326 
12327   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12328   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
12329             "    CDDDP83848_BMCR_REGISTER,\n"
12330             "    CDDDP83848_BMSR_REGISTER,\n"
12331             "    CDDDP83848_RBR_REGISTER};",
12332             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
12333                    "                                CDDDP83848_BMSR_REGISTER,\n"
12334                    "                                CDDDP83848_RBR_REGISTER};",
12335                    NoBinPacking));
12336 
12337   // FIXME: The alignment of these trailing comments might be bad. Then again,
12338   // this might be utterly useless in real code.
12339   verifyFormat("Constructor::Constructor()\n"
12340                "    : some_value{         //\n"
12341                "                 aaaaaaa, //\n"
12342                "                 bbbbbbb} {}");
12343 
12344   // In braced lists, the first comment is always assumed to belong to the
12345   // first element. Thus, it can be moved to the next or previous line as
12346   // appropriate.
12347   EXPECT_EQ("function({// First element:\n"
12348             "          1,\n"
12349             "          // Second element:\n"
12350             "          2});",
12351             format("function({\n"
12352                    "    // First element:\n"
12353                    "    1,\n"
12354                    "    // Second element:\n"
12355                    "    2});"));
12356   EXPECT_EQ("std::vector<int> MyNumbers{\n"
12357             "    // First element:\n"
12358             "    1,\n"
12359             "    // Second element:\n"
12360             "    2};",
12361             format("std::vector<int> MyNumbers{// First element:\n"
12362                    "                           1,\n"
12363                    "                           // Second element:\n"
12364                    "                           2};",
12365                    getLLVMStyleWithColumns(30)));
12366   // A trailing comma should still lead to an enforced line break and no
12367   // binpacking.
12368   EXPECT_EQ("vector<int> SomeVector = {\n"
12369             "    // aaa\n"
12370             "    1,\n"
12371             "    2,\n"
12372             "};",
12373             format("vector<int> SomeVector = { // aaa\n"
12374                    "    1, 2, };"));
12375 
12376   // C++11 brace initializer list l-braces should not be treated any differently
12377   // when breaking before lambda bodies is enabled
12378   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
12379   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
12380   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
12381   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
12382   verifyFormat(
12383       "std::runtime_error{\n"
12384       "    \"Long string which will force a break onto the next line...\"};",
12385       BreakBeforeLambdaBody);
12386 
12387   FormatStyle ExtraSpaces = getLLVMStyle();
12388   ExtraSpaces.Cpp11BracedListStyle = false;
12389   ExtraSpaces.ColumnLimit = 75;
12390   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
12391   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
12392   verifyFormat("f({ 1, 2 });", ExtraSpaces);
12393   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
12394   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
12395   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
12396   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
12397   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
12398   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
12399   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
12400   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
12401   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
12402   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
12403   verifyFormat("class Class {\n"
12404                "  T member = { arg1, arg2 };\n"
12405                "};",
12406                ExtraSpaces);
12407   verifyFormat(
12408       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12409       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
12410       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
12411       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
12412       ExtraSpaces);
12413   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
12414   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
12415                ExtraSpaces);
12416   verifyFormat(
12417       "someFunction(OtherParam,\n"
12418       "             BracedList{ // comment 1 (Forcing interesting break)\n"
12419       "                         param1, param2,\n"
12420       "                         // comment 2\n"
12421       "                         param3, param4 });",
12422       ExtraSpaces);
12423   verifyFormat(
12424       "std::this_thread::sleep_for(\n"
12425       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
12426       ExtraSpaces);
12427   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
12428                "    aaaaaaa,\n"
12429                "    aaaaaaaaaa,\n"
12430                "    aaaaa,\n"
12431                "    aaaaaaaaaaaaaaa,\n"
12432                "    aaa,\n"
12433                "    aaaaaaaaaa,\n"
12434                "    a,\n"
12435                "    aaaaaaaaaaaaaaaaaaaaa,\n"
12436                "    aaaaaaaaaaaa,\n"
12437                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
12438                "    aaaaaaa,\n"
12439                "    a};");
12440   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
12441   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
12442   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
12443 
12444   // Avoid breaking between initializer/equal sign and opening brace
12445   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
12446   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
12447                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12448                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12449                "  { \"ccccccccccccccccccccc\", 2 }\n"
12450                "};",
12451                ExtraSpaces);
12452   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
12453                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12454                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12455                "  { \"ccccccccccccccccccccc\", 2 }\n"
12456                "};",
12457                ExtraSpaces);
12458 
12459   FormatStyle SpaceBeforeBrace = getLLVMStyle();
12460   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
12461   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
12462   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
12463 
12464   FormatStyle SpaceBetweenBraces = getLLVMStyle();
12465   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
12466   SpaceBetweenBraces.SpacesInParentheses = true;
12467   SpaceBetweenBraces.SpacesInSquareBrackets = true;
12468   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
12469   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
12470   verifyFormat("vector< int > x{ // comment 1\n"
12471                "                 1, 2, 3, 4 };",
12472                SpaceBetweenBraces);
12473   SpaceBetweenBraces.ColumnLimit = 20;
12474   EXPECT_EQ("vector< int > x{\n"
12475             "    1, 2, 3, 4 };",
12476             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12477   SpaceBetweenBraces.ColumnLimit = 24;
12478   EXPECT_EQ("vector< int > x{ 1, 2,\n"
12479             "                 3, 4 };",
12480             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12481   EXPECT_EQ("vector< int > x{\n"
12482             "    1,\n"
12483             "    2,\n"
12484             "    3,\n"
12485             "    4,\n"
12486             "};",
12487             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12488   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12489   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12490   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12491 }
12492 
12493 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12494   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12495                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12496                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12497                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12498                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12499                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12500   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12501                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12502                "                 1, 22, 333, 4444, 55555, //\n"
12503                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12504                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12505   verifyFormat(
12506       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12507       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12508       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12509       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12510       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12511       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12512       "                 7777777};");
12513   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12514                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12515                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12516   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12517                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12518                "    // Separating comment.\n"
12519                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12520   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12521                "    // Leading comment\n"
12522                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12523                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12524   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12525                "                 1, 1, 1, 1};",
12526                getLLVMStyleWithColumns(39));
12527   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12528                "                 1, 1, 1, 1};",
12529                getLLVMStyleWithColumns(38));
12530   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12531                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12532                getLLVMStyleWithColumns(43));
12533   verifyFormat(
12534       "static unsigned SomeValues[10][3] = {\n"
12535       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12536       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12537   verifyFormat("static auto fields = new vector<string>{\n"
12538                "    \"aaaaaaaaaaaaa\",\n"
12539                "    \"aaaaaaaaaaaaa\",\n"
12540                "    \"aaaaaaaaaaaa\",\n"
12541                "    \"aaaaaaaaaaaaaa\",\n"
12542                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12543                "    \"aaaaaaaaaaaa\",\n"
12544                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12545                "};");
12546   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12547   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12548                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12549                "                 3, cccccccccccccccccccccc};",
12550                getLLVMStyleWithColumns(60));
12551 
12552   // Trailing commas.
12553   verifyFormat("vector<int> x = {\n"
12554                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12555                "};",
12556                getLLVMStyleWithColumns(39));
12557   verifyFormat("vector<int> x = {\n"
12558                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12559                "};",
12560                getLLVMStyleWithColumns(39));
12561   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12562                "                 1, 1, 1, 1,\n"
12563                "                 /**/ /**/};",
12564                getLLVMStyleWithColumns(39));
12565 
12566   // Trailing comment in the first line.
12567   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12568                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12569                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12570                "    11111111,   22222222,   333333333,   44444444};");
12571   // Trailing comment in the last line.
12572   verifyFormat("int aaaaa[] = {\n"
12573                "    1, 2, 3, // comment\n"
12574                "    4, 5, 6  // comment\n"
12575                "};");
12576 
12577   // With nested lists, we should either format one item per line or all nested
12578   // lists one on line.
12579   // FIXME: For some nested lists, we can do better.
12580   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12581                "        {aaaaaaaaaaaaaaaaaaa},\n"
12582                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12583                "        {aaaaaaaaaaaaaaaaa}};",
12584                getLLVMStyleWithColumns(60));
12585   verifyFormat(
12586       "SomeStruct my_struct_array = {\n"
12587       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12588       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12589       "    {aaa, aaa},\n"
12590       "    {aaa, aaa},\n"
12591       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12592       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12593       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12594 
12595   // No column layout should be used here.
12596   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12597                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12598 
12599   verifyNoCrash("a<,");
12600 
12601   // No braced initializer here.
12602   verifyFormat("void f() {\n"
12603                "  struct Dummy {};\n"
12604                "  f(v);\n"
12605                "}");
12606 
12607   // Long lists should be formatted in columns even if they are nested.
12608   verifyFormat(
12609       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12610       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12611       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12612       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12613       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12614       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12615 
12616   // Allow "single-column" layout even if that violates the column limit. There
12617   // isn't going to be a better way.
12618   verifyFormat("std::vector<int> a = {\n"
12619                "    aaaaaaaa,\n"
12620                "    aaaaaaaa,\n"
12621                "    aaaaaaaa,\n"
12622                "    aaaaaaaa,\n"
12623                "    aaaaaaaaaa,\n"
12624                "    aaaaaaaa,\n"
12625                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12626                getLLVMStyleWithColumns(30));
12627   verifyFormat("vector<int> aaaa = {\n"
12628                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12629                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12630                "    aaaaaa.aaaaaaa,\n"
12631                "    aaaaaa.aaaaaaa,\n"
12632                "    aaaaaa.aaaaaaa,\n"
12633                "    aaaaaa.aaaaaaa,\n"
12634                "};");
12635 
12636   // Don't create hanging lists.
12637   verifyFormat("someFunction(Param, {List1, List2,\n"
12638                "                     List3});",
12639                getLLVMStyleWithColumns(35));
12640   verifyFormat("someFunction(Param, Param,\n"
12641                "             {List1, List2,\n"
12642                "              List3});",
12643                getLLVMStyleWithColumns(35));
12644   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12645                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12646 }
12647 
12648 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12649   FormatStyle DoNotMerge = getLLVMStyle();
12650   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12651 
12652   verifyFormat("void f() { return 42; }");
12653   verifyFormat("void f() {\n"
12654                "  return 42;\n"
12655                "}",
12656                DoNotMerge);
12657   verifyFormat("void f() {\n"
12658                "  // Comment\n"
12659                "}");
12660   verifyFormat("{\n"
12661                "#error {\n"
12662                "  int a;\n"
12663                "}");
12664   verifyFormat("{\n"
12665                "  int a;\n"
12666                "#error {\n"
12667                "}");
12668   verifyFormat("void f() {} // comment");
12669   verifyFormat("void f() { int a; } // comment");
12670   verifyFormat("void f() {\n"
12671                "} // comment",
12672                DoNotMerge);
12673   verifyFormat("void f() {\n"
12674                "  int a;\n"
12675                "} // comment",
12676                DoNotMerge);
12677   verifyFormat("void f() {\n"
12678                "} // comment",
12679                getLLVMStyleWithColumns(15));
12680 
12681   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12682   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12683 
12684   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12685   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12686   verifyFormat("class C {\n"
12687                "  C()\n"
12688                "      : iiiiiiii(nullptr),\n"
12689                "        kkkkkkk(nullptr),\n"
12690                "        mmmmmmm(nullptr),\n"
12691                "        nnnnnnn(nullptr) {}\n"
12692                "};",
12693                getGoogleStyle());
12694 
12695   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12696   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12697   EXPECT_EQ("class C {\n"
12698             "  A() : b(0) {}\n"
12699             "};",
12700             format("class C{A():b(0){}};", NoColumnLimit));
12701   EXPECT_EQ("A()\n"
12702             "    : b(0) {\n"
12703             "}",
12704             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12705 
12706   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12707   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12708       FormatStyle::SFS_None;
12709   EXPECT_EQ("A()\n"
12710             "    : b(0) {\n"
12711             "}",
12712             format("A():b(0){}", DoNotMergeNoColumnLimit));
12713   EXPECT_EQ("A()\n"
12714             "    : b(0) {\n"
12715             "}",
12716             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12717 
12718   verifyFormat("#define A          \\\n"
12719                "  void f() {       \\\n"
12720                "    int i;         \\\n"
12721                "  }",
12722                getLLVMStyleWithColumns(20));
12723   verifyFormat("#define A           \\\n"
12724                "  void f() { int i; }",
12725                getLLVMStyleWithColumns(21));
12726   verifyFormat("#define A            \\\n"
12727                "  void f() {         \\\n"
12728                "    int i;           \\\n"
12729                "  }                  \\\n"
12730                "  int j;",
12731                getLLVMStyleWithColumns(22));
12732   verifyFormat("#define A             \\\n"
12733                "  void f() { int i; } \\\n"
12734                "  int j;",
12735                getLLVMStyleWithColumns(23));
12736 }
12737 
12738 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12739   FormatStyle MergeEmptyOnly = getLLVMStyle();
12740   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12741   verifyFormat("class C {\n"
12742                "  int f() {}\n"
12743                "};",
12744                MergeEmptyOnly);
12745   verifyFormat("class C {\n"
12746                "  int f() {\n"
12747                "    return 42;\n"
12748                "  }\n"
12749                "};",
12750                MergeEmptyOnly);
12751   verifyFormat("int f() {}", MergeEmptyOnly);
12752   verifyFormat("int f() {\n"
12753                "  return 42;\n"
12754                "}",
12755                MergeEmptyOnly);
12756 
12757   // Also verify behavior when BraceWrapping.AfterFunction = true
12758   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12759   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12760   verifyFormat("int f() {}", MergeEmptyOnly);
12761   verifyFormat("class C {\n"
12762                "  int f() {}\n"
12763                "};",
12764                MergeEmptyOnly);
12765 }
12766 
12767 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12768   FormatStyle MergeInlineOnly = getLLVMStyle();
12769   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12770   verifyFormat("class C {\n"
12771                "  int f() { return 42; }\n"
12772                "};",
12773                MergeInlineOnly);
12774   verifyFormat("int f() {\n"
12775                "  return 42;\n"
12776                "}",
12777                MergeInlineOnly);
12778 
12779   // SFS_Inline implies SFS_Empty
12780   verifyFormat("class C {\n"
12781                "  int f() {}\n"
12782                "};",
12783                MergeInlineOnly);
12784   verifyFormat("int f() {}", MergeInlineOnly);
12785   // https://llvm.org/PR54147
12786   verifyFormat("auto lambda = []() {\n"
12787                "  // comment\n"
12788                "  f();\n"
12789                "  g();\n"
12790                "};",
12791                MergeInlineOnly);
12792 
12793   verifyFormat("class C {\n"
12794                "#ifdef A\n"
12795                "  int f() { return 42; }\n"
12796                "#endif\n"
12797                "};",
12798                MergeInlineOnly);
12799 
12800   verifyFormat("struct S {\n"
12801                "// comment\n"
12802                "#ifdef FOO\n"
12803                "  int foo() { bar(); }\n"
12804                "#endif\n"
12805                "};",
12806                MergeInlineOnly);
12807 
12808   // Also verify behavior when BraceWrapping.AfterFunction = true
12809   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12810   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12811   verifyFormat("class C {\n"
12812                "  int f() { return 42; }\n"
12813                "};",
12814                MergeInlineOnly);
12815   verifyFormat("int f()\n"
12816                "{\n"
12817                "  return 42;\n"
12818                "}",
12819                MergeInlineOnly);
12820 
12821   // SFS_Inline implies SFS_Empty
12822   verifyFormat("int f() {}", MergeInlineOnly);
12823   verifyFormat("class C {\n"
12824                "  int f() {}\n"
12825                "};",
12826                MergeInlineOnly);
12827 
12828   MergeInlineOnly.BraceWrapping.AfterClass = true;
12829   MergeInlineOnly.BraceWrapping.AfterStruct = true;
12830   verifyFormat("class C\n"
12831                "{\n"
12832                "  int f() { return 42; }\n"
12833                "};",
12834                MergeInlineOnly);
12835   verifyFormat("struct C\n"
12836                "{\n"
12837                "  int f() { return 42; }\n"
12838                "};",
12839                MergeInlineOnly);
12840   verifyFormat("int f()\n"
12841                "{\n"
12842                "  return 42;\n"
12843                "}",
12844                MergeInlineOnly);
12845   verifyFormat("int f() {}", MergeInlineOnly);
12846   verifyFormat("class C\n"
12847                "{\n"
12848                "  int f() { return 42; }\n"
12849                "};",
12850                MergeInlineOnly);
12851   verifyFormat("struct C\n"
12852                "{\n"
12853                "  int f() { return 42; }\n"
12854                "};",
12855                MergeInlineOnly);
12856   verifyFormat("struct C\n"
12857                "// comment\n"
12858                "/* comment */\n"
12859                "// comment\n"
12860                "{\n"
12861                "  int f() { return 42; }\n"
12862                "};",
12863                MergeInlineOnly);
12864   verifyFormat("/* comment */ struct C\n"
12865                "{\n"
12866                "  int f() { return 42; }\n"
12867                "};",
12868                MergeInlineOnly);
12869 }
12870 
12871 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12872   FormatStyle MergeInlineOnly = getLLVMStyle();
12873   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12874       FormatStyle::SFS_InlineOnly;
12875   verifyFormat("class C {\n"
12876                "  int f() { return 42; }\n"
12877                "};",
12878                MergeInlineOnly);
12879   verifyFormat("int f() {\n"
12880                "  return 42;\n"
12881                "}",
12882                MergeInlineOnly);
12883 
12884   // SFS_InlineOnly does not imply SFS_Empty
12885   verifyFormat("class C {\n"
12886                "  int f() {}\n"
12887                "};",
12888                MergeInlineOnly);
12889   verifyFormat("int f() {\n"
12890                "}",
12891                MergeInlineOnly);
12892 
12893   // Also verify behavior when BraceWrapping.AfterFunction = true
12894   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12895   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12896   verifyFormat("class C {\n"
12897                "  int f() { return 42; }\n"
12898                "};",
12899                MergeInlineOnly);
12900   verifyFormat("int f()\n"
12901                "{\n"
12902                "  return 42;\n"
12903                "}",
12904                MergeInlineOnly);
12905 
12906   // SFS_InlineOnly does not imply SFS_Empty
12907   verifyFormat("int f()\n"
12908                "{\n"
12909                "}",
12910                MergeInlineOnly);
12911   verifyFormat("class C {\n"
12912                "  int f() {}\n"
12913                "};",
12914                MergeInlineOnly);
12915 }
12916 
12917 TEST_F(FormatTest, SplitEmptyFunction) {
12918   FormatStyle Style = getLLVMStyleWithColumns(40);
12919   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12920   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12921   Style.BraceWrapping.AfterFunction = true;
12922   Style.BraceWrapping.SplitEmptyFunction = false;
12923 
12924   verifyFormat("int f()\n"
12925                "{}",
12926                Style);
12927   verifyFormat("int f()\n"
12928                "{\n"
12929                "  return 42;\n"
12930                "}",
12931                Style);
12932   verifyFormat("int f()\n"
12933                "{\n"
12934                "  // some comment\n"
12935                "}",
12936                Style);
12937 
12938   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12939   verifyFormat("int f() {}", Style);
12940   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12941                "{}",
12942                Style);
12943   verifyFormat("int f()\n"
12944                "{\n"
12945                "  return 0;\n"
12946                "}",
12947                Style);
12948 
12949   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12950   verifyFormat("class Foo {\n"
12951                "  int f() {}\n"
12952                "};\n",
12953                Style);
12954   verifyFormat("class Foo {\n"
12955                "  int f() { return 0; }\n"
12956                "};\n",
12957                Style);
12958   verifyFormat("class Foo {\n"
12959                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12960                "  {}\n"
12961                "};\n",
12962                Style);
12963   verifyFormat("class Foo {\n"
12964                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12965                "  {\n"
12966                "    return 0;\n"
12967                "  }\n"
12968                "};\n",
12969                Style);
12970 
12971   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12972   verifyFormat("int f() {}", Style);
12973   verifyFormat("int f() { return 0; }", Style);
12974   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12975                "{}",
12976                Style);
12977   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12978                "{\n"
12979                "  return 0;\n"
12980                "}",
12981                Style);
12982 }
12983 
12984 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12985   FormatStyle Style = getLLVMStyleWithColumns(40);
12986   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12987   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12988   Style.BraceWrapping.AfterFunction = true;
12989   Style.BraceWrapping.SplitEmptyFunction = true;
12990   Style.BraceWrapping.SplitEmptyRecord = false;
12991 
12992   verifyFormat("class C {};", Style);
12993   verifyFormat("struct C {};", Style);
12994   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12995                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12996                "{\n"
12997                "}",
12998                Style);
12999   verifyFormat("class C {\n"
13000                "  C()\n"
13001                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
13002                "        bbbbbbbbbbbbbbbbbbb()\n"
13003                "  {\n"
13004                "  }\n"
13005                "  void\n"
13006                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
13007                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
13008                "  {\n"
13009                "  }\n"
13010                "};",
13011                Style);
13012 }
13013 
13014 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
13015   FormatStyle Style = getLLVMStyle();
13016   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
13017   verifyFormat("#ifdef A\n"
13018                "int f() {}\n"
13019                "#else\n"
13020                "int g() {}\n"
13021                "#endif",
13022                Style);
13023 }
13024 
13025 TEST_F(FormatTest, SplitEmptyClass) {
13026   FormatStyle Style = getLLVMStyle();
13027   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13028   Style.BraceWrapping.AfterClass = true;
13029   Style.BraceWrapping.SplitEmptyRecord = false;
13030 
13031   verifyFormat("class Foo\n"
13032                "{};",
13033                Style);
13034   verifyFormat("/* something */ class Foo\n"
13035                "{};",
13036                Style);
13037   verifyFormat("template <typename X> class Foo\n"
13038                "{};",
13039                Style);
13040   verifyFormat("class Foo\n"
13041                "{\n"
13042                "  Foo();\n"
13043                "};",
13044                Style);
13045   verifyFormat("typedef class Foo\n"
13046                "{\n"
13047                "} Foo_t;",
13048                Style);
13049 
13050   Style.BraceWrapping.SplitEmptyRecord = true;
13051   Style.BraceWrapping.AfterStruct = true;
13052   verifyFormat("class rep\n"
13053                "{\n"
13054                "};",
13055                Style);
13056   verifyFormat("struct rep\n"
13057                "{\n"
13058                "};",
13059                Style);
13060   verifyFormat("template <typename T> class rep\n"
13061                "{\n"
13062                "};",
13063                Style);
13064   verifyFormat("template <typename T> struct rep\n"
13065                "{\n"
13066                "};",
13067                Style);
13068   verifyFormat("class rep\n"
13069                "{\n"
13070                "  int x;\n"
13071                "};",
13072                Style);
13073   verifyFormat("struct rep\n"
13074                "{\n"
13075                "  int x;\n"
13076                "};",
13077                Style);
13078   verifyFormat("template <typename T> class rep\n"
13079                "{\n"
13080                "  int x;\n"
13081                "};",
13082                Style);
13083   verifyFormat("template <typename T> struct rep\n"
13084                "{\n"
13085                "  int x;\n"
13086                "};",
13087                Style);
13088   verifyFormat("template <typename T> class rep // Foo\n"
13089                "{\n"
13090                "  int x;\n"
13091                "};",
13092                Style);
13093   verifyFormat("template <typename T> struct rep // Bar\n"
13094                "{\n"
13095                "  int x;\n"
13096                "};",
13097                Style);
13098 
13099   verifyFormat("template <typename T> class rep<T>\n"
13100                "{\n"
13101                "  int x;\n"
13102                "};",
13103                Style);
13104 
13105   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13106                "{\n"
13107                "  int x;\n"
13108                "};",
13109                Style);
13110   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13111                "{\n"
13112                "};",
13113                Style);
13114 
13115   verifyFormat("#include \"stdint.h\"\n"
13116                "namespace rep {}",
13117                Style);
13118   verifyFormat("#include <stdint.h>\n"
13119                "namespace rep {}",
13120                Style);
13121   verifyFormat("#include <stdint.h>\n"
13122                "namespace rep {}",
13123                "#include <stdint.h>\n"
13124                "namespace rep {\n"
13125                "\n"
13126                "\n"
13127                "}",
13128                Style);
13129 }
13130 
13131 TEST_F(FormatTest, SplitEmptyStruct) {
13132   FormatStyle Style = getLLVMStyle();
13133   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13134   Style.BraceWrapping.AfterStruct = true;
13135   Style.BraceWrapping.SplitEmptyRecord = false;
13136 
13137   verifyFormat("struct Foo\n"
13138                "{};",
13139                Style);
13140   verifyFormat("/* something */ struct Foo\n"
13141                "{};",
13142                Style);
13143   verifyFormat("template <typename X> struct Foo\n"
13144                "{};",
13145                Style);
13146   verifyFormat("struct Foo\n"
13147                "{\n"
13148                "  Foo();\n"
13149                "};",
13150                Style);
13151   verifyFormat("typedef struct Foo\n"
13152                "{\n"
13153                "} Foo_t;",
13154                Style);
13155   // typedef struct Bar {} Bar_t;
13156 }
13157 
13158 TEST_F(FormatTest, SplitEmptyUnion) {
13159   FormatStyle Style = getLLVMStyle();
13160   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13161   Style.BraceWrapping.AfterUnion = true;
13162   Style.BraceWrapping.SplitEmptyRecord = false;
13163 
13164   verifyFormat("union Foo\n"
13165                "{};",
13166                Style);
13167   verifyFormat("/* something */ union Foo\n"
13168                "{};",
13169                Style);
13170   verifyFormat("union Foo\n"
13171                "{\n"
13172                "  A,\n"
13173                "};",
13174                Style);
13175   verifyFormat("typedef union Foo\n"
13176                "{\n"
13177                "} Foo_t;",
13178                Style);
13179 }
13180 
13181 TEST_F(FormatTest, SplitEmptyNamespace) {
13182   FormatStyle Style = getLLVMStyle();
13183   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13184   Style.BraceWrapping.AfterNamespace = true;
13185   Style.BraceWrapping.SplitEmptyNamespace = false;
13186 
13187   verifyFormat("namespace Foo\n"
13188                "{};",
13189                Style);
13190   verifyFormat("/* something */ namespace Foo\n"
13191                "{};",
13192                Style);
13193   verifyFormat("inline namespace Foo\n"
13194                "{};",
13195                Style);
13196   verifyFormat("/* something */ inline namespace Foo\n"
13197                "{};",
13198                Style);
13199   verifyFormat("export namespace Foo\n"
13200                "{};",
13201                Style);
13202   verifyFormat("namespace Foo\n"
13203                "{\n"
13204                "void Bar();\n"
13205                "};",
13206                Style);
13207 }
13208 
13209 TEST_F(FormatTest, NeverMergeShortRecords) {
13210   FormatStyle Style = getLLVMStyle();
13211 
13212   verifyFormat("class Foo {\n"
13213                "  Foo();\n"
13214                "};",
13215                Style);
13216   verifyFormat("typedef class Foo {\n"
13217                "  Foo();\n"
13218                "} Foo_t;",
13219                Style);
13220   verifyFormat("struct Foo {\n"
13221                "  Foo();\n"
13222                "};",
13223                Style);
13224   verifyFormat("typedef struct Foo {\n"
13225                "  Foo();\n"
13226                "} Foo_t;",
13227                Style);
13228   verifyFormat("union Foo {\n"
13229                "  A,\n"
13230                "};",
13231                Style);
13232   verifyFormat("typedef union Foo {\n"
13233                "  A,\n"
13234                "} Foo_t;",
13235                Style);
13236   verifyFormat("namespace Foo {\n"
13237                "void Bar();\n"
13238                "};",
13239                Style);
13240 
13241   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13242   Style.BraceWrapping.AfterClass = true;
13243   Style.BraceWrapping.AfterStruct = true;
13244   Style.BraceWrapping.AfterUnion = true;
13245   Style.BraceWrapping.AfterNamespace = true;
13246   verifyFormat("class Foo\n"
13247                "{\n"
13248                "  Foo();\n"
13249                "};",
13250                Style);
13251   verifyFormat("typedef class Foo\n"
13252                "{\n"
13253                "  Foo();\n"
13254                "} Foo_t;",
13255                Style);
13256   verifyFormat("struct Foo\n"
13257                "{\n"
13258                "  Foo();\n"
13259                "};",
13260                Style);
13261   verifyFormat("typedef struct Foo\n"
13262                "{\n"
13263                "  Foo();\n"
13264                "} Foo_t;",
13265                Style);
13266   verifyFormat("union Foo\n"
13267                "{\n"
13268                "  A,\n"
13269                "};",
13270                Style);
13271   verifyFormat("typedef union Foo\n"
13272                "{\n"
13273                "  A,\n"
13274                "} Foo_t;",
13275                Style);
13276   verifyFormat("namespace Foo\n"
13277                "{\n"
13278                "void Bar();\n"
13279                "};",
13280                Style);
13281 }
13282 
13283 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
13284   // Elaborate type variable declarations.
13285   verifyFormat("struct foo a = {bar};\nint n;");
13286   verifyFormat("class foo a = {bar};\nint n;");
13287   verifyFormat("union foo a = {bar};\nint n;");
13288 
13289   // Elaborate types inside function definitions.
13290   verifyFormat("struct foo f() {}\nint n;");
13291   verifyFormat("class foo f() {}\nint n;");
13292   verifyFormat("union foo f() {}\nint n;");
13293 
13294   // Templates.
13295   verifyFormat("template <class X> void f() {}\nint n;");
13296   verifyFormat("template <struct X> void f() {}\nint n;");
13297   verifyFormat("template <union X> void f() {}\nint n;");
13298 
13299   // Actual definitions...
13300   verifyFormat("struct {\n} n;");
13301   verifyFormat(
13302       "template <template <class T, class Y>, class Z> class X {\n} n;");
13303   verifyFormat("union Z {\n  int n;\n} x;");
13304   verifyFormat("class MACRO Z {\n} n;");
13305   verifyFormat("class MACRO(X) Z {\n} n;");
13306   verifyFormat("class __attribute__(X) Z {\n} n;");
13307   verifyFormat("class __declspec(X) Z {\n} n;");
13308   verifyFormat("class A##B##C {\n} n;");
13309   verifyFormat("class alignas(16) Z {\n} n;");
13310   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
13311   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
13312 
13313   // Redefinition from nested context:
13314   verifyFormat("class A::B::C {\n} n;");
13315 
13316   // Template definitions.
13317   verifyFormat(
13318       "template <typename F>\n"
13319       "Matcher(const Matcher<F> &Other,\n"
13320       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
13321       "                             !is_same<F, T>::value>::type * = 0)\n"
13322       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
13323 
13324   // FIXME: This is still incorrectly handled at the formatter side.
13325   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
13326   verifyFormat("int i = SomeFunction(a<b, a> b);");
13327 
13328   // FIXME:
13329   // This now gets parsed incorrectly as class definition.
13330   // verifyFormat("class A<int> f() {\n}\nint n;");
13331 
13332   // Elaborate types where incorrectly parsing the structural element would
13333   // break the indent.
13334   verifyFormat("if (true)\n"
13335                "  class X x;\n"
13336                "else\n"
13337                "  f();\n");
13338 
13339   // This is simply incomplete. Formatting is not important, but must not crash.
13340   verifyFormat("class A:");
13341 }
13342 
13343 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
13344   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
13345             format("#error Leave     all         white!!!!! space* alone!\n"));
13346   EXPECT_EQ(
13347       "#warning Leave     all         white!!!!! space* alone!\n",
13348       format("#warning Leave     all         white!!!!! space* alone!\n"));
13349   EXPECT_EQ("#error 1", format("  #  error   1"));
13350   EXPECT_EQ("#warning 1", format("  #  warning 1"));
13351 }
13352 
13353 TEST_F(FormatTest, FormatHashIfExpressions) {
13354   verifyFormat("#if AAAA && BBBB");
13355   verifyFormat("#if (AAAA && BBBB)");
13356   verifyFormat("#elif (AAAA && BBBB)");
13357   // FIXME: Come up with a better indentation for #elif.
13358   verifyFormat(
13359       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
13360       "    defined(BBBBBBBB)\n"
13361       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
13362       "    defined(BBBBBBBB)\n"
13363       "#endif",
13364       getLLVMStyleWithColumns(65));
13365 }
13366 
13367 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
13368   FormatStyle AllowsMergedIf = getGoogleStyle();
13369   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
13370       FormatStyle::SIS_WithoutElse;
13371   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
13372   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
13373   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
13374   EXPECT_EQ("if (true) return 42;",
13375             format("if (true)\nreturn 42;", AllowsMergedIf));
13376   FormatStyle ShortMergedIf = AllowsMergedIf;
13377   ShortMergedIf.ColumnLimit = 25;
13378   verifyFormat("#define A \\\n"
13379                "  if (true) return 42;",
13380                ShortMergedIf);
13381   verifyFormat("#define A \\\n"
13382                "  f();    \\\n"
13383                "  if (true)\n"
13384                "#define B",
13385                ShortMergedIf);
13386   verifyFormat("#define A \\\n"
13387                "  f();    \\\n"
13388                "  if (true)\n"
13389                "g();",
13390                ShortMergedIf);
13391   verifyFormat("{\n"
13392                "#ifdef A\n"
13393                "  // Comment\n"
13394                "  if (true) continue;\n"
13395                "#endif\n"
13396                "  // Comment\n"
13397                "  if (true) continue;\n"
13398                "}",
13399                ShortMergedIf);
13400   ShortMergedIf.ColumnLimit = 33;
13401   verifyFormat("#define A \\\n"
13402                "  if constexpr (true) return 42;",
13403                ShortMergedIf);
13404   verifyFormat("#define A \\\n"
13405                "  if CONSTEXPR (true) return 42;",
13406                ShortMergedIf);
13407   ShortMergedIf.ColumnLimit = 29;
13408   verifyFormat("#define A                   \\\n"
13409                "  if (aaaaaaaaaa) return 1; \\\n"
13410                "  return 2;",
13411                ShortMergedIf);
13412   ShortMergedIf.ColumnLimit = 28;
13413   verifyFormat("#define A         \\\n"
13414                "  if (aaaaaaaaaa) \\\n"
13415                "    return 1;     \\\n"
13416                "  return 2;",
13417                ShortMergedIf);
13418   verifyFormat("#define A                \\\n"
13419                "  if constexpr (aaaaaaa) \\\n"
13420                "    return 1;            \\\n"
13421                "  return 2;",
13422                ShortMergedIf);
13423   verifyFormat("#define A                \\\n"
13424                "  if CONSTEXPR (aaaaaaa) \\\n"
13425                "    return 1;            \\\n"
13426                "  return 2;",
13427                ShortMergedIf);
13428 
13429   verifyFormat("//\n"
13430                "#define a \\\n"
13431                "  if      \\\n"
13432                "  0",
13433                getChromiumStyle(FormatStyle::LK_Cpp));
13434 }
13435 
13436 TEST_F(FormatTest, FormatStarDependingOnContext) {
13437   verifyFormat("void f(int *a);");
13438   verifyFormat("void f() { f(fint * b); }");
13439   verifyFormat("class A {\n  void f(int *a);\n};");
13440   verifyFormat("class A {\n  int *a;\n};");
13441   verifyFormat("namespace a {\n"
13442                "namespace b {\n"
13443                "class A {\n"
13444                "  void f() {}\n"
13445                "  int *a;\n"
13446                "};\n"
13447                "} // namespace b\n"
13448                "} // namespace a");
13449 }
13450 
13451 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13452   verifyFormat("while");
13453   verifyFormat("operator");
13454 }
13455 
13456 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13457   // This code would be painfully slow to format if we didn't skip it.
13458   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
13459                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13460                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13461                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13462                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13463                    "A(1, 1)\n"
13464                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
13465                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13466                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13467                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13468                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13469                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13470                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13471                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13472                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13473                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
13474   // Deeply nested part is untouched, rest is formatted.
13475   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13476             format(std::string("int    i;\n") + Code + "int    j;\n",
13477                    getLLVMStyle(), SC_ExpectIncomplete));
13478 }
13479 
13480 //===----------------------------------------------------------------------===//
13481 // Objective-C tests.
13482 //===----------------------------------------------------------------------===//
13483 
13484 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13485   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13486   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13487             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13488   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13489   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13490   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13491             format("-(NSInteger)Method3:(id)anObject;"));
13492   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13493             format("-(NSInteger)Method4:(id)anObject;"));
13494   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13495             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13496   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13497             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13498   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13499             "forAllCells:(BOOL)flag;",
13500             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13501                    "forAllCells:(BOOL)flag;"));
13502 
13503   // Very long objectiveC method declaration.
13504   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13505                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13506   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13507                "                    inRange:(NSRange)range\n"
13508                "                   outRange:(NSRange)out_range\n"
13509                "                  outRange1:(NSRange)out_range1\n"
13510                "                  outRange2:(NSRange)out_range2\n"
13511                "                  outRange3:(NSRange)out_range3\n"
13512                "                  outRange4:(NSRange)out_range4\n"
13513                "                  outRange5:(NSRange)out_range5\n"
13514                "                  outRange6:(NSRange)out_range6\n"
13515                "                  outRange7:(NSRange)out_range7\n"
13516                "                  outRange8:(NSRange)out_range8\n"
13517                "                  outRange9:(NSRange)out_range9;");
13518 
13519   // When the function name has to be wrapped.
13520   FormatStyle Style = getLLVMStyle();
13521   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13522   // and always indents instead.
13523   Style.IndentWrappedFunctionNames = false;
13524   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13525                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13526                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13527                "}",
13528                Style);
13529   Style.IndentWrappedFunctionNames = true;
13530   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13531                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13532                "               anotherName:(NSString)dddddddddddddd {\n"
13533                "}",
13534                Style);
13535 
13536   verifyFormat("- (int)sum:(vector<int>)numbers;");
13537   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13538   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13539   // protocol lists (but not for template classes):
13540   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13541 
13542   verifyFormat("- (int (*)())foo:(int (*)())f;");
13543   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13544 
13545   // If there's no return type (very rare in practice!), LLVM and Google style
13546   // agree.
13547   verifyFormat("- foo;");
13548   verifyFormat("- foo:(int)f;");
13549   verifyGoogleFormat("- foo:(int)foo;");
13550 }
13551 
13552 TEST_F(FormatTest, BreaksStringLiterals) {
13553   EXPECT_EQ("\"some text \"\n"
13554             "\"other\";",
13555             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13556   EXPECT_EQ("\"some text \"\n"
13557             "\"other\";",
13558             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13559   EXPECT_EQ(
13560       "#define A  \\\n"
13561       "  \"some \"  \\\n"
13562       "  \"text \"  \\\n"
13563       "  \"other\";",
13564       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13565   EXPECT_EQ(
13566       "#define A  \\\n"
13567       "  \"so \"    \\\n"
13568       "  \"text \"  \\\n"
13569       "  \"other\";",
13570       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13571 
13572   EXPECT_EQ("\"some text\"",
13573             format("\"some text\"", getLLVMStyleWithColumns(1)));
13574   EXPECT_EQ("\"some text\"",
13575             format("\"some text\"", getLLVMStyleWithColumns(11)));
13576   EXPECT_EQ("\"some \"\n"
13577             "\"text\"",
13578             format("\"some text\"", getLLVMStyleWithColumns(10)));
13579   EXPECT_EQ("\"some \"\n"
13580             "\"text\"",
13581             format("\"some text\"", getLLVMStyleWithColumns(7)));
13582   EXPECT_EQ("\"some\"\n"
13583             "\" tex\"\n"
13584             "\"t\"",
13585             format("\"some text\"", getLLVMStyleWithColumns(6)));
13586   EXPECT_EQ("\"some\"\n"
13587             "\" tex\"\n"
13588             "\" and\"",
13589             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13590   EXPECT_EQ("\"some\"\n"
13591             "\"/tex\"\n"
13592             "\"/and\"",
13593             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13594 
13595   EXPECT_EQ("variable =\n"
13596             "    \"long string \"\n"
13597             "    \"literal\";",
13598             format("variable = \"long string literal\";",
13599                    getLLVMStyleWithColumns(20)));
13600 
13601   EXPECT_EQ("variable = f(\n"
13602             "    \"long string \"\n"
13603             "    \"literal\",\n"
13604             "    short,\n"
13605             "    loooooooooooooooooooong);",
13606             format("variable = f(\"long string literal\", short, "
13607                    "loooooooooooooooooooong);",
13608                    getLLVMStyleWithColumns(20)));
13609 
13610   EXPECT_EQ(
13611       "f(g(\"long string \"\n"
13612       "    \"literal\"),\n"
13613       "  b);",
13614       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13615   EXPECT_EQ("f(g(\"long string \"\n"
13616             "    \"literal\",\n"
13617             "    a),\n"
13618             "  b);",
13619             format("f(g(\"long string literal\", a), b);",
13620                    getLLVMStyleWithColumns(20)));
13621   EXPECT_EQ(
13622       "f(\"one two\".split(\n"
13623       "    variable));",
13624       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13625   EXPECT_EQ("f(\"one two three four five six \"\n"
13626             "  \"seven\".split(\n"
13627             "      really_looooong_variable));",
13628             format("f(\"one two three four five six seven\"."
13629                    "split(really_looooong_variable));",
13630                    getLLVMStyleWithColumns(33)));
13631 
13632   EXPECT_EQ("f(\"some \"\n"
13633             "  \"text\",\n"
13634             "  other);",
13635             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13636 
13637   // Only break as a last resort.
13638   verifyFormat(
13639       "aaaaaaaaaaaaaaaaaaaa(\n"
13640       "    aaaaaaaaaaaaaaaaaaaa,\n"
13641       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13642 
13643   EXPECT_EQ("\"splitmea\"\n"
13644             "\"trandomp\"\n"
13645             "\"oint\"",
13646             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13647 
13648   EXPECT_EQ("\"split/\"\n"
13649             "\"pathat/\"\n"
13650             "\"slashes\"",
13651             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13652 
13653   EXPECT_EQ("\"split/\"\n"
13654             "\"pathat/\"\n"
13655             "\"slashes\"",
13656             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13657   EXPECT_EQ("\"split at \"\n"
13658             "\"spaces/at/\"\n"
13659             "\"slashes.at.any$\"\n"
13660             "\"non-alphanumeric%\"\n"
13661             "\"1111111111characte\"\n"
13662             "\"rs\"",
13663             format("\"split at "
13664                    "spaces/at/"
13665                    "slashes.at."
13666                    "any$non-"
13667                    "alphanumeric%"
13668                    "1111111111characte"
13669                    "rs\"",
13670                    getLLVMStyleWithColumns(20)));
13671 
13672   // Verify that splitting the strings understands
13673   // Style::AlwaysBreakBeforeMultilineStrings.
13674   EXPECT_EQ("aaaaaaaaaaaa(\n"
13675             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13676             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13677             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13678                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13679                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13680                    getGoogleStyle()));
13681   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13682             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13683             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13684                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13685                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13686                    getGoogleStyle()));
13687   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13688             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13689             format("llvm::outs() << "
13690                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13691                    "aaaaaaaaaaaaaaaaaaa\";"));
13692   EXPECT_EQ("ffff(\n"
13693             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13694             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13695             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13696                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13697                    getGoogleStyle()));
13698 
13699   FormatStyle Style = getLLVMStyleWithColumns(12);
13700   Style.BreakStringLiterals = false;
13701   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13702 
13703   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13704   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13705   EXPECT_EQ("#define A \\\n"
13706             "  \"some \" \\\n"
13707             "  \"text \" \\\n"
13708             "  \"other\";",
13709             format("#define A \"some text other\";", AlignLeft));
13710 }
13711 
13712 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13713   EXPECT_EQ("C a = \"some more \"\n"
13714             "      \"text\";",
13715             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13716 }
13717 
13718 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13719   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13720   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13721   EXPECT_EQ("int i = a(b());",
13722             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13723 }
13724 
13725 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13726   EXPECT_EQ(
13727       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13728       "(\n"
13729       "    \"x\t\");",
13730       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13731              "aaaaaaa("
13732              "\"x\t\");"));
13733 }
13734 
13735 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13736   EXPECT_EQ(
13737       "u8\"utf8 string \"\n"
13738       "u8\"literal\";",
13739       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13740   EXPECT_EQ(
13741       "u\"utf16 string \"\n"
13742       "u\"literal\";",
13743       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13744   EXPECT_EQ(
13745       "U\"utf32 string \"\n"
13746       "U\"literal\";",
13747       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13748   EXPECT_EQ("L\"wide string \"\n"
13749             "L\"literal\";",
13750             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13751   EXPECT_EQ("@\"NSString \"\n"
13752             "@\"literal\";",
13753             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13754   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13755 
13756   // This input makes clang-format try to split the incomplete unicode escape
13757   // sequence, which used to lead to a crasher.
13758   verifyNoCrash(
13759       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13760       getLLVMStyleWithColumns(60));
13761 }
13762 
13763 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13764   FormatStyle Style = getGoogleStyleWithColumns(15);
13765   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13766   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13767   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13768   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13769   EXPECT_EQ("u8R\"x(raw literal)x\";",
13770             format("u8R\"x(raw literal)x\";", Style));
13771 }
13772 
13773 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13774   FormatStyle Style = getLLVMStyleWithColumns(20);
13775   EXPECT_EQ(
13776       "_T(\"aaaaaaaaaaaaaa\")\n"
13777       "_T(\"aaaaaaaaaaaaaa\")\n"
13778       "_T(\"aaaaaaaaaaaa\")",
13779       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13780   EXPECT_EQ("f(x,\n"
13781             "  _T(\"aaaaaaaaaaaa\")\n"
13782             "  _T(\"aaa\"),\n"
13783             "  z);",
13784             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13785 
13786   // FIXME: Handle embedded spaces in one iteration.
13787   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13788   //            "_T(\"aaaaaaaaaaaaa\")\n"
13789   //            "_T(\"aaaaaaaaaaaaa\")\n"
13790   //            "_T(\"a\")",
13791   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13792   //                   getLLVMStyleWithColumns(20)));
13793   EXPECT_EQ(
13794       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13795       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13796   EXPECT_EQ("f(\n"
13797             "#if !TEST\n"
13798             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13799             "#endif\n"
13800             ");",
13801             format("f(\n"
13802                    "#if !TEST\n"
13803                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13804                    "#endif\n"
13805                    ");"));
13806   EXPECT_EQ("f(\n"
13807             "\n"
13808             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13809             format("f(\n"
13810                    "\n"
13811                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13812   // Regression test for accessing tokens past the end of a vector in the
13813   // TokenLexer.
13814   verifyNoCrash(R"(_T(
13815 "
13816 )
13817 )");
13818 }
13819 
13820 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13821   // In a function call with two operands, the second can be broken with no line
13822   // break before it.
13823   EXPECT_EQ(
13824       "func(a, \"long long \"\n"
13825       "        \"long long\");",
13826       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13827   // In a function call with three operands, the second must be broken with a
13828   // line break before it.
13829   EXPECT_EQ("func(a,\n"
13830             "     \"long long long \"\n"
13831             "     \"long\",\n"
13832             "     c);",
13833             format("func(a, \"long long long long\", c);",
13834                    getLLVMStyleWithColumns(24)));
13835   // In a function call with three operands, the third must be broken with a
13836   // line break before it.
13837   EXPECT_EQ("func(a, b,\n"
13838             "     \"long long long \"\n"
13839             "     \"long\");",
13840             format("func(a, b, \"long long long long\");",
13841                    getLLVMStyleWithColumns(24)));
13842   // In a function call with three operands, both the second and the third must
13843   // be broken with a line break before them.
13844   EXPECT_EQ("func(a,\n"
13845             "     \"long long long \"\n"
13846             "     \"long\",\n"
13847             "     \"long long long \"\n"
13848             "     \"long\");",
13849             format("func(a, \"long long long long\", \"long long long long\");",
13850                    getLLVMStyleWithColumns(24)));
13851   // In a chain of << with two operands, the second can be broken with no line
13852   // break before it.
13853   EXPECT_EQ("a << \"line line \"\n"
13854             "     \"line\";",
13855             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13856   // In a chain of << with three operands, the second can be broken with no line
13857   // break before it.
13858   EXPECT_EQ(
13859       "abcde << \"line \"\n"
13860       "         \"line line\"\n"
13861       "      << c;",
13862       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13863   // In a chain of << with three operands, the third must be broken with a line
13864   // break before it.
13865   EXPECT_EQ(
13866       "a << b\n"
13867       "  << \"line line \"\n"
13868       "     \"line\";",
13869       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13870   // In a chain of << with three operands, the second can be broken with no line
13871   // break before it and the third must be broken with a line break before it.
13872   EXPECT_EQ("abcd << \"line line \"\n"
13873             "        \"line\"\n"
13874             "     << \"line line \"\n"
13875             "        \"line\";",
13876             format("abcd << \"line line line\" << \"line line line\";",
13877                    getLLVMStyleWithColumns(20)));
13878   // In a chain of binary operators with two operands, the second can be broken
13879   // with no line break before it.
13880   EXPECT_EQ(
13881       "abcd + \"line line \"\n"
13882       "       \"line line\";",
13883       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13884   // In a chain of binary operators with three operands, the second must be
13885   // broken with a line break before it.
13886   EXPECT_EQ("abcd +\n"
13887             "    \"line line \"\n"
13888             "    \"line line\" +\n"
13889             "    e;",
13890             format("abcd + \"line line line line\" + e;",
13891                    getLLVMStyleWithColumns(20)));
13892   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13893   // the first must be broken with a line break before it.
13894   FormatStyle Style = getLLVMStyleWithColumns(25);
13895   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13896   EXPECT_EQ("someFunction(\n"
13897             "    \"long long long \"\n"
13898             "    \"long\",\n"
13899             "    a);",
13900             format("someFunction(\"long long long long\", a);", Style));
13901 }
13902 
13903 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13904   EXPECT_EQ(
13905       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13906       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13907       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13908       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13909              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13910              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13911 }
13912 
13913 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13914   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13915             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13916   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13917             "multiline raw string literal xxxxxxxxxxxxxx\n"
13918             ")x\",\n"
13919             "              a),\n"
13920             "            b);",
13921             format("fffffffffff(g(R\"x(\n"
13922                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13923                    ")x\", a), b);",
13924                    getGoogleStyleWithColumns(20)));
13925   EXPECT_EQ("fffffffffff(\n"
13926             "    g(R\"x(qqq\n"
13927             "multiline raw string literal xxxxxxxxxxxxxx\n"
13928             ")x\",\n"
13929             "      a),\n"
13930             "    b);",
13931             format("fffffffffff(g(R\"x(qqq\n"
13932                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13933                    ")x\", a), b);",
13934                    getGoogleStyleWithColumns(20)));
13935 
13936   EXPECT_EQ("fffffffffff(R\"x(\n"
13937             "multiline raw string literal xxxxxxxxxxxxxx\n"
13938             ")x\");",
13939             format("fffffffffff(R\"x(\n"
13940                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13941                    ")x\");",
13942                    getGoogleStyleWithColumns(20)));
13943   EXPECT_EQ("fffffffffff(R\"x(\n"
13944             "multiline raw string literal xxxxxxxxxxxxxx\n"
13945             ")x\" + bbbbbb);",
13946             format("fffffffffff(R\"x(\n"
13947                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13948                    ")x\" +   bbbbbb);",
13949                    getGoogleStyleWithColumns(20)));
13950   EXPECT_EQ("fffffffffff(\n"
13951             "    R\"x(\n"
13952             "multiline raw string literal xxxxxxxxxxxxxx\n"
13953             ")x\" +\n"
13954             "    bbbbbb);",
13955             format("fffffffffff(\n"
13956                    " R\"x(\n"
13957                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13958                    ")x\" + bbbbbb);",
13959                    getGoogleStyleWithColumns(20)));
13960   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13961             format("fffffffffff(\n"
13962                    " R\"(single line raw string)\" + bbbbbb);"));
13963 }
13964 
13965 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13966   verifyFormat("string a = \"unterminated;");
13967   EXPECT_EQ("function(\"unterminated,\n"
13968             "         OtherParameter);",
13969             format("function(  \"unterminated,\n"
13970                    "    OtherParameter);"));
13971 }
13972 
13973 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13974   FormatStyle Style = getLLVMStyle();
13975   Style.Standard = FormatStyle::LS_Cpp03;
13976   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13977             format("#define x(_a) printf(\"foo\"_a);", Style));
13978 }
13979 
13980 TEST_F(FormatTest, CppLexVersion) {
13981   FormatStyle Style = getLLVMStyle();
13982   // Formatting of x * y differs if x is a type.
13983   verifyFormat("void foo() { MACRO(a * b); }", Style);
13984   verifyFormat("void foo() { MACRO(int *b); }", Style);
13985 
13986   // LLVM style uses latest lexer.
13987   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13988   Style.Standard = FormatStyle::LS_Cpp17;
13989   // But in c++17, char8_t isn't a keyword.
13990   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13991 }
13992 
13993 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13994 
13995 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13996   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13997             "             \"ddeeefff\");",
13998             format("someFunction(\"aaabbbcccdddeeefff\");",
13999                    getLLVMStyleWithColumns(25)));
14000   EXPECT_EQ("someFunction1234567890(\n"
14001             "    \"aaabbbcccdddeeefff\");",
14002             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14003                    getLLVMStyleWithColumns(26)));
14004   EXPECT_EQ("someFunction1234567890(\n"
14005             "    \"aaabbbcccdddeeeff\"\n"
14006             "    \"f\");",
14007             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14008                    getLLVMStyleWithColumns(25)));
14009   EXPECT_EQ("someFunction1234567890(\n"
14010             "    \"aaabbbcccdddeeeff\"\n"
14011             "    \"f\");",
14012             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14013                    getLLVMStyleWithColumns(24)));
14014   EXPECT_EQ("someFunction(\n"
14015             "    \"aaabbbcc ddde \"\n"
14016             "    \"efff\");",
14017             format("someFunction(\"aaabbbcc ddde efff\");",
14018                    getLLVMStyleWithColumns(25)));
14019   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
14020             "             \"ddeeefff\");",
14021             format("someFunction(\"aaabbbccc ddeeefff\");",
14022                    getLLVMStyleWithColumns(25)));
14023   EXPECT_EQ("someFunction1234567890(\n"
14024             "    \"aaabb \"\n"
14025             "    \"cccdddeeefff\");",
14026             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
14027                    getLLVMStyleWithColumns(25)));
14028   EXPECT_EQ("#define A          \\\n"
14029             "  string s =       \\\n"
14030             "      \"123456789\"  \\\n"
14031             "      \"0\";         \\\n"
14032             "  int i;",
14033             format("#define A string s = \"1234567890\"; int i;",
14034                    getLLVMStyleWithColumns(20)));
14035   EXPECT_EQ("someFunction(\n"
14036             "    \"aaabbbcc \"\n"
14037             "    \"dddeeefff\");",
14038             format("someFunction(\"aaabbbcc dddeeefff\");",
14039                    getLLVMStyleWithColumns(25)));
14040 }
14041 
14042 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
14043   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
14044   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
14045   EXPECT_EQ("\"test\"\n"
14046             "\"\\n\"",
14047             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
14048   EXPECT_EQ("\"tes\\\\\"\n"
14049             "\"n\"",
14050             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
14051   EXPECT_EQ("\"\\\\\\\\\"\n"
14052             "\"\\n\"",
14053             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
14054   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
14055   EXPECT_EQ("\"\\uff01\"\n"
14056             "\"test\"",
14057             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
14058   EXPECT_EQ("\"\\Uff01ff02\"",
14059             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
14060   EXPECT_EQ("\"\\x000000000001\"\n"
14061             "\"next\"",
14062             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
14063   EXPECT_EQ("\"\\x000000000001next\"",
14064             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
14065   EXPECT_EQ("\"\\x000000000001\"",
14066             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
14067   EXPECT_EQ("\"test\"\n"
14068             "\"\\000000\"\n"
14069             "\"000001\"",
14070             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
14071   EXPECT_EQ("\"test\\000\"\n"
14072             "\"00000000\"\n"
14073             "\"1\"",
14074             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
14075 }
14076 
14077 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
14078   verifyFormat("void f() {\n"
14079                "  return g() {}\n"
14080                "  void h() {}");
14081   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
14082                "g();\n"
14083                "}");
14084 }
14085 
14086 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
14087   verifyFormat(
14088       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
14089 }
14090 
14091 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
14092   verifyFormat("class X {\n"
14093                "  void f() {\n"
14094                "  }\n"
14095                "};",
14096                getLLVMStyleWithColumns(12));
14097 }
14098 
14099 TEST_F(FormatTest, ConfigurableIndentWidth) {
14100   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
14101   EightIndent.IndentWidth = 8;
14102   EightIndent.ContinuationIndentWidth = 8;
14103   verifyFormat("void f() {\n"
14104                "        someFunction();\n"
14105                "        if (true) {\n"
14106                "                f();\n"
14107                "        }\n"
14108                "}",
14109                EightIndent);
14110   verifyFormat("class X {\n"
14111                "        void f() {\n"
14112                "        }\n"
14113                "};",
14114                EightIndent);
14115   verifyFormat("int x[] = {\n"
14116                "        call(),\n"
14117                "        call()};",
14118                EightIndent);
14119 }
14120 
14121 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
14122   verifyFormat("double\n"
14123                "f();",
14124                getLLVMStyleWithColumns(8));
14125 }
14126 
14127 TEST_F(FormatTest, ConfigurableUseOfTab) {
14128   FormatStyle Tab = getLLVMStyleWithColumns(42);
14129   Tab.IndentWidth = 8;
14130   Tab.UseTab = FormatStyle::UT_Always;
14131   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14132 
14133   EXPECT_EQ("if (aaaaaaaa && // q\n"
14134             "    bb)\t\t// w\n"
14135             "\t;",
14136             format("if (aaaaaaaa &&// q\n"
14137                    "bb)// w\n"
14138                    ";",
14139                    Tab));
14140   EXPECT_EQ("if (aaa && bbb) // w\n"
14141             "\t;",
14142             format("if(aaa&&bbb)// w\n"
14143                    ";",
14144                    Tab));
14145 
14146   verifyFormat("class X {\n"
14147                "\tvoid f() {\n"
14148                "\t\tsomeFunction(parameter1,\n"
14149                "\t\t\t     parameter2);\n"
14150                "\t}\n"
14151                "};",
14152                Tab);
14153   verifyFormat("#define A                        \\\n"
14154                "\tvoid f() {               \\\n"
14155                "\t\tsomeFunction(    \\\n"
14156                "\t\t    parameter1,  \\\n"
14157                "\t\t    parameter2); \\\n"
14158                "\t}",
14159                Tab);
14160   verifyFormat("int a;\t      // x\n"
14161                "int bbbbbbbb; // x\n",
14162                Tab);
14163 
14164   FormatStyle TabAlignment = Tab;
14165   TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
14166   TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
14167   verifyFormat("unsigned long long big;\n"
14168                "char*\t\t   ptr;",
14169                TabAlignment);
14170   TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
14171   verifyFormat("unsigned long long big;\n"
14172                "char *\t\t   ptr;",
14173                TabAlignment);
14174   TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
14175   verifyFormat("unsigned long long big;\n"
14176                "char\t\t  *ptr;",
14177                TabAlignment);
14178 
14179   Tab.TabWidth = 4;
14180   Tab.IndentWidth = 8;
14181   verifyFormat("class TabWidth4Indent8 {\n"
14182                "\t\tvoid f() {\n"
14183                "\t\t\t\tsomeFunction(parameter1,\n"
14184                "\t\t\t\t\t\t\t parameter2);\n"
14185                "\t\t}\n"
14186                "};",
14187                Tab);
14188 
14189   Tab.TabWidth = 4;
14190   Tab.IndentWidth = 4;
14191   verifyFormat("class TabWidth4Indent4 {\n"
14192                "\tvoid f() {\n"
14193                "\t\tsomeFunction(parameter1,\n"
14194                "\t\t\t\t\t parameter2);\n"
14195                "\t}\n"
14196                "};",
14197                Tab);
14198 
14199   Tab.TabWidth = 8;
14200   Tab.IndentWidth = 4;
14201   verifyFormat("class TabWidth8Indent4 {\n"
14202                "    void f() {\n"
14203                "\tsomeFunction(parameter1,\n"
14204                "\t\t     parameter2);\n"
14205                "    }\n"
14206                "};",
14207                Tab);
14208 
14209   Tab.TabWidth = 8;
14210   Tab.IndentWidth = 8;
14211   EXPECT_EQ("/*\n"
14212             "\t      a\t\tcomment\n"
14213             "\t      in multiple lines\n"
14214             "       */",
14215             format("   /*\t \t \n"
14216                    " \t \t a\t\tcomment\t \t\n"
14217                    " \t \t in multiple lines\t\n"
14218                    " \t  */",
14219                    Tab));
14220 
14221   TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
14222   TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
14223   verifyFormat("void f() {\n"
14224                "\tunsigned long long big;\n"
14225                "\tchar*              ptr;\n"
14226                "}",
14227                TabAlignment);
14228   TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
14229   verifyFormat("void f() {\n"
14230                "\tunsigned long long big;\n"
14231                "\tchar *             ptr;\n"
14232                "}",
14233                TabAlignment);
14234   TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
14235   verifyFormat("void f() {\n"
14236                "\tunsigned long long big;\n"
14237                "\tchar              *ptr;\n"
14238                "}",
14239                TabAlignment);
14240 
14241   Tab.UseTab = FormatStyle::UT_ForIndentation;
14242   verifyFormat("{\n"
14243                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14244                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14245                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14246                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14247                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14248                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14249                "};",
14250                Tab);
14251   verifyFormat("enum AA {\n"
14252                "\ta1, // Force multiple lines\n"
14253                "\ta2,\n"
14254                "\ta3\n"
14255                "};",
14256                Tab);
14257   EXPECT_EQ("if (aaaaaaaa && // q\n"
14258             "    bb)         // w\n"
14259             "\t;",
14260             format("if (aaaaaaaa &&// q\n"
14261                    "bb)// w\n"
14262                    ";",
14263                    Tab));
14264   verifyFormat("class X {\n"
14265                "\tvoid f() {\n"
14266                "\t\tsomeFunction(parameter1,\n"
14267                "\t\t             parameter2);\n"
14268                "\t}\n"
14269                "};",
14270                Tab);
14271   verifyFormat("{\n"
14272                "\tQ(\n"
14273                "\t    {\n"
14274                "\t\t    int a;\n"
14275                "\t\t    someFunction(aaaaaaaa,\n"
14276                "\t\t                 bbbbbbb);\n"
14277                "\t    },\n"
14278                "\t    p);\n"
14279                "}",
14280                Tab);
14281   EXPECT_EQ("{\n"
14282             "\t/* aaaa\n"
14283             "\t   bbbb */\n"
14284             "}",
14285             format("{\n"
14286                    "/* aaaa\n"
14287                    "   bbbb */\n"
14288                    "}",
14289                    Tab));
14290   EXPECT_EQ("{\n"
14291             "\t/*\n"
14292             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14293             "\t  bbbbbbbbbbbbb\n"
14294             "\t*/\n"
14295             "}",
14296             format("{\n"
14297                    "/*\n"
14298                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14299                    "*/\n"
14300                    "}",
14301                    Tab));
14302   EXPECT_EQ("{\n"
14303             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14304             "\t// bbbbbbbbbbbbb\n"
14305             "}",
14306             format("{\n"
14307                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14308                    "}",
14309                    Tab));
14310   EXPECT_EQ("{\n"
14311             "\t/*\n"
14312             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14313             "\t  bbbbbbbbbbbbb\n"
14314             "\t*/\n"
14315             "}",
14316             format("{\n"
14317                    "\t/*\n"
14318                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14319                    "\t*/\n"
14320                    "}",
14321                    Tab));
14322   EXPECT_EQ("{\n"
14323             "\t/*\n"
14324             "\n"
14325             "\t*/\n"
14326             "}",
14327             format("{\n"
14328                    "\t/*\n"
14329                    "\n"
14330                    "\t*/\n"
14331                    "}",
14332                    Tab));
14333   EXPECT_EQ("{\n"
14334             "\t/*\n"
14335             " asdf\n"
14336             "\t*/\n"
14337             "}",
14338             format("{\n"
14339                    "\t/*\n"
14340                    " asdf\n"
14341                    "\t*/\n"
14342                    "}",
14343                    Tab));
14344 
14345   verifyFormat("void f() {\n"
14346                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14347                "\t            : bbbbbbbbbbbbbbbbbb\n"
14348                "}",
14349                Tab);
14350   FormatStyle TabNoBreak = Tab;
14351   TabNoBreak.BreakBeforeTernaryOperators = false;
14352   verifyFormat("void f() {\n"
14353                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14354                "\t              bbbbbbbbbbbbbbbbbb\n"
14355                "}",
14356                TabNoBreak);
14357   verifyFormat("void f() {\n"
14358                "\treturn true ?\n"
14359                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14360                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14361                "}",
14362                TabNoBreak);
14363 
14364   Tab.UseTab = FormatStyle::UT_Never;
14365   EXPECT_EQ("/*\n"
14366             "              a\t\tcomment\n"
14367             "              in multiple lines\n"
14368             "       */",
14369             format("   /*\t \t \n"
14370                    " \t \t a\t\tcomment\t \t\n"
14371                    " \t \t in multiple lines\t\n"
14372                    " \t  */",
14373                    Tab));
14374   EXPECT_EQ("/* some\n"
14375             "   comment */",
14376             format(" \t \t /* some\n"
14377                    " \t \t    comment */",
14378                    Tab));
14379   EXPECT_EQ("int a; /* some\n"
14380             "   comment */",
14381             format(" \t \t int a; /* some\n"
14382                    " \t \t    comment */",
14383                    Tab));
14384 
14385   EXPECT_EQ("int a; /* some\n"
14386             "comment */",
14387             format(" \t \t int\ta; /* some\n"
14388                    " \t \t    comment */",
14389                    Tab));
14390   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14391             "    comment */",
14392             format(" \t \t f(\"\t\t\"); /* some\n"
14393                    " \t \t    comment */",
14394                    Tab));
14395   EXPECT_EQ("{\n"
14396             "        /*\n"
14397             "         * Comment\n"
14398             "         */\n"
14399             "        int i;\n"
14400             "}",
14401             format("{\n"
14402                    "\t/*\n"
14403                    "\t * Comment\n"
14404                    "\t */\n"
14405                    "\t int i;\n"
14406                    "}",
14407                    Tab));
14408 
14409   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14410   Tab.TabWidth = 8;
14411   Tab.IndentWidth = 8;
14412   EXPECT_EQ("if (aaaaaaaa && // q\n"
14413             "    bb)         // w\n"
14414             "\t;",
14415             format("if (aaaaaaaa &&// q\n"
14416                    "bb)// w\n"
14417                    ";",
14418                    Tab));
14419   EXPECT_EQ("if (aaa && bbb) // w\n"
14420             "\t;",
14421             format("if(aaa&&bbb)// w\n"
14422                    ";",
14423                    Tab));
14424   verifyFormat("class X {\n"
14425                "\tvoid f() {\n"
14426                "\t\tsomeFunction(parameter1,\n"
14427                "\t\t\t     parameter2);\n"
14428                "\t}\n"
14429                "};",
14430                Tab);
14431   verifyFormat("#define A                        \\\n"
14432                "\tvoid f() {               \\\n"
14433                "\t\tsomeFunction(    \\\n"
14434                "\t\t    parameter1,  \\\n"
14435                "\t\t    parameter2); \\\n"
14436                "\t}",
14437                Tab);
14438   Tab.TabWidth = 4;
14439   Tab.IndentWidth = 8;
14440   verifyFormat("class TabWidth4Indent8 {\n"
14441                "\t\tvoid f() {\n"
14442                "\t\t\t\tsomeFunction(parameter1,\n"
14443                "\t\t\t\t\t\t\t parameter2);\n"
14444                "\t\t}\n"
14445                "};",
14446                Tab);
14447   Tab.TabWidth = 4;
14448   Tab.IndentWidth = 4;
14449   verifyFormat("class TabWidth4Indent4 {\n"
14450                "\tvoid f() {\n"
14451                "\t\tsomeFunction(parameter1,\n"
14452                "\t\t\t\t\t parameter2);\n"
14453                "\t}\n"
14454                "};",
14455                Tab);
14456   Tab.TabWidth = 8;
14457   Tab.IndentWidth = 4;
14458   verifyFormat("class TabWidth8Indent4 {\n"
14459                "    void f() {\n"
14460                "\tsomeFunction(parameter1,\n"
14461                "\t\t     parameter2);\n"
14462                "    }\n"
14463                "};",
14464                Tab);
14465   Tab.TabWidth = 8;
14466   Tab.IndentWidth = 8;
14467   EXPECT_EQ("/*\n"
14468             "\t      a\t\tcomment\n"
14469             "\t      in multiple lines\n"
14470             "       */",
14471             format("   /*\t \t \n"
14472                    " \t \t a\t\tcomment\t \t\n"
14473                    " \t \t in multiple lines\t\n"
14474                    " \t  */",
14475                    Tab));
14476   verifyFormat("{\n"
14477                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14478                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14479                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14480                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14481                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14482                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14483                "};",
14484                Tab);
14485   verifyFormat("enum AA {\n"
14486                "\ta1, // Force multiple lines\n"
14487                "\ta2,\n"
14488                "\ta3\n"
14489                "};",
14490                Tab);
14491   EXPECT_EQ("if (aaaaaaaa && // q\n"
14492             "    bb)         // w\n"
14493             "\t;",
14494             format("if (aaaaaaaa &&// q\n"
14495                    "bb)// w\n"
14496                    ";",
14497                    Tab));
14498   verifyFormat("class X {\n"
14499                "\tvoid f() {\n"
14500                "\t\tsomeFunction(parameter1,\n"
14501                "\t\t\t     parameter2);\n"
14502                "\t}\n"
14503                "};",
14504                Tab);
14505   verifyFormat("{\n"
14506                "\tQ(\n"
14507                "\t    {\n"
14508                "\t\t    int a;\n"
14509                "\t\t    someFunction(aaaaaaaa,\n"
14510                "\t\t\t\t bbbbbbb);\n"
14511                "\t    },\n"
14512                "\t    p);\n"
14513                "}",
14514                Tab);
14515   EXPECT_EQ("{\n"
14516             "\t/* aaaa\n"
14517             "\t   bbbb */\n"
14518             "}",
14519             format("{\n"
14520                    "/* aaaa\n"
14521                    "   bbbb */\n"
14522                    "}",
14523                    Tab));
14524   EXPECT_EQ("{\n"
14525             "\t/*\n"
14526             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14527             "\t  bbbbbbbbbbbbb\n"
14528             "\t*/\n"
14529             "}",
14530             format("{\n"
14531                    "/*\n"
14532                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14533                    "*/\n"
14534                    "}",
14535                    Tab));
14536   EXPECT_EQ("{\n"
14537             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14538             "\t// bbbbbbbbbbbbb\n"
14539             "}",
14540             format("{\n"
14541                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14542                    "}",
14543                    Tab));
14544   EXPECT_EQ("{\n"
14545             "\t/*\n"
14546             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14547             "\t  bbbbbbbbbbbbb\n"
14548             "\t*/\n"
14549             "}",
14550             format("{\n"
14551                    "\t/*\n"
14552                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14553                    "\t*/\n"
14554                    "}",
14555                    Tab));
14556   EXPECT_EQ("{\n"
14557             "\t/*\n"
14558             "\n"
14559             "\t*/\n"
14560             "}",
14561             format("{\n"
14562                    "\t/*\n"
14563                    "\n"
14564                    "\t*/\n"
14565                    "}",
14566                    Tab));
14567   EXPECT_EQ("{\n"
14568             "\t/*\n"
14569             " asdf\n"
14570             "\t*/\n"
14571             "}",
14572             format("{\n"
14573                    "\t/*\n"
14574                    " asdf\n"
14575                    "\t*/\n"
14576                    "}",
14577                    Tab));
14578   EXPECT_EQ("/* some\n"
14579             "   comment */",
14580             format(" \t \t /* some\n"
14581                    " \t \t    comment */",
14582                    Tab));
14583   EXPECT_EQ("int a; /* some\n"
14584             "   comment */",
14585             format(" \t \t int a; /* some\n"
14586                    " \t \t    comment */",
14587                    Tab));
14588   EXPECT_EQ("int a; /* some\n"
14589             "comment */",
14590             format(" \t \t int\ta; /* some\n"
14591                    " \t \t    comment */",
14592                    Tab));
14593   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14594             "    comment */",
14595             format(" \t \t f(\"\t\t\"); /* some\n"
14596                    " \t \t    comment */",
14597                    Tab));
14598   EXPECT_EQ("{\n"
14599             "\t/*\n"
14600             "\t * Comment\n"
14601             "\t */\n"
14602             "\tint i;\n"
14603             "}",
14604             format("{\n"
14605                    "\t/*\n"
14606                    "\t * Comment\n"
14607                    "\t */\n"
14608                    "\t int i;\n"
14609                    "}",
14610                    Tab));
14611   Tab.TabWidth = 2;
14612   Tab.IndentWidth = 2;
14613   EXPECT_EQ("{\n"
14614             "\t/* aaaa\n"
14615             "\t\t bbbb */\n"
14616             "}",
14617             format("{\n"
14618                    "/* aaaa\n"
14619                    "\t bbbb */\n"
14620                    "}",
14621                    Tab));
14622   EXPECT_EQ("{\n"
14623             "\t/*\n"
14624             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14625             "\t\tbbbbbbbbbbbbb\n"
14626             "\t*/\n"
14627             "}",
14628             format("{\n"
14629                    "/*\n"
14630                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14631                    "*/\n"
14632                    "}",
14633                    Tab));
14634   Tab.AlignConsecutiveAssignments.Enabled = true;
14635   Tab.AlignConsecutiveDeclarations.Enabled = true;
14636   Tab.TabWidth = 4;
14637   Tab.IndentWidth = 4;
14638   verifyFormat("class Assign {\n"
14639                "\tvoid f() {\n"
14640                "\t\tint         x      = 123;\n"
14641                "\t\tint         random = 4;\n"
14642                "\t\tstd::string alphabet =\n"
14643                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14644                "\t}\n"
14645                "};",
14646                Tab);
14647 
14648   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14649   Tab.TabWidth = 8;
14650   Tab.IndentWidth = 8;
14651   EXPECT_EQ("if (aaaaaaaa && // q\n"
14652             "    bb)         // w\n"
14653             "\t;",
14654             format("if (aaaaaaaa &&// q\n"
14655                    "bb)// w\n"
14656                    ";",
14657                    Tab));
14658   EXPECT_EQ("if (aaa && bbb) // w\n"
14659             "\t;",
14660             format("if(aaa&&bbb)// w\n"
14661                    ";",
14662                    Tab));
14663   verifyFormat("class X {\n"
14664                "\tvoid f() {\n"
14665                "\t\tsomeFunction(parameter1,\n"
14666                "\t\t             parameter2);\n"
14667                "\t}\n"
14668                "};",
14669                Tab);
14670   verifyFormat("#define A                        \\\n"
14671                "\tvoid f() {               \\\n"
14672                "\t\tsomeFunction(    \\\n"
14673                "\t\t    parameter1,  \\\n"
14674                "\t\t    parameter2); \\\n"
14675                "\t}",
14676                Tab);
14677   Tab.TabWidth = 4;
14678   Tab.IndentWidth = 8;
14679   verifyFormat("class TabWidth4Indent8 {\n"
14680                "\t\tvoid f() {\n"
14681                "\t\t\t\tsomeFunction(parameter1,\n"
14682                "\t\t\t\t             parameter2);\n"
14683                "\t\t}\n"
14684                "};",
14685                Tab);
14686   Tab.TabWidth = 4;
14687   Tab.IndentWidth = 4;
14688   verifyFormat("class TabWidth4Indent4 {\n"
14689                "\tvoid f() {\n"
14690                "\t\tsomeFunction(parameter1,\n"
14691                "\t\t             parameter2);\n"
14692                "\t}\n"
14693                "};",
14694                Tab);
14695   Tab.TabWidth = 8;
14696   Tab.IndentWidth = 4;
14697   verifyFormat("class TabWidth8Indent4 {\n"
14698                "    void f() {\n"
14699                "\tsomeFunction(parameter1,\n"
14700                "\t             parameter2);\n"
14701                "    }\n"
14702                "};",
14703                Tab);
14704   Tab.TabWidth = 8;
14705   Tab.IndentWidth = 8;
14706   EXPECT_EQ("/*\n"
14707             "              a\t\tcomment\n"
14708             "              in multiple lines\n"
14709             "       */",
14710             format("   /*\t \t \n"
14711                    " \t \t a\t\tcomment\t \t\n"
14712                    " \t \t in multiple lines\t\n"
14713                    " \t  */",
14714                    Tab));
14715   verifyFormat("{\n"
14716                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14717                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14718                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14719                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14720                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14721                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14722                "};",
14723                Tab);
14724   verifyFormat("enum AA {\n"
14725                "\ta1, // Force multiple lines\n"
14726                "\ta2,\n"
14727                "\ta3\n"
14728                "};",
14729                Tab);
14730   EXPECT_EQ("if (aaaaaaaa && // q\n"
14731             "    bb)         // w\n"
14732             "\t;",
14733             format("if (aaaaaaaa &&// q\n"
14734                    "bb)// w\n"
14735                    ";",
14736                    Tab));
14737   verifyFormat("class X {\n"
14738                "\tvoid f() {\n"
14739                "\t\tsomeFunction(parameter1,\n"
14740                "\t\t             parameter2);\n"
14741                "\t}\n"
14742                "};",
14743                Tab);
14744   verifyFormat("{\n"
14745                "\tQ(\n"
14746                "\t    {\n"
14747                "\t\t    int a;\n"
14748                "\t\t    someFunction(aaaaaaaa,\n"
14749                "\t\t                 bbbbbbb);\n"
14750                "\t    },\n"
14751                "\t    p);\n"
14752                "}",
14753                Tab);
14754   EXPECT_EQ("{\n"
14755             "\t/* aaaa\n"
14756             "\t   bbbb */\n"
14757             "}",
14758             format("{\n"
14759                    "/* aaaa\n"
14760                    "   bbbb */\n"
14761                    "}",
14762                    Tab));
14763   EXPECT_EQ("{\n"
14764             "\t/*\n"
14765             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14766             "\t  bbbbbbbbbbbbb\n"
14767             "\t*/\n"
14768             "}",
14769             format("{\n"
14770                    "/*\n"
14771                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14772                    "*/\n"
14773                    "}",
14774                    Tab));
14775   EXPECT_EQ("{\n"
14776             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14777             "\t// bbbbbbbbbbbbb\n"
14778             "}",
14779             format("{\n"
14780                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14781                    "}",
14782                    Tab));
14783   EXPECT_EQ("{\n"
14784             "\t/*\n"
14785             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14786             "\t  bbbbbbbbbbbbb\n"
14787             "\t*/\n"
14788             "}",
14789             format("{\n"
14790                    "\t/*\n"
14791                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14792                    "\t*/\n"
14793                    "}",
14794                    Tab));
14795   EXPECT_EQ("{\n"
14796             "\t/*\n"
14797             "\n"
14798             "\t*/\n"
14799             "}",
14800             format("{\n"
14801                    "\t/*\n"
14802                    "\n"
14803                    "\t*/\n"
14804                    "}",
14805                    Tab));
14806   EXPECT_EQ("{\n"
14807             "\t/*\n"
14808             " asdf\n"
14809             "\t*/\n"
14810             "}",
14811             format("{\n"
14812                    "\t/*\n"
14813                    " asdf\n"
14814                    "\t*/\n"
14815                    "}",
14816                    Tab));
14817   EXPECT_EQ("/* some\n"
14818             "   comment */",
14819             format(" \t \t /* some\n"
14820                    " \t \t    comment */",
14821                    Tab));
14822   EXPECT_EQ("int a; /* some\n"
14823             "   comment */",
14824             format(" \t \t int a; /* some\n"
14825                    " \t \t    comment */",
14826                    Tab));
14827   EXPECT_EQ("int a; /* some\n"
14828             "comment */",
14829             format(" \t \t int\ta; /* some\n"
14830                    " \t \t    comment */",
14831                    Tab));
14832   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14833             "    comment */",
14834             format(" \t \t f(\"\t\t\"); /* some\n"
14835                    " \t \t    comment */",
14836                    Tab));
14837   EXPECT_EQ("{\n"
14838             "\t/*\n"
14839             "\t * Comment\n"
14840             "\t */\n"
14841             "\tint i;\n"
14842             "}",
14843             format("{\n"
14844                    "\t/*\n"
14845                    "\t * Comment\n"
14846                    "\t */\n"
14847                    "\t int i;\n"
14848                    "}",
14849                    Tab));
14850   Tab.TabWidth = 2;
14851   Tab.IndentWidth = 2;
14852   EXPECT_EQ("{\n"
14853             "\t/* aaaa\n"
14854             "\t   bbbb */\n"
14855             "}",
14856             format("{\n"
14857                    "/* aaaa\n"
14858                    "   bbbb */\n"
14859                    "}",
14860                    Tab));
14861   EXPECT_EQ("{\n"
14862             "\t/*\n"
14863             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14864             "\t  bbbbbbbbbbbbb\n"
14865             "\t*/\n"
14866             "}",
14867             format("{\n"
14868                    "/*\n"
14869                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14870                    "*/\n"
14871                    "}",
14872                    Tab));
14873   Tab.AlignConsecutiveAssignments.Enabled = true;
14874   Tab.AlignConsecutiveDeclarations.Enabled = true;
14875   Tab.TabWidth = 4;
14876   Tab.IndentWidth = 4;
14877   verifyFormat("class Assign {\n"
14878                "\tvoid f() {\n"
14879                "\t\tint         x      = 123;\n"
14880                "\t\tint         random = 4;\n"
14881                "\t\tstd::string alphabet =\n"
14882                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14883                "\t}\n"
14884                "};",
14885                Tab);
14886   Tab.AlignOperands = FormatStyle::OAS_Align;
14887   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14888                "                 cccccccccccccccccccc;",
14889                Tab);
14890   // no alignment
14891   verifyFormat("int aaaaaaaaaa =\n"
14892                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14893                Tab);
14894   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14895                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14896                "                        : 333333333333333;",
14897                Tab);
14898   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14899   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14900   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14901                "               + cccccccccccccccccccc;",
14902                Tab);
14903 }
14904 
14905 TEST_F(FormatTest, ZeroTabWidth) {
14906   FormatStyle Tab = getLLVMStyleWithColumns(42);
14907   Tab.IndentWidth = 8;
14908   Tab.UseTab = FormatStyle::UT_Never;
14909   Tab.TabWidth = 0;
14910   EXPECT_EQ("void a(){\n"
14911             "    // line starts with '\t'\n"
14912             "};",
14913             format("void a(){\n"
14914                    "\t// line starts with '\t'\n"
14915                    "};",
14916                    Tab));
14917 
14918   EXPECT_EQ("void a(){\n"
14919             "    // line starts with '\t'\n"
14920             "};",
14921             format("void a(){\n"
14922                    "\t\t// line starts with '\t'\n"
14923                    "};",
14924                    Tab));
14925 
14926   Tab.UseTab = FormatStyle::UT_ForIndentation;
14927   EXPECT_EQ("void a(){\n"
14928             "    // line starts with '\t'\n"
14929             "};",
14930             format("void a(){\n"
14931                    "\t// line starts with '\t'\n"
14932                    "};",
14933                    Tab));
14934 
14935   EXPECT_EQ("void a(){\n"
14936             "    // line starts with '\t'\n"
14937             "};",
14938             format("void a(){\n"
14939                    "\t\t// line starts with '\t'\n"
14940                    "};",
14941                    Tab));
14942 
14943   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14944   EXPECT_EQ("void a(){\n"
14945             "    // line starts with '\t'\n"
14946             "};",
14947             format("void a(){\n"
14948                    "\t// line starts with '\t'\n"
14949                    "};",
14950                    Tab));
14951 
14952   EXPECT_EQ("void a(){\n"
14953             "    // line starts with '\t'\n"
14954             "};",
14955             format("void a(){\n"
14956                    "\t\t// line starts with '\t'\n"
14957                    "};",
14958                    Tab));
14959 
14960   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14961   EXPECT_EQ("void a(){\n"
14962             "    // line starts with '\t'\n"
14963             "};",
14964             format("void a(){\n"
14965                    "\t// line starts with '\t'\n"
14966                    "};",
14967                    Tab));
14968 
14969   EXPECT_EQ("void a(){\n"
14970             "    // line starts with '\t'\n"
14971             "};",
14972             format("void a(){\n"
14973                    "\t\t// line starts with '\t'\n"
14974                    "};",
14975                    Tab));
14976 
14977   Tab.UseTab = FormatStyle::UT_Always;
14978   EXPECT_EQ("void a(){\n"
14979             "// line starts with '\t'\n"
14980             "};",
14981             format("void a(){\n"
14982                    "\t// line starts with '\t'\n"
14983                    "};",
14984                    Tab));
14985 
14986   EXPECT_EQ("void a(){\n"
14987             "// line starts with '\t'\n"
14988             "};",
14989             format("void a(){\n"
14990                    "\t\t// line starts with '\t'\n"
14991                    "};",
14992                    Tab));
14993 }
14994 
14995 TEST_F(FormatTest, CalculatesOriginalColumn) {
14996   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14997             "q\"; /* some\n"
14998             "       comment */",
14999             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15000                    "q\"; /* some\n"
15001                    "       comment */",
15002                    getLLVMStyle()));
15003   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
15004             "/* some\n"
15005             "   comment */",
15006             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
15007                    " /* some\n"
15008                    "    comment */",
15009                    getLLVMStyle()));
15010   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15011             "qqq\n"
15012             "/* some\n"
15013             "   comment */",
15014             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15015                    "qqq\n"
15016                    " /* some\n"
15017                    "    comment */",
15018                    getLLVMStyle()));
15019   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15020             "wwww; /* some\n"
15021             "         comment */",
15022             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15023                    "wwww; /* some\n"
15024                    "         comment */",
15025                    getLLVMStyle()));
15026 }
15027 
15028 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
15029   FormatStyle NoSpace = getLLVMStyle();
15030   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
15031 
15032   verifyFormat("while(true)\n"
15033                "  continue;",
15034                NoSpace);
15035   verifyFormat("for(;;)\n"
15036                "  continue;",
15037                NoSpace);
15038   verifyFormat("if(true)\n"
15039                "  f();\n"
15040                "else if(true)\n"
15041                "  f();",
15042                NoSpace);
15043   verifyFormat("do {\n"
15044                "  do_something();\n"
15045                "} while(something());",
15046                NoSpace);
15047   verifyFormat("switch(x) {\n"
15048                "default:\n"
15049                "  break;\n"
15050                "}",
15051                NoSpace);
15052   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
15053   verifyFormat("size_t x = sizeof(x);", NoSpace);
15054   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
15055   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
15056   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
15057   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
15058   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
15059   verifyFormat("alignas(128) char a[128];", NoSpace);
15060   verifyFormat("size_t x = alignof(MyType);", NoSpace);
15061   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
15062   verifyFormat("int f() throw(Deprecated);", NoSpace);
15063   verifyFormat("typedef void (*cb)(int);", NoSpace);
15064   verifyFormat("T A::operator()();", NoSpace);
15065   verifyFormat("X A::operator++(T);", NoSpace);
15066   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
15067 
15068   FormatStyle Space = getLLVMStyle();
15069   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
15070 
15071   verifyFormat("int f ();", Space);
15072   verifyFormat("void f (int a, T b) {\n"
15073                "  while (true)\n"
15074                "    continue;\n"
15075                "}",
15076                Space);
15077   verifyFormat("if (true)\n"
15078                "  f ();\n"
15079                "else if (true)\n"
15080                "  f ();",
15081                Space);
15082   verifyFormat("do {\n"
15083                "  do_something ();\n"
15084                "} while (something ());",
15085                Space);
15086   verifyFormat("switch (x) {\n"
15087                "default:\n"
15088                "  break;\n"
15089                "}",
15090                Space);
15091   verifyFormat("A::A () : a (1) {}", Space);
15092   verifyFormat("void f () __attribute__ ((asdf));", Space);
15093   verifyFormat("*(&a + 1);\n"
15094                "&((&a)[1]);\n"
15095                "a[(b + c) * d];\n"
15096                "(((a + 1) * 2) + 3) * 4;",
15097                Space);
15098   verifyFormat("#define A(x) x", Space);
15099   verifyFormat("#define A (x) x", Space);
15100   verifyFormat("#if defined(x)\n"
15101                "#endif",
15102                Space);
15103   verifyFormat("auto i = std::make_unique<int> (5);", Space);
15104   verifyFormat("size_t x = sizeof (x);", Space);
15105   verifyFormat("auto f (int x) -> decltype (x);", Space);
15106   verifyFormat("auto f (int x) -> typeof (x);", Space);
15107   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
15108   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
15109   verifyFormat("int f (T x) noexcept (x.create ());", Space);
15110   verifyFormat("alignas (128) char a[128];", Space);
15111   verifyFormat("size_t x = alignof (MyType);", Space);
15112   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
15113   verifyFormat("int f () throw (Deprecated);", Space);
15114   verifyFormat("typedef void (*cb) (int);", Space);
15115   // FIXME these tests regressed behaviour.
15116   // verifyFormat("T A::operator() ();", Space);
15117   // verifyFormat("X A::operator++ (T);", Space);
15118   verifyFormat("auto lambda = [] () { return 0; };", Space);
15119   verifyFormat("int x = int (y);", Space);
15120   verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space);
15121   verifyFormat("__builtin_LINE ()", Space);
15122   verifyFormat("__builtin_UNKNOWN ()", Space);
15123 
15124   FormatStyle SomeSpace = getLLVMStyle();
15125   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
15126 
15127   verifyFormat("[]() -> float {}", SomeSpace);
15128   verifyFormat("[] (auto foo) {}", SomeSpace);
15129   verifyFormat("[foo]() -> int {}", SomeSpace);
15130   verifyFormat("int f();", SomeSpace);
15131   verifyFormat("void f (int a, T b) {\n"
15132                "  while (true)\n"
15133                "    continue;\n"
15134                "}",
15135                SomeSpace);
15136   verifyFormat("if (true)\n"
15137                "  f();\n"
15138                "else if (true)\n"
15139                "  f();",
15140                SomeSpace);
15141   verifyFormat("do {\n"
15142                "  do_something();\n"
15143                "} while (something());",
15144                SomeSpace);
15145   verifyFormat("switch (x) {\n"
15146                "default:\n"
15147                "  break;\n"
15148                "}",
15149                SomeSpace);
15150   verifyFormat("A::A() : a (1) {}", SomeSpace);
15151   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
15152   verifyFormat("*(&a + 1);\n"
15153                "&((&a)[1]);\n"
15154                "a[(b + c) * d];\n"
15155                "(((a + 1) * 2) + 3) * 4;",
15156                SomeSpace);
15157   verifyFormat("#define A(x) x", SomeSpace);
15158   verifyFormat("#define A (x) x", SomeSpace);
15159   verifyFormat("#if defined(x)\n"
15160                "#endif",
15161                SomeSpace);
15162   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
15163   verifyFormat("size_t x = sizeof (x);", SomeSpace);
15164   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
15165   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
15166   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
15167   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
15168   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
15169   verifyFormat("alignas (128) char a[128];", SomeSpace);
15170   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
15171   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15172                SomeSpace);
15173   verifyFormat("int f() throw (Deprecated);", SomeSpace);
15174   verifyFormat("typedef void (*cb) (int);", SomeSpace);
15175   verifyFormat("T A::operator()();", SomeSpace);
15176   // FIXME these tests regressed behaviour.
15177   // verifyFormat("X A::operator++ (T);", SomeSpace);
15178   verifyFormat("int x = int (y);", SomeSpace);
15179   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
15180 
15181   FormatStyle SpaceControlStatements = getLLVMStyle();
15182   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15183   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
15184 
15185   verifyFormat("while (true)\n"
15186                "  continue;",
15187                SpaceControlStatements);
15188   verifyFormat("if (true)\n"
15189                "  f();\n"
15190                "else if (true)\n"
15191                "  f();",
15192                SpaceControlStatements);
15193   verifyFormat("for (;;) {\n"
15194                "  do_something();\n"
15195                "}",
15196                SpaceControlStatements);
15197   verifyFormat("do {\n"
15198                "  do_something();\n"
15199                "} while (something());",
15200                SpaceControlStatements);
15201   verifyFormat("switch (x) {\n"
15202                "default:\n"
15203                "  break;\n"
15204                "}",
15205                SpaceControlStatements);
15206 
15207   FormatStyle SpaceFuncDecl = getLLVMStyle();
15208   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15209   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
15210 
15211   verifyFormat("int f ();", SpaceFuncDecl);
15212   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
15213   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
15214   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
15215   verifyFormat("#define A(x) x", SpaceFuncDecl);
15216   verifyFormat("#define A (x) x", SpaceFuncDecl);
15217   verifyFormat("#if defined(x)\n"
15218                "#endif",
15219                SpaceFuncDecl);
15220   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
15221   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
15222   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
15223   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
15224   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
15225   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
15226   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
15227   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
15228   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
15229   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15230                SpaceFuncDecl);
15231   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
15232   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
15233   // FIXME these tests regressed behaviour.
15234   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
15235   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
15236   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
15237   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
15238   verifyFormat("int x = int(y);", SpaceFuncDecl);
15239   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15240                SpaceFuncDecl);
15241 
15242   FormatStyle SpaceFuncDef = getLLVMStyle();
15243   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15244   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
15245 
15246   verifyFormat("int f();", SpaceFuncDef);
15247   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
15248   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
15249   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
15250   verifyFormat("#define A(x) x", SpaceFuncDef);
15251   verifyFormat("#define A (x) x", SpaceFuncDef);
15252   verifyFormat("#if defined(x)\n"
15253                "#endif",
15254                SpaceFuncDef);
15255   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
15256   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
15257   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
15258   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
15259   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
15260   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
15261   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
15262   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
15263   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
15264   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15265                SpaceFuncDef);
15266   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
15267   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
15268   verifyFormat("T A::operator()();", SpaceFuncDef);
15269   verifyFormat("X A::operator++(T);", SpaceFuncDef);
15270   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
15271   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
15272   verifyFormat("int x = int(y);", SpaceFuncDef);
15273   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15274                SpaceFuncDef);
15275 
15276   FormatStyle SpaceIfMacros = getLLVMStyle();
15277   SpaceIfMacros.IfMacros.clear();
15278   SpaceIfMacros.IfMacros.push_back("MYIF");
15279   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15280   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
15281   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
15282   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
15283   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
15284 
15285   FormatStyle SpaceForeachMacros = getLLVMStyle();
15286   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
15287             FormatStyle::SBS_Never);
15288   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
15289   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15290   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
15291   verifyFormat("for (;;) {\n"
15292                "}",
15293                SpaceForeachMacros);
15294   verifyFormat("foreach (Item *item, itemlist) {\n"
15295                "}",
15296                SpaceForeachMacros);
15297   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15298                "}",
15299                SpaceForeachMacros);
15300   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15301                "}",
15302                SpaceForeachMacros);
15303   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15304 
15305   FormatStyle SomeSpace2 = getLLVMStyle();
15306   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15307   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15308   verifyFormat("[]() -> float {}", SomeSpace2);
15309   verifyFormat("[] (auto foo) {}", SomeSpace2);
15310   verifyFormat("[foo]() -> int {}", SomeSpace2);
15311   verifyFormat("int f();", SomeSpace2);
15312   verifyFormat("void f (int a, T b) {\n"
15313                "  while (true)\n"
15314                "    continue;\n"
15315                "}",
15316                SomeSpace2);
15317   verifyFormat("if (true)\n"
15318                "  f();\n"
15319                "else if (true)\n"
15320                "  f();",
15321                SomeSpace2);
15322   verifyFormat("do {\n"
15323                "  do_something();\n"
15324                "} while (something());",
15325                SomeSpace2);
15326   verifyFormat("switch (x) {\n"
15327                "default:\n"
15328                "  break;\n"
15329                "}",
15330                SomeSpace2);
15331   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15332   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15333   verifyFormat("*(&a + 1);\n"
15334                "&((&a)[1]);\n"
15335                "a[(b + c) * d];\n"
15336                "(((a + 1) * 2) + 3) * 4;",
15337                SomeSpace2);
15338   verifyFormat("#define A(x) x", SomeSpace2);
15339   verifyFormat("#define A (x) x", SomeSpace2);
15340   verifyFormat("#if defined(x)\n"
15341                "#endif",
15342                SomeSpace2);
15343   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15344   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15345   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15346   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15347   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15348   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15349   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15350   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15351   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15352   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15353                SomeSpace2);
15354   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15355   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15356   verifyFormat("T A::operator()();", SomeSpace2);
15357   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15358   verifyFormat("int x = int (y);", SomeSpace2);
15359   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15360 
15361   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15362   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15363   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15364       .AfterOverloadedOperator = true;
15365 
15366   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15367   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15368   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15369   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15370 
15371   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15372       .AfterOverloadedOperator = false;
15373 
15374   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15375   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15376   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15377   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15378 
15379   auto SpaceAfterRequires = getLLVMStyle();
15380   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15381   EXPECT_FALSE(
15382       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15383   EXPECT_FALSE(
15384       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15385   verifyFormat("void f(auto x)\n"
15386                "  requires requires(int i) { x + i; }\n"
15387                "{}",
15388                SpaceAfterRequires);
15389   verifyFormat("void f(auto x)\n"
15390                "  requires(requires(int i) { x + i; })\n"
15391                "{}",
15392                SpaceAfterRequires);
15393   verifyFormat("if (requires(int i) { x + i; })\n"
15394                "  return;",
15395                SpaceAfterRequires);
15396   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15397   verifyFormat("template <typename T>\n"
15398                "  requires(Foo<T>)\n"
15399                "class Bar;",
15400                SpaceAfterRequires);
15401 
15402   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15403   verifyFormat("void f(auto x)\n"
15404                "  requires requires(int i) { x + i; }\n"
15405                "{}",
15406                SpaceAfterRequires);
15407   verifyFormat("void f(auto x)\n"
15408                "  requires (requires(int i) { x + i; })\n"
15409                "{}",
15410                SpaceAfterRequires);
15411   verifyFormat("if (requires(int i) { x + i; })\n"
15412                "  return;",
15413                SpaceAfterRequires);
15414   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15415   verifyFormat("template <typename T>\n"
15416                "  requires (Foo<T>)\n"
15417                "class Bar;",
15418                SpaceAfterRequires);
15419 
15420   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15421   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15422   verifyFormat("void f(auto x)\n"
15423                "  requires requires (int i) { x + i; }\n"
15424                "{}",
15425                SpaceAfterRequires);
15426   verifyFormat("void f(auto x)\n"
15427                "  requires(requires (int i) { x + i; })\n"
15428                "{}",
15429                SpaceAfterRequires);
15430   verifyFormat("if (requires (int i) { x + i; })\n"
15431                "  return;",
15432                SpaceAfterRequires);
15433   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15434   verifyFormat("template <typename T>\n"
15435                "  requires(Foo<T>)\n"
15436                "class Bar;",
15437                SpaceAfterRequires);
15438 
15439   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15440   verifyFormat("void f(auto x)\n"
15441                "  requires requires (int i) { x + i; }\n"
15442                "{}",
15443                SpaceAfterRequires);
15444   verifyFormat("void f(auto x)\n"
15445                "  requires (requires (int i) { x + i; })\n"
15446                "{}",
15447                SpaceAfterRequires);
15448   verifyFormat("if (requires (int i) { x + i; })\n"
15449                "  return;",
15450                SpaceAfterRequires);
15451   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15452   verifyFormat("template <typename T>\n"
15453                "  requires (Foo<T>)\n"
15454                "class Bar;",
15455                SpaceAfterRequires);
15456 }
15457 
15458 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15459   FormatStyle Spaces = getLLVMStyle();
15460   Spaces.SpaceAfterLogicalNot = true;
15461 
15462   verifyFormat("bool x = ! y", Spaces);
15463   verifyFormat("if (! isFailure())", Spaces);
15464   verifyFormat("if (! (a && b))", Spaces);
15465   verifyFormat("\"Error!\"", Spaces);
15466   verifyFormat("! ! x", Spaces);
15467 }
15468 
15469 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15470   FormatStyle Spaces = getLLVMStyle();
15471 
15472   Spaces.SpacesInParentheses = true;
15473   verifyFormat("do_something( ::globalVar );", Spaces);
15474   verifyFormat("call( x, y, z );", Spaces);
15475   verifyFormat("call();", Spaces);
15476   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15477   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15478                Spaces);
15479   verifyFormat("while ( (bool)1 )\n"
15480                "  continue;",
15481                Spaces);
15482   verifyFormat("for ( ;; )\n"
15483                "  continue;",
15484                Spaces);
15485   verifyFormat("if ( true )\n"
15486                "  f();\n"
15487                "else if ( true )\n"
15488                "  f();",
15489                Spaces);
15490   verifyFormat("do {\n"
15491                "  do_something( (int)i );\n"
15492                "} while ( something() );",
15493                Spaces);
15494   verifyFormat("switch ( x ) {\n"
15495                "default:\n"
15496                "  break;\n"
15497                "}",
15498                Spaces);
15499 
15500   Spaces.SpacesInParentheses = false;
15501   Spaces.SpacesInCStyleCastParentheses = true;
15502   verifyFormat("Type *A = ( Type * )P;", Spaces);
15503   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15504   verifyFormat("x = ( int32 )y;", Spaces);
15505   verifyFormat("int a = ( int )(2.0f);", Spaces);
15506   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15507   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15508   verifyFormat("#define x (( int )-1)", Spaces);
15509 
15510   // Run the first set of tests again with:
15511   Spaces.SpacesInParentheses = false;
15512   Spaces.SpaceInEmptyParentheses = true;
15513   Spaces.SpacesInCStyleCastParentheses = true;
15514   verifyFormat("call(x, y, z);", Spaces);
15515   verifyFormat("call( );", Spaces);
15516   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15517   verifyFormat("while (( bool )1)\n"
15518                "  continue;",
15519                Spaces);
15520   verifyFormat("for (;;)\n"
15521                "  continue;",
15522                Spaces);
15523   verifyFormat("if (true)\n"
15524                "  f( );\n"
15525                "else if (true)\n"
15526                "  f( );",
15527                Spaces);
15528   verifyFormat("do {\n"
15529                "  do_something(( int )i);\n"
15530                "} while (something( ));",
15531                Spaces);
15532   verifyFormat("switch (x) {\n"
15533                "default:\n"
15534                "  break;\n"
15535                "}",
15536                Spaces);
15537 
15538   // Run the first set of tests again with:
15539   Spaces.SpaceAfterCStyleCast = true;
15540   verifyFormat("call(x, y, z);", Spaces);
15541   verifyFormat("call( );", Spaces);
15542   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15543   verifyFormat("while (( bool ) 1)\n"
15544                "  continue;",
15545                Spaces);
15546   verifyFormat("for (;;)\n"
15547                "  continue;",
15548                Spaces);
15549   verifyFormat("if (true)\n"
15550                "  f( );\n"
15551                "else if (true)\n"
15552                "  f( );",
15553                Spaces);
15554   verifyFormat("do {\n"
15555                "  do_something(( int ) i);\n"
15556                "} while (something( ));",
15557                Spaces);
15558   verifyFormat("switch (x) {\n"
15559                "default:\n"
15560                "  break;\n"
15561                "}",
15562                Spaces);
15563   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15564   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15565   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15566   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15567   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15568 
15569   // Run subset of tests again with:
15570   Spaces.SpacesInCStyleCastParentheses = false;
15571   Spaces.SpaceAfterCStyleCast = true;
15572   verifyFormat("while ((bool) 1)\n"
15573                "  continue;",
15574                Spaces);
15575   verifyFormat("do {\n"
15576                "  do_something((int) i);\n"
15577                "} while (something( ));",
15578                Spaces);
15579 
15580   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15581   verifyFormat("size_t idx = (size_t) a;", Spaces);
15582   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15583   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15584   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15585   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15586   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15587   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15588   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15589   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15590   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15591   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15592   Spaces.ColumnLimit = 80;
15593   Spaces.IndentWidth = 4;
15594   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15595   verifyFormat("void foo( ) {\n"
15596                "    size_t foo = (*(function))(\n"
15597                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15598                "BarrrrrrrrrrrrLong,\n"
15599                "        FoooooooooLooooong);\n"
15600                "}",
15601                Spaces);
15602   Spaces.SpaceAfterCStyleCast = false;
15603   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15604   verifyFormat("size_t idx = (size_t)a;", Spaces);
15605   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15606   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15607   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15608   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15609   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15610 
15611   verifyFormat("void foo( ) {\n"
15612                "    size_t foo = (*(function))(\n"
15613                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15614                "BarrrrrrrrrrrrLong,\n"
15615                "        FoooooooooLooooong);\n"
15616                "}",
15617                Spaces);
15618 }
15619 
15620 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15621   verifyFormat("int a[5];");
15622   verifyFormat("a[3] += 42;");
15623 
15624   FormatStyle Spaces = getLLVMStyle();
15625   Spaces.SpacesInSquareBrackets = true;
15626   // Not lambdas.
15627   verifyFormat("int a[ 5 ];", Spaces);
15628   verifyFormat("a[ 3 ] += 42;", Spaces);
15629   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15630   verifyFormat("double &operator[](int i) { return 0; }\n"
15631                "int i;",
15632                Spaces);
15633   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15634   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15635   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15636   // Lambdas.
15637   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15638   verifyFormat("return [ i, args... ] {};", Spaces);
15639   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15640   verifyFormat("int foo = [ = ]() {};", Spaces);
15641   verifyFormat("int foo = [ & ]() {};", Spaces);
15642   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15643   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15644 }
15645 
15646 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15647   FormatStyle NoSpaceStyle = getLLVMStyle();
15648   verifyFormat("int a[5];", NoSpaceStyle);
15649   verifyFormat("a[3] += 42;", NoSpaceStyle);
15650 
15651   verifyFormat("int a[1];", NoSpaceStyle);
15652   verifyFormat("int 1 [a];", NoSpaceStyle);
15653   verifyFormat("int a[1][2];", NoSpaceStyle);
15654   verifyFormat("a[7] = 5;", NoSpaceStyle);
15655   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15656   verifyFormat("f([] {})", NoSpaceStyle);
15657 
15658   FormatStyle Space = getLLVMStyle();
15659   Space.SpaceBeforeSquareBrackets = true;
15660   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15661   verifyFormat("return [i, args...] {};", Space);
15662 
15663   verifyFormat("int a [5];", Space);
15664   verifyFormat("a [3] += 42;", Space);
15665   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15666   verifyFormat("double &operator[](int i) { return 0; }\n"
15667                "int i;",
15668                Space);
15669   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15670   verifyFormat("int i = a [a][a]->f();", Space);
15671   verifyFormat("int i = (*b) [a]->f();", Space);
15672 
15673   verifyFormat("int a [1];", Space);
15674   verifyFormat("int 1 [a];", Space);
15675   verifyFormat("int a [1][2];", Space);
15676   verifyFormat("a [7] = 5;", Space);
15677   verifyFormat("int a = (f()) [23];", Space);
15678   verifyFormat("f([] {})", Space);
15679 }
15680 
15681 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15682   verifyFormat("int a = 5;");
15683   verifyFormat("a += 42;");
15684   verifyFormat("a or_eq 8;");
15685 
15686   FormatStyle Spaces = getLLVMStyle();
15687   Spaces.SpaceBeforeAssignmentOperators = false;
15688   verifyFormat("int a= 5;", Spaces);
15689   verifyFormat("a+= 42;", Spaces);
15690   verifyFormat("a or_eq 8;", Spaces);
15691 }
15692 
15693 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15694   verifyFormat("class Foo : public Bar {};");
15695   verifyFormat("Foo::Foo() : foo(1) {}");
15696   verifyFormat("for (auto a : b) {\n}");
15697   verifyFormat("int x = a ? b : c;");
15698   verifyFormat("{\n"
15699                "label0:\n"
15700                "  int x = 0;\n"
15701                "}");
15702   verifyFormat("switch (x) {\n"
15703                "case 1:\n"
15704                "default:\n"
15705                "}");
15706   verifyFormat("switch (allBraces) {\n"
15707                "case 1: {\n"
15708                "  break;\n"
15709                "}\n"
15710                "case 2: {\n"
15711                "  [[fallthrough]];\n"
15712                "}\n"
15713                "default: {\n"
15714                "  break;\n"
15715                "}\n"
15716                "}");
15717 
15718   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15719   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15720   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15721   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15722   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15723   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15724   verifyFormat("{\n"
15725                "label1:\n"
15726                "  int x = 0;\n"
15727                "}",
15728                CtorInitializerStyle);
15729   verifyFormat("switch (x) {\n"
15730                "case 1:\n"
15731                "default:\n"
15732                "}",
15733                CtorInitializerStyle);
15734   verifyFormat("switch (allBraces) {\n"
15735                "case 1: {\n"
15736                "  break;\n"
15737                "}\n"
15738                "case 2: {\n"
15739                "  [[fallthrough]];\n"
15740                "}\n"
15741                "default: {\n"
15742                "  break;\n"
15743                "}\n"
15744                "}",
15745                CtorInitializerStyle);
15746   CtorInitializerStyle.BreakConstructorInitializers =
15747       FormatStyle::BCIS_AfterColon;
15748   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15749                "    aaaaaaaaaaaaaaaa(1),\n"
15750                "    bbbbbbbbbbbbbbbb(2) {}",
15751                CtorInitializerStyle);
15752   CtorInitializerStyle.BreakConstructorInitializers =
15753       FormatStyle::BCIS_BeforeComma;
15754   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15755                "    : aaaaaaaaaaaaaaaa(1)\n"
15756                "    , bbbbbbbbbbbbbbbb(2) {}",
15757                CtorInitializerStyle);
15758   CtorInitializerStyle.BreakConstructorInitializers =
15759       FormatStyle::BCIS_BeforeColon;
15760   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15761                "    : aaaaaaaaaaaaaaaa(1),\n"
15762                "      bbbbbbbbbbbbbbbb(2) {}",
15763                CtorInitializerStyle);
15764   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15765   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15766                ": aaaaaaaaaaaaaaaa(1),\n"
15767                "  bbbbbbbbbbbbbbbb(2) {}",
15768                CtorInitializerStyle);
15769 
15770   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15771   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15772   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15773   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15774   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15775   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15776   verifyFormat("{\n"
15777                "label2:\n"
15778                "  int x = 0;\n"
15779                "}",
15780                InheritanceStyle);
15781   verifyFormat("switch (x) {\n"
15782                "case 1:\n"
15783                "default:\n"
15784                "}",
15785                InheritanceStyle);
15786   verifyFormat("switch (allBraces) {\n"
15787                "case 1: {\n"
15788                "  break;\n"
15789                "}\n"
15790                "case 2: {\n"
15791                "  [[fallthrough]];\n"
15792                "}\n"
15793                "default: {\n"
15794                "  break;\n"
15795                "}\n"
15796                "}",
15797                InheritanceStyle);
15798   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15799   verifyFormat("class Foooooooooooooooooooooo\n"
15800                "    : public aaaaaaaaaaaaaaaaaa,\n"
15801                "      public bbbbbbbbbbbbbbbbbb {\n"
15802                "}",
15803                InheritanceStyle);
15804   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15805   verifyFormat("class Foooooooooooooooooooooo:\n"
15806                "    public aaaaaaaaaaaaaaaaaa,\n"
15807                "    public bbbbbbbbbbbbbbbbbb {\n"
15808                "}",
15809                InheritanceStyle);
15810   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15811   verifyFormat("class Foooooooooooooooooooooo\n"
15812                "    : public aaaaaaaaaaaaaaaaaa\n"
15813                "    , public bbbbbbbbbbbbbbbbbb {\n"
15814                "}",
15815                InheritanceStyle);
15816   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15817   verifyFormat("class Foooooooooooooooooooooo\n"
15818                "    : public aaaaaaaaaaaaaaaaaa,\n"
15819                "      public bbbbbbbbbbbbbbbbbb {\n"
15820                "}",
15821                InheritanceStyle);
15822   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15823   verifyFormat("class Foooooooooooooooooooooo\n"
15824                ": public aaaaaaaaaaaaaaaaaa,\n"
15825                "  public bbbbbbbbbbbbbbbbbb {}",
15826                InheritanceStyle);
15827 
15828   FormatStyle ForLoopStyle = getLLVMStyle();
15829   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15830   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15831   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15832   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15833   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15834   verifyFormat("{\n"
15835                "label2:\n"
15836                "  int x = 0;\n"
15837                "}",
15838                ForLoopStyle);
15839   verifyFormat("switch (x) {\n"
15840                "case 1:\n"
15841                "default:\n"
15842                "}",
15843                ForLoopStyle);
15844   verifyFormat("switch (allBraces) {\n"
15845                "case 1: {\n"
15846                "  break;\n"
15847                "}\n"
15848                "case 2: {\n"
15849                "  [[fallthrough]];\n"
15850                "}\n"
15851                "default: {\n"
15852                "  break;\n"
15853                "}\n"
15854                "}",
15855                ForLoopStyle);
15856 
15857   FormatStyle CaseStyle = getLLVMStyle();
15858   CaseStyle.SpaceBeforeCaseColon = true;
15859   verifyFormat("class Foo : public Bar {};", CaseStyle);
15860   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15861   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15862   verifyFormat("int x = a ? b : c;", CaseStyle);
15863   verifyFormat("switch (x) {\n"
15864                "case 1 :\n"
15865                "default :\n"
15866                "}",
15867                CaseStyle);
15868   verifyFormat("switch (allBraces) {\n"
15869                "case 1 : {\n"
15870                "  break;\n"
15871                "}\n"
15872                "case 2 : {\n"
15873                "  [[fallthrough]];\n"
15874                "}\n"
15875                "default : {\n"
15876                "  break;\n"
15877                "}\n"
15878                "}",
15879                CaseStyle);
15880 
15881   FormatStyle NoSpaceStyle = getLLVMStyle();
15882   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15883   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15884   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15885   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15886   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15887   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15888   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15889   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15890   verifyFormat("{\n"
15891                "label3:\n"
15892                "  int x = 0;\n"
15893                "}",
15894                NoSpaceStyle);
15895   verifyFormat("switch (x) {\n"
15896                "case 1:\n"
15897                "default:\n"
15898                "}",
15899                NoSpaceStyle);
15900   verifyFormat("switch (allBraces) {\n"
15901                "case 1: {\n"
15902                "  break;\n"
15903                "}\n"
15904                "case 2: {\n"
15905                "  [[fallthrough]];\n"
15906                "}\n"
15907                "default: {\n"
15908                "  break;\n"
15909                "}\n"
15910                "}",
15911                NoSpaceStyle);
15912 
15913   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15914   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15915   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15916   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15917   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15918   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15919   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15920   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15921   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15922   verifyFormat("{\n"
15923                "label3:\n"
15924                "  int x = 0;\n"
15925                "}",
15926                InvertedSpaceStyle);
15927   verifyFormat("switch (x) {\n"
15928                "case 1 :\n"
15929                "case 2 : {\n"
15930                "  break;\n"
15931                "}\n"
15932                "default :\n"
15933                "  break;\n"
15934                "}",
15935                InvertedSpaceStyle);
15936   verifyFormat("switch (allBraces) {\n"
15937                "case 1 : {\n"
15938                "  break;\n"
15939                "}\n"
15940                "case 2 : {\n"
15941                "  [[fallthrough]];\n"
15942                "}\n"
15943                "default : {\n"
15944                "  break;\n"
15945                "}\n"
15946                "}",
15947                InvertedSpaceStyle);
15948 }
15949 
15950 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15951   FormatStyle Style = getLLVMStyle();
15952 
15953   Style.PointerAlignment = FormatStyle::PAS_Left;
15954   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15955   verifyFormat("void* const* x = NULL;", Style);
15956 
15957 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15958   do {                                                                         \
15959     Style.PointerAlignment = FormatStyle::Pointers;                            \
15960     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15961     verifyFormat(Code, Style);                                                 \
15962   } while (false)
15963 
15964   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15965   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15966   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15967 
15968   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15969   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15970   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15971 
15972   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15973   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15974   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15975 
15976   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15977   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15978   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15979 
15980   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15981   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15982                         SAPQ_Default);
15983   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15984                         SAPQ_Default);
15985 
15986   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15987   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15988                         SAPQ_Before);
15989   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15990                         SAPQ_Before);
15991 
15992   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15993   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15994   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15995                         SAPQ_After);
15996 
15997   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15998   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15999   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
16000 
16001 #undef verifyQualifierSpaces
16002 
16003   FormatStyle Spaces = getLLVMStyle();
16004   Spaces.AttributeMacros.push_back("qualified");
16005   Spaces.PointerAlignment = FormatStyle::PAS_Right;
16006   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
16007   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
16008   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
16009   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
16010   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
16011   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16012   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
16013   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
16014   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
16015   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
16016   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
16017   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16018 
16019   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
16020   Spaces.PointerAlignment = FormatStyle::PAS_Left;
16021   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
16022   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
16023   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
16024   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
16025   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
16026   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16027   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
16028   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
16029   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
16030   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
16031   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
16032   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
16033   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16034 
16035   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
16036   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
16037   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
16038   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
16039   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
16040   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
16041   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
16042   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16043 }
16044 
16045 TEST_F(FormatTest, AlignConsecutiveMacros) {
16046   FormatStyle Style = getLLVMStyle();
16047   Style.AlignConsecutiveAssignments.Enabled = true;
16048   Style.AlignConsecutiveDeclarations.Enabled = true;
16049 
16050   verifyFormat("#define a 3\n"
16051                "#define bbbb 4\n"
16052                "#define ccc (5)",
16053                Style);
16054 
16055   verifyFormat("#define f(x) (x * x)\n"
16056                "#define fff(x, y, z) (x * y + z)\n"
16057                "#define ffff(x, y) (x - y)",
16058                Style);
16059 
16060   verifyFormat("#define foo(x, y) (x + y)\n"
16061                "#define bar (5, 6)(2 + 2)",
16062                Style);
16063 
16064   verifyFormat("#define a 3\n"
16065                "#define bbbb 4\n"
16066                "#define ccc (5)\n"
16067                "#define f(x) (x * x)\n"
16068                "#define fff(x, y, z) (x * y + z)\n"
16069                "#define ffff(x, y) (x - y)",
16070                Style);
16071 
16072   Style.AlignConsecutiveMacros.Enabled = true;
16073   verifyFormat("#define a    3\n"
16074                "#define bbbb 4\n"
16075                "#define ccc  (5)",
16076                Style);
16077 
16078   verifyFormat("#define true  1\n"
16079                "#define false 0",
16080                Style);
16081 
16082   verifyFormat("#define f(x)         (x * x)\n"
16083                "#define fff(x, y, z) (x * y + z)\n"
16084                "#define ffff(x, y)   (x - y)",
16085                Style);
16086 
16087   verifyFormat("#define foo(x, y) (x + y)\n"
16088                "#define bar       (5, 6)(2 + 2)",
16089                Style);
16090 
16091   verifyFormat("#define a            3\n"
16092                "#define bbbb         4\n"
16093                "#define ccc          (5)\n"
16094                "#define f(x)         (x * x)\n"
16095                "#define fff(x, y, z) (x * y + z)\n"
16096                "#define ffff(x, y)   (x - y)",
16097                Style);
16098 
16099   verifyFormat("#define a         5\n"
16100                "#define foo(x, y) (x + y)\n"
16101                "#define CCC       (6)\n"
16102                "auto lambda = []() {\n"
16103                "  auto  ii = 0;\n"
16104                "  float j  = 0;\n"
16105                "  return 0;\n"
16106                "};\n"
16107                "int   i  = 0;\n"
16108                "float i2 = 0;\n"
16109                "auto  v  = type{\n"
16110                "    i = 1,   //\n"
16111                "    (i = 2), //\n"
16112                "    i = 3    //\n"
16113                "};",
16114                Style);
16115 
16116   Style.AlignConsecutiveMacros.Enabled = false;
16117   Style.ColumnLimit = 20;
16118 
16119   verifyFormat("#define a          \\\n"
16120                "  \"aabbbbbbbbbbbb\"\n"
16121                "#define D          \\\n"
16122                "  \"aabbbbbbbbbbbb\" \\\n"
16123                "  \"ccddeeeeeeeee\"\n"
16124                "#define B          \\\n"
16125                "  \"QQQQQQQQQQQQQ\"  \\\n"
16126                "  \"FFFFFFFFFFFFF\"  \\\n"
16127                "  \"LLLLLLLL\"\n",
16128                Style);
16129 
16130   Style.AlignConsecutiveMacros.Enabled = true;
16131   verifyFormat("#define a          \\\n"
16132                "  \"aabbbbbbbbbbbb\"\n"
16133                "#define D          \\\n"
16134                "  \"aabbbbbbbbbbbb\" \\\n"
16135                "  \"ccddeeeeeeeee\"\n"
16136                "#define B          \\\n"
16137                "  \"QQQQQQQQQQQQQ\"  \\\n"
16138                "  \"FFFFFFFFFFFFF\"  \\\n"
16139                "  \"LLLLLLLL\"\n",
16140                Style);
16141 
16142   // Test across comments
16143   Style.MaxEmptyLinesToKeep = 10;
16144   Style.ReflowComments = false;
16145   Style.AlignConsecutiveMacros.AcrossComments = true;
16146   EXPECT_EQ("#define a    3\n"
16147             "// line comment\n"
16148             "#define bbbb 4\n"
16149             "#define ccc  (5)",
16150             format("#define a 3\n"
16151                    "// line comment\n"
16152                    "#define bbbb 4\n"
16153                    "#define ccc (5)",
16154                    Style));
16155 
16156   EXPECT_EQ("#define a    3\n"
16157             "/* block comment */\n"
16158             "#define bbbb 4\n"
16159             "#define ccc  (5)",
16160             format("#define a  3\n"
16161                    "/* block comment */\n"
16162                    "#define bbbb 4\n"
16163                    "#define ccc (5)",
16164                    Style));
16165 
16166   EXPECT_EQ("#define a    3\n"
16167             "/* multi-line *\n"
16168             " * block comment */\n"
16169             "#define bbbb 4\n"
16170             "#define ccc  (5)",
16171             format("#define a 3\n"
16172                    "/* multi-line *\n"
16173                    " * block comment */\n"
16174                    "#define bbbb 4\n"
16175                    "#define ccc (5)",
16176                    Style));
16177 
16178   EXPECT_EQ("#define a    3\n"
16179             "// multi-line line comment\n"
16180             "//\n"
16181             "#define bbbb 4\n"
16182             "#define ccc  (5)",
16183             format("#define a  3\n"
16184                    "// multi-line line comment\n"
16185                    "//\n"
16186                    "#define bbbb 4\n"
16187                    "#define ccc (5)",
16188                    Style));
16189 
16190   EXPECT_EQ("#define a 3\n"
16191             "// empty lines still break.\n"
16192             "\n"
16193             "#define bbbb 4\n"
16194             "#define ccc  (5)",
16195             format("#define a     3\n"
16196                    "// empty lines still break.\n"
16197                    "\n"
16198                    "#define bbbb     4\n"
16199                    "#define ccc  (5)",
16200                    Style));
16201 
16202   // Test across empty lines
16203   Style.AlignConsecutiveMacros.AcrossComments = false;
16204   Style.AlignConsecutiveMacros.AcrossEmptyLines = true;
16205   EXPECT_EQ("#define a    3\n"
16206             "\n"
16207             "#define bbbb 4\n"
16208             "#define ccc  (5)",
16209             format("#define a 3\n"
16210                    "\n"
16211                    "#define bbbb 4\n"
16212                    "#define ccc (5)",
16213                    Style));
16214 
16215   EXPECT_EQ("#define a    3\n"
16216             "\n"
16217             "\n"
16218             "\n"
16219             "#define bbbb 4\n"
16220             "#define ccc  (5)",
16221             format("#define a        3\n"
16222                    "\n"
16223                    "\n"
16224                    "\n"
16225                    "#define bbbb 4\n"
16226                    "#define ccc (5)",
16227                    Style));
16228 
16229   EXPECT_EQ("#define a 3\n"
16230             "// comments should break alignment\n"
16231             "//\n"
16232             "#define bbbb 4\n"
16233             "#define ccc  (5)",
16234             format("#define a        3\n"
16235                    "// comments should break alignment\n"
16236                    "//\n"
16237                    "#define bbbb 4\n"
16238                    "#define ccc (5)",
16239                    Style));
16240 
16241   // Test across empty lines and comments
16242   Style.AlignConsecutiveMacros.AcrossComments = true;
16243   verifyFormat("#define a    3\n"
16244                "\n"
16245                "// line comment\n"
16246                "#define bbbb 4\n"
16247                "#define ccc  (5)",
16248                Style);
16249 
16250   EXPECT_EQ("#define a    3\n"
16251             "\n"
16252             "\n"
16253             "/* multi-line *\n"
16254             " * block comment */\n"
16255             "\n"
16256             "\n"
16257             "#define bbbb 4\n"
16258             "#define ccc  (5)",
16259             format("#define a 3\n"
16260                    "\n"
16261                    "\n"
16262                    "/* multi-line *\n"
16263                    " * block comment */\n"
16264                    "\n"
16265                    "\n"
16266                    "#define bbbb 4\n"
16267                    "#define ccc (5)",
16268                    Style));
16269 
16270   EXPECT_EQ("#define a    3\n"
16271             "\n"
16272             "\n"
16273             "/* multi-line *\n"
16274             " * block comment */\n"
16275             "\n"
16276             "\n"
16277             "#define bbbb 4\n"
16278             "#define ccc  (5)",
16279             format("#define a 3\n"
16280                    "\n"
16281                    "\n"
16282                    "/* multi-line *\n"
16283                    " * block comment */\n"
16284                    "\n"
16285                    "\n"
16286                    "#define bbbb 4\n"
16287                    "#define ccc       (5)",
16288                    Style));
16289 }
16290 
16291 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
16292   FormatStyle Alignment = getLLVMStyle();
16293   Alignment.AlignConsecutiveMacros.Enabled = true;
16294   Alignment.AlignConsecutiveAssignments.Enabled = true;
16295   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16296 
16297   Alignment.MaxEmptyLinesToKeep = 10;
16298   /* Test alignment across empty lines */
16299   EXPECT_EQ("int a           = 5;\n"
16300             "\n"
16301             "int oneTwoThree = 123;",
16302             format("int a       = 5;\n"
16303                    "\n"
16304                    "int oneTwoThree= 123;",
16305                    Alignment));
16306   EXPECT_EQ("int a           = 5;\n"
16307             "int one         = 1;\n"
16308             "\n"
16309             "int oneTwoThree = 123;",
16310             format("int a = 5;\n"
16311                    "int one = 1;\n"
16312                    "\n"
16313                    "int oneTwoThree = 123;",
16314                    Alignment));
16315   EXPECT_EQ("int a           = 5;\n"
16316             "int one         = 1;\n"
16317             "\n"
16318             "int oneTwoThree = 123;\n"
16319             "int oneTwo      = 12;",
16320             format("int a = 5;\n"
16321                    "int one = 1;\n"
16322                    "\n"
16323                    "int oneTwoThree = 123;\n"
16324                    "int oneTwo = 12;",
16325                    Alignment));
16326 
16327   /* Test across comments */
16328   EXPECT_EQ("int a = 5;\n"
16329             "/* block comment */\n"
16330             "int oneTwoThree = 123;",
16331             format("int a = 5;\n"
16332                    "/* block comment */\n"
16333                    "int oneTwoThree=123;",
16334                    Alignment));
16335 
16336   EXPECT_EQ("int a = 5;\n"
16337             "// line comment\n"
16338             "int oneTwoThree = 123;",
16339             format("int a = 5;\n"
16340                    "// line comment\n"
16341                    "int oneTwoThree=123;",
16342                    Alignment));
16343 
16344   /* Test across comments and newlines */
16345   EXPECT_EQ("int a = 5;\n"
16346             "\n"
16347             "/* block comment */\n"
16348             "int oneTwoThree = 123;",
16349             format("int a = 5;\n"
16350                    "\n"
16351                    "/* block comment */\n"
16352                    "int oneTwoThree=123;",
16353                    Alignment));
16354 
16355   EXPECT_EQ("int a = 5;\n"
16356             "\n"
16357             "// line comment\n"
16358             "int oneTwoThree = 123;",
16359             format("int a = 5;\n"
16360                    "\n"
16361                    "// line comment\n"
16362                    "int oneTwoThree=123;",
16363                    Alignment));
16364 }
16365 
16366 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16367   FormatStyle Alignment = getLLVMStyle();
16368   Alignment.AlignConsecutiveDeclarations.Enabled = true;
16369   Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true;
16370   Alignment.AlignConsecutiveDeclarations.AcrossComments = true;
16371 
16372   Alignment.MaxEmptyLinesToKeep = 10;
16373   /* Test alignment across empty lines */
16374   EXPECT_EQ("int         a = 5;\n"
16375             "\n"
16376             "float const oneTwoThree = 123;",
16377             format("int a = 5;\n"
16378                    "\n"
16379                    "float const oneTwoThree = 123;",
16380                    Alignment));
16381   EXPECT_EQ("int         a = 5;\n"
16382             "float const one = 1;\n"
16383             "\n"
16384             "int         oneTwoThree = 123;",
16385             format("int a = 5;\n"
16386                    "float const one = 1;\n"
16387                    "\n"
16388                    "int oneTwoThree = 123;",
16389                    Alignment));
16390 
16391   /* Test across comments */
16392   EXPECT_EQ("float const a = 5;\n"
16393             "/* block comment */\n"
16394             "int         oneTwoThree = 123;",
16395             format("float const a = 5;\n"
16396                    "/* block comment */\n"
16397                    "int oneTwoThree=123;",
16398                    Alignment));
16399 
16400   EXPECT_EQ("float const a = 5;\n"
16401             "// line comment\n"
16402             "int         oneTwoThree = 123;",
16403             format("float const a = 5;\n"
16404                    "// line comment\n"
16405                    "int oneTwoThree=123;",
16406                    Alignment));
16407 
16408   /* Test across comments and newlines */
16409   EXPECT_EQ("float const a = 5;\n"
16410             "\n"
16411             "/* block comment */\n"
16412             "int         oneTwoThree = 123;",
16413             format("float const a = 5;\n"
16414                    "\n"
16415                    "/* block comment */\n"
16416                    "int         oneTwoThree=123;",
16417                    Alignment));
16418 
16419   EXPECT_EQ("float const a = 5;\n"
16420             "\n"
16421             "// line comment\n"
16422             "int         oneTwoThree = 123;",
16423             format("float const a = 5;\n"
16424                    "\n"
16425                    "// line comment\n"
16426                    "int oneTwoThree=123;",
16427                    Alignment));
16428 }
16429 
16430 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16431   FormatStyle Alignment = getLLVMStyle();
16432   Alignment.AlignConsecutiveBitFields.Enabled = true;
16433   Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true;
16434   Alignment.AlignConsecutiveBitFields.AcrossComments = true;
16435 
16436   Alignment.MaxEmptyLinesToKeep = 10;
16437   /* Test alignment across empty lines */
16438   EXPECT_EQ("int a            : 5;\n"
16439             "\n"
16440             "int longbitfield : 6;",
16441             format("int a : 5;\n"
16442                    "\n"
16443                    "int longbitfield : 6;",
16444                    Alignment));
16445   EXPECT_EQ("int a            : 5;\n"
16446             "int one          : 1;\n"
16447             "\n"
16448             "int longbitfield : 6;",
16449             format("int a : 5;\n"
16450                    "int one : 1;\n"
16451                    "\n"
16452                    "int longbitfield : 6;",
16453                    Alignment));
16454 
16455   /* Test across comments */
16456   EXPECT_EQ("int a            : 5;\n"
16457             "/* block comment */\n"
16458             "int longbitfield : 6;",
16459             format("int a : 5;\n"
16460                    "/* block comment */\n"
16461                    "int longbitfield : 6;",
16462                    Alignment));
16463   EXPECT_EQ("int a            : 5;\n"
16464             "int one          : 1;\n"
16465             "// line comment\n"
16466             "int longbitfield : 6;",
16467             format("int a : 5;\n"
16468                    "int one : 1;\n"
16469                    "// line comment\n"
16470                    "int longbitfield : 6;",
16471                    Alignment));
16472 
16473   /* Test across comments and newlines */
16474   EXPECT_EQ("int a            : 5;\n"
16475             "/* block comment */\n"
16476             "\n"
16477             "int longbitfield : 6;",
16478             format("int a : 5;\n"
16479                    "/* block comment */\n"
16480                    "\n"
16481                    "int longbitfield : 6;",
16482                    Alignment));
16483   EXPECT_EQ("int a            : 5;\n"
16484             "int one          : 1;\n"
16485             "\n"
16486             "// line comment\n"
16487             "\n"
16488             "int longbitfield : 6;",
16489             format("int a : 5;\n"
16490                    "int one : 1;\n"
16491                    "\n"
16492                    "// line comment \n"
16493                    "\n"
16494                    "int longbitfield : 6;",
16495                    Alignment));
16496 }
16497 
16498 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16499   FormatStyle Alignment = getLLVMStyle();
16500   Alignment.AlignConsecutiveMacros.Enabled = true;
16501   Alignment.AlignConsecutiveAssignments.Enabled = true;
16502   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16503 
16504   Alignment.MaxEmptyLinesToKeep = 10;
16505   /* Test alignment across empty lines */
16506   EXPECT_EQ("int a = 5;\n"
16507             "\n"
16508             "int oneTwoThree = 123;",
16509             format("int a       = 5;\n"
16510                    "\n"
16511                    "int oneTwoThree= 123;",
16512                    Alignment));
16513   EXPECT_EQ("int a   = 5;\n"
16514             "int one = 1;\n"
16515             "\n"
16516             "int oneTwoThree = 123;",
16517             format("int a = 5;\n"
16518                    "int one = 1;\n"
16519                    "\n"
16520                    "int oneTwoThree = 123;",
16521                    Alignment));
16522 
16523   /* Test across comments */
16524   EXPECT_EQ("int a           = 5;\n"
16525             "/* block comment */\n"
16526             "int oneTwoThree = 123;",
16527             format("int a = 5;\n"
16528                    "/* block comment */\n"
16529                    "int oneTwoThree=123;",
16530                    Alignment));
16531 
16532   EXPECT_EQ("int a           = 5;\n"
16533             "// line comment\n"
16534             "int oneTwoThree = 123;",
16535             format("int a = 5;\n"
16536                    "// line comment\n"
16537                    "int oneTwoThree=123;",
16538                    Alignment));
16539 
16540   EXPECT_EQ("int a           = 5;\n"
16541             "/*\n"
16542             " * multi-line block comment\n"
16543             " */\n"
16544             "int oneTwoThree = 123;",
16545             format("int a = 5;\n"
16546                    "/*\n"
16547                    " * multi-line block comment\n"
16548                    " */\n"
16549                    "int oneTwoThree=123;",
16550                    Alignment));
16551 
16552   EXPECT_EQ("int a           = 5;\n"
16553             "//\n"
16554             "// multi-line line comment\n"
16555             "//\n"
16556             "int oneTwoThree = 123;",
16557             format("int a = 5;\n"
16558                    "//\n"
16559                    "// multi-line line comment\n"
16560                    "//\n"
16561                    "int oneTwoThree=123;",
16562                    Alignment));
16563 
16564   /* Test across comments and newlines */
16565   EXPECT_EQ("int a = 5;\n"
16566             "\n"
16567             "/* block comment */\n"
16568             "int oneTwoThree = 123;",
16569             format("int a = 5;\n"
16570                    "\n"
16571                    "/* block comment */\n"
16572                    "int oneTwoThree=123;",
16573                    Alignment));
16574 
16575   EXPECT_EQ("int a = 5;\n"
16576             "\n"
16577             "// line comment\n"
16578             "int oneTwoThree = 123;",
16579             format("int a = 5;\n"
16580                    "\n"
16581                    "// line comment\n"
16582                    "int oneTwoThree=123;",
16583                    Alignment));
16584 }
16585 
16586 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16587   FormatStyle Alignment = getLLVMStyle();
16588   Alignment.AlignConsecutiveMacros.Enabled = true;
16589   Alignment.AlignConsecutiveAssignments.Enabled = true;
16590   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16591   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16592   verifyFormat("int a           = 5;\n"
16593                "int oneTwoThree = 123;",
16594                Alignment);
16595   verifyFormat("int a           = method();\n"
16596                "int oneTwoThree = 133;",
16597                Alignment);
16598   verifyFormat("a &= 5;\n"
16599                "bcd *= 5;\n"
16600                "ghtyf += 5;\n"
16601                "dvfvdb -= 5;\n"
16602                "a /= 5;\n"
16603                "vdsvsv %= 5;\n"
16604                "sfdbddfbdfbb ^= 5;\n"
16605                "dvsdsv |= 5;\n"
16606                "int dsvvdvsdvvv = 123;",
16607                Alignment);
16608   verifyFormat("int i = 1, j = 10;\n"
16609                "something = 2000;",
16610                Alignment);
16611   verifyFormat("something = 2000;\n"
16612                "int i = 1, j = 10;\n",
16613                Alignment);
16614   verifyFormat("something = 2000;\n"
16615                "another   = 911;\n"
16616                "int i = 1, j = 10;\n"
16617                "oneMore = 1;\n"
16618                "i       = 2;",
16619                Alignment);
16620   verifyFormat("int a   = 5;\n"
16621                "int one = 1;\n"
16622                "method();\n"
16623                "int oneTwoThree = 123;\n"
16624                "int oneTwo      = 12;",
16625                Alignment);
16626   verifyFormat("int oneTwoThree = 123;\n"
16627                "int oneTwo      = 12;\n"
16628                "method();\n",
16629                Alignment);
16630   verifyFormat("int oneTwoThree = 123; // comment\n"
16631                "int oneTwo      = 12;  // comment",
16632                Alignment);
16633 
16634   // Bug 25167
16635   /* Uncomment when fixed
16636     verifyFormat("#if A\n"
16637                  "#else\n"
16638                  "int aaaaaaaa = 12;\n"
16639                  "#endif\n"
16640                  "#if B\n"
16641                  "#else\n"
16642                  "int a = 12;\n"
16643                  "#endif\n",
16644                  Alignment);
16645     verifyFormat("enum foo {\n"
16646                  "#if A\n"
16647                  "#else\n"
16648                  "  aaaaaaaa = 12;\n"
16649                  "#endif\n"
16650                  "#if B\n"
16651                  "#else\n"
16652                  "  a = 12;\n"
16653                  "#endif\n"
16654                  "};\n",
16655                  Alignment);
16656   */
16657 
16658   Alignment.MaxEmptyLinesToKeep = 10;
16659   /* Test alignment across empty lines */
16660   EXPECT_EQ("int a           = 5;\n"
16661             "\n"
16662             "int oneTwoThree = 123;",
16663             format("int a       = 5;\n"
16664                    "\n"
16665                    "int oneTwoThree= 123;",
16666                    Alignment));
16667   EXPECT_EQ("int a           = 5;\n"
16668             "int one         = 1;\n"
16669             "\n"
16670             "int oneTwoThree = 123;",
16671             format("int a = 5;\n"
16672                    "int one = 1;\n"
16673                    "\n"
16674                    "int oneTwoThree = 123;",
16675                    Alignment));
16676   EXPECT_EQ("int a           = 5;\n"
16677             "int one         = 1;\n"
16678             "\n"
16679             "int oneTwoThree = 123;\n"
16680             "int oneTwo      = 12;",
16681             format("int a = 5;\n"
16682                    "int one = 1;\n"
16683                    "\n"
16684                    "int oneTwoThree = 123;\n"
16685                    "int oneTwo = 12;",
16686                    Alignment));
16687 
16688   /* Test across comments */
16689   EXPECT_EQ("int a           = 5;\n"
16690             "/* block comment */\n"
16691             "int oneTwoThree = 123;",
16692             format("int a = 5;\n"
16693                    "/* block comment */\n"
16694                    "int oneTwoThree=123;",
16695                    Alignment));
16696 
16697   EXPECT_EQ("int a           = 5;\n"
16698             "// line comment\n"
16699             "int oneTwoThree = 123;",
16700             format("int a = 5;\n"
16701                    "// line comment\n"
16702                    "int oneTwoThree=123;",
16703                    Alignment));
16704 
16705   /* Test across comments and newlines */
16706   EXPECT_EQ("int a           = 5;\n"
16707             "\n"
16708             "/* block comment */\n"
16709             "int oneTwoThree = 123;",
16710             format("int a = 5;\n"
16711                    "\n"
16712                    "/* block comment */\n"
16713                    "int oneTwoThree=123;",
16714                    Alignment));
16715 
16716   EXPECT_EQ("int a           = 5;\n"
16717             "\n"
16718             "// line comment\n"
16719             "int oneTwoThree = 123;",
16720             format("int a = 5;\n"
16721                    "\n"
16722                    "// line comment\n"
16723                    "int oneTwoThree=123;",
16724                    Alignment));
16725 
16726   EXPECT_EQ("int a           = 5;\n"
16727             "//\n"
16728             "// multi-line line comment\n"
16729             "//\n"
16730             "int oneTwoThree = 123;",
16731             format("int a = 5;\n"
16732                    "//\n"
16733                    "// multi-line line comment\n"
16734                    "//\n"
16735                    "int oneTwoThree=123;",
16736                    Alignment));
16737 
16738   EXPECT_EQ("int a           = 5;\n"
16739             "/*\n"
16740             " *  multi-line block comment\n"
16741             " */\n"
16742             "int oneTwoThree = 123;",
16743             format("int a = 5;\n"
16744                    "/*\n"
16745                    " *  multi-line block comment\n"
16746                    " */\n"
16747                    "int oneTwoThree=123;",
16748                    Alignment));
16749 
16750   EXPECT_EQ("int a           = 5;\n"
16751             "\n"
16752             "/* block comment */\n"
16753             "\n"
16754             "\n"
16755             "\n"
16756             "int oneTwoThree = 123;",
16757             format("int a = 5;\n"
16758                    "\n"
16759                    "/* block comment */\n"
16760                    "\n"
16761                    "\n"
16762                    "\n"
16763                    "int oneTwoThree=123;",
16764                    Alignment));
16765 
16766   EXPECT_EQ("int a           = 5;\n"
16767             "\n"
16768             "// line comment\n"
16769             "\n"
16770             "\n"
16771             "\n"
16772             "int oneTwoThree = 123;",
16773             format("int a = 5;\n"
16774                    "\n"
16775                    "// line comment\n"
16776                    "\n"
16777                    "\n"
16778                    "\n"
16779                    "int oneTwoThree=123;",
16780                    Alignment));
16781 
16782   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16783   verifyFormat("#define A \\\n"
16784                "  int aaaa       = 12; \\\n"
16785                "  int b          = 23; \\\n"
16786                "  int ccc        = 234; \\\n"
16787                "  int dddddddddd = 2345;",
16788                Alignment);
16789   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16790   verifyFormat("#define A               \\\n"
16791                "  int aaaa       = 12;  \\\n"
16792                "  int b          = 23;  \\\n"
16793                "  int ccc        = 234; \\\n"
16794                "  int dddddddddd = 2345;",
16795                Alignment);
16796   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16797   verifyFormat("#define A                                                      "
16798                "                \\\n"
16799                "  int aaaa       = 12;                                         "
16800                "                \\\n"
16801                "  int b          = 23;                                         "
16802                "                \\\n"
16803                "  int ccc        = 234;                                        "
16804                "                \\\n"
16805                "  int dddddddddd = 2345;",
16806                Alignment);
16807   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16808                "k = 4, int l = 5,\n"
16809                "                  int m = 6) {\n"
16810                "  int j      = 10;\n"
16811                "  otherThing = 1;\n"
16812                "}",
16813                Alignment);
16814   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16815                "  int i   = 1;\n"
16816                "  int j   = 2;\n"
16817                "  int big = 10000;\n"
16818                "}",
16819                Alignment);
16820   verifyFormat("class C {\n"
16821                "public:\n"
16822                "  int i            = 1;\n"
16823                "  virtual void f() = 0;\n"
16824                "};",
16825                Alignment);
16826   verifyFormat("int i = 1;\n"
16827                "if (SomeType t = getSomething()) {\n"
16828                "}\n"
16829                "int j   = 2;\n"
16830                "int big = 10000;",
16831                Alignment);
16832   verifyFormat("int j = 7;\n"
16833                "for (int k = 0; k < N; ++k) {\n"
16834                "}\n"
16835                "int j   = 2;\n"
16836                "int big = 10000;\n"
16837                "}",
16838                Alignment);
16839   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16840   verifyFormat("int i = 1;\n"
16841                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16842                "    = someLooooooooooooooooongFunction();\n"
16843                "int j = 2;",
16844                Alignment);
16845   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16846   verifyFormat("int i = 1;\n"
16847                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16848                "    someLooooooooooooooooongFunction();\n"
16849                "int j = 2;",
16850                Alignment);
16851 
16852   verifyFormat("auto lambda = []() {\n"
16853                "  auto i = 0;\n"
16854                "  return 0;\n"
16855                "};\n"
16856                "int i  = 0;\n"
16857                "auto v = type{\n"
16858                "    i = 1,   //\n"
16859                "    (i = 2), //\n"
16860                "    i = 3    //\n"
16861                "};",
16862                Alignment);
16863 
16864   verifyFormat(
16865       "int i      = 1;\n"
16866       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16867       "                          loooooooooooooooooooooongParameterB);\n"
16868       "int j      = 2;",
16869       Alignment);
16870 
16871   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16872                "          typename B   = very_long_type_name_1,\n"
16873                "          typename T_2 = very_long_type_name_2>\n"
16874                "auto foo() {}\n",
16875                Alignment);
16876   verifyFormat("int a, b = 1;\n"
16877                "int c  = 2;\n"
16878                "int dd = 3;\n",
16879                Alignment);
16880   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16881                "float b[1][] = {{3.f}};\n",
16882                Alignment);
16883   verifyFormat("for (int i = 0; i < 1; i++)\n"
16884                "  int x = 1;\n",
16885                Alignment);
16886   verifyFormat("for (i = 0; i < 1; i++)\n"
16887                "  x = 1;\n"
16888                "y = 1;\n",
16889                Alignment);
16890 
16891   Alignment.ReflowComments = true;
16892   Alignment.ColumnLimit = 50;
16893   EXPECT_EQ("int x   = 0;\n"
16894             "int yy  = 1; /// specificlennospace\n"
16895             "int zzz = 2;\n",
16896             format("int x   = 0;\n"
16897                    "int yy  = 1; ///specificlennospace\n"
16898                    "int zzz = 2;\n",
16899                    Alignment));
16900 }
16901 
16902 TEST_F(FormatTest, AlignCompoundAssignments) {
16903   FormatStyle Alignment = getLLVMStyle();
16904   Alignment.AlignConsecutiveAssignments.Enabled = true;
16905   Alignment.AlignConsecutiveAssignments.AlignCompound = true;
16906   Alignment.AlignConsecutiveAssignments.PadOperators = false;
16907   verifyFormat("sfdbddfbdfbb    = 5;\n"
16908                "dvsdsv          = 5;\n"
16909                "int dsvvdvsdvvv = 123;",
16910                Alignment);
16911   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16912                "dvsdsv         |= 5;\n"
16913                "int dsvvdvsdvvv = 123;",
16914                Alignment);
16915   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16916                "dvsdsv        <<= 5;\n"
16917                "int dsvvdvsdvvv = 123;",
16918                Alignment);
16919   // Test that `<=` is not treated as a compound assignment.
16920   verifyFormat("aa &= 5;\n"
16921                "b <= 10;\n"
16922                "c = 15;",
16923                Alignment);
16924   Alignment.AlignConsecutiveAssignments.PadOperators = true;
16925   verifyFormat("sfdbddfbdfbb    = 5;\n"
16926                "dvsdsv          = 5;\n"
16927                "int dsvvdvsdvvv = 123;",
16928                Alignment);
16929   verifyFormat("sfdbddfbdfbb    ^= 5;\n"
16930                "dvsdsv          |= 5;\n"
16931                "int dsvvdvsdvvv  = 123;",
16932                Alignment);
16933   verifyFormat("sfdbddfbdfbb     ^= 5;\n"
16934                "dvsdsv          <<= 5;\n"
16935                "int dsvvdvsdvvv   = 123;",
16936                Alignment);
16937   EXPECT_EQ("a   += 5;\n"
16938             "one  = 1;\n"
16939             "\n"
16940             "oneTwoThree = 123;\n",
16941             format("a += 5;\n"
16942                    "one = 1;\n"
16943                    "\n"
16944                    "oneTwoThree = 123;\n",
16945                    Alignment));
16946   EXPECT_EQ("a   += 5;\n"
16947             "one  = 1;\n"
16948             "//\n"
16949             "oneTwoThree = 123;\n",
16950             format("a += 5;\n"
16951                    "one = 1;\n"
16952                    "//\n"
16953                    "oneTwoThree = 123;\n",
16954                    Alignment));
16955   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16956   EXPECT_EQ("a           += 5;\n"
16957             "one          = 1;\n"
16958             "\n"
16959             "oneTwoThree  = 123;\n",
16960             format("a += 5;\n"
16961                    "one = 1;\n"
16962                    "\n"
16963                    "oneTwoThree = 123;\n",
16964                    Alignment));
16965   EXPECT_EQ("a   += 5;\n"
16966             "one  = 1;\n"
16967             "//\n"
16968             "oneTwoThree = 123;\n",
16969             format("a += 5;\n"
16970                    "one = 1;\n"
16971                    "//\n"
16972                    "oneTwoThree = 123;\n",
16973                    Alignment));
16974   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false;
16975   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16976   EXPECT_EQ("a   += 5;\n"
16977             "one  = 1;\n"
16978             "\n"
16979             "oneTwoThree = 123;\n",
16980             format("a += 5;\n"
16981                    "one = 1;\n"
16982                    "\n"
16983                    "oneTwoThree = 123;\n",
16984                    Alignment));
16985   EXPECT_EQ("a           += 5;\n"
16986             "one          = 1;\n"
16987             "//\n"
16988             "oneTwoThree  = 123;\n",
16989             format("a += 5;\n"
16990                    "one = 1;\n"
16991                    "//\n"
16992                    "oneTwoThree = 123;\n",
16993                    Alignment));
16994   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16995   EXPECT_EQ("a            += 5;\n"
16996             "one         >>= 1;\n"
16997             "\n"
16998             "oneTwoThree   = 123;\n",
16999             format("a += 5;\n"
17000                    "one >>= 1;\n"
17001                    "\n"
17002                    "oneTwoThree = 123;\n",
17003                    Alignment));
17004   EXPECT_EQ("a            += 5;\n"
17005             "one           = 1;\n"
17006             "//\n"
17007             "oneTwoThree <<= 123;\n",
17008             format("a += 5;\n"
17009                    "one = 1;\n"
17010                    "//\n"
17011                    "oneTwoThree <<= 123;\n",
17012                    Alignment));
17013 }
17014 
17015 TEST_F(FormatTest, AlignConsecutiveAssignments) {
17016   FormatStyle Alignment = getLLVMStyle();
17017   Alignment.AlignConsecutiveMacros.Enabled = true;
17018   verifyFormat("int a = 5;\n"
17019                "int oneTwoThree = 123;",
17020                Alignment);
17021   verifyFormat("int a = 5;\n"
17022                "int oneTwoThree = 123;",
17023                Alignment);
17024 
17025   Alignment.AlignConsecutiveAssignments.Enabled = true;
17026   verifyFormat("int a           = 5;\n"
17027                "int oneTwoThree = 123;",
17028                Alignment);
17029   verifyFormat("int a           = method();\n"
17030                "int oneTwoThree = 133;",
17031                Alignment);
17032   verifyFormat("aa <= 5;\n"
17033                "a &= 5;\n"
17034                "bcd *= 5;\n"
17035                "ghtyf += 5;\n"
17036                "dvfvdb -= 5;\n"
17037                "a /= 5;\n"
17038                "vdsvsv %= 5;\n"
17039                "sfdbddfbdfbb ^= 5;\n"
17040                "dvsdsv |= 5;\n"
17041                "int dsvvdvsdvvv = 123;",
17042                Alignment);
17043   verifyFormat("int i = 1, j = 10;\n"
17044                "something = 2000;",
17045                Alignment);
17046   verifyFormat("something = 2000;\n"
17047                "int i = 1, j = 10;\n",
17048                Alignment);
17049   verifyFormat("something = 2000;\n"
17050                "another   = 911;\n"
17051                "int i = 1, j = 10;\n"
17052                "oneMore = 1;\n"
17053                "i       = 2;",
17054                Alignment);
17055   verifyFormat("int a   = 5;\n"
17056                "int one = 1;\n"
17057                "method();\n"
17058                "int oneTwoThree = 123;\n"
17059                "int oneTwo      = 12;",
17060                Alignment);
17061   verifyFormat("int oneTwoThree = 123;\n"
17062                "int oneTwo      = 12;\n"
17063                "method();\n",
17064                Alignment);
17065   verifyFormat("int oneTwoThree = 123; // comment\n"
17066                "int oneTwo      = 12;  // comment",
17067                Alignment);
17068   verifyFormat("int f()         = default;\n"
17069                "int &operator() = default;\n"
17070                "int &operator=() {",
17071                Alignment);
17072   verifyFormat("int f()         = delete;\n"
17073                "int &operator() = delete;\n"
17074                "int &operator=() {",
17075                Alignment);
17076   verifyFormat("int f()         = default; // comment\n"
17077                "int &operator() = default; // comment\n"
17078                "int &operator=() {",
17079                Alignment);
17080   verifyFormat("int f()         = default;\n"
17081                "int &operator() = default;\n"
17082                "int &operator==() {",
17083                Alignment);
17084   verifyFormat("int f()         = default;\n"
17085                "int &operator() = default;\n"
17086                "int &operator<=() {",
17087                Alignment);
17088   verifyFormat("int f()         = default;\n"
17089                "int &operator() = default;\n"
17090                "int &operator!=() {",
17091                Alignment);
17092   verifyFormat("int f()         = default;\n"
17093                "int &operator() = default;\n"
17094                "int &operator=();",
17095                Alignment);
17096   verifyFormat("int f()         = delete;\n"
17097                "int &operator() = delete;\n"
17098                "int &operator=();",
17099                Alignment);
17100   verifyFormat("/* long long padding */ int f() = default;\n"
17101                "int &operator()                 = default;\n"
17102                "int &operator/**/ =();",
17103                Alignment);
17104   // https://llvm.org/PR33697
17105   FormatStyle AlignmentWithPenalty = getLLVMStyle();
17106   AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true;
17107   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
17108   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
17109                "  void f() = delete;\n"
17110                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
17111                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
17112                "};\n",
17113                AlignmentWithPenalty);
17114 
17115   // Bug 25167
17116   /* Uncomment when fixed
17117     verifyFormat("#if A\n"
17118                  "#else\n"
17119                  "int aaaaaaaa = 12;\n"
17120                  "#endif\n"
17121                  "#if B\n"
17122                  "#else\n"
17123                  "int a = 12;\n"
17124                  "#endif\n",
17125                  Alignment);
17126     verifyFormat("enum foo {\n"
17127                  "#if A\n"
17128                  "#else\n"
17129                  "  aaaaaaaa = 12;\n"
17130                  "#endif\n"
17131                  "#if B\n"
17132                  "#else\n"
17133                  "  a = 12;\n"
17134                  "#endif\n"
17135                  "};\n",
17136                  Alignment);
17137   */
17138 
17139   EXPECT_EQ("int a = 5;\n"
17140             "\n"
17141             "int oneTwoThree = 123;",
17142             format("int a       = 5;\n"
17143                    "\n"
17144                    "int oneTwoThree= 123;",
17145                    Alignment));
17146   EXPECT_EQ("int a   = 5;\n"
17147             "int one = 1;\n"
17148             "\n"
17149             "int oneTwoThree = 123;",
17150             format("int a = 5;\n"
17151                    "int one = 1;\n"
17152                    "\n"
17153                    "int oneTwoThree = 123;",
17154                    Alignment));
17155   EXPECT_EQ("int a   = 5;\n"
17156             "int one = 1;\n"
17157             "\n"
17158             "int oneTwoThree = 123;\n"
17159             "int oneTwo      = 12;",
17160             format("int a = 5;\n"
17161                    "int one = 1;\n"
17162                    "\n"
17163                    "int oneTwoThree = 123;\n"
17164                    "int oneTwo = 12;",
17165                    Alignment));
17166   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17167   verifyFormat("#define A \\\n"
17168                "  int aaaa       = 12; \\\n"
17169                "  int b          = 23; \\\n"
17170                "  int ccc        = 234; \\\n"
17171                "  int dddddddddd = 2345;",
17172                Alignment);
17173   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17174   verifyFormat("#define A               \\\n"
17175                "  int aaaa       = 12;  \\\n"
17176                "  int b          = 23;  \\\n"
17177                "  int ccc        = 234; \\\n"
17178                "  int dddddddddd = 2345;",
17179                Alignment);
17180   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17181   verifyFormat("#define A                                                      "
17182                "                \\\n"
17183                "  int aaaa       = 12;                                         "
17184                "                \\\n"
17185                "  int b          = 23;                                         "
17186                "                \\\n"
17187                "  int ccc        = 234;                                        "
17188                "                \\\n"
17189                "  int dddddddddd = 2345;",
17190                Alignment);
17191   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17192                "k = 4, int l = 5,\n"
17193                "                  int m = 6) {\n"
17194                "  int j      = 10;\n"
17195                "  otherThing = 1;\n"
17196                "}",
17197                Alignment);
17198   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17199                "  int i   = 1;\n"
17200                "  int j   = 2;\n"
17201                "  int big = 10000;\n"
17202                "}",
17203                Alignment);
17204   verifyFormat("class C {\n"
17205                "public:\n"
17206                "  int i            = 1;\n"
17207                "  virtual void f() = 0;\n"
17208                "};",
17209                Alignment);
17210   verifyFormat("int i = 1;\n"
17211                "if (SomeType t = getSomething()) {\n"
17212                "}\n"
17213                "int j   = 2;\n"
17214                "int big = 10000;",
17215                Alignment);
17216   verifyFormat("int j = 7;\n"
17217                "for (int k = 0; k < N; ++k) {\n"
17218                "}\n"
17219                "int j   = 2;\n"
17220                "int big = 10000;\n"
17221                "}",
17222                Alignment);
17223   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17224   verifyFormat("int i = 1;\n"
17225                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17226                "    = someLooooooooooooooooongFunction();\n"
17227                "int j = 2;",
17228                Alignment);
17229   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17230   verifyFormat("int i = 1;\n"
17231                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17232                "    someLooooooooooooooooongFunction();\n"
17233                "int j = 2;",
17234                Alignment);
17235 
17236   verifyFormat("auto lambda = []() {\n"
17237                "  auto i = 0;\n"
17238                "  return 0;\n"
17239                "};\n"
17240                "int i  = 0;\n"
17241                "auto v = type{\n"
17242                "    i = 1,   //\n"
17243                "    (i = 2), //\n"
17244                "    i = 3    //\n"
17245                "};",
17246                Alignment);
17247 
17248   verifyFormat(
17249       "int i      = 1;\n"
17250       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17251       "                          loooooooooooooooooooooongParameterB);\n"
17252       "int j      = 2;",
17253       Alignment);
17254 
17255   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17256                "          typename B   = very_long_type_name_1,\n"
17257                "          typename T_2 = very_long_type_name_2>\n"
17258                "auto foo() {}\n",
17259                Alignment);
17260   verifyFormat("int a, b = 1;\n"
17261                "int c  = 2;\n"
17262                "int dd = 3;\n",
17263                Alignment);
17264   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17265                "float b[1][] = {{3.f}};\n",
17266                Alignment);
17267   verifyFormat("for (int i = 0; i < 1; i++)\n"
17268                "  int x = 1;\n",
17269                Alignment);
17270   verifyFormat("for (i = 0; i < 1; i++)\n"
17271                "  x = 1;\n"
17272                "y = 1;\n",
17273                Alignment);
17274 
17275   EXPECT_EQ(Alignment.ReflowComments, true);
17276   Alignment.ColumnLimit = 50;
17277   EXPECT_EQ("int x   = 0;\n"
17278             "int yy  = 1; /// specificlennospace\n"
17279             "int zzz = 2;\n",
17280             format("int x   = 0;\n"
17281                    "int yy  = 1; ///specificlennospace\n"
17282                    "int zzz = 2;\n",
17283                    Alignment));
17284 
17285   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17286                "auto b                     = [] {\n"
17287                "  f();\n"
17288                "  return;\n"
17289                "};",
17290                Alignment);
17291   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17292                "auto b                     = g([] {\n"
17293                "  f();\n"
17294                "  return;\n"
17295                "});",
17296                Alignment);
17297   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17298                "auto b                     = g(param, [] {\n"
17299                "  f();\n"
17300                "  return;\n"
17301                "});",
17302                Alignment);
17303   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17304                "auto b                     = [] {\n"
17305                "  if (condition) {\n"
17306                "    return;\n"
17307                "  }\n"
17308                "};",
17309                Alignment);
17310 
17311   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17312                "           ccc ? aaaaa : bbbbb,\n"
17313                "           dddddddddddddddddddddddddd);",
17314                Alignment);
17315   // FIXME: https://llvm.org/PR53497
17316   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
17317   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17318   //              "    ccc ? aaaaa : bbbbb,\n"
17319   //              "    dddddddddddddddddddddddddd);",
17320   //              Alignment);
17321 
17322   // Confirm proper handling of AlignConsecutiveAssignments with
17323   // BinPackArguments.
17324   // See https://llvm.org/PR55360
17325   Alignment = getLLVMStyleWithColumns(50);
17326   Alignment.AlignConsecutiveAssignments.Enabled = true;
17327   Alignment.BinPackArguments = false;
17328   verifyFormat("int a_long_name = 1;\n"
17329                "auto b          = B({a_long_name, a_long_name},\n"
17330                "                    {a_longer_name_for_wrap,\n"
17331                "                     a_longer_name_for_wrap});",
17332                Alignment);
17333   verifyFormat("int a_long_name = 1;\n"
17334                "auto b          = B{{a_long_name, a_long_name},\n"
17335                "                    {a_longer_name_for_wrap,\n"
17336                "                     a_longer_name_for_wrap}};",
17337                Alignment);
17338 }
17339 
17340 TEST_F(FormatTest, AlignConsecutiveBitFields) {
17341   FormatStyle Alignment = getLLVMStyle();
17342   Alignment.AlignConsecutiveBitFields.Enabled = true;
17343   verifyFormat("int const a     : 5;\n"
17344                "int oneTwoThree : 23;",
17345                Alignment);
17346 
17347   // Initializers are allowed starting with c++2a
17348   verifyFormat("int const a     : 5 = 1;\n"
17349                "int oneTwoThree : 23 = 0;",
17350                Alignment);
17351 
17352   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17353   verifyFormat("int const a           : 5;\n"
17354                "int       oneTwoThree : 23;",
17355                Alignment);
17356 
17357   verifyFormat("int const a           : 5;  // comment\n"
17358                "int       oneTwoThree : 23; // comment",
17359                Alignment);
17360 
17361   verifyFormat("int const a           : 5 = 1;\n"
17362                "int       oneTwoThree : 23 = 0;",
17363                Alignment);
17364 
17365   Alignment.AlignConsecutiveAssignments.Enabled = true;
17366   verifyFormat("int const a           : 5  = 1;\n"
17367                "int       oneTwoThree : 23 = 0;",
17368                Alignment);
17369   verifyFormat("int const a           : 5  = {1};\n"
17370                "int       oneTwoThree : 23 = 0;",
17371                Alignment);
17372 
17373   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
17374   verifyFormat("int const a          :5;\n"
17375                "int       oneTwoThree:23;",
17376                Alignment);
17377 
17378   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
17379   verifyFormat("int const a           :5;\n"
17380                "int       oneTwoThree :23;",
17381                Alignment);
17382 
17383   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
17384   verifyFormat("int const a          : 5;\n"
17385                "int       oneTwoThree: 23;",
17386                Alignment);
17387 
17388   // Known limitations: ':' is only recognized as a bitfield colon when
17389   // followed by a number.
17390   /*
17391   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
17392                "int a           : 5;",
17393                Alignment);
17394   */
17395 }
17396 
17397 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
17398   FormatStyle Alignment = getLLVMStyle();
17399   Alignment.AlignConsecutiveMacros.Enabled = true;
17400   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17401   verifyFormat("float const a = 5;\n"
17402                "int oneTwoThree = 123;",
17403                Alignment);
17404   verifyFormat("int a = 5;\n"
17405                "float const oneTwoThree = 123;",
17406                Alignment);
17407 
17408   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17409   verifyFormat("float const a = 5;\n"
17410                "int         oneTwoThree = 123;",
17411                Alignment);
17412   verifyFormat("int         a = method();\n"
17413                "float const oneTwoThree = 133;",
17414                Alignment);
17415   verifyFormat("int i = 1, j = 10;\n"
17416                "something = 2000;",
17417                Alignment);
17418   verifyFormat("something = 2000;\n"
17419                "int i = 1, j = 10;\n",
17420                Alignment);
17421   verifyFormat("float      something = 2000;\n"
17422                "double     another = 911;\n"
17423                "int        i = 1, j = 10;\n"
17424                "const int *oneMore = 1;\n"
17425                "unsigned   i = 2;",
17426                Alignment);
17427   verifyFormat("float a = 5;\n"
17428                "int   one = 1;\n"
17429                "method();\n"
17430                "const double       oneTwoThree = 123;\n"
17431                "const unsigned int oneTwo = 12;",
17432                Alignment);
17433   verifyFormat("int      oneTwoThree{0}; // comment\n"
17434                "unsigned oneTwo;         // comment",
17435                Alignment);
17436   verifyFormat("unsigned int       *a;\n"
17437                "int                *b;\n"
17438                "unsigned int Const *c;\n"
17439                "unsigned int const *d;\n"
17440                "unsigned int Const &e;\n"
17441                "unsigned int const &f;",
17442                Alignment);
17443   verifyFormat("Const unsigned int *c;\n"
17444                "const unsigned int *d;\n"
17445                "Const unsigned int &e;\n"
17446                "const unsigned int &f;\n"
17447                "const unsigned      g;\n"
17448                "Const unsigned      h;",
17449                Alignment);
17450   EXPECT_EQ("float const a = 5;\n"
17451             "\n"
17452             "int oneTwoThree = 123;",
17453             format("float const   a = 5;\n"
17454                    "\n"
17455                    "int           oneTwoThree= 123;",
17456                    Alignment));
17457   EXPECT_EQ("float a = 5;\n"
17458             "int   one = 1;\n"
17459             "\n"
17460             "unsigned oneTwoThree = 123;",
17461             format("float    a = 5;\n"
17462                    "int      one = 1;\n"
17463                    "\n"
17464                    "unsigned oneTwoThree = 123;",
17465                    Alignment));
17466   EXPECT_EQ("float a = 5;\n"
17467             "int   one = 1;\n"
17468             "\n"
17469             "unsigned oneTwoThree = 123;\n"
17470             "int      oneTwo = 12;",
17471             format("float    a = 5;\n"
17472                    "int one = 1;\n"
17473                    "\n"
17474                    "unsigned oneTwoThree = 123;\n"
17475                    "int oneTwo = 12;",
17476                    Alignment));
17477   // Function prototype alignment
17478   verifyFormat("int    a();\n"
17479                "double b();",
17480                Alignment);
17481   verifyFormat("int    a(int x);\n"
17482                "double b();",
17483                Alignment);
17484   unsigned OldColumnLimit = Alignment.ColumnLimit;
17485   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17486   // otherwise the function parameters will be re-flowed onto a single line.
17487   Alignment.ColumnLimit = 0;
17488   EXPECT_EQ("int    a(int   x,\n"
17489             "         float y);\n"
17490             "double b(int    x,\n"
17491             "         double y);",
17492             format("int a(int x,\n"
17493                    " float y);\n"
17494                    "double b(int x,\n"
17495                    " double y);",
17496                    Alignment));
17497   // This ensures that function parameters of function declarations are
17498   // correctly indented when their owning functions are indented.
17499   // The failure case here is for 'double y' to not be indented enough.
17500   EXPECT_EQ("double a(int x);\n"
17501             "int    b(int    y,\n"
17502             "         double z);",
17503             format("double a(int x);\n"
17504                    "int b(int y,\n"
17505                    " double z);",
17506                    Alignment));
17507   // Set ColumnLimit low so that we induce wrapping immediately after
17508   // the function name and opening paren.
17509   Alignment.ColumnLimit = 13;
17510   verifyFormat("int function(\n"
17511                "    int  x,\n"
17512                "    bool y);",
17513                Alignment);
17514   Alignment.ColumnLimit = OldColumnLimit;
17515   // Ensure function pointers don't screw up recursive alignment
17516   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17517                "double b();",
17518                Alignment);
17519   Alignment.AlignConsecutiveAssignments.Enabled = true;
17520   // Ensure recursive alignment is broken by function braces, so that the
17521   // "a = 1" does not align with subsequent assignments inside the function
17522   // body.
17523   verifyFormat("int func(int a = 1) {\n"
17524                "  int b  = 2;\n"
17525                "  int cc = 3;\n"
17526                "}",
17527                Alignment);
17528   verifyFormat("float      something = 2000;\n"
17529                "double     another   = 911;\n"
17530                "int        i = 1, j = 10;\n"
17531                "const int *oneMore = 1;\n"
17532                "unsigned   i       = 2;",
17533                Alignment);
17534   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17535                "unsigned oneTwo      = 0;   // comment",
17536                Alignment);
17537   // Make sure that scope is correctly tracked, in the absence of braces
17538   verifyFormat("for (int i = 0; i < n; i++)\n"
17539                "  j = i;\n"
17540                "double x = 1;\n",
17541                Alignment);
17542   verifyFormat("if (int i = 0)\n"
17543                "  j = i;\n"
17544                "double x = 1;\n",
17545                Alignment);
17546   // Ensure operator[] and operator() are comprehended
17547   verifyFormat("struct test {\n"
17548                "  long long int foo();\n"
17549                "  int           operator[](int a);\n"
17550                "  double        bar();\n"
17551                "};\n",
17552                Alignment);
17553   verifyFormat("struct test {\n"
17554                "  long long int foo();\n"
17555                "  int           operator()(int a);\n"
17556                "  double        bar();\n"
17557                "};\n",
17558                Alignment);
17559   // http://llvm.org/PR52914
17560   verifyFormat("char *a[]     = {\"a\", // comment\n"
17561                "                 \"bb\"};\n"
17562                "int   bbbbbbb = 0;",
17563                Alignment);
17564 
17565   // PAS_Right
17566   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17567             "  int const i   = 1;\n"
17568             "  int      *j   = 2;\n"
17569             "  int       big = 10000;\n"
17570             "\n"
17571             "  unsigned oneTwoThree = 123;\n"
17572             "  int      oneTwo      = 12;\n"
17573             "  method();\n"
17574             "  float k  = 2;\n"
17575             "  int   ll = 10000;\n"
17576             "}",
17577             format("void SomeFunction(int parameter= 0) {\n"
17578                    " int const  i= 1;\n"
17579                    "  int *j=2;\n"
17580                    " int big  =  10000;\n"
17581                    "\n"
17582                    "unsigned oneTwoThree  =123;\n"
17583                    "int oneTwo = 12;\n"
17584                    "  method();\n"
17585                    "float k= 2;\n"
17586                    "int ll=10000;\n"
17587                    "}",
17588                    Alignment));
17589   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17590             "  int const i   = 1;\n"
17591             "  int     **j   = 2, ***k;\n"
17592             "  int      &k   = i;\n"
17593             "  int     &&l   = i + j;\n"
17594             "  int       big = 10000;\n"
17595             "\n"
17596             "  unsigned oneTwoThree = 123;\n"
17597             "  int      oneTwo      = 12;\n"
17598             "  method();\n"
17599             "  float k  = 2;\n"
17600             "  int   ll = 10000;\n"
17601             "}",
17602             format("void SomeFunction(int parameter= 0) {\n"
17603                    " int const  i= 1;\n"
17604                    "  int **j=2,***k;\n"
17605                    "int &k=i;\n"
17606                    "int &&l=i+j;\n"
17607                    " int big  =  10000;\n"
17608                    "\n"
17609                    "unsigned oneTwoThree  =123;\n"
17610                    "int oneTwo = 12;\n"
17611                    "  method();\n"
17612                    "float k= 2;\n"
17613                    "int ll=10000;\n"
17614                    "}",
17615                    Alignment));
17616   // variables are aligned at their name, pointers are at the right most
17617   // position
17618   verifyFormat("int   *a;\n"
17619                "int  **b;\n"
17620                "int ***c;\n"
17621                "int    foobar;\n",
17622                Alignment);
17623 
17624   // PAS_Left
17625   FormatStyle AlignmentLeft = Alignment;
17626   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17627   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17628             "  int const i   = 1;\n"
17629             "  int*      j   = 2;\n"
17630             "  int       big = 10000;\n"
17631             "\n"
17632             "  unsigned oneTwoThree = 123;\n"
17633             "  int      oneTwo      = 12;\n"
17634             "  method();\n"
17635             "  float k  = 2;\n"
17636             "  int   ll = 10000;\n"
17637             "}",
17638             format("void SomeFunction(int parameter= 0) {\n"
17639                    " int const  i= 1;\n"
17640                    "  int *j=2;\n"
17641                    " int big  =  10000;\n"
17642                    "\n"
17643                    "unsigned oneTwoThree  =123;\n"
17644                    "int oneTwo = 12;\n"
17645                    "  method();\n"
17646                    "float k= 2;\n"
17647                    "int ll=10000;\n"
17648                    "}",
17649                    AlignmentLeft));
17650   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17651             "  int const i   = 1;\n"
17652             "  int**     j   = 2;\n"
17653             "  int&      k   = i;\n"
17654             "  int&&     l   = i + j;\n"
17655             "  int       big = 10000;\n"
17656             "\n"
17657             "  unsigned oneTwoThree = 123;\n"
17658             "  int      oneTwo      = 12;\n"
17659             "  method();\n"
17660             "  float k  = 2;\n"
17661             "  int   ll = 10000;\n"
17662             "}",
17663             format("void SomeFunction(int parameter= 0) {\n"
17664                    " int const  i= 1;\n"
17665                    "  int **j=2;\n"
17666                    "int &k=i;\n"
17667                    "int &&l=i+j;\n"
17668                    " int big  =  10000;\n"
17669                    "\n"
17670                    "unsigned oneTwoThree  =123;\n"
17671                    "int oneTwo = 12;\n"
17672                    "  method();\n"
17673                    "float k= 2;\n"
17674                    "int ll=10000;\n"
17675                    "}",
17676                    AlignmentLeft));
17677   // variables are aligned at their name, pointers are at the left most position
17678   verifyFormat("int*   a;\n"
17679                "int**  b;\n"
17680                "int*** c;\n"
17681                "int    foobar;\n",
17682                AlignmentLeft);
17683 
17684   // PAS_Middle
17685   FormatStyle AlignmentMiddle = Alignment;
17686   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17687   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17688             "  int const i   = 1;\n"
17689             "  int *     j   = 2;\n"
17690             "  int       big = 10000;\n"
17691             "\n"
17692             "  unsigned oneTwoThree = 123;\n"
17693             "  int      oneTwo      = 12;\n"
17694             "  method();\n"
17695             "  float k  = 2;\n"
17696             "  int   ll = 10000;\n"
17697             "}",
17698             format("void SomeFunction(int parameter= 0) {\n"
17699                    " int const  i= 1;\n"
17700                    "  int *j=2;\n"
17701                    " int big  =  10000;\n"
17702                    "\n"
17703                    "unsigned oneTwoThree  =123;\n"
17704                    "int oneTwo = 12;\n"
17705                    "  method();\n"
17706                    "float k= 2;\n"
17707                    "int ll=10000;\n"
17708                    "}",
17709                    AlignmentMiddle));
17710   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17711             "  int const i   = 1;\n"
17712             "  int **    j   = 2, ***k;\n"
17713             "  int &     k   = i;\n"
17714             "  int &&    l   = i + j;\n"
17715             "  int       big = 10000;\n"
17716             "\n"
17717             "  unsigned oneTwoThree = 123;\n"
17718             "  int      oneTwo      = 12;\n"
17719             "  method();\n"
17720             "  float k  = 2;\n"
17721             "  int   ll = 10000;\n"
17722             "}",
17723             format("void SomeFunction(int parameter= 0) {\n"
17724                    " int const  i= 1;\n"
17725                    "  int **j=2,***k;\n"
17726                    "int &k=i;\n"
17727                    "int &&l=i+j;\n"
17728                    " int big  =  10000;\n"
17729                    "\n"
17730                    "unsigned oneTwoThree  =123;\n"
17731                    "int oneTwo = 12;\n"
17732                    "  method();\n"
17733                    "float k= 2;\n"
17734                    "int ll=10000;\n"
17735                    "}",
17736                    AlignmentMiddle));
17737   // variables are aligned at their name, pointers are in the middle
17738   verifyFormat("int *   a;\n"
17739                "int *   b;\n"
17740                "int *** c;\n"
17741                "int     foobar;\n",
17742                AlignmentMiddle);
17743 
17744   Alignment.AlignConsecutiveAssignments.Enabled = false;
17745   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17746   verifyFormat("#define A \\\n"
17747                "  int       aaaa = 12; \\\n"
17748                "  float     b = 23; \\\n"
17749                "  const int ccc = 234; \\\n"
17750                "  unsigned  dddddddddd = 2345;",
17751                Alignment);
17752   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17753   verifyFormat("#define A              \\\n"
17754                "  int       aaaa = 12; \\\n"
17755                "  float     b = 23;    \\\n"
17756                "  const int ccc = 234; \\\n"
17757                "  unsigned  dddddddddd = 2345;",
17758                Alignment);
17759   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17760   Alignment.ColumnLimit = 30;
17761   verifyFormat("#define A                    \\\n"
17762                "  int       aaaa = 12;       \\\n"
17763                "  float     b = 23;          \\\n"
17764                "  const int ccc = 234;       \\\n"
17765                "  int       dddddddddd = 2345;",
17766                Alignment);
17767   Alignment.ColumnLimit = 80;
17768   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17769                "k = 4, int l = 5,\n"
17770                "                  int m = 6) {\n"
17771                "  const int j = 10;\n"
17772                "  otherThing = 1;\n"
17773                "}",
17774                Alignment);
17775   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17776                "  int const i = 1;\n"
17777                "  int      *j = 2;\n"
17778                "  int       big = 10000;\n"
17779                "}",
17780                Alignment);
17781   verifyFormat("class C {\n"
17782                "public:\n"
17783                "  int          i = 1;\n"
17784                "  virtual void f() = 0;\n"
17785                "};",
17786                Alignment);
17787   verifyFormat("float i = 1;\n"
17788                "if (SomeType t = getSomething()) {\n"
17789                "}\n"
17790                "const unsigned j = 2;\n"
17791                "int            big = 10000;",
17792                Alignment);
17793   verifyFormat("float j = 7;\n"
17794                "for (int k = 0; k < N; ++k) {\n"
17795                "}\n"
17796                "unsigned j = 2;\n"
17797                "int      big = 10000;\n"
17798                "}",
17799                Alignment);
17800   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17801   verifyFormat("float              i = 1;\n"
17802                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17803                "    = someLooooooooooooooooongFunction();\n"
17804                "int j = 2;",
17805                Alignment);
17806   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17807   verifyFormat("int                i = 1;\n"
17808                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17809                "    someLooooooooooooooooongFunction();\n"
17810                "int j = 2;",
17811                Alignment);
17812 
17813   Alignment.AlignConsecutiveAssignments.Enabled = true;
17814   verifyFormat("auto lambda = []() {\n"
17815                "  auto  ii = 0;\n"
17816                "  float j  = 0;\n"
17817                "  return 0;\n"
17818                "};\n"
17819                "int   i  = 0;\n"
17820                "float i2 = 0;\n"
17821                "auto  v  = type{\n"
17822                "    i = 1,   //\n"
17823                "    (i = 2), //\n"
17824                "    i = 3    //\n"
17825                "};",
17826                Alignment);
17827   Alignment.AlignConsecutiveAssignments.Enabled = false;
17828 
17829   verifyFormat(
17830       "int      i = 1;\n"
17831       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17832       "                          loooooooooooooooooooooongParameterB);\n"
17833       "int      j = 2;",
17834       Alignment);
17835 
17836   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17837   // We expect declarations and assignments to align, as long as it doesn't
17838   // exceed the column limit, starting a new alignment sequence whenever it
17839   // happens.
17840   Alignment.AlignConsecutiveAssignments.Enabled = true;
17841   Alignment.ColumnLimit = 30;
17842   verifyFormat("float    ii              = 1;\n"
17843                "unsigned j               = 2;\n"
17844                "int someVerylongVariable = 1;\n"
17845                "AnotherLongType  ll = 123456;\n"
17846                "VeryVeryLongType k  = 2;\n"
17847                "int              myvar = 1;",
17848                Alignment);
17849   Alignment.ColumnLimit = 80;
17850   Alignment.AlignConsecutiveAssignments.Enabled = false;
17851 
17852   verifyFormat(
17853       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17854       "          typename LongType, typename B>\n"
17855       "auto foo() {}\n",
17856       Alignment);
17857   verifyFormat("float a, b = 1;\n"
17858                "int   c = 2;\n"
17859                "int   dd = 3;\n",
17860                Alignment);
17861   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17862                "float b[1][] = {{3.f}};\n",
17863                Alignment);
17864   Alignment.AlignConsecutiveAssignments.Enabled = true;
17865   verifyFormat("float a, b = 1;\n"
17866                "int   c  = 2;\n"
17867                "int   dd = 3;\n",
17868                Alignment);
17869   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17870                "float b[1][] = {{3.f}};\n",
17871                Alignment);
17872   Alignment.AlignConsecutiveAssignments.Enabled = false;
17873 
17874   Alignment.ColumnLimit = 30;
17875   Alignment.BinPackParameters = false;
17876   verifyFormat("void foo(float     a,\n"
17877                "         float     b,\n"
17878                "         int       c,\n"
17879                "         uint32_t *d) {\n"
17880                "  int   *e = 0;\n"
17881                "  float  f = 0;\n"
17882                "  double g = 0;\n"
17883                "}\n"
17884                "void bar(ino_t     a,\n"
17885                "         int       b,\n"
17886                "         uint32_t *c,\n"
17887                "         bool      d) {}\n",
17888                Alignment);
17889   Alignment.BinPackParameters = true;
17890   Alignment.ColumnLimit = 80;
17891 
17892   // Bug 33507
17893   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17894   verifyFormat(
17895       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
17896       "  static const Version verVs2017;\n"
17897       "  return true;\n"
17898       "});\n",
17899       Alignment);
17900   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17901 
17902   // See llvm.org/PR35641
17903   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17904   verifyFormat("int func() { //\n"
17905                "  int      b;\n"
17906                "  unsigned c;\n"
17907                "}",
17908                Alignment);
17909 
17910   // See PR37175
17911   FormatStyle Style = getMozillaStyle();
17912   Style.AlignConsecutiveDeclarations.Enabled = true;
17913   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
17914             "foo(int a);",
17915             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
17916 
17917   Alignment.PointerAlignment = FormatStyle::PAS_Left;
17918   verifyFormat("unsigned int*       a;\n"
17919                "int*                b;\n"
17920                "unsigned int Const* c;\n"
17921                "unsigned int const* d;\n"
17922                "unsigned int Const& e;\n"
17923                "unsigned int const& f;",
17924                Alignment);
17925   verifyFormat("Const unsigned int* c;\n"
17926                "const unsigned int* d;\n"
17927                "Const unsigned int& e;\n"
17928                "const unsigned int& f;\n"
17929                "const unsigned      g;\n"
17930                "Const unsigned      h;",
17931                Alignment);
17932 
17933   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17934   verifyFormat("unsigned int *       a;\n"
17935                "int *                b;\n"
17936                "unsigned int Const * c;\n"
17937                "unsigned int const * d;\n"
17938                "unsigned int Const & e;\n"
17939                "unsigned int const & f;",
17940                Alignment);
17941   verifyFormat("Const unsigned int * c;\n"
17942                "const unsigned int * d;\n"
17943                "Const unsigned int & e;\n"
17944                "const unsigned int & f;\n"
17945                "const unsigned       g;\n"
17946                "Const unsigned       h;",
17947                Alignment);
17948 
17949   // See PR46529
17950   FormatStyle BracedAlign = getLLVMStyle();
17951   BracedAlign.AlignConsecutiveDeclarations.Enabled = true;
17952   verifyFormat("const auto result{[]() {\n"
17953                "  const auto something = 1;\n"
17954                "  return 2;\n"
17955                "}};",
17956                BracedAlign);
17957   verifyFormat("int foo{[]() {\n"
17958                "  int bar{0};\n"
17959                "  return 0;\n"
17960                "}()};",
17961                BracedAlign);
17962   BracedAlign.Cpp11BracedListStyle = false;
17963   verifyFormat("const auto result{ []() {\n"
17964                "  const auto something = 1;\n"
17965                "  return 2;\n"
17966                "} };",
17967                BracedAlign);
17968   verifyFormat("int foo{ []() {\n"
17969                "  int bar{ 0 };\n"
17970                "  return 0;\n"
17971                "}() };",
17972                BracedAlign);
17973 }
17974 
17975 TEST_F(FormatTest, AlignWithLineBreaks) {
17976   auto Style = getLLVMStyleWithColumns(120);
17977 
17978   EXPECT_EQ(Style.AlignConsecutiveAssignments,
17979             FormatStyle::AlignConsecutiveStyle(
17980                 {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
17981                  /*AcrossComments=*/false, /*AlignCompound=*/false,
17982                  /*PadOperators=*/true}));
17983   EXPECT_EQ(Style.AlignConsecutiveDeclarations,
17984             FormatStyle::AlignConsecutiveStyle({}));
17985   verifyFormat("void foo() {\n"
17986                "  int myVar = 5;\n"
17987                "  double x = 3.14;\n"
17988                "  auto str = \"Hello \"\n"
17989                "             \"World\";\n"
17990                "  auto s = \"Hello \"\n"
17991                "           \"Again\";\n"
17992                "}",
17993                Style);
17994 
17995   // clang-format off
17996   verifyFormat("void foo() {\n"
17997                "  const int capacityBefore = Entries.capacity();\n"
17998                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17999                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18000                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18001                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18002                "}",
18003                Style);
18004   // clang-format on
18005 
18006   Style.AlignConsecutiveAssignments.Enabled = true;
18007   verifyFormat("void foo() {\n"
18008                "  int myVar = 5;\n"
18009                "  double x  = 3.14;\n"
18010                "  auto str  = \"Hello \"\n"
18011                "              \"World\";\n"
18012                "  auto s    = \"Hello \"\n"
18013                "              \"Again\";\n"
18014                "}",
18015                Style);
18016 
18017   // clang-format off
18018   verifyFormat("void foo() {\n"
18019                "  const int capacityBefore = Entries.capacity();\n"
18020                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18021                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18022                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18023                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18024                "}",
18025                Style);
18026   // clang-format on
18027 
18028   Style.AlignConsecutiveAssignments.Enabled = false;
18029   Style.AlignConsecutiveDeclarations.Enabled = true;
18030   verifyFormat("void foo() {\n"
18031                "  int    myVar = 5;\n"
18032                "  double x = 3.14;\n"
18033                "  auto   str = \"Hello \"\n"
18034                "               \"World\";\n"
18035                "  auto   s = \"Hello \"\n"
18036                "             \"Again\";\n"
18037                "}",
18038                Style);
18039 
18040   // clang-format off
18041   verifyFormat("void foo() {\n"
18042                "  const int  capacityBefore = Entries.capacity();\n"
18043                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18044                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18045                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18046                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18047                "}",
18048                Style);
18049   // clang-format on
18050 
18051   Style.AlignConsecutiveAssignments.Enabled = true;
18052   Style.AlignConsecutiveDeclarations.Enabled = true;
18053 
18054   verifyFormat("void foo() {\n"
18055                "  int    myVar = 5;\n"
18056                "  double x     = 3.14;\n"
18057                "  auto   str   = \"Hello \"\n"
18058                "                 \"World\";\n"
18059                "  auto   s     = \"Hello \"\n"
18060                "                 \"Again\";\n"
18061                "}",
18062                Style);
18063 
18064   // clang-format off
18065   verifyFormat("void foo() {\n"
18066                "  const int  capacityBefore = Entries.capacity();\n"
18067                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18068                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18069                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18070                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18071                "}",
18072                Style);
18073   // clang-format on
18074 
18075   Style = getLLVMStyleWithColumns(20);
18076   Style.AlignConsecutiveAssignments.Enabled = true;
18077   Style.IndentWidth = 4;
18078 
18079   verifyFormat("void foo() {\n"
18080                "    int i1 = 1;\n"
18081                "    int j  = 0;\n"
18082                "    int k  = bar(\n"
18083                "        argument1,\n"
18084                "        argument2);\n"
18085                "}",
18086                Style);
18087 
18088   verifyFormat("unsigned i = 0;\n"
18089                "int a[]    = {\n"
18090                "    1234567890,\n"
18091                "    -1234567890};",
18092                Style);
18093 
18094   Style.ColumnLimit = 120;
18095 
18096   // clang-format off
18097   verifyFormat("void SomeFunc() {\n"
18098                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18099                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18100                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18101                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18102                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18103                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18104                "}",
18105                Style);
18106   // clang-format on
18107 
18108   Style.BinPackArguments = false;
18109 
18110   // clang-format off
18111   verifyFormat("void SomeFunc() {\n"
18112                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
18113                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18114                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
18115                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18116                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
18117                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18118                "}",
18119                Style);
18120   // clang-format on
18121 }
18122 
18123 TEST_F(FormatTest, AlignWithInitializerPeriods) {
18124   auto Style = getLLVMStyleWithColumns(60);
18125 
18126   verifyFormat("void foo1(void) {\n"
18127                "  BYTE p[1] = 1;\n"
18128                "  A B = {.one_foooooooooooooooo = 2,\n"
18129                "         .two_fooooooooooooo = 3,\n"
18130                "         .three_fooooooooooooo = 4};\n"
18131                "  BYTE payload = 2;\n"
18132                "}",
18133                Style);
18134 
18135   Style.AlignConsecutiveAssignments.Enabled = true;
18136   Style.AlignConsecutiveDeclarations.Enabled = false;
18137   verifyFormat("void foo2(void) {\n"
18138                "  BYTE p[1]    = 1;\n"
18139                "  A B          = {.one_foooooooooooooooo = 2,\n"
18140                "                  .two_fooooooooooooo    = 3,\n"
18141                "                  .three_fooooooooooooo  = 4};\n"
18142                "  BYTE payload = 2;\n"
18143                "}",
18144                Style);
18145 
18146   Style.AlignConsecutiveAssignments.Enabled = false;
18147   Style.AlignConsecutiveDeclarations.Enabled = true;
18148   verifyFormat("void foo3(void) {\n"
18149                "  BYTE p[1] = 1;\n"
18150                "  A    B = {.one_foooooooooooooooo = 2,\n"
18151                "            .two_fooooooooooooo = 3,\n"
18152                "            .three_fooooooooooooo = 4};\n"
18153                "  BYTE payload = 2;\n"
18154                "}",
18155                Style);
18156 
18157   Style.AlignConsecutiveAssignments.Enabled = true;
18158   Style.AlignConsecutiveDeclarations.Enabled = true;
18159   verifyFormat("void foo4(void) {\n"
18160                "  BYTE p[1]    = 1;\n"
18161                "  A    B       = {.one_foooooooooooooooo = 2,\n"
18162                "                  .two_fooooooooooooo    = 3,\n"
18163                "                  .three_fooooooooooooo  = 4};\n"
18164                "  BYTE payload = 2;\n"
18165                "}",
18166                Style);
18167 }
18168 
18169 TEST_F(FormatTest, LinuxBraceBreaking) {
18170   FormatStyle LinuxBraceStyle = getLLVMStyle();
18171   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
18172   verifyFormat("namespace a\n"
18173                "{\n"
18174                "class A\n"
18175                "{\n"
18176                "  void f()\n"
18177                "  {\n"
18178                "    if (true) {\n"
18179                "      a();\n"
18180                "      b();\n"
18181                "    } else {\n"
18182                "      a();\n"
18183                "    }\n"
18184                "  }\n"
18185                "  void g() { return; }\n"
18186                "};\n"
18187                "struct B {\n"
18188                "  int x;\n"
18189                "};\n"
18190                "} // namespace a\n",
18191                LinuxBraceStyle);
18192   verifyFormat("enum X {\n"
18193                "  Y = 0,\n"
18194                "}\n",
18195                LinuxBraceStyle);
18196   verifyFormat("struct S {\n"
18197                "  int Type;\n"
18198                "  union {\n"
18199                "    int x;\n"
18200                "    double y;\n"
18201                "  } Value;\n"
18202                "  class C\n"
18203                "  {\n"
18204                "    MyFavoriteType Value;\n"
18205                "  } Class;\n"
18206                "}\n",
18207                LinuxBraceStyle);
18208 }
18209 
18210 TEST_F(FormatTest, MozillaBraceBreaking) {
18211   FormatStyle MozillaBraceStyle = getLLVMStyle();
18212   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
18213   MozillaBraceStyle.FixNamespaceComments = false;
18214   verifyFormat("namespace a {\n"
18215                "class A\n"
18216                "{\n"
18217                "  void f()\n"
18218                "  {\n"
18219                "    if (true) {\n"
18220                "      a();\n"
18221                "      b();\n"
18222                "    }\n"
18223                "  }\n"
18224                "  void g() { return; }\n"
18225                "};\n"
18226                "enum E\n"
18227                "{\n"
18228                "  A,\n"
18229                "  // foo\n"
18230                "  B,\n"
18231                "  C\n"
18232                "};\n"
18233                "struct B\n"
18234                "{\n"
18235                "  int x;\n"
18236                "};\n"
18237                "}\n",
18238                MozillaBraceStyle);
18239   verifyFormat("struct S\n"
18240                "{\n"
18241                "  int Type;\n"
18242                "  union\n"
18243                "  {\n"
18244                "    int x;\n"
18245                "    double y;\n"
18246                "  } Value;\n"
18247                "  class C\n"
18248                "  {\n"
18249                "    MyFavoriteType Value;\n"
18250                "  } Class;\n"
18251                "}\n",
18252                MozillaBraceStyle);
18253 }
18254 
18255 TEST_F(FormatTest, StroustrupBraceBreaking) {
18256   FormatStyle StroustrupBraceStyle = getLLVMStyle();
18257   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18258   verifyFormat("namespace a {\n"
18259                "class A {\n"
18260                "  void f()\n"
18261                "  {\n"
18262                "    if (true) {\n"
18263                "      a();\n"
18264                "      b();\n"
18265                "    }\n"
18266                "  }\n"
18267                "  void g() { return; }\n"
18268                "};\n"
18269                "struct B {\n"
18270                "  int x;\n"
18271                "};\n"
18272                "} // namespace a\n",
18273                StroustrupBraceStyle);
18274 
18275   verifyFormat("void foo()\n"
18276                "{\n"
18277                "  if (a) {\n"
18278                "    a();\n"
18279                "  }\n"
18280                "  else {\n"
18281                "    b();\n"
18282                "  }\n"
18283                "}\n",
18284                StroustrupBraceStyle);
18285 
18286   verifyFormat("#ifdef _DEBUG\n"
18287                "int foo(int i = 0)\n"
18288                "#else\n"
18289                "int foo(int i = 5)\n"
18290                "#endif\n"
18291                "{\n"
18292                "  return i;\n"
18293                "}",
18294                StroustrupBraceStyle);
18295 
18296   verifyFormat("void foo() {}\n"
18297                "void bar()\n"
18298                "#ifdef _DEBUG\n"
18299                "{\n"
18300                "  foo();\n"
18301                "}\n"
18302                "#else\n"
18303                "{\n"
18304                "}\n"
18305                "#endif",
18306                StroustrupBraceStyle);
18307 
18308   verifyFormat("void foobar() { int i = 5; }\n"
18309                "#ifdef _DEBUG\n"
18310                "void bar() {}\n"
18311                "#else\n"
18312                "void bar() { foobar(); }\n"
18313                "#endif",
18314                StroustrupBraceStyle);
18315 }
18316 
18317 TEST_F(FormatTest, AllmanBraceBreaking) {
18318   FormatStyle AllmanBraceStyle = getLLVMStyle();
18319   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
18320 
18321   EXPECT_EQ("namespace a\n"
18322             "{\n"
18323             "void f();\n"
18324             "void g();\n"
18325             "} // namespace a\n",
18326             format("namespace a\n"
18327                    "{\n"
18328                    "void f();\n"
18329                    "void g();\n"
18330                    "}\n",
18331                    AllmanBraceStyle));
18332 
18333   verifyFormat("namespace a\n"
18334                "{\n"
18335                "class A\n"
18336                "{\n"
18337                "  void f()\n"
18338                "  {\n"
18339                "    if (true)\n"
18340                "    {\n"
18341                "      a();\n"
18342                "      b();\n"
18343                "    }\n"
18344                "  }\n"
18345                "  void g() { return; }\n"
18346                "};\n"
18347                "struct B\n"
18348                "{\n"
18349                "  int x;\n"
18350                "};\n"
18351                "union C\n"
18352                "{\n"
18353                "};\n"
18354                "} // namespace a",
18355                AllmanBraceStyle);
18356 
18357   verifyFormat("void f()\n"
18358                "{\n"
18359                "  if (true)\n"
18360                "  {\n"
18361                "    a();\n"
18362                "  }\n"
18363                "  else if (false)\n"
18364                "  {\n"
18365                "    b();\n"
18366                "  }\n"
18367                "  else\n"
18368                "  {\n"
18369                "    c();\n"
18370                "  }\n"
18371                "}\n",
18372                AllmanBraceStyle);
18373 
18374   verifyFormat("void f()\n"
18375                "{\n"
18376                "  for (int i = 0; i < 10; ++i)\n"
18377                "  {\n"
18378                "    a();\n"
18379                "  }\n"
18380                "  while (false)\n"
18381                "  {\n"
18382                "    b();\n"
18383                "  }\n"
18384                "  do\n"
18385                "  {\n"
18386                "    c();\n"
18387                "  } while (false)\n"
18388                "}\n",
18389                AllmanBraceStyle);
18390 
18391   verifyFormat("void f(int a)\n"
18392                "{\n"
18393                "  switch (a)\n"
18394                "  {\n"
18395                "  case 0:\n"
18396                "    break;\n"
18397                "  case 1:\n"
18398                "  {\n"
18399                "    break;\n"
18400                "  }\n"
18401                "  case 2:\n"
18402                "  {\n"
18403                "  }\n"
18404                "  break;\n"
18405                "  default:\n"
18406                "    break;\n"
18407                "  }\n"
18408                "}\n",
18409                AllmanBraceStyle);
18410 
18411   verifyFormat("enum X\n"
18412                "{\n"
18413                "  Y = 0,\n"
18414                "}\n",
18415                AllmanBraceStyle);
18416   verifyFormat("enum X\n"
18417                "{\n"
18418                "  Y = 0\n"
18419                "}\n",
18420                AllmanBraceStyle);
18421 
18422   verifyFormat("@interface BSApplicationController ()\n"
18423                "{\n"
18424                "@private\n"
18425                "  id _extraIvar;\n"
18426                "}\n"
18427                "@end\n",
18428                AllmanBraceStyle);
18429 
18430   verifyFormat("#ifdef _DEBUG\n"
18431                "int foo(int i = 0)\n"
18432                "#else\n"
18433                "int foo(int i = 5)\n"
18434                "#endif\n"
18435                "{\n"
18436                "  return i;\n"
18437                "}",
18438                AllmanBraceStyle);
18439 
18440   verifyFormat("void foo() {}\n"
18441                "void bar()\n"
18442                "#ifdef _DEBUG\n"
18443                "{\n"
18444                "  foo();\n"
18445                "}\n"
18446                "#else\n"
18447                "{\n"
18448                "}\n"
18449                "#endif",
18450                AllmanBraceStyle);
18451 
18452   verifyFormat("void foobar() { int i = 5; }\n"
18453                "#ifdef _DEBUG\n"
18454                "void bar() {}\n"
18455                "#else\n"
18456                "void bar() { foobar(); }\n"
18457                "#endif",
18458                AllmanBraceStyle);
18459 
18460   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18461             FormatStyle::SLS_All);
18462 
18463   verifyFormat("[](int i) { return i + 2; };\n"
18464                "[](int i, int j)\n"
18465                "{\n"
18466                "  auto x = i + j;\n"
18467                "  auto y = i * j;\n"
18468                "  return x ^ y;\n"
18469                "};\n"
18470                "void foo()\n"
18471                "{\n"
18472                "  auto shortLambda = [](int i) { return i + 2; };\n"
18473                "  auto longLambda = [](int i, int j)\n"
18474                "  {\n"
18475                "    auto x = i + j;\n"
18476                "    auto y = i * j;\n"
18477                "    return x ^ y;\n"
18478                "  };\n"
18479                "}",
18480                AllmanBraceStyle);
18481 
18482   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18483 
18484   verifyFormat("[](int i)\n"
18485                "{\n"
18486                "  return i + 2;\n"
18487                "};\n"
18488                "[](int i, int j)\n"
18489                "{\n"
18490                "  auto x = i + j;\n"
18491                "  auto y = i * j;\n"
18492                "  return x ^ y;\n"
18493                "};\n"
18494                "void foo()\n"
18495                "{\n"
18496                "  auto shortLambda = [](int i)\n"
18497                "  {\n"
18498                "    return i + 2;\n"
18499                "  };\n"
18500                "  auto longLambda = [](int i, int j)\n"
18501                "  {\n"
18502                "    auto x = i + j;\n"
18503                "    auto y = i * j;\n"
18504                "    return x ^ y;\n"
18505                "  };\n"
18506                "}",
18507                AllmanBraceStyle);
18508 
18509   // Reset
18510   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18511 
18512   // This shouldn't affect ObjC blocks..
18513   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18514                "  // ...\n"
18515                "  int i;\n"
18516                "}];",
18517                AllmanBraceStyle);
18518   verifyFormat("void (^block)(void) = ^{\n"
18519                "  // ...\n"
18520                "  int i;\n"
18521                "};",
18522                AllmanBraceStyle);
18523   // .. or dict literals.
18524   verifyFormat("void f()\n"
18525                "{\n"
18526                "  // ...\n"
18527                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18528                "}",
18529                AllmanBraceStyle);
18530   verifyFormat("void f()\n"
18531                "{\n"
18532                "  // ...\n"
18533                "  [object someMethod:@{a : @\"b\"}];\n"
18534                "}",
18535                AllmanBraceStyle);
18536   verifyFormat("int f()\n"
18537                "{ // comment\n"
18538                "  return 42;\n"
18539                "}",
18540                AllmanBraceStyle);
18541 
18542   AllmanBraceStyle.ColumnLimit = 19;
18543   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18544   AllmanBraceStyle.ColumnLimit = 18;
18545   verifyFormat("void f()\n"
18546                "{\n"
18547                "  int i;\n"
18548                "}",
18549                AllmanBraceStyle);
18550   AllmanBraceStyle.ColumnLimit = 80;
18551 
18552   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18553   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18554       FormatStyle::SIS_WithoutElse;
18555   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18556   verifyFormat("void f(bool b)\n"
18557                "{\n"
18558                "  if (b)\n"
18559                "  {\n"
18560                "    return;\n"
18561                "  }\n"
18562                "}\n",
18563                BreakBeforeBraceShortIfs);
18564   verifyFormat("void f(bool b)\n"
18565                "{\n"
18566                "  if constexpr (b)\n"
18567                "  {\n"
18568                "    return;\n"
18569                "  }\n"
18570                "}\n",
18571                BreakBeforeBraceShortIfs);
18572   verifyFormat("void f(bool b)\n"
18573                "{\n"
18574                "  if CONSTEXPR (b)\n"
18575                "  {\n"
18576                "    return;\n"
18577                "  }\n"
18578                "}\n",
18579                BreakBeforeBraceShortIfs);
18580   verifyFormat("void f(bool b)\n"
18581                "{\n"
18582                "  if (b) return;\n"
18583                "}\n",
18584                BreakBeforeBraceShortIfs);
18585   verifyFormat("void f(bool b)\n"
18586                "{\n"
18587                "  if constexpr (b) return;\n"
18588                "}\n",
18589                BreakBeforeBraceShortIfs);
18590   verifyFormat("void f(bool b)\n"
18591                "{\n"
18592                "  if CONSTEXPR (b) return;\n"
18593                "}\n",
18594                BreakBeforeBraceShortIfs);
18595   verifyFormat("void f(bool b)\n"
18596                "{\n"
18597                "  while (b)\n"
18598                "  {\n"
18599                "    return;\n"
18600                "  }\n"
18601                "}\n",
18602                BreakBeforeBraceShortIfs);
18603 }
18604 
18605 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18606   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18607   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18608 
18609   // Make a few changes to the style for testing purposes
18610   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18611       FormatStyle::SFS_Empty;
18612   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18613 
18614   // FIXME: this test case can't decide whether there should be a blank line
18615   // after the ~D() line or not. It adds one if one doesn't exist in the test
18616   // and it removes the line if one exists.
18617   /*
18618   verifyFormat("class A;\n"
18619                "namespace B\n"
18620                "  {\n"
18621                "class C;\n"
18622                "// Comment\n"
18623                "class D\n"
18624                "  {\n"
18625                "public:\n"
18626                "  D();\n"
18627                "  ~D() {}\n"
18628                "private:\n"
18629                "  enum E\n"
18630                "    {\n"
18631                "    F\n"
18632                "    }\n"
18633                "  };\n"
18634                "  } // namespace B\n",
18635                WhitesmithsBraceStyle);
18636   */
18637 
18638   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18639   verifyFormat("namespace a\n"
18640                "  {\n"
18641                "class A\n"
18642                "  {\n"
18643                "  void f()\n"
18644                "    {\n"
18645                "    if (true)\n"
18646                "      {\n"
18647                "      a();\n"
18648                "      b();\n"
18649                "      }\n"
18650                "    }\n"
18651                "  void g()\n"
18652                "    {\n"
18653                "    return;\n"
18654                "    }\n"
18655                "  };\n"
18656                "struct B\n"
18657                "  {\n"
18658                "  int x;\n"
18659                "  };\n"
18660                "  } // namespace a",
18661                WhitesmithsBraceStyle);
18662 
18663   verifyFormat("namespace a\n"
18664                "  {\n"
18665                "namespace b\n"
18666                "  {\n"
18667                "class A\n"
18668                "  {\n"
18669                "  void f()\n"
18670                "    {\n"
18671                "    if (true)\n"
18672                "      {\n"
18673                "      a();\n"
18674                "      b();\n"
18675                "      }\n"
18676                "    }\n"
18677                "  void g()\n"
18678                "    {\n"
18679                "    return;\n"
18680                "    }\n"
18681                "  };\n"
18682                "struct B\n"
18683                "  {\n"
18684                "  int x;\n"
18685                "  };\n"
18686                "  } // namespace b\n"
18687                "  } // namespace a",
18688                WhitesmithsBraceStyle);
18689 
18690   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18691   verifyFormat("namespace a\n"
18692                "  {\n"
18693                "namespace b\n"
18694                "  {\n"
18695                "  class A\n"
18696                "    {\n"
18697                "    void f()\n"
18698                "      {\n"
18699                "      if (true)\n"
18700                "        {\n"
18701                "        a();\n"
18702                "        b();\n"
18703                "        }\n"
18704                "      }\n"
18705                "    void g()\n"
18706                "      {\n"
18707                "      return;\n"
18708                "      }\n"
18709                "    };\n"
18710                "  struct B\n"
18711                "    {\n"
18712                "    int x;\n"
18713                "    };\n"
18714                "  } // namespace b\n"
18715                "  } // namespace a",
18716                WhitesmithsBraceStyle);
18717 
18718   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18719   verifyFormat("namespace a\n"
18720                "  {\n"
18721                "  namespace b\n"
18722                "    {\n"
18723                "    class A\n"
18724                "      {\n"
18725                "      void f()\n"
18726                "        {\n"
18727                "        if (true)\n"
18728                "          {\n"
18729                "          a();\n"
18730                "          b();\n"
18731                "          }\n"
18732                "        }\n"
18733                "      void g()\n"
18734                "        {\n"
18735                "        return;\n"
18736                "        }\n"
18737                "      };\n"
18738                "    struct B\n"
18739                "      {\n"
18740                "      int x;\n"
18741                "      };\n"
18742                "    } // namespace b\n"
18743                "  }   // namespace a",
18744                WhitesmithsBraceStyle);
18745 
18746   verifyFormat("void f()\n"
18747                "  {\n"
18748                "  if (true)\n"
18749                "    {\n"
18750                "    a();\n"
18751                "    }\n"
18752                "  else if (false)\n"
18753                "    {\n"
18754                "    b();\n"
18755                "    }\n"
18756                "  else\n"
18757                "    {\n"
18758                "    c();\n"
18759                "    }\n"
18760                "  }\n",
18761                WhitesmithsBraceStyle);
18762 
18763   verifyFormat("void f()\n"
18764                "  {\n"
18765                "  for (int i = 0; i < 10; ++i)\n"
18766                "    {\n"
18767                "    a();\n"
18768                "    }\n"
18769                "  while (false)\n"
18770                "    {\n"
18771                "    b();\n"
18772                "    }\n"
18773                "  do\n"
18774                "    {\n"
18775                "    c();\n"
18776                "    } while (false)\n"
18777                "  }\n",
18778                WhitesmithsBraceStyle);
18779 
18780   WhitesmithsBraceStyle.IndentCaseLabels = true;
18781   verifyFormat("void switchTest1(int a)\n"
18782                "  {\n"
18783                "  switch (a)\n"
18784                "    {\n"
18785                "    case 2:\n"
18786                "      {\n"
18787                "      }\n"
18788                "      break;\n"
18789                "    }\n"
18790                "  }\n",
18791                WhitesmithsBraceStyle);
18792 
18793   verifyFormat("void switchTest2(int a)\n"
18794                "  {\n"
18795                "  switch (a)\n"
18796                "    {\n"
18797                "    case 0:\n"
18798                "      break;\n"
18799                "    case 1:\n"
18800                "      {\n"
18801                "      break;\n"
18802                "      }\n"
18803                "    case 2:\n"
18804                "      {\n"
18805                "      }\n"
18806                "      break;\n"
18807                "    default:\n"
18808                "      break;\n"
18809                "    }\n"
18810                "  }\n",
18811                WhitesmithsBraceStyle);
18812 
18813   verifyFormat("void switchTest3(int a)\n"
18814                "  {\n"
18815                "  switch (a)\n"
18816                "    {\n"
18817                "    case 0:\n"
18818                "      {\n"
18819                "      foo(x);\n"
18820                "      }\n"
18821                "      break;\n"
18822                "    default:\n"
18823                "      {\n"
18824                "      foo(1);\n"
18825                "      }\n"
18826                "      break;\n"
18827                "    }\n"
18828                "  }\n",
18829                WhitesmithsBraceStyle);
18830 
18831   WhitesmithsBraceStyle.IndentCaseLabels = false;
18832 
18833   verifyFormat("void switchTest4(int a)\n"
18834                "  {\n"
18835                "  switch (a)\n"
18836                "    {\n"
18837                "  case 2:\n"
18838                "    {\n"
18839                "    }\n"
18840                "    break;\n"
18841                "    }\n"
18842                "  }\n",
18843                WhitesmithsBraceStyle);
18844 
18845   verifyFormat("void switchTest5(int a)\n"
18846                "  {\n"
18847                "  switch (a)\n"
18848                "    {\n"
18849                "  case 0:\n"
18850                "    break;\n"
18851                "  case 1:\n"
18852                "    {\n"
18853                "    foo();\n"
18854                "    break;\n"
18855                "    }\n"
18856                "  case 2:\n"
18857                "    {\n"
18858                "    }\n"
18859                "    break;\n"
18860                "  default:\n"
18861                "    break;\n"
18862                "    }\n"
18863                "  }\n",
18864                WhitesmithsBraceStyle);
18865 
18866   verifyFormat("void switchTest6(int a)\n"
18867                "  {\n"
18868                "  switch (a)\n"
18869                "    {\n"
18870                "  case 0:\n"
18871                "    {\n"
18872                "    foo(x);\n"
18873                "    }\n"
18874                "    break;\n"
18875                "  default:\n"
18876                "    {\n"
18877                "    foo(1);\n"
18878                "    }\n"
18879                "    break;\n"
18880                "    }\n"
18881                "  }\n",
18882                WhitesmithsBraceStyle);
18883 
18884   verifyFormat("enum X\n"
18885                "  {\n"
18886                "  Y = 0, // testing\n"
18887                "  }\n",
18888                WhitesmithsBraceStyle);
18889 
18890   verifyFormat("enum X\n"
18891                "  {\n"
18892                "  Y = 0\n"
18893                "  }\n",
18894                WhitesmithsBraceStyle);
18895   verifyFormat("enum X\n"
18896                "  {\n"
18897                "  Y = 0,\n"
18898                "  Z = 1\n"
18899                "  };\n",
18900                WhitesmithsBraceStyle);
18901 
18902   verifyFormat("@interface BSApplicationController ()\n"
18903                "  {\n"
18904                "@private\n"
18905                "  id _extraIvar;\n"
18906                "  }\n"
18907                "@end\n",
18908                WhitesmithsBraceStyle);
18909 
18910   verifyFormat("#ifdef _DEBUG\n"
18911                "int foo(int i = 0)\n"
18912                "#else\n"
18913                "int foo(int i = 5)\n"
18914                "#endif\n"
18915                "  {\n"
18916                "  return i;\n"
18917                "  }",
18918                WhitesmithsBraceStyle);
18919 
18920   verifyFormat("void foo() {}\n"
18921                "void bar()\n"
18922                "#ifdef _DEBUG\n"
18923                "  {\n"
18924                "  foo();\n"
18925                "  }\n"
18926                "#else\n"
18927                "  {\n"
18928                "  }\n"
18929                "#endif",
18930                WhitesmithsBraceStyle);
18931 
18932   verifyFormat("void foobar()\n"
18933                "  {\n"
18934                "  int i = 5;\n"
18935                "  }\n"
18936                "#ifdef _DEBUG\n"
18937                "void bar()\n"
18938                "  {\n"
18939                "  }\n"
18940                "#else\n"
18941                "void bar()\n"
18942                "  {\n"
18943                "  foobar();\n"
18944                "  }\n"
18945                "#endif",
18946                WhitesmithsBraceStyle);
18947 
18948   // This shouldn't affect ObjC blocks..
18949   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18950                "  // ...\n"
18951                "  int i;\n"
18952                "}];",
18953                WhitesmithsBraceStyle);
18954   verifyFormat("void (^block)(void) = ^{\n"
18955                "  // ...\n"
18956                "  int i;\n"
18957                "};",
18958                WhitesmithsBraceStyle);
18959   // .. or dict literals.
18960   verifyFormat("void f()\n"
18961                "  {\n"
18962                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18963                "  }",
18964                WhitesmithsBraceStyle);
18965 
18966   verifyFormat("int f()\n"
18967                "  { // comment\n"
18968                "  return 42;\n"
18969                "  }",
18970                WhitesmithsBraceStyle);
18971 
18972   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
18973   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18974       FormatStyle::SIS_OnlyFirstIf;
18975   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18976   verifyFormat("void f(bool b)\n"
18977                "  {\n"
18978                "  if (b)\n"
18979                "    {\n"
18980                "    return;\n"
18981                "    }\n"
18982                "  }\n",
18983                BreakBeforeBraceShortIfs);
18984   verifyFormat("void f(bool b)\n"
18985                "  {\n"
18986                "  if (b) return;\n"
18987                "  }\n",
18988                BreakBeforeBraceShortIfs);
18989   verifyFormat("void f(bool b)\n"
18990                "  {\n"
18991                "  while (b)\n"
18992                "    {\n"
18993                "    return;\n"
18994                "    }\n"
18995                "  }\n",
18996                BreakBeforeBraceShortIfs);
18997 }
18998 
18999 TEST_F(FormatTest, GNUBraceBreaking) {
19000   FormatStyle GNUBraceStyle = getLLVMStyle();
19001   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
19002   verifyFormat("namespace a\n"
19003                "{\n"
19004                "class A\n"
19005                "{\n"
19006                "  void f()\n"
19007                "  {\n"
19008                "    int a;\n"
19009                "    {\n"
19010                "      int b;\n"
19011                "    }\n"
19012                "    if (true)\n"
19013                "      {\n"
19014                "        a();\n"
19015                "        b();\n"
19016                "      }\n"
19017                "  }\n"
19018                "  void g() { return; }\n"
19019                "}\n"
19020                "} // namespace a",
19021                GNUBraceStyle);
19022 
19023   verifyFormat("void f()\n"
19024                "{\n"
19025                "  if (true)\n"
19026                "    {\n"
19027                "      a();\n"
19028                "    }\n"
19029                "  else if (false)\n"
19030                "    {\n"
19031                "      b();\n"
19032                "    }\n"
19033                "  else\n"
19034                "    {\n"
19035                "      c();\n"
19036                "    }\n"
19037                "}\n",
19038                GNUBraceStyle);
19039 
19040   verifyFormat("void f()\n"
19041                "{\n"
19042                "  for (int i = 0; i < 10; ++i)\n"
19043                "    {\n"
19044                "      a();\n"
19045                "    }\n"
19046                "  while (false)\n"
19047                "    {\n"
19048                "      b();\n"
19049                "    }\n"
19050                "  do\n"
19051                "    {\n"
19052                "      c();\n"
19053                "    }\n"
19054                "  while (false);\n"
19055                "}\n",
19056                GNUBraceStyle);
19057 
19058   verifyFormat("void f(int a)\n"
19059                "{\n"
19060                "  switch (a)\n"
19061                "    {\n"
19062                "    case 0:\n"
19063                "      break;\n"
19064                "    case 1:\n"
19065                "      {\n"
19066                "        break;\n"
19067                "      }\n"
19068                "    case 2:\n"
19069                "      {\n"
19070                "      }\n"
19071                "      break;\n"
19072                "    default:\n"
19073                "      break;\n"
19074                "    }\n"
19075                "}\n",
19076                GNUBraceStyle);
19077 
19078   verifyFormat("enum X\n"
19079                "{\n"
19080                "  Y = 0,\n"
19081                "}\n",
19082                GNUBraceStyle);
19083 
19084   verifyFormat("@interface BSApplicationController ()\n"
19085                "{\n"
19086                "@private\n"
19087                "  id _extraIvar;\n"
19088                "}\n"
19089                "@end\n",
19090                GNUBraceStyle);
19091 
19092   verifyFormat("#ifdef _DEBUG\n"
19093                "int foo(int i = 0)\n"
19094                "#else\n"
19095                "int foo(int i = 5)\n"
19096                "#endif\n"
19097                "{\n"
19098                "  return i;\n"
19099                "}",
19100                GNUBraceStyle);
19101 
19102   verifyFormat("void foo() {}\n"
19103                "void bar()\n"
19104                "#ifdef _DEBUG\n"
19105                "{\n"
19106                "  foo();\n"
19107                "}\n"
19108                "#else\n"
19109                "{\n"
19110                "}\n"
19111                "#endif",
19112                GNUBraceStyle);
19113 
19114   verifyFormat("void foobar() { int i = 5; }\n"
19115                "#ifdef _DEBUG\n"
19116                "void bar() {}\n"
19117                "#else\n"
19118                "void bar() { foobar(); }\n"
19119                "#endif",
19120                GNUBraceStyle);
19121 }
19122 
19123 TEST_F(FormatTest, WebKitBraceBreaking) {
19124   FormatStyle WebKitBraceStyle = getLLVMStyle();
19125   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
19126   WebKitBraceStyle.FixNamespaceComments = false;
19127   verifyFormat("namespace a {\n"
19128                "class A {\n"
19129                "  void f()\n"
19130                "  {\n"
19131                "    if (true) {\n"
19132                "      a();\n"
19133                "      b();\n"
19134                "    }\n"
19135                "  }\n"
19136                "  void g() { return; }\n"
19137                "};\n"
19138                "enum E {\n"
19139                "  A,\n"
19140                "  // foo\n"
19141                "  B,\n"
19142                "  C\n"
19143                "};\n"
19144                "struct B {\n"
19145                "  int x;\n"
19146                "};\n"
19147                "}\n",
19148                WebKitBraceStyle);
19149   verifyFormat("struct S {\n"
19150                "  int Type;\n"
19151                "  union {\n"
19152                "    int x;\n"
19153                "    double y;\n"
19154                "  } Value;\n"
19155                "  class C {\n"
19156                "    MyFavoriteType Value;\n"
19157                "  } Class;\n"
19158                "};\n",
19159                WebKitBraceStyle);
19160 }
19161 
19162 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
19163   verifyFormat("void f() {\n"
19164                "  try {\n"
19165                "  } catch (const Exception &e) {\n"
19166                "  }\n"
19167                "}\n",
19168                getLLVMStyle());
19169 }
19170 
19171 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
19172   auto Style = getLLVMStyle();
19173   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19174   Style.AlignConsecutiveAssignments.Enabled = true;
19175   Style.AlignConsecutiveDeclarations.Enabled = true;
19176   verifyFormat("struct test demo[] = {\n"
19177                "    {56,    23, \"hello\"},\n"
19178                "    {-1, 93463, \"world\"},\n"
19179                "    { 7,     5,    \"!!\"}\n"
19180                "};\n",
19181                Style);
19182 
19183   verifyFormat("struct test demo[] = {\n"
19184                "    {56,    23, \"hello\"}, // first line\n"
19185                "    {-1, 93463, \"world\"}, // second line\n"
19186                "    { 7,     5,    \"!!\"}  // third line\n"
19187                "};\n",
19188                Style);
19189 
19190   verifyFormat("struct test demo[4] = {\n"
19191                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19192                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19193                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19194                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19195                "};\n",
19196                Style);
19197 
19198   verifyFormat("struct test demo[3] = {\n"
19199                "    {56,    23, \"hello\"},\n"
19200                "    {-1, 93463, \"world\"},\n"
19201                "    { 7,     5,    \"!!\"}\n"
19202                "};\n",
19203                Style);
19204 
19205   verifyFormat("struct test demo[3] = {\n"
19206                "    {int{56},    23, \"hello\"},\n"
19207                "    {int{-1}, 93463, \"world\"},\n"
19208                "    { int{7},     5,    \"!!\"}\n"
19209                "};\n",
19210                Style);
19211 
19212   verifyFormat("struct test demo[] = {\n"
19213                "    {56,    23, \"hello\"},\n"
19214                "    {-1, 93463, \"world\"},\n"
19215                "    { 7,     5,    \"!!\"},\n"
19216                "};\n",
19217                Style);
19218 
19219   verifyFormat("test demo[] = {\n"
19220                "    {56,    23, \"hello\"},\n"
19221                "    {-1, 93463, \"world\"},\n"
19222                "    { 7,     5,    \"!!\"},\n"
19223                "};\n",
19224                Style);
19225 
19226   verifyFormat("demo = std::array<struct test, 3>{\n"
19227                "    test{56,    23, \"hello\"},\n"
19228                "    test{-1, 93463, \"world\"},\n"
19229                "    test{ 7,     5,    \"!!\"},\n"
19230                "};\n",
19231                Style);
19232 
19233   verifyFormat("test demo[] = {\n"
19234                "    {56,    23, \"hello\"},\n"
19235                "#if X\n"
19236                "    {-1, 93463, \"world\"},\n"
19237                "#endif\n"
19238                "    { 7,     5,    \"!!\"}\n"
19239                "};\n",
19240                Style);
19241 
19242   verifyFormat(
19243       "test demo[] = {\n"
19244       "    { 7,    23,\n"
19245       "     \"hello world i am a very long line that really, in any\"\n"
19246       "     \"just world, ought to be split over multiple lines\"},\n"
19247       "    {-1, 93463,                                  \"world\"},\n"
19248       "    {56,     5,                                     \"!!\"}\n"
19249       "};\n",
19250       Style);
19251 
19252   verifyFormat("return GradForUnaryCwise(g, {\n"
19253                "                                {{\"sign\"}, \"Sign\",  "
19254                "  {\"x\", \"dy\"}},\n"
19255                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
19256                ", \"sign\"}},\n"
19257                "});\n",
19258                Style);
19259 
19260   Style.ColumnLimit = 0;
19261   EXPECT_EQ(
19262       "test demo[] = {\n"
19263       "    {56,    23, \"hello world i am a very long line that really, "
19264       "in any just world, ought to be split over multiple lines\"},\n"
19265       "    {-1, 93463,                                                  "
19266       "                                                 \"world\"},\n"
19267       "    { 7,     5,                                                  "
19268       "                                                    \"!!\"},\n"
19269       "};",
19270       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19271              "that really, in any just world, ought to be split over multiple "
19272              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19273              Style));
19274 
19275   Style.ColumnLimit = 80;
19276   verifyFormat("test demo[] = {\n"
19277                "    {56,    23, /* a comment */ \"hello\"},\n"
19278                "    {-1, 93463,                 \"world\"},\n"
19279                "    { 7,     5,                    \"!!\"}\n"
19280                "};\n",
19281                Style);
19282 
19283   verifyFormat("test demo[] = {\n"
19284                "    {56,    23,                    \"hello\"},\n"
19285                "    {-1, 93463, \"world\" /* comment here */},\n"
19286                "    { 7,     5,                       \"!!\"}\n"
19287                "};\n",
19288                Style);
19289 
19290   verifyFormat("test demo[] = {\n"
19291                "    {56, /* a comment */ 23, \"hello\"},\n"
19292                "    {-1,              93463, \"world\"},\n"
19293                "    { 7,                  5,    \"!!\"}\n"
19294                "};\n",
19295                Style);
19296 
19297   Style.ColumnLimit = 20;
19298   EXPECT_EQ(
19299       "demo = std::array<\n"
19300       "    struct test, 3>{\n"
19301       "    test{\n"
19302       "         56,    23,\n"
19303       "         \"hello \"\n"
19304       "         \"world i \"\n"
19305       "         \"am a very \"\n"
19306       "         \"long line \"\n"
19307       "         \"that \"\n"
19308       "         \"really, \"\n"
19309       "         \"in any \"\n"
19310       "         \"just \"\n"
19311       "         \"world, \"\n"
19312       "         \"ought to \"\n"
19313       "         \"be split \"\n"
19314       "         \"over \"\n"
19315       "         \"multiple \"\n"
19316       "         \"lines\"},\n"
19317       "    test{-1, 93463,\n"
19318       "         \"world\"},\n"
19319       "    test{ 7,     5,\n"
19320       "         \"!!\"   },\n"
19321       "};",
19322       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19323              "i am a very long line that really, in any just world, ought "
19324              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19325              "test{7, 5, \"!!\"},};",
19326              Style));
19327   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19328   Style = getLLVMStyleWithColumns(50);
19329   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19330   verifyFormat("static A x = {\n"
19331                "    {{init1, init2, init3, init4},\n"
19332                "     {init1, init2, init3, init4}}\n"
19333                "};",
19334                Style);
19335   // TODO: Fix the indentations below when this option is fully functional.
19336   verifyFormat("int a[][] = {\n"
19337                "    {\n"
19338                "     {0, 2}, //\n"
19339                " {1, 2}  //\n"
19340                "    }\n"
19341                "};",
19342                Style);
19343   Style.ColumnLimit = 100;
19344   EXPECT_EQ(
19345       "test demo[] = {\n"
19346       "    {56,    23,\n"
19347       "     \"hello world i am a very long line that really, in any just world"
19348       ", ought to be split over \"\n"
19349       "     \"multiple lines\"  },\n"
19350       "    {-1, 93463, \"world\"},\n"
19351       "    { 7,     5,    \"!!\"},\n"
19352       "};",
19353       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19354              "that really, in any just world, ought to be split over multiple "
19355              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19356              Style));
19357 
19358   Style = getLLVMStyleWithColumns(50);
19359   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19360   verifyFormat("struct test demo[] = {\n"
19361                "    {56,    23, \"hello\"},\n"
19362                "    {-1, 93463, \"world\"},\n"
19363                "    { 7,     5,    \"!!\"}\n"
19364                "};\n"
19365                "static A x = {\n"
19366                "    {{init1, init2, init3, init4},\n"
19367                "     {init1, init2, init3, init4}}\n"
19368                "};",
19369                Style);
19370   Style.ColumnLimit = 100;
19371   Style.AlignConsecutiveAssignments.AcrossComments = true;
19372   Style.AlignConsecutiveDeclarations.AcrossComments = true;
19373   verifyFormat("struct test demo[] = {\n"
19374                "    {56,    23, \"hello\"},\n"
19375                "    {-1, 93463, \"world\"},\n"
19376                "    { 7,     5,    \"!!\"}\n"
19377                "};\n"
19378                "struct test demo[4] = {\n"
19379                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19380                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19381                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19382                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19383                "};\n",
19384                Style);
19385   EXPECT_EQ(
19386       "test demo[] = {\n"
19387       "    {56,\n"
19388       "     \"hello world i am a very long line that really, in any just world"
19389       ", ought to be split over \"\n"
19390       "     \"multiple lines\",    23},\n"
19391       "    {-1,      \"world\", 93463},\n"
19392       "    { 7,         \"!!\",     5},\n"
19393       "};",
19394       format("test demo[] = {{56, \"hello world i am a very long line "
19395              "that really, in any just world, ought to be split over multiple "
19396              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
19397              Style));
19398 }
19399 
19400 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
19401   auto Style = getLLVMStyle();
19402   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19403   /* FIXME: This case gets misformatted.
19404   verifyFormat("auto foo = Items{\n"
19405                "    Section{0, bar(), },\n"
19406                "    Section{1, boo()  }\n"
19407                "};\n",
19408                Style);
19409   */
19410   verifyFormat("auto foo = Items{\n"
19411                "    Section{\n"
19412                "            0, bar(),\n"
19413                "            }\n"
19414                "};\n",
19415                Style);
19416   verifyFormat("struct test demo[] = {\n"
19417                "    {56, 23,    \"hello\"},\n"
19418                "    {-1, 93463, \"world\"},\n"
19419                "    {7,  5,     \"!!\"   }\n"
19420                "};\n",
19421                Style);
19422   verifyFormat("struct test demo[] = {\n"
19423                "    {56, 23,    \"hello\"}, // first line\n"
19424                "    {-1, 93463, \"world\"}, // second line\n"
19425                "    {7,  5,     \"!!\"   }  // third line\n"
19426                "};\n",
19427                Style);
19428   verifyFormat("struct test demo[4] = {\n"
19429                "    {56,  23,    21, \"oh\"      }, // first line\n"
19430                "    {-1,  93463, 22, \"my\"      }, // second line\n"
19431                "    {7,   5,     1,  \"goodness\"}  // third line\n"
19432                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
19433                "};\n",
19434                Style);
19435   verifyFormat("struct test demo[3] = {\n"
19436                "    {56, 23,    \"hello\"},\n"
19437                "    {-1, 93463, \"world\"},\n"
19438                "    {7,  5,     \"!!\"   }\n"
19439                "};\n",
19440                Style);
19441 
19442   verifyFormat("struct test demo[3] = {\n"
19443                "    {int{56}, 23,    \"hello\"},\n"
19444                "    {int{-1}, 93463, \"world\"},\n"
19445                "    {int{7},  5,     \"!!\"   }\n"
19446                "};\n",
19447                Style);
19448   verifyFormat("struct test demo[] = {\n"
19449                "    {56, 23,    \"hello\"},\n"
19450                "    {-1, 93463, \"world\"},\n"
19451                "    {7,  5,     \"!!\"   },\n"
19452                "};\n",
19453                Style);
19454   verifyFormat("test demo[] = {\n"
19455                "    {56, 23,    \"hello\"},\n"
19456                "    {-1, 93463, \"world\"},\n"
19457                "    {7,  5,     \"!!\"   },\n"
19458                "};\n",
19459                Style);
19460   verifyFormat("demo = std::array<struct test, 3>{\n"
19461                "    test{56, 23,    \"hello\"},\n"
19462                "    test{-1, 93463, \"world\"},\n"
19463                "    test{7,  5,     \"!!\"   },\n"
19464                "};\n",
19465                Style);
19466   verifyFormat("test demo[] = {\n"
19467                "    {56, 23,    \"hello\"},\n"
19468                "#if X\n"
19469                "    {-1, 93463, \"world\"},\n"
19470                "#endif\n"
19471                "    {7,  5,     \"!!\"   }\n"
19472                "};\n",
19473                Style);
19474   verifyFormat(
19475       "test demo[] = {\n"
19476       "    {7,  23,\n"
19477       "     \"hello world i am a very long line that really, in any\"\n"
19478       "     \"just world, ought to be split over multiple lines\"},\n"
19479       "    {-1, 93463, \"world\"                                 },\n"
19480       "    {56, 5,     \"!!\"                                    }\n"
19481       "};\n",
19482       Style);
19483 
19484   verifyFormat("return GradForUnaryCwise(g, {\n"
19485                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19486                "\"dy\"}   },\n"
19487                "                                {{\"dx\"},   \"Mul\",  "
19488                "{\"dy\", \"sign\"}},\n"
19489                "});\n",
19490                Style);
19491 
19492   Style.ColumnLimit = 0;
19493   EXPECT_EQ(
19494       "test demo[] = {\n"
19495       "    {56, 23,    \"hello world i am a very long line that really, in any "
19496       "just world, ought to be split over multiple lines\"},\n"
19497       "    {-1, 93463, \"world\"                                               "
19498       "                                                   },\n"
19499       "    {7,  5,     \"!!\"                                                  "
19500       "                                                   },\n"
19501       "};",
19502       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19503              "that really, in any just world, ought to be split over multiple "
19504              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19505              Style));
19506 
19507   Style.ColumnLimit = 80;
19508   verifyFormat("test demo[] = {\n"
19509                "    {56, 23,    /* a comment */ \"hello\"},\n"
19510                "    {-1, 93463, \"world\"                },\n"
19511                "    {7,  5,     \"!!\"                   }\n"
19512                "};\n",
19513                Style);
19514 
19515   verifyFormat("test demo[] = {\n"
19516                "    {56, 23,    \"hello\"                   },\n"
19517                "    {-1, 93463, \"world\" /* comment here */},\n"
19518                "    {7,  5,     \"!!\"                      }\n"
19519                "};\n",
19520                Style);
19521 
19522   verifyFormat("test demo[] = {\n"
19523                "    {56, /* a comment */ 23, \"hello\"},\n"
19524                "    {-1, 93463,              \"world\"},\n"
19525                "    {7,  5,                  \"!!\"   }\n"
19526                "};\n",
19527                Style);
19528 
19529   Style.ColumnLimit = 20;
19530   EXPECT_EQ(
19531       "demo = std::array<\n"
19532       "    struct test, 3>{\n"
19533       "    test{\n"
19534       "         56, 23,\n"
19535       "         \"hello \"\n"
19536       "         \"world i \"\n"
19537       "         \"am a very \"\n"
19538       "         \"long line \"\n"
19539       "         \"that \"\n"
19540       "         \"really, \"\n"
19541       "         \"in any \"\n"
19542       "         \"just \"\n"
19543       "         \"world, \"\n"
19544       "         \"ought to \"\n"
19545       "         \"be split \"\n"
19546       "         \"over \"\n"
19547       "         \"multiple \"\n"
19548       "         \"lines\"},\n"
19549       "    test{-1, 93463,\n"
19550       "         \"world\"},\n"
19551       "    test{7,  5,\n"
19552       "         \"!!\"   },\n"
19553       "};",
19554       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19555              "i am a very long line that really, in any just world, ought "
19556              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19557              "test{7, 5, \"!!\"},};",
19558              Style));
19559 
19560   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19561   Style = getLLVMStyleWithColumns(50);
19562   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19563   verifyFormat("static A x = {\n"
19564                "    {{init1, init2, init3, init4},\n"
19565                "     {init1, init2, init3, init4}}\n"
19566                "};",
19567                Style);
19568   Style.ColumnLimit = 100;
19569   EXPECT_EQ(
19570       "test demo[] = {\n"
19571       "    {56, 23,\n"
19572       "     \"hello world i am a very long line that really, in any just world"
19573       ", ought to be split over \"\n"
19574       "     \"multiple lines\"  },\n"
19575       "    {-1, 93463, \"world\"},\n"
19576       "    {7,  5,     \"!!\"   },\n"
19577       "};",
19578       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19579              "that really, in any just world, ought to be split over multiple "
19580              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19581              Style));
19582 }
19583 
19584 TEST_F(FormatTest, UnderstandsPragmas) {
19585   verifyFormat("#pragma omp reduction(| : var)");
19586   verifyFormat("#pragma omp reduction(+ : var)");
19587 
19588   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19589             "(including parentheses).",
19590             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19591                    "(including parentheses)."));
19592 }
19593 
19594 TEST_F(FormatTest, UnderstandPragmaOption) {
19595   verifyFormat("#pragma option -C -A");
19596 
19597   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19598 }
19599 
19600 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19601   FormatStyle Style = getLLVMStyleWithColumns(20);
19602 
19603   // See PR41213
19604   EXPECT_EQ("/*\n"
19605             " *\t9012345\n"
19606             " * /8901\n"
19607             " */",
19608             format("/*\n"
19609                    " *\t9012345 /8901\n"
19610                    " */",
19611                    Style));
19612   EXPECT_EQ("/*\n"
19613             " *345678\n"
19614             " *\t/8901\n"
19615             " */",
19616             format("/*\n"
19617                    " *345678\t/8901\n"
19618                    " */",
19619                    Style));
19620 
19621   verifyFormat("int a; // the\n"
19622                "       // comment",
19623                Style);
19624   EXPECT_EQ("int a; /* first line\n"
19625             "        * second\n"
19626             "        * line third\n"
19627             "        * line\n"
19628             "        */",
19629             format("int a; /* first line\n"
19630                    "        * second\n"
19631                    "        * line third\n"
19632                    "        * line\n"
19633                    "        */",
19634                    Style));
19635   EXPECT_EQ("int a; // first line\n"
19636             "       // second\n"
19637             "       // line third\n"
19638             "       // line",
19639             format("int a; // first line\n"
19640                    "       // second line\n"
19641                    "       // third line",
19642                    Style));
19643 
19644   Style.PenaltyExcessCharacter = 90;
19645   verifyFormat("int a; // the comment", Style);
19646   EXPECT_EQ("int a; // the comment\n"
19647             "       // aaa",
19648             format("int a; // the comment aaa", Style));
19649   EXPECT_EQ("int a; /* first line\n"
19650             "        * second line\n"
19651             "        * third line\n"
19652             "        */",
19653             format("int a; /* first line\n"
19654                    "        * second line\n"
19655                    "        * third line\n"
19656                    "        */",
19657                    Style));
19658   EXPECT_EQ("int a; // first line\n"
19659             "       // second line\n"
19660             "       // third line",
19661             format("int a; // first line\n"
19662                    "       // second line\n"
19663                    "       // third line",
19664                    Style));
19665   // FIXME: Investigate why this is not getting the same layout as the test
19666   // above.
19667   EXPECT_EQ("int a; /* first line\n"
19668             "        * second line\n"
19669             "        * third line\n"
19670             "        */",
19671             format("int a; /* first line second line third line"
19672                    "\n*/",
19673                    Style));
19674 
19675   EXPECT_EQ("// foo bar baz bazfoo\n"
19676             "// foo bar foo bar\n",
19677             format("// foo bar baz bazfoo\n"
19678                    "// foo bar foo           bar\n",
19679                    Style));
19680   EXPECT_EQ("// foo bar baz bazfoo\n"
19681             "// foo bar foo bar\n",
19682             format("// foo bar baz      bazfoo\n"
19683                    "// foo            bar foo bar\n",
19684                    Style));
19685 
19686   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19687   // next one.
19688   EXPECT_EQ("// foo bar baz bazfoo\n"
19689             "// bar foo bar\n",
19690             format("// foo bar baz      bazfoo bar\n"
19691                    "// foo            bar\n",
19692                    Style));
19693 
19694   EXPECT_EQ("// foo bar baz bazfoo\n"
19695             "// foo bar baz bazfoo\n"
19696             "// bar foo bar\n",
19697             format("// foo bar baz      bazfoo\n"
19698                    "// foo bar baz      bazfoo bar\n"
19699                    "// foo bar\n",
19700                    Style));
19701 
19702   EXPECT_EQ("// foo bar baz bazfoo\n"
19703             "// foo bar baz bazfoo\n"
19704             "// bar foo bar\n",
19705             format("// foo bar baz      bazfoo\n"
19706                    "// foo bar baz      bazfoo bar\n"
19707                    "// foo           bar\n",
19708                    Style));
19709 
19710   // Make sure we do not keep protruding characters if strict mode reflow is
19711   // cheaper than keeping protruding characters.
19712   Style.ColumnLimit = 21;
19713   EXPECT_EQ(
19714       "// foo foo foo foo\n"
19715       "// foo foo foo foo\n"
19716       "// foo foo foo foo\n",
19717       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19718 
19719   EXPECT_EQ("int a = /* long block\n"
19720             "           comment */\n"
19721             "    42;",
19722             format("int a = /* long block comment */ 42;", Style));
19723 }
19724 
19725 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19726   FormatStyle Style = getLLVMStyle();
19727   Style.ColumnLimit = 8;
19728   Style.PenaltyExcessCharacter = 15;
19729   verifyFormat("int foo(\n"
19730                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19731                Style);
19732   Style.PenaltyBreakOpenParenthesis = 200;
19733   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19734             format("int foo(\n"
19735                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19736                    Style));
19737 }
19738 
19739 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19740   FormatStyle Style = getLLVMStyle();
19741   Style.ColumnLimit = 5;
19742   Style.PenaltyExcessCharacter = 150;
19743   verifyFormat("foo((\n"
19744                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19745 
19746                Style);
19747   Style.PenaltyBreakOpenParenthesis = 100000;
19748   EXPECT_EQ("foo((int)\n"
19749             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19750             format("foo((\n"
19751                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19752                    Style));
19753 }
19754 
19755 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19756   FormatStyle Style = getLLVMStyle();
19757   Style.ColumnLimit = 4;
19758   Style.PenaltyExcessCharacter = 100;
19759   verifyFormat("for (\n"
19760                "    int iiiiiiiiiiiiiiiii =\n"
19761                "        0;\n"
19762                "    iiiiiiiiiiiiiiiii <\n"
19763                "    2;\n"
19764                "    iiiiiiiiiiiiiiiii++) {\n"
19765                "}",
19766 
19767                Style);
19768   Style.PenaltyBreakOpenParenthesis = 1250;
19769   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19770             "         0;\n"
19771             "     iiiiiiiiiiiiiiiii <\n"
19772             "     2;\n"
19773             "     iiiiiiiiiiiiiiiii++) {\n"
19774             "}",
19775             format("for (\n"
19776                    "    int iiiiiiiiiiiiiiiii =\n"
19777                    "        0;\n"
19778                    "    iiiiiiiiiiiiiiiii <\n"
19779                    "    2;\n"
19780                    "    iiiiiiiiiiiiiiiii++) {\n"
19781                    "}",
19782                    Style));
19783 }
19784 
19785 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19786   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19787   EXPECT_EQ(Styles[0], Styles[i])                                              \
19788       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19789 
19790 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19791   SmallVector<FormatStyle, 3> Styles;
19792   Styles.resize(3);
19793 
19794   Styles[0] = getLLVMStyle();
19795   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19796   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19797   EXPECT_ALL_STYLES_EQUAL(Styles);
19798 
19799   Styles[0] = getGoogleStyle();
19800   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19801   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19802   EXPECT_ALL_STYLES_EQUAL(Styles);
19803 
19804   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19805   EXPECT_TRUE(
19806       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19807   EXPECT_TRUE(
19808       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19809   EXPECT_ALL_STYLES_EQUAL(Styles);
19810 
19811   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19812   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19813   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19814   EXPECT_ALL_STYLES_EQUAL(Styles);
19815 
19816   Styles[0] = getMozillaStyle();
19817   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19818   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19819   EXPECT_ALL_STYLES_EQUAL(Styles);
19820 
19821   Styles[0] = getWebKitStyle();
19822   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19823   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19824   EXPECT_ALL_STYLES_EQUAL(Styles);
19825 
19826   Styles[0] = getGNUStyle();
19827   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19828   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19829   EXPECT_ALL_STYLES_EQUAL(Styles);
19830 
19831   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19832 }
19833 
19834 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19835   SmallVector<FormatStyle, 8> Styles;
19836   Styles.resize(2);
19837 
19838   Styles[0] = getGoogleStyle();
19839   Styles[1] = getLLVMStyle();
19840   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19841   EXPECT_ALL_STYLES_EQUAL(Styles);
19842 
19843   Styles.resize(5);
19844   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19845   Styles[1] = getLLVMStyle();
19846   Styles[1].Language = FormatStyle::LK_JavaScript;
19847   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19848 
19849   Styles[2] = getLLVMStyle();
19850   Styles[2].Language = FormatStyle::LK_JavaScript;
19851   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19852                                   "BasedOnStyle: Google",
19853                                   &Styles[2])
19854                    .value());
19855 
19856   Styles[3] = getLLVMStyle();
19857   Styles[3].Language = FormatStyle::LK_JavaScript;
19858   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19859                                   "Language: JavaScript",
19860                                   &Styles[3])
19861                    .value());
19862 
19863   Styles[4] = getLLVMStyle();
19864   Styles[4].Language = FormatStyle::LK_JavaScript;
19865   EXPECT_EQ(0, parseConfiguration("---\n"
19866                                   "BasedOnStyle: LLVM\n"
19867                                   "IndentWidth: 123\n"
19868                                   "---\n"
19869                                   "BasedOnStyle: Google\n"
19870                                   "Language: JavaScript",
19871                                   &Styles[4])
19872                    .value());
19873   EXPECT_ALL_STYLES_EQUAL(Styles);
19874 }
19875 
19876 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
19877   Style.FIELD = false;                                                         \
19878   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
19879   EXPECT_TRUE(Style.FIELD);                                                    \
19880   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
19881   EXPECT_FALSE(Style.FIELD);
19882 
19883 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
19884 
19885 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
19886   Style.STRUCT.FIELD = false;                                                  \
19887   EXPECT_EQ(0,                                                                 \
19888             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
19889                 .value());                                                     \
19890   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
19891   EXPECT_EQ(0,                                                                 \
19892             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
19893                 .value());                                                     \
19894   EXPECT_FALSE(Style.STRUCT.FIELD);
19895 
19896 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
19897   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
19898 
19899 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
19900   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
19901   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
19902   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
19903 
19904 TEST_F(FormatTest, ParsesConfigurationBools) {
19905   FormatStyle Style = {};
19906   Style.Language = FormatStyle::LK_Cpp;
19907   CHECK_PARSE_BOOL(AlignTrailingComments);
19908   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
19909   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
19910   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
19911   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
19912   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
19913   CHECK_PARSE_BOOL(BinPackArguments);
19914   CHECK_PARSE_BOOL(BinPackParameters);
19915   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
19916   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
19917   CHECK_PARSE_BOOL(BreakStringLiterals);
19918   CHECK_PARSE_BOOL(CompactNamespaces);
19919   CHECK_PARSE_BOOL(DeriveLineEnding);
19920   CHECK_PARSE_BOOL(DerivePointerAlignment);
19921   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
19922   CHECK_PARSE_BOOL(DisableFormat);
19923   CHECK_PARSE_BOOL(IndentAccessModifiers);
19924   CHECK_PARSE_BOOL(IndentCaseLabels);
19925   CHECK_PARSE_BOOL(IndentCaseBlocks);
19926   CHECK_PARSE_BOOL(IndentGotoLabels);
19927   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
19928   CHECK_PARSE_BOOL(IndentRequiresClause);
19929   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
19930   CHECK_PARSE_BOOL(InsertBraces);
19931   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
19932   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
19933   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
19934   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
19935   CHECK_PARSE_BOOL(ReflowComments);
19936   CHECK_PARSE_BOOL(RemoveBracesLLVM);
19937   CHECK_PARSE_BOOL(SortUsingDeclarations);
19938   CHECK_PARSE_BOOL(SpacesInParentheses);
19939   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
19940   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
19941   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
19942   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
19943   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
19944   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
19945   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
19946   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
19947   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
19948   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
19949   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
19950   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
19951   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
19952   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
19953   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
19954   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
19955   CHECK_PARSE_BOOL(UseCRLF);
19956 
19957   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
19958   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
19959   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
19960   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
19961   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
19962   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
19963   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
19964   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
19965   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
19966   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
19967   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
19968   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
19969   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
19970   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
19971   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
19972   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
19973   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
19974   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
19975   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
19976   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19977                           AfterFunctionDeclarationName);
19978   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19979                           AfterFunctionDefinitionName);
19980   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
19981   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
19982   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
19983 }
19984 
19985 #undef CHECK_PARSE_BOOL
19986 
19987 TEST_F(FormatTest, ParsesConfiguration) {
19988   FormatStyle Style = {};
19989   Style.Language = FormatStyle::LK_Cpp;
19990   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
19991   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
19992               ConstructorInitializerIndentWidth, 1234u);
19993   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
19994   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
19995   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
19996   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
19997   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
19998               PenaltyBreakBeforeFirstCallParameter, 1234u);
19999   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
20000               PenaltyBreakTemplateDeclaration, 1234u);
20001   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
20002               1234u);
20003   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
20004   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
20005               PenaltyReturnTypeOnItsOwnLine, 1234u);
20006   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
20007               SpacesBeforeTrailingComments, 1234u);
20008   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
20009   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
20010   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
20011 
20012   Style.QualifierAlignment = FormatStyle::QAS_Right;
20013   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
20014               FormatStyle::QAS_Leave);
20015   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
20016               FormatStyle::QAS_Right);
20017   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
20018               FormatStyle::QAS_Left);
20019   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
20020               FormatStyle::QAS_Custom);
20021 
20022   Style.QualifierOrder.clear();
20023   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
20024               std::vector<std::string>({"const", "volatile", "type"}));
20025   Style.QualifierOrder.clear();
20026   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
20027               std::vector<std::string>({"const", "type"}));
20028   Style.QualifierOrder.clear();
20029   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
20030               std::vector<std::string>({"volatile", "type"}));
20031 
20032 #define CHECK_ALIGN_CONSECUTIVE(FIELD)                                         \
20033   do {                                                                         \
20034     Style.FIELD.Enabled = true;                                                \
20035     CHECK_PARSE(#FIELD ": None", FIELD,                                        \
20036                 FormatStyle::AlignConsecutiveStyle(                            \
20037                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
20038                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20039                      /*PadOperators=*/true}));                                 \
20040     CHECK_PARSE(#FIELD ": Consecutive", FIELD,                                 \
20041                 FormatStyle::AlignConsecutiveStyle(                            \
20042                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
20043                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20044                      /*PadOperators=*/true}));                                 \
20045     CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD,                            \
20046                 FormatStyle::AlignConsecutiveStyle(                            \
20047                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
20048                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20049                      /*PadOperators=*/true}));                                 \
20050     CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD,                 \
20051                 FormatStyle::AlignConsecutiveStyle(                            \
20052                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
20053                      /*AcrossComments=*/true, /*AlignCompound=*/false,         \
20054                      /*PadOperators=*/true}));                                 \
20055     /* For backwards compability, false / true should still parse */           \
20056     CHECK_PARSE(#FIELD ": false", FIELD,                                       \
20057                 FormatStyle::AlignConsecutiveStyle(                            \
20058                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
20059                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20060                      /*PadOperators=*/true}));                                 \
20061     CHECK_PARSE(#FIELD ": true", FIELD,                                        \
20062                 FormatStyle::AlignConsecutiveStyle(                            \
20063                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
20064                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20065                      /*PadOperators=*/true}));                                 \
20066                                                                                \
20067     CHECK_PARSE_NESTED_BOOL(FIELD, Enabled);                                   \
20068     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines);                          \
20069     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments);                            \
20070     CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound);                             \
20071     CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators);                              \
20072   } while (false)
20073 
20074   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments);
20075   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields);
20076   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros);
20077   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations);
20078 
20079 #undef CHECK_ALIGN_CONSECUTIVE
20080 
20081   Style.PointerAlignment = FormatStyle::PAS_Middle;
20082   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
20083               FormatStyle::PAS_Left);
20084   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
20085               FormatStyle::PAS_Right);
20086   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
20087               FormatStyle::PAS_Middle);
20088   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
20089   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
20090               FormatStyle::RAS_Pointer);
20091   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
20092               FormatStyle::RAS_Left);
20093   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
20094               FormatStyle::RAS_Right);
20095   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
20096               FormatStyle::RAS_Middle);
20097   // For backward compatibility:
20098   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
20099               FormatStyle::PAS_Left);
20100   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
20101               FormatStyle::PAS_Right);
20102   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
20103               FormatStyle::PAS_Middle);
20104 
20105   Style.Standard = FormatStyle::LS_Auto;
20106   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
20107   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
20108   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
20109   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
20110   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
20111   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
20112   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
20113   // Legacy aliases:
20114   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
20115   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
20116   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
20117   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
20118 
20119   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
20120   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
20121               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
20122   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
20123               FormatStyle::BOS_None);
20124   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
20125               FormatStyle::BOS_All);
20126   // For backward compatibility:
20127   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
20128               FormatStyle::BOS_None);
20129   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
20130               FormatStyle::BOS_All);
20131 
20132   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
20133   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
20134               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20135   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
20136               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
20137   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
20138               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
20139   // For backward compatibility:
20140   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
20141               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20142 
20143   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
20144   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
20145               FormatStyle::BILS_AfterComma);
20146   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
20147               FormatStyle::BILS_BeforeComma);
20148   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
20149               FormatStyle::BILS_AfterColon);
20150   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
20151               FormatStyle::BILS_BeforeColon);
20152   // For backward compatibility:
20153   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
20154               FormatStyle::BILS_BeforeComma);
20155 
20156   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20157   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
20158               FormatStyle::PCIS_Never);
20159   CHECK_PARSE("PackConstructorInitializers: BinPack",
20160               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20161   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
20162               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20163   CHECK_PARSE("PackConstructorInitializers: NextLine",
20164               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20165   // For backward compatibility:
20166   CHECK_PARSE("BasedOnStyle: Google\n"
20167               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20168               "AllowAllConstructorInitializersOnNextLine: false",
20169               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20170   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20171   CHECK_PARSE("BasedOnStyle: Google\n"
20172               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
20173               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20174   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20175               "AllowAllConstructorInitializersOnNextLine: true",
20176               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20177   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20178   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20179               "AllowAllConstructorInitializersOnNextLine: false",
20180               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20181 
20182   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
20183   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
20184               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
20185   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
20186               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
20187   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
20188               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
20189   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
20190               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
20191 
20192   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20193   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
20194               FormatStyle::BAS_Align);
20195   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
20196               FormatStyle::BAS_DontAlign);
20197   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
20198               FormatStyle::BAS_AlwaysBreak);
20199   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
20200               FormatStyle::BAS_BlockIndent);
20201   // For backward compatibility:
20202   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
20203               FormatStyle::BAS_DontAlign);
20204   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
20205               FormatStyle::BAS_Align);
20206 
20207   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
20208   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
20209               FormatStyle::ENAS_DontAlign);
20210   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
20211               FormatStyle::ENAS_Left);
20212   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
20213               FormatStyle::ENAS_Right);
20214   // For backward compatibility:
20215   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
20216               FormatStyle::ENAS_Left);
20217   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
20218               FormatStyle::ENAS_Right);
20219 
20220   Style.AlignOperands = FormatStyle::OAS_Align;
20221   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
20222               FormatStyle::OAS_DontAlign);
20223   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
20224   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
20225               FormatStyle::OAS_AlignAfterOperator);
20226   // For backward compatibility:
20227   CHECK_PARSE("AlignOperands: false", AlignOperands,
20228               FormatStyle::OAS_DontAlign);
20229   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
20230 
20231   Style.UseTab = FormatStyle::UT_ForIndentation;
20232   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
20233   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
20234   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
20235   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
20236               FormatStyle::UT_ForContinuationAndIndentation);
20237   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
20238               FormatStyle::UT_AlignWithSpaces);
20239   // For backward compatibility:
20240   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
20241   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
20242 
20243   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
20244   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
20245               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20246   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
20247               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
20248   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
20249               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20250   // For backward compatibility:
20251   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
20252               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20253   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
20254               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20255 
20256   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
20257   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
20258               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20259   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
20260               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
20261   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
20262               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
20263   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
20264               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20265   // For backward compatibility:
20266   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
20267               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20268   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
20269               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20270 
20271   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
20272   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
20273               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
20274   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
20275               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
20276   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
20277               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
20278   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
20279               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
20280 
20281   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
20282   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
20283               FormatStyle::SBPO_Never);
20284   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
20285               FormatStyle::SBPO_Always);
20286   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
20287               FormatStyle::SBPO_ControlStatements);
20288   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
20289               SpaceBeforeParens,
20290               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20291   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
20292               FormatStyle::SBPO_NonEmptyParentheses);
20293   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
20294               FormatStyle::SBPO_Custom);
20295   // For backward compatibility:
20296   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
20297               FormatStyle::SBPO_Never);
20298   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
20299               FormatStyle::SBPO_ControlStatements);
20300   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
20301               SpaceBeforeParens,
20302               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20303 
20304   Style.ColumnLimit = 123;
20305   FormatStyle BaseStyle = getLLVMStyle();
20306   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
20307   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
20308 
20309   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
20310   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
20311               FormatStyle::BS_Attach);
20312   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
20313               FormatStyle::BS_Linux);
20314   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
20315               FormatStyle::BS_Mozilla);
20316   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
20317               FormatStyle::BS_Stroustrup);
20318   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
20319               FormatStyle::BS_Allman);
20320   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
20321               FormatStyle::BS_Whitesmiths);
20322   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
20323   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
20324               FormatStyle::BS_WebKit);
20325   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
20326               FormatStyle::BS_Custom);
20327 
20328   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
20329   CHECK_PARSE("BraceWrapping:\n"
20330               "  AfterControlStatement: MultiLine",
20331               BraceWrapping.AfterControlStatement,
20332               FormatStyle::BWACS_MultiLine);
20333   CHECK_PARSE("BraceWrapping:\n"
20334               "  AfterControlStatement: Always",
20335               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20336   CHECK_PARSE("BraceWrapping:\n"
20337               "  AfterControlStatement: Never",
20338               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20339   // For backward compatibility:
20340   CHECK_PARSE("BraceWrapping:\n"
20341               "  AfterControlStatement: true",
20342               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20343   CHECK_PARSE("BraceWrapping:\n"
20344               "  AfterControlStatement: false",
20345               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20346 
20347   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
20348   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
20349               FormatStyle::RTBS_None);
20350   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
20351               FormatStyle::RTBS_All);
20352   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
20353               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
20354   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
20355               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
20356   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
20357               AlwaysBreakAfterReturnType,
20358               FormatStyle::RTBS_TopLevelDefinitions);
20359 
20360   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
20361   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
20362               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
20363   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
20364               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20365   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
20366               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20367   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
20368               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20369   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
20370               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20371 
20372   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
20373   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
20374               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
20375   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
20376               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
20377   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
20378               AlwaysBreakAfterDefinitionReturnType,
20379               FormatStyle::DRTBS_TopLevel);
20380 
20381   Style.NamespaceIndentation = FormatStyle::NI_All;
20382   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
20383               FormatStyle::NI_None);
20384   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
20385               FormatStyle::NI_Inner);
20386   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
20387               FormatStyle::NI_All);
20388 
20389   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
20390   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
20391               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20392   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
20393               AllowShortIfStatementsOnASingleLine,
20394               FormatStyle::SIS_WithoutElse);
20395   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
20396               AllowShortIfStatementsOnASingleLine,
20397               FormatStyle::SIS_OnlyFirstIf);
20398   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
20399               AllowShortIfStatementsOnASingleLine,
20400               FormatStyle::SIS_AllIfsAndElse);
20401   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
20402               AllowShortIfStatementsOnASingleLine,
20403               FormatStyle::SIS_OnlyFirstIf);
20404   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
20405               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20406   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
20407               AllowShortIfStatementsOnASingleLine,
20408               FormatStyle::SIS_WithoutElse);
20409 
20410   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
20411   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
20412               FormatStyle::IEBS_AfterExternBlock);
20413   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
20414               FormatStyle::IEBS_Indent);
20415   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
20416               FormatStyle::IEBS_NoIndent);
20417   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
20418               FormatStyle::IEBS_Indent);
20419   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
20420               FormatStyle::IEBS_NoIndent);
20421 
20422   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
20423   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
20424               FormatStyle::BFCS_Both);
20425   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
20426               FormatStyle::BFCS_None);
20427   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
20428               FormatStyle::BFCS_Before);
20429   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
20430               FormatStyle::BFCS_After);
20431 
20432   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
20433   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
20434               FormatStyle::SJSIO_After);
20435   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
20436               FormatStyle::SJSIO_Before);
20437 
20438   // FIXME: This is required because parsing a configuration simply overwrites
20439   // the first N elements of the list instead of resetting it.
20440   Style.ForEachMacros.clear();
20441   std::vector<std::string> BoostForeach;
20442   BoostForeach.push_back("BOOST_FOREACH");
20443   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20444   std::vector<std::string> BoostAndQForeach;
20445   BoostAndQForeach.push_back("BOOST_FOREACH");
20446   BoostAndQForeach.push_back("Q_FOREACH");
20447   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20448               BoostAndQForeach);
20449 
20450   Style.IfMacros.clear();
20451   std::vector<std::string> CustomIfs;
20452   CustomIfs.push_back("MYIF");
20453   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20454 
20455   Style.AttributeMacros.clear();
20456   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20457               std::vector<std::string>{"__capability"});
20458   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20459               std::vector<std::string>({"attr1", "attr2"}));
20460 
20461   Style.StatementAttributeLikeMacros.clear();
20462   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20463               StatementAttributeLikeMacros,
20464               std::vector<std::string>({"emit", "Q_EMIT"}));
20465 
20466   Style.StatementMacros.clear();
20467   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20468               std::vector<std::string>{"QUNUSED"});
20469   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20470               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20471 
20472   Style.NamespaceMacros.clear();
20473   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20474               std::vector<std::string>{"TESTSUITE"});
20475   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20476               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20477 
20478   Style.WhitespaceSensitiveMacros.clear();
20479   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20480               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20481   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20482               WhitespaceSensitiveMacros,
20483               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20484   Style.WhitespaceSensitiveMacros.clear();
20485   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
20486               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20487   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
20488               WhitespaceSensitiveMacros,
20489               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20490 
20491   Style.IncludeStyle.IncludeCategories.clear();
20492   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20493       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20494   CHECK_PARSE("IncludeCategories:\n"
20495               "  - Regex: abc/.*\n"
20496               "    Priority: 2\n"
20497               "  - Regex: .*\n"
20498               "    Priority: 1\n"
20499               "    CaseSensitive: true\n",
20500               IncludeStyle.IncludeCategories, ExpectedCategories);
20501   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20502               "abc$");
20503   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20504               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20505 
20506   Style.SortIncludes = FormatStyle::SI_Never;
20507   CHECK_PARSE("SortIncludes: true", SortIncludes,
20508               FormatStyle::SI_CaseSensitive);
20509   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20510   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20511               FormatStyle::SI_CaseInsensitive);
20512   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20513               FormatStyle::SI_CaseSensitive);
20514   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20515 
20516   Style.RawStringFormats.clear();
20517   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20518       {
20519           FormatStyle::LK_TextProto,
20520           {"pb", "proto"},
20521           {"PARSE_TEXT_PROTO"},
20522           /*CanonicalDelimiter=*/"",
20523           "llvm",
20524       },
20525       {
20526           FormatStyle::LK_Cpp,
20527           {"cc", "cpp"},
20528           {"C_CODEBLOCK", "CPPEVAL"},
20529           /*CanonicalDelimiter=*/"cc",
20530           /*BasedOnStyle=*/"",
20531       },
20532   };
20533 
20534   CHECK_PARSE("RawStringFormats:\n"
20535               "  - Language: TextProto\n"
20536               "    Delimiters:\n"
20537               "      - 'pb'\n"
20538               "      - 'proto'\n"
20539               "    EnclosingFunctions:\n"
20540               "      - 'PARSE_TEXT_PROTO'\n"
20541               "    BasedOnStyle: llvm\n"
20542               "  - Language: Cpp\n"
20543               "    Delimiters:\n"
20544               "      - 'cc'\n"
20545               "      - 'cpp'\n"
20546               "    EnclosingFunctions:\n"
20547               "      - 'C_CODEBLOCK'\n"
20548               "      - 'CPPEVAL'\n"
20549               "    CanonicalDelimiter: 'cc'",
20550               RawStringFormats, ExpectedRawStringFormats);
20551 
20552   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20553               "  Minimum: 0\n"
20554               "  Maximum: 0",
20555               SpacesInLineCommentPrefix.Minimum, 0u);
20556   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20557   Style.SpacesInLineCommentPrefix.Minimum = 1;
20558   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20559               "  Minimum: 2",
20560               SpacesInLineCommentPrefix.Minimum, 0u);
20561   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20562               "  Maximum: -1",
20563               SpacesInLineCommentPrefix.Maximum, -1u);
20564   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20565               "  Minimum: 2",
20566               SpacesInLineCommentPrefix.Minimum, 2u);
20567   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20568               "  Maximum: 1",
20569               SpacesInLineCommentPrefix.Maximum, 1u);
20570   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20571 
20572   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20573   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20574   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20575               FormatStyle::SIAS_Always);
20576   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20577   // For backward compatibility:
20578   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20579   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20580 
20581   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20582               FormatStyle::RCPS_WithPreceding);
20583   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20584               FormatStyle::RCPS_WithFollowing);
20585   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20586               FormatStyle::RCPS_SingleLine);
20587   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20588               FormatStyle::RCPS_OwnLine);
20589 
20590   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20591               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20592   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20593               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20594   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20595               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20596   // For backward compatibility:
20597   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20598               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20599   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20600               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20601 }
20602 
20603 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20604   FormatStyle Style = {};
20605   Style.Language = FormatStyle::LK_Cpp;
20606   CHECK_PARSE("Language: Cpp\n"
20607               "IndentWidth: 12",
20608               IndentWidth, 12u);
20609   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20610                                "IndentWidth: 34",
20611                                &Style),
20612             ParseError::Unsuitable);
20613   FormatStyle BinPackedTCS = {};
20614   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20615   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20616                                "InsertTrailingCommas: Wrapped",
20617                                &BinPackedTCS),
20618             ParseError::BinPackTrailingCommaConflict);
20619   EXPECT_EQ(12u, Style.IndentWidth);
20620   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20621   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20622 
20623   Style.Language = FormatStyle::LK_JavaScript;
20624   CHECK_PARSE("Language: JavaScript\n"
20625               "IndentWidth: 12",
20626               IndentWidth, 12u);
20627   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20628   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20629                                "IndentWidth: 34",
20630                                &Style),
20631             ParseError::Unsuitable);
20632   EXPECT_EQ(23u, Style.IndentWidth);
20633   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20634   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20635 
20636   CHECK_PARSE("BasedOnStyle: LLVM\n"
20637               "IndentWidth: 67",
20638               IndentWidth, 67u);
20639 
20640   CHECK_PARSE("---\n"
20641               "Language: JavaScript\n"
20642               "IndentWidth: 12\n"
20643               "---\n"
20644               "Language: Cpp\n"
20645               "IndentWidth: 34\n"
20646               "...\n",
20647               IndentWidth, 12u);
20648 
20649   Style.Language = FormatStyle::LK_Cpp;
20650   CHECK_PARSE("---\n"
20651               "Language: JavaScript\n"
20652               "IndentWidth: 12\n"
20653               "---\n"
20654               "Language: Cpp\n"
20655               "IndentWidth: 34\n"
20656               "...\n",
20657               IndentWidth, 34u);
20658   CHECK_PARSE("---\n"
20659               "IndentWidth: 78\n"
20660               "---\n"
20661               "Language: JavaScript\n"
20662               "IndentWidth: 56\n"
20663               "...\n",
20664               IndentWidth, 78u);
20665 
20666   Style.ColumnLimit = 123;
20667   Style.IndentWidth = 234;
20668   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20669   Style.TabWidth = 345;
20670   EXPECT_FALSE(parseConfiguration("---\n"
20671                                   "IndentWidth: 456\n"
20672                                   "BreakBeforeBraces: Allman\n"
20673                                   "---\n"
20674                                   "Language: JavaScript\n"
20675                                   "IndentWidth: 111\n"
20676                                   "TabWidth: 111\n"
20677                                   "---\n"
20678                                   "Language: Cpp\n"
20679                                   "BreakBeforeBraces: Stroustrup\n"
20680                                   "TabWidth: 789\n"
20681                                   "...\n",
20682                                   &Style));
20683   EXPECT_EQ(123u, Style.ColumnLimit);
20684   EXPECT_EQ(456u, Style.IndentWidth);
20685   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20686   EXPECT_EQ(789u, Style.TabWidth);
20687 
20688   EXPECT_EQ(parseConfiguration("---\n"
20689                                "Language: JavaScript\n"
20690                                "IndentWidth: 56\n"
20691                                "---\n"
20692                                "IndentWidth: 78\n"
20693                                "...\n",
20694                                &Style),
20695             ParseError::Error);
20696   EXPECT_EQ(parseConfiguration("---\n"
20697                                "Language: JavaScript\n"
20698                                "IndentWidth: 56\n"
20699                                "---\n"
20700                                "Language: JavaScript\n"
20701                                "IndentWidth: 78\n"
20702                                "...\n",
20703                                &Style),
20704             ParseError::Error);
20705 
20706   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20707 }
20708 
20709 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20710   FormatStyle Style = {};
20711   Style.Language = FormatStyle::LK_JavaScript;
20712   Style.BreakBeforeTernaryOperators = true;
20713   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20714   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20715 
20716   Style.BreakBeforeTernaryOperators = true;
20717   EXPECT_EQ(0, parseConfiguration("---\n"
20718                                   "BasedOnStyle: Google\n"
20719                                   "---\n"
20720                                   "Language: JavaScript\n"
20721                                   "IndentWidth: 76\n"
20722                                   "...\n",
20723                                   &Style)
20724                    .value());
20725   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20726   EXPECT_EQ(76u, Style.IndentWidth);
20727   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20728 }
20729 
20730 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20731   FormatStyle Style = getLLVMStyle();
20732   std::string YAML = configurationAsText(Style);
20733   FormatStyle ParsedStyle = {};
20734   ParsedStyle.Language = FormatStyle::LK_Cpp;
20735   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20736   EXPECT_EQ(Style, ParsedStyle);
20737 }
20738 
20739 TEST_F(FormatTest, WorksFor8bitEncodings) {
20740   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20741             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20742             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20743             "\"\xef\xee\xf0\xf3...\"",
20744             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20745                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20746                    "\xef\xee\xf0\xf3...\"",
20747                    getLLVMStyleWithColumns(12)));
20748 }
20749 
20750 TEST_F(FormatTest, HandlesUTF8BOM) {
20751   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20752   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20753             format("\xef\xbb\xbf#include <iostream>"));
20754   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20755             format("\xef\xbb\xbf\n#include <iostream>"));
20756 }
20757 
20758 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20759 #if !defined(_MSC_VER)
20760 
20761 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20762   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20763                getLLVMStyleWithColumns(35));
20764   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20765                getLLVMStyleWithColumns(31));
20766   verifyFormat("// Однажды в студёную зимнюю пору...",
20767                getLLVMStyleWithColumns(36));
20768   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20769   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20770                getLLVMStyleWithColumns(39));
20771   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20772                getLLVMStyleWithColumns(35));
20773 }
20774 
20775 TEST_F(FormatTest, SplitsUTF8Strings) {
20776   // Non-printable characters' width is currently considered to be the length in
20777   // bytes in UTF8. The characters can be displayed in very different manner
20778   // (zero-width, single width with a substitution glyph, expanded to their code
20779   // (e.g. "<8d>"), so there's no single correct way to handle them.
20780   EXPECT_EQ("\"aaaaÄ\"\n"
20781             "\"\xc2\x8d\";",
20782             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20783   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20784             "\"\xc2\x8d\";",
20785             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20786   EXPECT_EQ("\"Однажды, в \"\n"
20787             "\"студёную \"\n"
20788             "\"зимнюю \"\n"
20789             "\"пору,\"",
20790             format("\"Однажды, в студёную зимнюю пору,\"",
20791                    getLLVMStyleWithColumns(13)));
20792   EXPECT_EQ(
20793       "\"一 二 三 \"\n"
20794       "\"四 五六 \"\n"
20795       "\"七 八 九 \"\n"
20796       "\"十\"",
20797       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20798   EXPECT_EQ("\"一\t\"\n"
20799             "\"二 \t\"\n"
20800             "\"三 四 \"\n"
20801             "\"五\t\"\n"
20802             "\"六 \t\"\n"
20803             "\"七 \"\n"
20804             "\"八九十\tqq\"",
20805             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20806                    getLLVMStyleWithColumns(11)));
20807 
20808   // UTF8 character in an escape sequence.
20809   EXPECT_EQ("\"aaaaaa\"\n"
20810             "\"\\\xC2\x8D\"",
20811             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20812 }
20813 
20814 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20815   EXPECT_EQ("const char *sssss =\n"
20816             "    \"一二三四五六七八\\\n"
20817             " 九 十\";",
20818             format("const char *sssss = \"一二三四五六七八\\\n"
20819                    " 九 十\";",
20820                    getLLVMStyleWithColumns(30)));
20821 }
20822 
20823 TEST_F(FormatTest, SplitsUTF8LineComments) {
20824   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20825             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20826   EXPECT_EQ("// Я из лесу\n"
20827             "// вышел; был\n"
20828             "// сильный\n"
20829             "// мороз.",
20830             format("// Я из лесу вышел; был сильный мороз.",
20831                    getLLVMStyleWithColumns(13)));
20832   EXPECT_EQ("// 一二三\n"
20833             "// 四五六七\n"
20834             "// 八  九\n"
20835             "// 十",
20836             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20837 }
20838 
20839 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20840   EXPECT_EQ("/* Гляжу,\n"
20841             " * поднимается\n"
20842             " * медленно в\n"
20843             " * гору\n"
20844             " * Лошадка,\n"
20845             " * везущая\n"
20846             " * хворосту\n"
20847             " * воз. */",
20848             format("/* Гляжу, поднимается медленно в гору\n"
20849                    " * Лошадка, везущая хворосту воз. */",
20850                    getLLVMStyleWithColumns(13)));
20851   EXPECT_EQ(
20852       "/* 一二三\n"
20853       " * 四五六七\n"
20854       " * 八  九\n"
20855       " * 十  */",
20856       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20857   EXPECT_EQ("/* �������� ��������\n"
20858             " * ��������\n"
20859             " * ������-�� */",
20860             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20861 }
20862 
20863 #endif // _MSC_VER
20864 
20865 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
20866   FormatStyle Style = getLLVMStyle();
20867 
20868   Style.ConstructorInitializerIndentWidth = 4;
20869   verifyFormat(
20870       "SomeClass::Constructor()\n"
20871       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20872       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20873       Style);
20874 
20875   Style.ConstructorInitializerIndentWidth = 2;
20876   verifyFormat(
20877       "SomeClass::Constructor()\n"
20878       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20879       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20880       Style);
20881 
20882   Style.ConstructorInitializerIndentWidth = 0;
20883   verifyFormat(
20884       "SomeClass::Constructor()\n"
20885       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20886       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20887       Style);
20888   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20889   verifyFormat(
20890       "SomeLongTemplateVariableName<\n"
20891       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
20892       Style);
20893   verifyFormat("bool smaller = 1 < "
20894                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
20895                "                       "
20896                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
20897                Style);
20898 
20899   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
20900   verifyFormat("SomeClass::Constructor() :\n"
20901                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
20902                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
20903                Style);
20904 }
20905 
20906 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
20907   FormatStyle Style = getLLVMStyle();
20908   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20909   Style.ConstructorInitializerIndentWidth = 4;
20910   verifyFormat("SomeClass::Constructor()\n"
20911                "    : a(a)\n"
20912                "    , b(b)\n"
20913                "    , c(c) {}",
20914                Style);
20915   verifyFormat("SomeClass::Constructor()\n"
20916                "    : a(a) {}",
20917                Style);
20918 
20919   Style.ColumnLimit = 0;
20920   verifyFormat("SomeClass::Constructor()\n"
20921                "    : a(a) {}",
20922                Style);
20923   verifyFormat("SomeClass::Constructor() noexcept\n"
20924                "    : a(a) {}",
20925                Style);
20926   verifyFormat("SomeClass::Constructor()\n"
20927                "    : a(a)\n"
20928                "    , b(b)\n"
20929                "    , c(c) {}",
20930                Style);
20931   verifyFormat("SomeClass::Constructor()\n"
20932                "    : a(a) {\n"
20933                "  foo();\n"
20934                "  bar();\n"
20935                "}",
20936                Style);
20937 
20938   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
20939   verifyFormat("SomeClass::Constructor()\n"
20940                "    : a(a)\n"
20941                "    , b(b)\n"
20942                "    , c(c) {\n}",
20943                Style);
20944   verifyFormat("SomeClass::Constructor()\n"
20945                "    : a(a) {\n}",
20946                Style);
20947 
20948   Style.ColumnLimit = 80;
20949   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
20950   Style.ConstructorInitializerIndentWidth = 2;
20951   verifyFormat("SomeClass::Constructor()\n"
20952                "  : a(a)\n"
20953                "  , b(b)\n"
20954                "  , c(c) {}",
20955                Style);
20956 
20957   Style.ConstructorInitializerIndentWidth = 0;
20958   verifyFormat("SomeClass::Constructor()\n"
20959                ": a(a)\n"
20960                ", b(b)\n"
20961                ", c(c) {}",
20962                Style);
20963 
20964   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20965   Style.ConstructorInitializerIndentWidth = 4;
20966   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
20967   verifyFormat(
20968       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
20969       Style);
20970   verifyFormat(
20971       "SomeClass::Constructor()\n"
20972       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
20973       Style);
20974   Style.ConstructorInitializerIndentWidth = 4;
20975   Style.ColumnLimit = 60;
20976   verifyFormat("SomeClass::Constructor()\n"
20977                "    : aaaaaaaa(aaaaaaaa)\n"
20978                "    , aaaaaaaa(aaaaaaaa)\n"
20979                "    , aaaaaaaa(aaaaaaaa) {}",
20980                Style);
20981 }
20982 
20983 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
20984   FormatStyle Style = getLLVMStyle();
20985   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20986   Style.ConstructorInitializerIndentWidth = 4;
20987   verifyFormat("SomeClass::Constructor()\n"
20988                "    : a{a}\n"
20989                "    , b{b} {}",
20990                Style);
20991   verifyFormat("SomeClass::Constructor()\n"
20992                "    : a{a}\n"
20993                "#if CONDITION\n"
20994                "    , b{b}\n"
20995                "#endif\n"
20996                "{\n}",
20997                Style);
20998   Style.ConstructorInitializerIndentWidth = 2;
20999   verifyFormat("SomeClass::Constructor()\n"
21000                "#if CONDITION\n"
21001                "  : a{a}\n"
21002                "#endif\n"
21003                "  , b{b}\n"
21004                "  , c{c} {\n}",
21005                Style);
21006   Style.ConstructorInitializerIndentWidth = 0;
21007   verifyFormat("SomeClass::Constructor()\n"
21008                ": a{a}\n"
21009                "#ifdef CONDITION\n"
21010                ", b{b}\n"
21011                "#else\n"
21012                ", c{c}\n"
21013                "#endif\n"
21014                ", d{d} {\n}",
21015                Style);
21016   Style.ConstructorInitializerIndentWidth = 4;
21017   verifyFormat("SomeClass::Constructor()\n"
21018                "    : a{a}\n"
21019                "#if WINDOWS\n"
21020                "#if DEBUG\n"
21021                "    , b{0}\n"
21022                "#else\n"
21023                "    , b{1}\n"
21024                "#endif\n"
21025                "#else\n"
21026                "#if DEBUG\n"
21027                "    , b{2}\n"
21028                "#else\n"
21029                "    , b{3}\n"
21030                "#endif\n"
21031                "#endif\n"
21032                "{\n}",
21033                Style);
21034   verifyFormat("SomeClass::Constructor()\n"
21035                "    : a{a}\n"
21036                "#if WINDOWS\n"
21037                "    , b{0}\n"
21038                "#if DEBUG\n"
21039                "    , c{0}\n"
21040                "#else\n"
21041                "    , c{1}\n"
21042                "#endif\n"
21043                "#else\n"
21044                "#if DEBUG\n"
21045                "    , c{2}\n"
21046                "#else\n"
21047                "    , c{3}\n"
21048                "#endif\n"
21049                "    , b{1}\n"
21050                "#endif\n"
21051                "{\n}",
21052                Style);
21053 }
21054 
21055 TEST_F(FormatTest, Destructors) {
21056   verifyFormat("void F(int &i) { i.~int(); }");
21057   verifyFormat("void F(int &i) { i->~int(); }");
21058 }
21059 
21060 TEST_F(FormatTest, FormatsWithWebKitStyle) {
21061   FormatStyle Style = getWebKitStyle();
21062 
21063   // Don't indent in outer namespaces.
21064   verifyFormat("namespace outer {\n"
21065                "int i;\n"
21066                "namespace inner {\n"
21067                "    int i;\n"
21068                "} // namespace inner\n"
21069                "} // namespace outer\n"
21070                "namespace other_outer {\n"
21071                "int i;\n"
21072                "}",
21073                Style);
21074 
21075   // Don't indent case labels.
21076   verifyFormat("switch (variable) {\n"
21077                "case 1:\n"
21078                "case 2:\n"
21079                "    doSomething();\n"
21080                "    break;\n"
21081                "default:\n"
21082                "    ++variable;\n"
21083                "}",
21084                Style);
21085 
21086   // Wrap before binary operators.
21087   EXPECT_EQ("void f()\n"
21088             "{\n"
21089             "    if (aaaaaaaaaaaaaaaa\n"
21090             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
21091             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21092             "        return;\n"
21093             "}",
21094             format("void f() {\n"
21095                    "if (aaaaaaaaaaaaaaaa\n"
21096                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
21097                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21098                    "return;\n"
21099                    "}",
21100                    Style));
21101 
21102   // Allow functions on a single line.
21103   verifyFormat("void f() { return; }", Style);
21104 
21105   // Allow empty blocks on a single line and insert a space in empty blocks.
21106   EXPECT_EQ("void f() { }", format("void f() {}", Style));
21107   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
21108   // However, don't merge non-empty short loops.
21109   EXPECT_EQ("while (true) {\n"
21110             "    continue;\n"
21111             "}",
21112             format("while (true) { continue; }", Style));
21113 
21114   // Constructor initializers are formatted one per line with the "," on the
21115   // new line.
21116   verifyFormat("Constructor()\n"
21117                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
21118                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
21119                "          aaaaaaaaaaaaaa)\n"
21120                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
21121                "{\n"
21122                "}",
21123                Style);
21124   verifyFormat("SomeClass::Constructor()\n"
21125                "    : a(a)\n"
21126                "{\n"
21127                "}",
21128                Style);
21129   EXPECT_EQ("SomeClass::Constructor()\n"
21130             "    : a(a)\n"
21131             "{\n"
21132             "}",
21133             format("SomeClass::Constructor():a(a){}", Style));
21134   verifyFormat("SomeClass::Constructor()\n"
21135                "    : a(a)\n"
21136                "    , b(b)\n"
21137                "    , c(c)\n"
21138                "{\n"
21139                "}",
21140                Style);
21141   verifyFormat("SomeClass::Constructor()\n"
21142                "    : a(a)\n"
21143                "{\n"
21144                "    foo();\n"
21145                "    bar();\n"
21146                "}",
21147                Style);
21148 
21149   // Access specifiers should be aligned left.
21150   verifyFormat("class C {\n"
21151                "public:\n"
21152                "    int i;\n"
21153                "};",
21154                Style);
21155 
21156   // Do not align comments.
21157   verifyFormat("int a; // Do not\n"
21158                "double b; // align comments.",
21159                Style);
21160 
21161   // Do not align operands.
21162   EXPECT_EQ("ASSERT(aaaa\n"
21163             "    || bbbb);",
21164             format("ASSERT ( aaaa\n||bbbb);", Style));
21165 
21166   // Accept input's line breaks.
21167   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
21168             "    || bbbbbbbbbbbbbbb) {\n"
21169             "    i++;\n"
21170             "}",
21171             format("if (aaaaaaaaaaaaaaa\n"
21172                    "|| bbbbbbbbbbbbbbb) { i++; }",
21173                    Style));
21174   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
21175             "    i++;\n"
21176             "}",
21177             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
21178 
21179   // Don't automatically break all macro definitions (llvm.org/PR17842).
21180   verifyFormat("#define aNumber 10", Style);
21181   // However, generally keep the line breaks that the user authored.
21182   EXPECT_EQ("#define aNumber \\\n"
21183             "    10",
21184             format("#define aNumber \\\n"
21185                    " 10",
21186                    Style));
21187 
21188   // Keep empty and one-element array literals on a single line.
21189   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
21190             "                                  copyItems:YES];",
21191             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
21192                    "copyItems:YES];",
21193                    Style));
21194   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
21195             "                                  copyItems:YES];",
21196             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
21197                    "             copyItems:YES];",
21198                    Style));
21199   // FIXME: This does not seem right, there should be more indentation before
21200   // the array literal's entries. Nested blocks have the same problem.
21201   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21202             "    @\"a\",\n"
21203             "    @\"a\"\n"
21204             "]\n"
21205             "                                  copyItems:YES];",
21206             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21207                    "     @\"a\",\n"
21208                    "     @\"a\"\n"
21209                    "     ]\n"
21210                    "       copyItems:YES];",
21211                    Style));
21212   EXPECT_EQ(
21213       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21214       "                                  copyItems:YES];",
21215       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21216              "   copyItems:YES];",
21217              Style));
21218 
21219   verifyFormat("[self.a b:c c:d];", Style);
21220   EXPECT_EQ("[self.a b:c\n"
21221             "        c:d];",
21222             format("[self.a b:c\n"
21223                    "c:d];",
21224                    Style));
21225 }
21226 
21227 TEST_F(FormatTest, FormatsLambdas) {
21228   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
21229   verifyFormat(
21230       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
21231   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
21232   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
21233   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
21234   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
21235   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
21236   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
21237   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
21238   verifyFormat("int x = f(*+[] {});");
21239   verifyFormat("void f() {\n"
21240                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
21241                "}\n");
21242   verifyFormat("void f() {\n"
21243                "  other(x.begin(), //\n"
21244                "        x.end(),   //\n"
21245                "        [&](int, int) { return 1; });\n"
21246                "}\n");
21247   verifyFormat("void f() {\n"
21248                "  other.other.other.other.other(\n"
21249                "      x.begin(), x.end(),\n"
21250                "      [something, rather](int, int, int, int, int, int, int) { "
21251                "return 1; });\n"
21252                "}\n");
21253   verifyFormat(
21254       "void f() {\n"
21255       "  other.other.other.other.other(\n"
21256       "      x.begin(), x.end(),\n"
21257       "      [something, rather](int, int, int, int, int, int, int) {\n"
21258       "        //\n"
21259       "      });\n"
21260       "}\n");
21261   verifyFormat("SomeFunction([]() { // A cool function...\n"
21262                "  return 43;\n"
21263                "});");
21264   EXPECT_EQ("SomeFunction([]() {\n"
21265             "#define A a\n"
21266             "  return 43;\n"
21267             "});",
21268             format("SomeFunction([](){\n"
21269                    "#define A a\n"
21270                    "return 43;\n"
21271                    "});"));
21272   verifyFormat("void f() {\n"
21273                "  SomeFunction([](decltype(x), A *a) {});\n"
21274                "  SomeFunction([](typeof(x), A *a) {});\n"
21275                "  SomeFunction([](_Atomic(x), A *a) {});\n"
21276                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
21277                "}");
21278   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21279                "    [](const aaaaaaaaaa &a) { return a; });");
21280   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
21281                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
21282                "});");
21283   verifyFormat("Constructor()\n"
21284                "    : Field([] { // comment\n"
21285                "        int i;\n"
21286                "      }) {}");
21287   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
21288                "  return some_parameter.size();\n"
21289                "};");
21290   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
21291                "    [](const string &s) { return s; };");
21292   verifyFormat("int i = aaaaaa ? 1 //\n"
21293                "               : [] {\n"
21294                "                   return 2; //\n"
21295                "                 }();");
21296   verifyFormat("llvm::errs() << \"number of twos is \"\n"
21297                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
21298                "                  return x == 2; // force break\n"
21299                "                });");
21300   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21301                "    [=](int iiiiiiiiiiii) {\n"
21302                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
21303                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
21304                "    });",
21305                getLLVMStyleWithColumns(60));
21306 
21307   verifyFormat("SomeFunction({[&] {\n"
21308                "                // comment\n"
21309                "              },\n"
21310                "              [&] {\n"
21311                "                // comment\n"
21312                "              }});");
21313   verifyFormat("SomeFunction({[&] {\n"
21314                "  // comment\n"
21315                "}});");
21316   verifyFormat(
21317       "virtual aaaaaaaaaaaaaaaa(\n"
21318       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
21319       "    aaaaa aaaaaaaaa);");
21320 
21321   // Lambdas with return types.
21322   verifyFormat("int c = []() -> int { return 2; }();\n");
21323   verifyFormat("int c = []() -> int * { return 2; }();\n");
21324   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
21325   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
21326   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
21327   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
21328   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
21329   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
21330   verifyFormat("[a, a]() -> a<1> {};");
21331   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
21332   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
21333   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
21334   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
21335   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
21336   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
21337   verifyFormat("[]() -> foo<!5> { return {}; };");
21338   verifyFormat("[]() -> foo<~5> { return {}; };");
21339   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
21340   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
21341   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
21342   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
21343   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
21344   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
21345   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
21346   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
21347   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
21348   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
21349   verifyFormat("namespace bar {\n"
21350                "// broken:\n"
21351                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
21352                "} // namespace bar");
21353   verifyFormat("namespace bar {\n"
21354                "// broken:\n"
21355                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
21356                "} // namespace bar");
21357   verifyFormat("namespace bar {\n"
21358                "// broken:\n"
21359                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
21360                "} // namespace bar");
21361   verifyFormat("namespace bar {\n"
21362                "// broken:\n"
21363                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
21364                "} // namespace bar");
21365   verifyFormat("namespace bar {\n"
21366                "// broken:\n"
21367                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
21368                "} // namespace bar");
21369   verifyFormat("namespace bar {\n"
21370                "// broken:\n"
21371                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
21372                "} // namespace bar");
21373   verifyFormat("namespace bar {\n"
21374                "// broken:\n"
21375                "auto foo{[]() -> foo<!5> { return {}; }};\n"
21376                "} // namespace bar");
21377   verifyFormat("namespace bar {\n"
21378                "// broken:\n"
21379                "auto foo{[]() -> foo<~5> { return {}; }};\n"
21380                "} // namespace bar");
21381   verifyFormat("namespace bar {\n"
21382                "// broken:\n"
21383                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
21384                "} // namespace bar");
21385   verifyFormat("namespace bar {\n"
21386                "// broken:\n"
21387                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
21388                "} // namespace bar");
21389   verifyFormat("namespace bar {\n"
21390                "// broken:\n"
21391                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
21392                "} // namespace bar");
21393   verifyFormat("namespace bar {\n"
21394                "// broken:\n"
21395                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
21396                "} // namespace bar");
21397   verifyFormat("namespace bar {\n"
21398                "// broken:\n"
21399                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
21400                "} // namespace bar");
21401   verifyFormat("namespace bar {\n"
21402                "// broken:\n"
21403                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
21404                "} // namespace bar");
21405   verifyFormat("namespace bar {\n"
21406                "// broken:\n"
21407                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
21408                "} // namespace bar");
21409   verifyFormat("namespace bar {\n"
21410                "// broken:\n"
21411                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
21412                "} // namespace bar");
21413   verifyFormat("namespace bar {\n"
21414                "// broken:\n"
21415                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
21416                "} // namespace bar");
21417   verifyFormat("namespace bar {\n"
21418                "// broken:\n"
21419                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
21420                "} // namespace bar");
21421   verifyFormat("[]() -> a<1> {};");
21422   verifyFormat("[]() -> a<1> { ; };");
21423   verifyFormat("[]() -> a<1> { ; }();");
21424   verifyFormat("[a, a]() -> a<true> {};");
21425   verifyFormat("[]() -> a<true> {};");
21426   verifyFormat("[]() -> a<true> { ; };");
21427   verifyFormat("[]() -> a<true> { ; }();");
21428   verifyFormat("[a, a]() -> a<false> {};");
21429   verifyFormat("[]() -> a<false> {};");
21430   verifyFormat("[]() -> a<false> { ; };");
21431   verifyFormat("[]() -> a<false> { ; }();");
21432   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
21433   verifyFormat("namespace bar {\n"
21434                "auto foo{[]() -> foo<false> { ; }};\n"
21435                "} // namespace bar");
21436   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
21437                "                   int j) -> int {\n"
21438                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21439                "};");
21440   verifyFormat(
21441       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21442       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21443       "      return aaaaaaaaaaaaaaaaa;\n"
21444       "    });",
21445       getLLVMStyleWithColumns(70));
21446   verifyFormat("[]() //\n"
21447                "    -> int {\n"
21448                "  return 1; //\n"
21449                "};");
21450   verifyFormat("[]() -> Void<T...> {};");
21451   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21452   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21453   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21454   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21455   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21456   verifyFormat("return int{[x = x]() { return x; }()};");
21457 
21458   // Lambdas with explicit template argument lists.
21459   verifyFormat(
21460       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21461   verifyFormat("auto L = []<class T>(T) {\n"
21462                "  {\n"
21463                "    f();\n"
21464                "    g();\n"
21465                "  }\n"
21466                "};\n");
21467   verifyFormat("auto L = []<class... T>(T...) {\n"
21468                "  {\n"
21469                "    f();\n"
21470                "    g();\n"
21471                "  }\n"
21472                "};\n");
21473   verifyFormat("auto L = []<typename... T>(T...) {\n"
21474                "  {\n"
21475                "    f();\n"
21476                "    g();\n"
21477                "  }\n"
21478                "};\n");
21479   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21480                "  {\n"
21481                "    f();\n"
21482                "    g();\n"
21483                "  }\n"
21484                "};\n");
21485   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21486                "  {\n"
21487                "    f();\n"
21488                "    g();\n"
21489                "  }\n"
21490                "};\n");
21491 
21492   // Multiple lambdas in the same parentheses change indentation rules. These
21493   // lambdas are forced to start on new lines.
21494   verifyFormat("SomeFunction(\n"
21495                "    []() {\n"
21496                "      //\n"
21497                "    },\n"
21498                "    []() {\n"
21499                "      //\n"
21500                "    });");
21501 
21502   // A lambda passed as arg0 is always pushed to the next line.
21503   verifyFormat("SomeFunction(\n"
21504                "    [this] {\n"
21505                "      //\n"
21506                "    },\n"
21507                "    1);\n");
21508 
21509   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21510   // the arg0 case above.
21511   auto Style = getGoogleStyle();
21512   Style.BinPackArguments = false;
21513   verifyFormat("SomeFunction(\n"
21514                "    a,\n"
21515                "    [this] {\n"
21516                "      //\n"
21517                "    },\n"
21518                "    b);\n",
21519                Style);
21520   verifyFormat("SomeFunction(\n"
21521                "    a,\n"
21522                "    [this] {\n"
21523                "      //\n"
21524                "    },\n"
21525                "    b);\n");
21526 
21527   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21528   // the BinPackArguments value (as long as the code is wide enough).
21529   verifyFormat(
21530       "something->SomeFunction(\n"
21531       "    a,\n"
21532       "    [this] {\n"
21533       "      "
21534       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21535       "    },\n"
21536       "    b);\n");
21537 
21538   // A multi-line lambda is pulled up as long as the introducer fits on the
21539   // previous line and there are no further args.
21540   verifyFormat("function(1, [this, that] {\n"
21541                "  //\n"
21542                "});\n");
21543   verifyFormat("function([this, that] {\n"
21544                "  //\n"
21545                "});\n");
21546   // FIXME: this format is not ideal and we should consider forcing the first
21547   // arg onto its own line.
21548   verifyFormat("function(a, b, c, //\n"
21549                "         d, [this, that] {\n"
21550                "           //\n"
21551                "         });\n");
21552 
21553   // Multiple lambdas are treated correctly even when there is a short arg0.
21554   verifyFormat("SomeFunction(\n"
21555                "    1,\n"
21556                "    [this] {\n"
21557                "      //\n"
21558                "    },\n"
21559                "    [this] {\n"
21560                "      //\n"
21561                "    },\n"
21562                "    1);\n");
21563 
21564   // More complex introducers.
21565   verifyFormat("return [i, args...] {};");
21566 
21567   // Not lambdas.
21568   verifyFormat("constexpr char hello[]{\"hello\"};");
21569   verifyFormat("double &operator[](int i) { return 0; }\n"
21570                "int i;");
21571   verifyFormat("std::unique_ptr<int[]> foo() {}");
21572   verifyFormat("int i = a[a][a]->f();");
21573   verifyFormat("int i = (*b)[a]->f();");
21574 
21575   // Other corner cases.
21576   verifyFormat("void f() {\n"
21577                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21578                "  );\n"
21579                "}");
21580   verifyFormat("auto k = *[](int *j) { return j; }(&i);");
21581 
21582   // Lambdas created through weird macros.
21583   verifyFormat("void f() {\n"
21584                "  MACRO((const AA &a) { return 1; });\n"
21585                "  MACRO((AA &a) { return 1; });\n"
21586                "}");
21587 
21588   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21589                "      doo_dah();\n"
21590                "      doo_dah();\n"
21591                "    })) {\n"
21592                "}");
21593   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21594                "                doo_dah();\n"
21595                "                doo_dah();\n"
21596                "              })) {\n"
21597                "}");
21598   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21599                "                doo_dah();\n"
21600                "                doo_dah();\n"
21601                "              })) {\n"
21602                "}");
21603   verifyFormat("auto lambda = []() {\n"
21604                "  int a = 2\n"
21605                "#if A\n"
21606                "          + 2\n"
21607                "#endif\n"
21608                "      ;\n"
21609                "};");
21610 
21611   // Lambdas with complex multiline introducers.
21612   verifyFormat(
21613       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21614       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21615       "        -> ::std::unordered_set<\n"
21616       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21617       "      //\n"
21618       "    });");
21619 
21620   FormatStyle DoNotMerge = getLLVMStyle();
21621   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21622   verifyFormat("auto c = []() {\n"
21623                "  return b;\n"
21624                "};",
21625                "auto c = []() { return b; };", DoNotMerge);
21626   verifyFormat("auto c = []() {\n"
21627                "};",
21628                " auto c = []() {};", DoNotMerge);
21629 
21630   FormatStyle MergeEmptyOnly = getLLVMStyle();
21631   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21632   verifyFormat("auto c = []() {\n"
21633                "  return b;\n"
21634                "};",
21635                "auto c = []() {\n"
21636                "  return b;\n"
21637                " };",
21638                MergeEmptyOnly);
21639   verifyFormat("auto c = []() {};",
21640                "auto c = []() {\n"
21641                "};",
21642                MergeEmptyOnly);
21643 
21644   FormatStyle MergeInline = getLLVMStyle();
21645   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21646   verifyFormat("auto c = []() {\n"
21647                "  return b;\n"
21648                "};",
21649                "auto c = []() { return b; };", MergeInline);
21650   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21651                MergeInline);
21652   verifyFormat("function([]() { return b; }, a)",
21653                "function([]() { return b; }, a)", MergeInline);
21654   verifyFormat("function(a, []() { return b; })",
21655                "function(a, []() { return b; })", MergeInline);
21656 
21657   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21658   // AllowShortLambdasOnASingleLine
21659   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21660   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21661   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21662   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21663       FormatStyle::ShortLambdaStyle::SLS_None;
21664   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21665                "    []()\n"
21666                "    {\n"
21667                "      return 17;\n"
21668                "    });",
21669                LLVMWithBeforeLambdaBody);
21670   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21671                "    []()\n"
21672                "    {\n"
21673                "    });",
21674                LLVMWithBeforeLambdaBody);
21675   verifyFormat("auto fct_SLS_None = []()\n"
21676                "{\n"
21677                "  return 17;\n"
21678                "};",
21679                LLVMWithBeforeLambdaBody);
21680   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21681                "    []()\n"
21682                "    {\n"
21683                "      return Call(\n"
21684                "          []()\n"
21685                "          {\n"
21686                "            return 17;\n"
21687                "          });\n"
21688                "    });",
21689                LLVMWithBeforeLambdaBody);
21690   verifyFormat("void Fct() {\n"
21691                "  return {[]()\n"
21692                "          {\n"
21693                "            return 17;\n"
21694                "          }};\n"
21695                "}",
21696                LLVMWithBeforeLambdaBody);
21697 
21698   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21699       FormatStyle::ShortLambdaStyle::SLS_Empty;
21700   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21701                "    []()\n"
21702                "    {\n"
21703                "      return 17;\n"
21704                "    });",
21705                LLVMWithBeforeLambdaBody);
21706   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21707                LLVMWithBeforeLambdaBody);
21708   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21709                "ongFunctionName_SLS_Empty(\n"
21710                "    []() {});",
21711                LLVMWithBeforeLambdaBody);
21712   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21713                "                                []()\n"
21714                "                                {\n"
21715                "                                  return 17;\n"
21716                "                                });",
21717                LLVMWithBeforeLambdaBody);
21718   verifyFormat("auto fct_SLS_Empty = []()\n"
21719                "{\n"
21720                "  return 17;\n"
21721                "};",
21722                LLVMWithBeforeLambdaBody);
21723   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21724                "    []()\n"
21725                "    {\n"
21726                "      return Call([]() {});\n"
21727                "    });",
21728                LLVMWithBeforeLambdaBody);
21729   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21730                "                           []()\n"
21731                "                           {\n"
21732                "                             return Call([]() {});\n"
21733                "                           });",
21734                LLVMWithBeforeLambdaBody);
21735   verifyFormat(
21736       "FctWithLongLineInLambda_SLS_Empty(\n"
21737       "    []()\n"
21738       "    {\n"
21739       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21740       "                               AndShouldNotBeConsiderAsInline,\n"
21741       "                               LambdaBodyMustBeBreak);\n"
21742       "    });",
21743       LLVMWithBeforeLambdaBody);
21744 
21745   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21746       FormatStyle::ShortLambdaStyle::SLS_Inline;
21747   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21748                LLVMWithBeforeLambdaBody);
21749   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21750                LLVMWithBeforeLambdaBody);
21751   verifyFormat("auto fct_SLS_Inline = []()\n"
21752                "{\n"
21753                "  return 17;\n"
21754                "};",
21755                LLVMWithBeforeLambdaBody);
21756   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21757                "17; }); });",
21758                LLVMWithBeforeLambdaBody);
21759   verifyFormat(
21760       "FctWithLongLineInLambda_SLS_Inline(\n"
21761       "    []()\n"
21762       "    {\n"
21763       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21764       "                               AndShouldNotBeConsiderAsInline,\n"
21765       "                               LambdaBodyMustBeBreak);\n"
21766       "    });",
21767       LLVMWithBeforeLambdaBody);
21768   verifyFormat("FctWithMultipleParams_SLS_Inline("
21769                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21770                "                                 []() { return 17; });",
21771                LLVMWithBeforeLambdaBody);
21772   verifyFormat(
21773       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21774       LLVMWithBeforeLambdaBody);
21775 
21776   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21777       FormatStyle::ShortLambdaStyle::SLS_All;
21778   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21779                LLVMWithBeforeLambdaBody);
21780   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21781                LLVMWithBeforeLambdaBody);
21782   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21783                LLVMWithBeforeLambdaBody);
21784   verifyFormat("FctWithOneParam_SLS_All(\n"
21785                "    []()\n"
21786                "    {\n"
21787                "      // A cool function...\n"
21788                "      return 43;\n"
21789                "    });",
21790                LLVMWithBeforeLambdaBody);
21791   verifyFormat("FctWithMultipleParams_SLS_All("
21792                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21793                "                              []() { return 17; });",
21794                LLVMWithBeforeLambdaBody);
21795   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21796                LLVMWithBeforeLambdaBody);
21797   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21798                LLVMWithBeforeLambdaBody);
21799   verifyFormat(
21800       "FctWithLongLineInLambda_SLS_All(\n"
21801       "    []()\n"
21802       "    {\n"
21803       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21804       "                               AndShouldNotBeConsiderAsInline,\n"
21805       "                               LambdaBodyMustBeBreak);\n"
21806       "    });",
21807       LLVMWithBeforeLambdaBody);
21808   verifyFormat(
21809       "auto fct_SLS_All = []()\n"
21810       "{\n"
21811       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21812       "                           AndShouldNotBeConsiderAsInline,\n"
21813       "                           LambdaBodyMustBeBreak);\n"
21814       "};",
21815       LLVMWithBeforeLambdaBody);
21816   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21817   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21818                LLVMWithBeforeLambdaBody);
21819   verifyFormat(
21820       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21821       "                                FirstParam,\n"
21822       "                                SecondParam,\n"
21823       "                                ThirdParam,\n"
21824       "                                FourthParam);",
21825       LLVMWithBeforeLambdaBody);
21826   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21827                "    []() { return "
21828                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21829                "    FirstParam,\n"
21830                "    SecondParam,\n"
21831                "    ThirdParam,\n"
21832                "    FourthParam);",
21833                LLVMWithBeforeLambdaBody);
21834   verifyFormat(
21835       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21836       "                                SecondParam,\n"
21837       "                                ThirdParam,\n"
21838       "                                FourthParam,\n"
21839       "                                []() { return SomeValueNotSoLong; });",
21840       LLVMWithBeforeLambdaBody);
21841   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21842                "    []()\n"
21843                "    {\n"
21844                "      return "
21845                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21846                "eConsiderAsInline;\n"
21847                "    });",
21848                LLVMWithBeforeLambdaBody);
21849   verifyFormat(
21850       "FctWithLongLineInLambda_SLS_All(\n"
21851       "    []()\n"
21852       "    {\n"
21853       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21854       "                               AndShouldNotBeConsiderAsInline,\n"
21855       "                               LambdaBodyMustBeBreak);\n"
21856       "    });",
21857       LLVMWithBeforeLambdaBody);
21858   verifyFormat("FctWithTwoParams_SLS_All(\n"
21859                "    []()\n"
21860                "    {\n"
21861                "      // A cool function...\n"
21862                "      return 43;\n"
21863                "    },\n"
21864                "    87);",
21865                LLVMWithBeforeLambdaBody);
21866   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
21867                LLVMWithBeforeLambdaBody);
21868   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
21869                LLVMWithBeforeLambdaBody);
21870   verifyFormat(
21871       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
21872       LLVMWithBeforeLambdaBody);
21873   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
21874                "}); }, x);",
21875                LLVMWithBeforeLambdaBody);
21876   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21877                "    []()\n"
21878                "    {\n"
21879                "      // A cool function...\n"
21880                "      return Call([]() { return 17; });\n"
21881                "    });",
21882                LLVMWithBeforeLambdaBody);
21883   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21884                "    []()\n"
21885                "    {\n"
21886                "      return Call(\n"
21887                "          []()\n"
21888                "          {\n"
21889                "            // A cool function...\n"
21890                "            return 17;\n"
21891                "          });\n"
21892                "    });",
21893                LLVMWithBeforeLambdaBody);
21894 
21895   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21896       FormatStyle::ShortLambdaStyle::SLS_None;
21897 
21898   verifyFormat("auto select = [this]() -> const Library::Object *\n"
21899                "{\n"
21900                "  return MyAssignment::SelectFromList(this);\n"
21901                "};\n",
21902                LLVMWithBeforeLambdaBody);
21903 
21904   verifyFormat("auto select = [this]() -> const Library::Object &\n"
21905                "{\n"
21906                "  return MyAssignment::SelectFromList(this);\n"
21907                "};\n",
21908                LLVMWithBeforeLambdaBody);
21909 
21910   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
21911                "{\n"
21912                "  return MyAssignment::SelectFromList(this);\n"
21913                "};\n",
21914                LLVMWithBeforeLambdaBody);
21915 
21916   verifyFormat("namespace test {\n"
21917                "class Test {\n"
21918                "public:\n"
21919                "  Test() = default;\n"
21920                "};\n"
21921                "} // namespace test",
21922                LLVMWithBeforeLambdaBody);
21923 
21924   // Lambdas with different indentation styles.
21925   Style = getLLVMStyleWithColumns(100);
21926   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21927             "  return promise.then(\n"
21928             "      [this, &someVariable, someObject = "
21929             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21930             "        return someObject.startAsyncAction().then(\n"
21931             "            [this, &someVariable](AsyncActionResult result) "
21932             "mutable { result.processMore(); });\n"
21933             "      });\n"
21934             "}\n",
21935             format("SomeResult doSomething(SomeObject promise) {\n"
21936                    "  return promise.then([this, &someVariable, someObject = "
21937                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21938                    "    return someObject.startAsyncAction().then([this, "
21939                    "&someVariable](AsyncActionResult result) mutable {\n"
21940                    "      result.processMore();\n"
21941                    "    });\n"
21942                    "  });\n"
21943                    "}\n",
21944                    Style));
21945   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21946   verifyFormat("test() {\n"
21947                "  ([]() -> {\n"
21948                "    int b = 32;\n"
21949                "    return 3;\n"
21950                "  }).foo();\n"
21951                "}",
21952                Style);
21953   verifyFormat("test() {\n"
21954                "  []() -> {\n"
21955                "    int b = 32;\n"
21956                "    return 3;\n"
21957                "  }\n"
21958                "}",
21959                Style);
21960   verifyFormat("std::sort(v.begin(), v.end(),\n"
21961                "          [](const auto &someLongArgumentName, const auto "
21962                "&someOtherLongArgumentName) {\n"
21963                "  return someLongArgumentName.someMemberVariable < "
21964                "someOtherLongArgumentName.someMemberVariable;\n"
21965                "});",
21966                Style);
21967   verifyFormat("test() {\n"
21968                "  (\n"
21969                "      []() -> {\n"
21970                "        int b = 32;\n"
21971                "        return 3;\n"
21972                "      },\n"
21973                "      foo, bar)\n"
21974                "      .foo();\n"
21975                "}",
21976                Style);
21977   verifyFormat("test() {\n"
21978                "  ([]() -> {\n"
21979                "    int b = 32;\n"
21980                "    return 3;\n"
21981                "  })\n"
21982                "      .foo()\n"
21983                "      .bar();\n"
21984                "}",
21985                Style);
21986   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21987             "  return promise.then(\n"
21988             "      [this, &someVariable, someObject = "
21989             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21990             "    return someObject.startAsyncAction().then(\n"
21991             "        [this, &someVariable](AsyncActionResult result) mutable { "
21992             "result.processMore(); });\n"
21993             "  });\n"
21994             "}\n",
21995             format("SomeResult doSomething(SomeObject promise) {\n"
21996                    "  return promise.then([this, &someVariable, someObject = "
21997                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21998                    "    return someObject.startAsyncAction().then([this, "
21999                    "&someVariable](AsyncActionResult result) mutable {\n"
22000                    "      result.processMore();\n"
22001                    "    });\n"
22002                    "  });\n"
22003                    "}\n",
22004                    Style));
22005   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
22006             "  return promise.then([this, &someVariable] {\n"
22007             "    return someObject.startAsyncAction().then(\n"
22008             "        [this, &someVariable](AsyncActionResult result) mutable { "
22009             "result.processMore(); });\n"
22010             "  });\n"
22011             "}\n",
22012             format("SomeResult doSomething(SomeObject promise) {\n"
22013                    "  return promise.then([this, &someVariable] {\n"
22014                    "    return someObject.startAsyncAction().then([this, "
22015                    "&someVariable](AsyncActionResult result) mutable {\n"
22016                    "      result.processMore();\n"
22017                    "    });\n"
22018                    "  });\n"
22019                    "}\n",
22020                    Style));
22021   Style = getGoogleStyle();
22022   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
22023   EXPECT_EQ("#define A                                       \\\n"
22024             "  [] {                                          \\\n"
22025             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
22026             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
22027             "      }",
22028             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
22029                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
22030                    Style));
22031   // TODO: The current formatting has a minor issue that's not worth fixing
22032   // right now whereby the closing brace is indented relative to the signature
22033   // instead of being aligned. This only happens with macros.
22034 }
22035 
22036 TEST_F(FormatTest, LambdaWithLineComments) {
22037   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
22038   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
22039   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
22040   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
22041       FormatStyle::ShortLambdaStyle::SLS_All;
22042 
22043   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
22044   verifyFormat("auto k = []() // comment\n"
22045                "{ return; }",
22046                LLVMWithBeforeLambdaBody);
22047   verifyFormat("auto k = []() /* comment */ { return; }",
22048                LLVMWithBeforeLambdaBody);
22049   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
22050                LLVMWithBeforeLambdaBody);
22051   verifyFormat("auto k = []() // X\n"
22052                "{ return; }",
22053                LLVMWithBeforeLambdaBody);
22054   verifyFormat(
22055       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
22056       "{ return; }",
22057       LLVMWithBeforeLambdaBody);
22058 
22059   LLVMWithBeforeLambdaBody.ColumnLimit = 0;
22060 
22061   verifyFormat("foo([]()\n"
22062                "    {\n"
22063                "      bar();    //\n"
22064                "      return 1; // comment\n"
22065                "    }());",
22066                "foo([]() {\n"
22067                "  bar(); //\n"
22068                "  return 1; // comment\n"
22069                "}());",
22070                LLVMWithBeforeLambdaBody);
22071   verifyFormat("foo(\n"
22072                "    1, MACRO {\n"
22073                "      baz();\n"
22074                "      bar(); // comment\n"
22075                "    },\n"
22076                "    []() {});",
22077                "foo(\n"
22078                "  1, MACRO { baz(); bar(); // comment\n"
22079                "  }, []() {}\n"
22080                ");",
22081                LLVMWithBeforeLambdaBody);
22082 }
22083 
22084 TEST_F(FormatTest, EmptyLinesInLambdas) {
22085   verifyFormat("auto lambda = []() {\n"
22086                "  x(); //\n"
22087                "};",
22088                "auto lambda = []() {\n"
22089                "\n"
22090                "  x(); //\n"
22091                "\n"
22092                "};");
22093 }
22094 
22095 TEST_F(FormatTest, FormatsBlocks) {
22096   FormatStyle ShortBlocks = getLLVMStyle();
22097   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22098   verifyFormat("int (^Block)(int, int);", ShortBlocks);
22099   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
22100   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
22101   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
22102   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
22103   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
22104 
22105   verifyFormat("foo(^{ bar(); });", ShortBlocks);
22106   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
22107   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
22108 
22109   verifyFormat("[operation setCompletionBlock:^{\n"
22110                "  [self onOperationDone];\n"
22111                "}];");
22112   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
22113                "  [self onOperationDone];\n"
22114                "}]};");
22115   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
22116                "  f();\n"
22117                "}];");
22118   verifyFormat("int a = [operation block:^int(int *i) {\n"
22119                "  return 1;\n"
22120                "}];");
22121   verifyFormat("[myObject doSomethingWith:arg1\n"
22122                "                      aaa:^int(int *a) {\n"
22123                "                        return 1;\n"
22124                "                      }\n"
22125                "                      bbb:f(a * bbbbbbbb)];");
22126 
22127   verifyFormat("[operation setCompletionBlock:^{\n"
22128                "  [self.delegate newDataAvailable];\n"
22129                "}];",
22130                getLLVMStyleWithColumns(60));
22131   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
22132                "  NSString *path = [self sessionFilePath];\n"
22133                "  if (path) {\n"
22134                "    // ...\n"
22135                "  }\n"
22136                "});");
22137   verifyFormat("[[SessionService sharedService]\n"
22138                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22139                "      if (window) {\n"
22140                "        [self windowDidLoad:window];\n"
22141                "      } else {\n"
22142                "        [self errorLoadingWindow];\n"
22143                "      }\n"
22144                "    }];");
22145   verifyFormat("void (^largeBlock)(void) = ^{\n"
22146                "  // ...\n"
22147                "};\n",
22148                getLLVMStyleWithColumns(40));
22149   verifyFormat("[[SessionService sharedService]\n"
22150                "    loadWindowWithCompletionBlock: //\n"
22151                "        ^(SessionWindow *window) {\n"
22152                "          if (window) {\n"
22153                "            [self windowDidLoad:window];\n"
22154                "          } else {\n"
22155                "            [self errorLoadingWindow];\n"
22156                "          }\n"
22157                "        }];",
22158                getLLVMStyleWithColumns(60));
22159   verifyFormat("[myObject doSomethingWith:arg1\n"
22160                "    firstBlock:^(Foo *a) {\n"
22161                "      // ...\n"
22162                "      int i;\n"
22163                "    }\n"
22164                "    secondBlock:^(Bar *b) {\n"
22165                "      // ...\n"
22166                "      int i;\n"
22167                "    }\n"
22168                "    thirdBlock:^Foo(Bar *b) {\n"
22169                "      // ...\n"
22170                "      int i;\n"
22171                "    }];");
22172   verifyFormat("[myObject doSomethingWith:arg1\n"
22173                "               firstBlock:-1\n"
22174                "              secondBlock:^(Bar *b) {\n"
22175                "                // ...\n"
22176                "                int i;\n"
22177                "              }];");
22178 
22179   verifyFormat("f(^{\n"
22180                "  @autoreleasepool {\n"
22181                "    if (a) {\n"
22182                "      g();\n"
22183                "    }\n"
22184                "  }\n"
22185                "});");
22186   verifyFormat("Block b = ^int *(A *a, B *b) {}");
22187   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
22188                "};");
22189 
22190   FormatStyle FourIndent = getLLVMStyle();
22191   FourIndent.ObjCBlockIndentWidth = 4;
22192   verifyFormat("[operation setCompletionBlock:^{\n"
22193                "    [self onOperationDone];\n"
22194                "}];",
22195                FourIndent);
22196 }
22197 
22198 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
22199   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
22200 
22201   verifyFormat("[[SessionService sharedService] "
22202                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22203                "  if (window) {\n"
22204                "    [self windowDidLoad:window];\n"
22205                "  } else {\n"
22206                "    [self errorLoadingWindow];\n"
22207                "  }\n"
22208                "}];",
22209                ZeroColumn);
22210   EXPECT_EQ("[[SessionService sharedService]\n"
22211             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22212             "      if (window) {\n"
22213             "        [self windowDidLoad:window];\n"
22214             "      } else {\n"
22215             "        [self errorLoadingWindow];\n"
22216             "      }\n"
22217             "    }];",
22218             format("[[SessionService sharedService]\n"
22219                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22220                    "                if (window) {\n"
22221                    "    [self windowDidLoad:window];\n"
22222                    "  } else {\n"
22223                    "    [self errorLoadingWindow];\n"
22224                    "  }\n"
22225                    "}];",
22226                    ZeroColumn));
22227   verifyFormat("[myObject doSomethingWith:arg1\n"
22228                "    firstBlock:^(Foo *a) {\n"
22229                "      // ...\n"
22230                "      int i;\n"
22231                "    }\n"
22232                "    secondBlock:^(Bar *b) {\n"
22233                "      // ...\n"
22234                "      int i;\n"
22235                "    }\n"
22236                "    thirdBlock:^Foo(Bar *b) {\n"
22237                "      // ...\n"
22238                "      int i;\n"
22239                "    }];",
22240                ZeroColumn);
22241   verifyFormat("f(^{\n"
22242                "  @autoreleasepool {\n"
22243                "    if (a) {\n"
22244                "      g();\n"
22245                "    }\n"
22246                "  }\n"
22247                "});",
22248                ZeroColumn);
22249   verifyFormat("void (^largeBlock)(void) = ^{\n"
22250                "  // ...\n"
22251                "};",
22252                ZeroColumn);
22253 
22254   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22255   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
22256             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22257   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
22258   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
22259             "  int i;\n"
22260             "};",
22261             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22262 }
22263 
22264 TEST_F(FormatTest, SupportsCRLF) {
22265   EXPECT_EQ("int a;\r\n"
22266             "int b;\r\n"
22267             "int c;\r\n",
22268             format("int a;\r\n"
22269                    "  int b;\r\n"
22270                    "    int c;\r\n",
22271                    getLLVMStyle()));
22272   EXPECT_EQ("int a;\r\n"
22273             "int b;\r\n"
22274             "int c;\r\n",
22275             format("int a;\r\n"
22276                    "  int b;\n"
22277                    "    int c;\r\n",
22278                    getLLVMStyle()));
22279   EXPECT_EQ("int a;\n"
22280             "int b;\n"
22281             "int c;\n",
22282             format("int a;\r\n"
22283                    "  int b;\n"
22284                    "    int c;\n",
22285                    getLLVMStyle()));
22286   EXPECT_EQ("\"aaaaaaa \"\r\n"
22287             "\"bbbbbbb\";\r\n",
22288             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
22289   EXPECT_EQ("#define A \\\r\n"
22290             "  b;      \\\r\n"
22291             "  c;      \\\r\n"
22292             "  d;\r\n",
22293             format("#define A \\\r\n"
22294                    "  b; \\\r\n"
22295                    "  c; d; \r\n",
22296                    getGoogleStyle()));
22297 
22298   EXPECT_EQ("/*\r\n"
22299             "multi line block comments\r\n"
22300             "should not introduce\r\n"
22301             "an extra carriage return\r\n"
22302             "*/\r\n",
22303             format("/*\r\n"
22304                    "multi line block comments\r\n"
22305                    "should not introduce\r\n"
22306                    "an extra carriage return\r\n"
22307                    "*/\r\n"));
22308   EXPECT_EQ("/*\r\n"
22309             "\r\n"
22310             "*/",
22311             format("/*\r\n"
22312                    "    \r\r\r\n"
22313                    "*/"));
22314 
22315   FormatStyle style = getLLVMStyle();
22316 
22317   style.DeriveLineEnding = true;
22318   style.UseCRLF = false;
22319   EXPECT_EQ("union FooBarBazQux {\n"
22320             "  int foo;\n"
22321             "  int bar;\n"
22322             "  int baz;\n"
22323             "};",
22324             format("union FooBarBazQux {\r\n"
22325                    "  int foo;\n"
22326                    "  int bar;\r\n"
22327                    "  int baz;\n"
22328                    "};",
22329                    style));
22330   style.UseCRLF = true;
22331   EXPECT_EQ("union FooBarBazQux {\r\n"
22332             "  int foo;\r\n"
22333             "  int bar;\r\n"
22334             "  int baz;\r\n"
22335             "};",
22336             format("union FooBarBazQux {\r\n"
22337                    "  int foo;\n"
22338                    "  int bar;\r\n"
22339                    "  int baz;\n"
22340                    "};",
22341                    style));
22342 
22343   style.DeriveLineEnding = false;
22344   style.UseCRLF = false;
22345   EXPECT_EQ("union FooBarBazQux {\n"
22346             "  int foo;\n"
22347             "  int bar;\n"
22348             "  int baz;\n"
22349             "  int qux;\n"
22350             "};",
22351             format("union FooBarBazQux {\r\n"
22352                    "  int foo;\n"
22353                    "  int bar;\r\n"
22354                    "  int baz;\n"
22355                    "  int qux;\r\n"
22356                    "};",
22357                    style));
22358   style.UseCRLF = true;
22359   EXPECT_EQ("union FooBarBazQux {\r\n"
22360             "  int foo;\r\n"
22361             "  int bar;\r\n"
22362             "  int baz;\r\n"
22363             "  int qux;\r\n"
22364             "};",
22365             format("union FooBarBazQux {\r\n"
22366                    "  int foo;\n"
22367                    "  int bar;\r\n"
22368                    "  int baz;\n"
22369                    "  int qux;\n"
22370                    "};",
22371                    style));
22372 
22373   style.DeriveLineEnding = true;
22374   style.UseCRLF = false;
22375   EXPECT_EQ("union FooBarBazQux {\r\n"
22376             "  int foo;\r\n"
22377             "  int bar;\r\n"
22378             "  int baz;\r\n"
22379             "  int qux;\r\n"
22380             "};",
22381             format("union FooBarBazQux {\r\n"
22382                    "  int foo;\n"
22383                    "  int bar;\r\n"
22384                    "  int baz;\n"
22385                    "  int qux;\r\n"
22386                    "};",
22387                    style));
22388   style.UseCRLF = true;
22389   EXPECT_EQ("union FooBarBazQux {\n"
22390             "  int foo;\n"
22391             "  int bar;\n"
22392             "  int baz;\n"
22393             "  int qux;\n"
22394             "};",
22395             format("union FooBarBazQux {\r\n"
22396                    "  int foo;\n"
22397                    "  int bar;\r\n"
22398                    "  int baz;\n"
22399                    "  int qux;\n"
22400                    "};",
22401                    style));
22402 }
22403 
22404 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
22405   verifyFormat("MY_CLASS(C) {\n"
22406                "  int i;\n"
22407                "  int j;\n"
22408                "};");
22409 }
22410 
22411 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
22412   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
22413   TwoIndent.ContinuationIndentWidth = 2;
22414 
22415   EXPECT_EQ("int i =\n"
22416             "  longFunction(\n"
22417             "    arg);",
22418             format("int i = longFunction(arg);", TwoIndent));
22419 
22420   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
22421   SixIndent.ContinuationIndentWidth = 6;
22422 
22423   EXPECT_EQ("int i =\n"
22424             "      longFunction(\n"
22425             "            arg);",
22426             format("int i = longFunction(arg);", SixIndent));
22427 }
22428 
22429 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
22430   FormatStyle Style = getLLVMStyle();
22431   verifyFormat("int Foo::getter(\n"
22432                "    //\n"
22433                ") const {\n"
22434                "  return foo;\n"
22435                "}",
22436                Style);
22437   verifyFormat("void Foo::setter(\n"
22438                "    //\n"
22439                ") {\n"
22440                "  foo = 1;\n"
22441                "}",
22442                Style);
22443 }
22444 
22445 TEST_F(FormatTest, SpacesInAngles) {
22446   FormatStyle Spaces = getLLVMStyle();
22447   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22448 
22449   verifyFormat("vector< ::std::string > x1;", Spaces);
22450   verifyFormat("Foo< int, Bar > x2;", Spaces);
22451   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
22452 
22453   verifyFormat("static_cast< int >(arg);", Spaces);
22454   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
22455   verifyFormat("f< int, float >();", Spaces);
22456   verifyFormat("template <> g() {}", Spaces);
22457   verifyFormat("template < std::vector< int > > f() {}", Spaces);
22458   verifyFormat("std::function< void(int, int) > fct;", Spaces);
22459   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
22460                Spaces);
22461 
22462   Spaces.Standard = FormatStyle::LS_Cpp03;
22463   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22464   verifyFormat("A< A< int > >();", Spaces);
22465 
22466   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22467   verifyFormat("A<A<int> >();", Spaces);
22468 
22469   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22470   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22471                Spaces);
22472   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22473                Spaces);
22474 
22475   verifyFormat("A<A<int> >();", Spaces);
22476   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22477   verifyFormat("A< A< int > >();", Spaces);
22478 
22479   Spaces.Standard = FormatStyle::LS_Cpp11;
22480   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22481   verifyFormat("A< A< int > >();", Spaces);
22482 
22483   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22484   verifyFormat("vector<::std::string> x4;", Spaces);
22485   verifyFormat("vector<int> x5;", Spaces);
22486   verifyFormat("Foo<int, Bar> x6;", Spaces);
22487   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22488 
22489   verifyFormat("A<A<int>>();", Spaces);
22490 
22491   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22492   verifyFormat("vector<::std::string> x4;", Spaces);
22493   verifyFormat("vector< ::std::string > x4;", Spaces);
22494   verifyFormat("vector<int> x5;", Spaces);
22495   verifyFormat("vector< int > x5;", Spaces);
22496   verifyFormat("Foo<int, Bar> x6;", Spaces);
22497   verifyFormat("Foo< int, Bar > x6;", Spaces);
22498   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22499   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22500 
22501   verifyFormat("A<A<int>>();", Spaces);
22502   verifyFormat("A< A< int > >();", Spaces);
22503   verifyFormat("A<A<int > >();", Spaces);
22504   verifyFormat("A< A< int>>();", Spaces);
22505 
22506   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22507   verifyFormat("// clang-format off\n"
22508                "foo<<<1, 1>>>();\n"
22509                "// clang-format on\n",
22510                Spaces);
22511   verifyFormat("// clang-format off\n"
22512                "foo< < <1, 1> > >();\n"
22513                "// clang-format on\n",
22514                Spaces);
22515 }
22516 
22517 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22518   FormatStyle Style = getLLVMStyle();
22519   Style.SpaceAfterTemplateKeyword = false;
22520   verifyFormat("template<int> void foo();", Style);
22521 }
22522 
22523 TEST_F(FormatTest, TripleAngleBrackets) {
22524   verifyFormat("f<<<1, 1>>>();");
22525   verifyFormat("f<<<1, 1, 1, s>>>();");
22526   verifyFormat("f<<<a, b, c, d>>>();");
22527   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22528   verifyFormat("f<param><<<1, 1>>>();");
22529   verifyFormat("f<1><<<1, 1>>>();");
22530   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22531   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22532                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22533   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22534                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22535 }
22536 
22537 TEST_F(FormatTest, MergeLessLessAtEnd) {
22538   verifyFormat("<<");
22539   EXPECT_EQ("< < <", format("\\\n<<<"));
22540   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22541                "aaallvm::outs() <<");
22542   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22543                "aaaallvm::outs()\n    <<");
22544 }
22545 
22546 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22547   std::string code = "#if A\n"
22548                      "#if B\n"
22549                      "a.\n"
22550                      "#endif\n"
22551                      "    a = 1;\n"
22552                      "#else\n"
22553                      "#endif\n"
22554                      "#if C\n"
22555                      "#else\n"
22556                      "#endif\n";
22557   EXPECT_EQ(code, format(code));
22558 }
22559 
22560 TEST_F(FormatTest, HandleConflictMarkers) {
22561   // Git/SVN conflict markers.
22562   EXPECT_EQ("int a;\n"
22563             "void f() {\n"
22564             "  callme(some(parameter1,\n"
22565             "<<<<<<< text by the vcs\n"
22566             "              parameter2),\n"
22567             "||||||| text by the vcs\n"
22568             "              parameter2),\n"
22569             "         parameter3,\n"
22570             "======= text by the vcs\n"
22571             "              parameter2, parameter3),\n"
22572             ">>>>>>> text by the vcs\n"
22573             "         otherparameter);\n",
22574             format("int a;\n"
22575                    "void f() {\n"
22576                    "  callme(some(parameter1,\n"
22577                    "<<<<<<< text by the vcs\n"
22578                    "  parameter2),\n"
22579                    "||||||| text by the vcs\n"
22580                    "  parameter2),\n"
22581                    "  parameter3,\n"
22582                    "======= text by the vcs\n"
22583                    "  parameter2,\n"
22584                    "  parameter3),\n"
22585                    ">>>>>>> text by the vcs\n"
22586                    "  otherparameter);\n"));
22587 
22588   // Perforce markers.
22589   EXPECT_EQ("void f() {\n"
22590             "  function(\n"
22591             ">>>> text by the vcs\n"
22592             "      parameter,\n"
22593             "==== text by the vcs\n"
22594             "      parameter,\n"
22595             "==== text by the vcs\n"
22596             "      parameter,\n"
22597             "<<<< text by the vcs\n"
22598             "      parameter);\n",
22599             format("void f() {\n"
22600                    "  function(\n"
22601                    ">>>> text by the vcs\n"
22602                    "  parameter,\n"
22603                    "==== text by the vcs\n"
22604                    "  parameter,\n"
22605                    "==== text by the vcs\n"
22606                    "  parameter,\n"
22607                    "<<<< text by the vcs\n"
22608                    "  parameter);\n"));
22609 
22610   EXPECT_EQ("<<<<<<<\n"
22611             "|||||||\n"
22612             "=======\n"
22613             ">>>>>>>",
22614             format("<<<<<<<\n"
22615                    "|||||||\n"
22616                    "=======\n"
22617                    ">>>>>>>"));
22618 
22619   EXPECT_EQ("<<<<<<<\n"
22620             "|||||||\n"
22621             "int i;\n"
22622             "=======\n"
22623             ">>>>>>>",
22624             format("<<<<<<<\n"
22625                    "|||||||\n"
22626                    "int i;\n"
22627                    "=======\n"
22628                    ">>>>>>>"));
22629 
22630   // FIXME: Handle parsing of macros around conflict markers correctly:
22631   EXPECT_EQ("#define Macro \\\n"
22632             "<<<<<<<\n"
22633             "Something \\\n"
22634             "|||||||\n"
22635             "Else \\\n"
22636             "=======\n"
22637             "Other \\\n"
22638             ">>>>>>>\n"
22639             "    End int i;\n",
22640             format("#define Macro \\\n"
22641                    "<<<<<<<\n"
22642                    "  Something \\\n"
22643                    "|||||||\n"
22644                    "  Else \\\n"
22645                    "=======\n"
22646                    "  Other \\\n"
22647                    ">>>>>>>\n"
22648                    "  End\n"
22649                    "int i;\n"));
22650 
22651   verifyFormat(R"(====
22652 #ifdef A
22653 a
22654 #else
22655 b
22656 #endif
22657 )");
22658 }
22659 
22660 TEST_F(FormatTest, DisableRegions) {
22661   EXPECT_EQ("int i;\n"
22662             "// clang-format off\n"
22663             "  int j;\n"
22664             "// clang-format on\n"
22665             "int k;",
22666             format(" int  i;\n"
22667                    "   // clang-format off\n"
22668                    "  int j;\n"
22669                    " // clang-format on\n"
22670                    "   int   k;"));
22671   EXPECT_EQ("int i;\n"
22672             "/* clang-format off */\n"
22673             "  int j;\n"
22674             "/* clang-format on */\n"
22675             "int k;",
22676             format(" int  i;\n"
22677                    "   /* clang-format off */\n"
22678                    "  int j;\n"
22679                    " /* clang-format on */\n"
22680                    "   int   k;"));
22681 
22682   // Don't reflow comments within disabled regions.
22683   EXPECT_EQ("// clang-format off\n"
22684             "// long long long long long long line\n"
22685             "/* clang-format on */\n"
22686             "/* long long long\n"
22687             " * long long long\n"
22688             " * line */\n"
22689             "int i;\n"
22690             "/* clang-format off */\n"
22691             "/* long long long long long long line */\n",
22692             format("// clang-format off\n"
22693                    "// long long long long long long line\n"
22694                    "/* clang-format on */\n"
22695                    "/* long long long long long long line */\n"
22696                    "int i;\n"
22697                    "/* clang-format off */\n"
22698                    "/* long long long long long long line */\n",
22699                    getLLVMStyleWithColumns(20)));
22700 }
22701 
22702 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22703   format("? ) =");
22704   verifyNoCrash("#define a\\\n /**/}");
22705 }
22706 
22707 TEST_F(FormatTest, FormatsTableGenCode) {
22708   FormatStyle Style = getLLVMStyle();
22709   Style.Language = FormatStyle::LK_TableGen;
22710   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22711 }
22712 
22713 TEST_F(FormatTest, ArrayOfTemplates) {
22714   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22715             format("auto a = new unique_ptr<int > [ 10];"));
22716 
22717   FormatStyle Spaces = getLLVMStyle();
22718   Spaces.SpacesInSquareBrackets = true;
22719   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22720             format("auto a = new unique_ptr<int > [10];", Spaces));
22721 }
22722 
22723 TEST_F(FormatTest, ArrayAsTemplateType) {
22724   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22725             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22726 
22727   FormatStyle Spaces = getLLVMStyle();
22728   Spaces.SpacesInSquareBrackets = true;
22729   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22730             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22731 }
22732 
22733 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22734 
22735 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22736   llvm::vfs::InMemoryFileSystem FS;
22737   auto Style1 = getStyle("file", "", "Google", "", &FS);
22738   ASSERT_TRUE((bool)Style1);
22739   ASSERT_EQ(*Style1, getGoogleStyle());
22740 }
22741 
22742 TEST(FormatStyle, GetStyleOfFile) {
22743   llvm::vfs::InMemoryFileSystem FS;
22744   // Test 1: format file in the same directory.
22745   ASSERT_TRUE(
22746       FS.addFile("/a/.clang-format", 0,
22747                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22748   ASSERT_TRUE(
22749       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22750   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22751   ASSERT_TRUE((bool)Style1);
22752   ASSERT_EQ(*Style1, getLLVMStyle());
22753 
22754   // Test 2.1: fallback to default.
22755   ASSERT_TRUE(
22756       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22757   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22758   ASSERT_TRUE((bool)Style2);
22759   ASSERT_EQ(*Style2, getMozillaStyle());
22760 
22761   // Test 2.2: no format on 'none' fallback style.
22762   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22763   ASSERT_TRUE((bool)Style2);
22764   ASSERT_EQ(*Style2, getNoStyle());
22765 
22766   // Test 2.3: format if config is found with no based style while fallback is
22767   // 'none'.
22768   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22769                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22770   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22771   ASSERT_TRUE((bool)Style2);
22772   ASSERT_EQ(*Style2, getLLVMStyle());
22773 
22774   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22775   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22776   ASSERT_TRUE((bool)Style2);
22777   ASSERT_EQ(*Style2, getLLVMStyle());
22778 
22779   // Test 3: format file in parent directory.
22780   ASSERT_TRUE(
22781       FS.addFile("/c/.clang-format", 0,
22782                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22783   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22784                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22785   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22786   ASSERT_TRUE((bool)Style3);
22787   ASSERT_EQ(*Style3, getGoogleStyle());
22788 
22789   // Test 4: error on invalid fallback style
22790   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22791   ASSERT_FALSE((bool)Style4);
22792   llvm::consumeError(Style4.takeError());
22793 
22794   // Test 5: error on invalid yaml on command line
22795   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22796   ASSERT_FALSE((bool)Style5);
22797   llvm::consumeError(Style5.takeError());
22798 
22799   // Test 6: error on invalid style
22800   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22801   ASSERT_FALSE((bool)Style6);
22802   llvm::consumeError(Style6.takeError());
22803 
22804   // Test 7: found config file, error on parsing it
22805   ASSERT_TRUE(
22806       FS.addFile("/d/.clang-format", 0,
22807                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22808                                                   "InvalidKey: InvalidValue")));
22809   ASSERT_TRUE(
22810       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22811   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22812   ASSERT_FALSE((bool)Style7a);
22813   llvm::consumeError(Style7a.takeError());
22814 
22815   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22816   ASSERT_TRUE((bool)Style7b);
22817 
22818   // Test 8: inferred per-language defaults apply.
22819   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22820   ASSERT_TRUE((bool)StyleTd);
22821   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22822 
22823   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22824   // fallback style.
22825   ASSERT_TRUE(FS.addFile(
22826       "/e/sub/.clang-format", 0,
22827       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22828                                        "ColumnLimit: 20")));
22829   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22830                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22831   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22832   ASSERT_TRUE(static_cast<bool>(Style9));
22833   ASSERT_EQ(*Style9, [] {
22834     auto Style = getNoStyle();
22835     Style.ColumnLimit = 20;
22836     return Style;
22837   }());
22838 
22839   // Test 9.1.2: propagate more than one level with no parent file.
22840   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22841                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22842   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22843                          llvm::MemoryBuffer::getMemBuffer(
22844                              "BasedOnStyle: InheritParentConfig\n"
22845                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22846   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22847 
22848   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22849   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22850   ASSERT_TRUE(static_cast<bool>(Style9));
22851   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22852     auto Style = getNoStyle();
22853     Style.ColumnLimit = 20;
22854     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22855     return Style;
22856   }());
22857 
22858   // Test 9.2: with LLVM fallback style
22859   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22860   ASSERT_TRUE(static_cast<bool>(Style9));
22861   ASSERT_EQ(*Style9, [] {
22862     auto Style = getLLVMStyle();
22863     Style.ColumnLimit = 20;
22864     return Style;
22865   }());
22866 
22867   // Test 9.3: with a parent file
22868   ASSERT_TRUE(
22869       FS.addFile("/e/.clang-format", 0,
22870                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
22871                                                   "UseTab: Always")));
22872   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22873   ASSERT_TRUE(static_cast<bool>(Style9));
22874   ASSERT_EQ(*Style9, [] {
22875     auto Style = getGoogleStyle();
22876     Style.ColumnLimit = 20;
22877     Style.UseTab = FormatStyle::UT_Always;
22878     return Style;
22879   }());
22880 
22881   // Test 9.4: propagate more than one level with a parent file.
22882   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
22883     auto Style = getGoogleStyle();
22884     Style.ColumnLimit = 20;
22885     Style.UseTab = FormatStyle::UT_Always;
22886     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22887     return Style;
22888   }();
22889 
22890   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22891   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22892   ASSERT_TRUE(static_cast<bool>(Style9));
22893   ASSERT_EQ(*Style9, SubSubStyle);
22894 
22895   // Test 9.5: use InheritParentConfig as style name
22896   Style9 =
22897       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
22898   ASSERT_TRUE(static_cast<bool>(Style9));
22899   ASSERT_EQ(*Style9, SubSubStyle);
22900 
22901   // Test 9.6: use command line style with inheritance
22902   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
22903                     "none", "", &FS);
22904   ASSERT_TRUE(static_cast<bool>(Style9));
22905   ASSERT_EQ(*Style9, SubSubStyle);
22906 
22907   // Test 9.7: use command line style with inheritance and own config
22908   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
22909                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
22910                     "/e/sub/code.cpp", "none", "", &FS);
22911   ASSERT_TRUE(static_cast<bool>(Style9));
22912   ASSERT_EQ(*Style9, SubSubStyle);
22913 
22914   // Test 9.8: use inheritance from a file without BasedOnStyle
22915   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
22916                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
22917   ASSERT_TRUE(
22918       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
22919                  llvm::MemoryBuffer::getMemBuffer(
22920                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
22921   // Make sure we do not use the fallback style
22922   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
22923   ASSERT_TRUE(static_cast<bool>(Style9));
22924   ASSERT_EQ(*Style9, [] {
22925     auto Style = getLLVMStyle();
22926     Style.ColumnLimit = 123;
22927     return Style;
22928   }());
22929 
22930   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
22931   ASSERT_TRUE(static_cast<bool>(Style9));
22932   ASSERT_EQ(*Style9, [] {
22933     auto Style = getLLVMStyle();
22934     Style.ColumnLimit = 123;
22935     Style.IndentWidth = 7;
22936     return Style;
22937   }());
22938 
22939   // Test 9.9: use inheritance from a specific config file.
22940   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
22941                     "none", "", &FS);
22942   ASSERT_TRUE(static_cast<bool>(Style9));
22943   ASSERT_EQ(*Style9, SubSubStyle);
22944 }
22945 
22946 TEST(FormatStyle, GetStyleOfSpecificFile) {
22947   llvm::vfs::InMemoryFileSystem FS;
22948   // Specify absolute path to a format file in a parent directory.
22949   ASSERT_TRUE(
22950       FS.addFile("/e/.clang-format", 0,
22951                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22952   ASSERT_TRUE(
22953       FS.addFile("/e/explicit.clang-format", 0,
22954                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22955   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
22956                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22957   auto Style = getStyle("file:/e/explicit.clang-format",
22958                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22959   ASSERT_TRUE(static_cast<bool>(Style));
22960   ASSERT_EQ(*Style, getGoogleStyle());
22961 
22962   // Specify relative path to a format file.
22963   ASSERT_TRUE(
22964       FS.addFile("../../e/explicit.clang-format", 0,
22965                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22966   Style = getStyle("file:../../e/explicit.clang-format",
22967                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22968   ASSERT_TRUE(static_cast<bool>(Style));
22969   ASSERT_EQ(*Style, getGoogleStyle());
22970 
22971   // Specify path to a format file that does not exist.
22972   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
22973                    "LLVM", "", &FS);
22974   ASSERT_FALSE(static_cast<bool>(Style));
22975   llvm::consumeError(Style.takeError());
22976 
22977   // Specify path to a file on the filesystem.
22978   SmallString<128> FormatFilePath;
22979   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
22980       "FormatFileTest", "tpl", FormatFilePath);
22981   EXPECT_FALSE((bool)ECF);
22982   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
22983   EXPECT_FALSE((bool)ECF);
22984   FormatFileTest << "BasedOnStyle: Google\n";
22985   FormatFileTest.close();
22986 
22987   SmallString<128> TestFilePath;
22988   std::error_code ECT =
22989       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
22990   EXPECT_FALSE((bool)ECT);
22991   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
22992   CodeFileTest << "int i;\n";
22993   CodeFileTest.close();
22994 
22995   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
22996   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
22997 
22998   llvm::sys::fs::remove(FormatFilePath.c_str());
22999   llvm::sys::fs::remove(TestFilePath.c_str());
23000   ASSERT_TRUE(static_cast<bool>(Style));
23001   ASSERT_EQ(*Style, getGoogleStyle());
23002 }
23003 
23004 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
23005   // Column limit is 20.
23006   std::string Code = "Type *a =\n"
23007                      "    new Type();\n"
23008                      "g(iiiii, 0, jjjjj,\n"
23009                      "  0, kkkkk, 0, mm);\n"
23010                      "int  bad     = format   ;";
23011   std::string Expected = "auto a = new Type();\n"
23012                          "g(iiiii, nullptr,\n"
23013                          "  jjjjj, nullptr,\n"
23014                          "  kkkkk, nullptr,\n"
23015                          "  mm);\n"
23016                          "int  bad     = format   ;";
23017   FileID ID = Context.createInMemoryFile("format.cpp", Code);
23018   tooling::Replacements Replaces = toReplacements(
23019       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
23020                             "auto "),
23021        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
23022                             "nullptr"),
23023        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
23024                             "nullptr"),
23025        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
23026                             "nullptr")});
23027 
23028   FormatStyle Style = getLLVMStyle();
23029   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
23030   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
23031   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
23032       << llvm::toString(FormattedReplaces.takeError()) << "\n";
23033   auto Result = applyAllReplacements(Code, *FormattedReplaces);
23034   EXPECT_TRUE(static_cast<bool>(Result));
23035   EXPECT_EQ(Expected, *Result);
23036 }
23037 
23038 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
23039   std::string Code = "#include \"a.h\"\n"
23040                      "#include \"c.h\"\n"
23041                      "\n"
23042                      "int main() {\n"
23043                      "  return 0;\n"
23044                      "}";
23045   std::string Expected = "#include \"a.h\"\n"
23046                          "#include \"b.h\"\n"
23047                          "#include \"c.h\"\n"
23048                          "\n"
23049                          "int main() {\n"
23050                          "  return 0;\n"
23051                          "}";
23052   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
23053   tooling::Replacements Replaces = toReplacements(
23054       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
23055                             "#include \"b.h\"\n")});
23056 
23057   FormatStyle Style = getLLVMStyle();
23058   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
23059   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
23060   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
23061       << llvm::toString(FormattedReplaces.takeError()) << "\n";
23062   auto Result = applyAllReplacements(Code, *FormattedReplaces);
23063   EXPECT_TRUE(static_cast<bool>(Result));
23064   EXPECT_EQ(Expected, *Result);
23065 }
23066 
23067 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
23068   EXPECT_EQ("using std::cin;\n"
23069             "using std::cout;",
23070             format("using std::cout;\n"
23071                    "using std::cin;",
23072                    getGoogleStyle()));
23073 }
23074 
23075 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
23076   FormatStyle Style = getLLVMStyle();
23077   Style.Standard = FormatStyle::LS_Cpp03;
23078   // cpp03 recognize this string as identifier u8 and literal character 'a'
23079   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
23080 }
23081 
23082 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
23083   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
23084   // all modes, including C++11, C++14 and C++17
23085   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
23086 }
23087 
23088 TEST_F(FormatTest, DoNotFormatLikelyXml) {
23089   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
23090   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
23091 }
23092 
23093 TEST_F(FormatTest, StructuredBindings) {
23094   // Structured bindings is a C++17 feature.
23095   // all modes, including C++11, C++14 and C++17
23096   verifyFormat("auto [a, b] = f();");
23097   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
23098   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
23099   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
23100   EXPECT_EQ("auto const volatile [a, b] = f();",
23101             format("auto  const   volatile[a, b] = f();"));
23102   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
23103   EXPECT_EQ("auto &[a, b, c] = f();",
23104             format("auto   &[  a  ,  b,c   ] = f();"));
23105   EXPECT_EQ("auto &&[a, b, c] = f();",
23106             format("auto   &&[  a  ,  b,c   ] = f();"));
23107   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
23108   EXPECT_EQ("auto const volatile &&[a, b] = f();",
23109             format("auto  const  volatile  &&[a, b] = f();"));
23110   EXPECT_EQ("auto const &&[a, b] = f();",
23111             format("auto  const   &&  [a, b] = f();"));
23112   EXPECT_EQ("const auto &[a, b] = f();",
23113             format("const  auto  &  [a, b] = f();"));
23114   EXPECT_EQ("const auto volatile &&[a, b] = f();",
23115             format("const  auto   volatile  &&[a, b] = f();"));
23116   EXPECT_EQ("volatile const auto &&[a, b] = f();",
23117             format("volatile  const  auto   &&[a, b] = f();"));
23118   EXPECT_EQ("const auto &&[a, b] = f();",
23119             format("const  auto  &&  [a, b] = f();"));
23120 
23121   // Make sure we don't mistake structured bindings for lambdas.
23122   FormatStyle PointerMiddle = getLLVMStyle();
23123   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
23124   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
23125   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
23126   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
23127   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
23128   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
23129   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
23130   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
23131   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
23132   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
23133   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
23134   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
23135   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
23136 
23137   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
23138             format("for (const auto   &&   [a, b] : some_range) {\n}"));
23139   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
23140             format("for (const auto   &   [a, b] : some_range) {\n}"));
23141   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
23142             format("for (const auto[a, b] : some_range) {\n}"));
23143   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
23144   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
23145   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
23146   EXPECT_EQ("auto const &[x, y](expr);",
23147             format("auto  const  &  [x,y]  (expr);"));
23148   EXPECT_EQ("auto const &&[x, y](expr);",
23149             format("auto  const  &&  [x,y]  (expr);"));
23150   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
23151   EXPECT_EQ("auto const &[x, y]{expr};",
23152             format("auto  const  &  [x,y]  {expr};"));
23153   EXPECT_EQ("auto const &&[x, y]{expr};",
23154             format("auto  const  &&  [x,y]  {expr};"));
23155 
23156   FormatStyle Spaces = getLLVMStyle();
23157   Spaces.SpacesInSquareBrackets = true;
23158   verifyFormat("auto [ a, b ] = f();", Spaces);
23159   verifyFormat("auto &&[ a, b ] = f();", Spaces);
23160   verifyFormat("auto &[ a, b ] = f();", Spaces);
23161   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
23162   verifyFormat("auto const &[ a, b ] = f();", Spaces);
23163 }
23164 
23165 TEST_F(FormatTest, FileAndCode) {
23166   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
23167   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
23168   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
23169   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
23170   EXPECT_EQ(FormatStyle::LK_ObjC,
23171             guessLanguage("foo.h", "@interface Foo\n@end\n"));
23172   EXPECT_EQ(
23173       FormatStyle::LK_ObjC,
23174       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
23175   EXPECT_EQ(FormatStyle::LK_ObjC,
23176             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
23177   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
23178   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
23179   EXPECT_EQ(FormatStyle::LK_ObjC,
23180             guessLanguage("foo", "@interface Foo\n@end\n"));
23181   EXPECT_EQ(FormatStyle::LK_ObjC,
23182             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
23183   EXPECT_EQ(
23184       FormatStyle::LK_ObjC,
23185       guessLanguage("foo.h",
23186                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
23187   EXPECT_EQ(
23188       FormatStyle::LK_Cpp,
23189       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
23190   // Only one of the two preprocessor regions has ObjC-like code.
23191   EXPECT_EQ(FormatStyle::LK_ObjC,
23192             guessLanguage("foo.h", "#if A\n"
23193                                    "#define B() C\n"
23194                                    "#else\n"
23195                                    "#define B() [NSString a:@\"\"]\n"
23196                                    "#endif\n"));
23197 }
23198 
23199 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
23200   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
23201   EXPECT_EQ(FormatStyle::LK_ObjC,
23202             guessLanguage("foo.h", "array[[calculator getIndex]];"));
23203   EXPECT_EQ(FormatStyle::LK_Cpp,
23204             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
23205   EXPECT_EQ(
23206       FormatStyle::LK_Cpp,
23207       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
23208   EXPECT_EQ(FormatStyle::LK_ObjC,
23209             guessLanguage("foo.h", "[[noreturn foo] bar];"));
23210   EXPECT_EQ(FormatStyle::LK_Cpp,
23211             guessLanguage("foo.h", "[[clang::fallthrough]];"));
23212   EXPECT_EQ(FormatStyle::LK_ObjC,
23213             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
23214   EXPECT_EQ(FormatStyle::LK_Cpp,
23215             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
23216   EXPECT_EQ(FormatStyle::LK_Cpp,
23217             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
23218   EXPECT_EQ(FormatStyle::LK_ObjC,
23219             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
23220   EXPECT_EQ(FormatStyle::LK_Cpp,
23221             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
23222   EXPECT_EQ(
23223       FormatStyle::LK_Cpp,
23224       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
23225   EXPECT_EQ(
23226       FormatStyle::LK_Cpp,
23227       guessLanguage("foo.h",
23228                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
23229   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
23230 }
23231 
23232 TEST_F(FormatTest, GuessLanguageWithCaret) {
23233   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
23234   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
23235   EXPECT_EQ(FormatStyle::LK_ObjC,
23236             guessLanguage("foo.h", "int(^)(char, float);"));
23237   EXPECT_EQ(FormatStyle::LK_ObjC,
23238             guessLanguage("foo.h", "int(^foo)(char, float);"));
23239   EXPECT_EQ(FormatStyle::LK_ObjC,
23240             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
23241   EXPECT_EQ(FormatStyle::LK_ObjC,
23242             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
23243   EXPECT_EQ(
23244       FormatStyle::LK_ObjC,
23245       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
23246 }
23247 
23248 TEST_F(FormatTest, GuessLanguageWithPragmas) {
23249   EXPECT_EQ(FormatStyle::LK_Cpp,
23250             guessLanguage("foo.h", "__pragma(warning(disable:))"));
23251   EXPECT_EQ(FormatStyle::LK_Cpp,
23252             guessLanguage("foo.h", "#pragma(warning(disable:))"));
23253   EXPECT_EQ(FormatStyle::LK_Cpp,
23254             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
23255 }
23256 
23257 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
23258   // ASM symbolic names are identifiers that must be surrounded by [] without
23259   // space in between:
23260   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
23261 
23262   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
23263   verifyFormat(R"(//
23264 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
23265 )");
23266 
23267   // A list of several ASM symbolic names.
23268   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
23269 
23270   // ASM symbolic names in inline ASM with inputs and outputs.
23271   verifyFormat(R"(//
23272 asm("cmoveq %1, %2, %[result]"
23273     : [result] "=r"(result)
23274     : "r"(test), "r"(new), "[result]"(old));
23275 )");
23276 
23277   // ASM symbolic names in inline ASM with no outputs.
23278   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
23279 }
23280 
23281 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
23282   EXPECT_EQ(FormatStyle::LK_Cpp,
23283             guessLanguage("foo.h", "void f() {\n"
23284                                    "  asm (\"mov %[e], %[d]\"\n"
23285                                    "     : [d] \"=rm\" (d)\n"
23286                                    "       [e] \"rm\" (*e));\n"
23287                                    "}"));
23288   EXPECT_EQ(FormatStyle::LK_Cpp,
23289             guessLanguage("foo.h", "void f() {\n"
23290                                    "  _asm (\"mov %[e], %[d]\"\n"
23291                                    "     : [d] \"=rm\" (d)\n"
23292                                    "       [e] \"rm\" (*e));\n"
23293                                    "}"));
23294   EXPECT_EQ(FormatStyle::LK_Cpp,
23295             guessLanguage("foo.h", "void f() {\n"
23296                                    "  __asm (\"mov %[e], %[d]\"\n"
23297                                    "     : [d] \"=rm\" (d)\n"
23298                                    "       [e] \"rm\" (*e));\n"
23299                                    "}"));
23300   EXPECT_EQ(FormatStyle::LK_Cpp,
23301             guessLanguage("foo.h", "void f() {\n"
23302                                    "  __asm__ (\"mov %[e], %[d]\"\n"
23303                                    "     : [d] \"=rm\" (d)\n"
23304                                    "       [e] \"rm\" (*e));\n"
23305                                    "}"));
23306   EXPECT_EQ(FormatStyle::LK_Cpp,
23307             guessLanguage("foo.h", "void f() {\n"
23308                                    "  asm (\"mov %[e], %[d]\"\n"
23309                                    "     : [d] \"=rm\" (d),\n"
23310                                    "       [e] \"rm\" (*e));\n"
23311                                    "}"));
23312   EXPECT_EQ(FormatStyle::LK_Cpp,
23313             guessLanguage("foo.h", "void f() {\n"
23314                                    "  asm volatile (\"mov %[e], %[d]\"\n"
23315                                    "     : [d] \"=rm\" (d)\n"
23316                                    "       [e] \"rm\" (*e));\n"
23317                                    "}"));
23318 }
23319 
23320 TEST_F(FormatTest, GuessLanguageWithChildLines) {
23321   EXPECT_EQ(FormatStyle::LK_Cpp,
23322             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
23323   EXPECT_EQ(FormatStyle::LK_ObjC,
23324             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
23325   EXPECT_EQ(
23326       FormatStyle::LK_Cpp,
23327       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
23328   EXPECT_EQ(
23329       FormatStyle::LK_ObjC,
23330       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
23331 }
23332 
23333 TEST_F(FormatTest, TypenameMacros) {
23334   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
23335 
23336   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
23337   FormatStyle Google = getGoogleStyleWithColumns(0);
23338   Google.TypenameMacros = TypenameMacros;
23339   verifyFormat("struct foo {\n"
23340                "  int bar;\n"
23341                "  TAILQ_ENTRY(a) bleh;\n"
23342                "};",
23343                Google);
23344 
23345   FormatStyle Macros = getLLVMStyle();
23346   Macros.TypenameMacros = TypenameMacros;
23347 
23348   verifyFormat("STACK_OF(int) a;", Macros);
23349   verifyFormat("STACK_OF(int) *a;", Macros);
23350   verifyFormat("STACK_OF(int const *) *a;", Macros);
23351   verifyFormat("STACK_OF(int *const) *a;", Macros);
23352   verifyFormat("STACK_OF(int, string) a;", Macros);
23353   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
23354   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
23355   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
23356   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
23357   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
23358   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
23359 
23360   Macros.PointerAlignment = FormatStyle::PAS_Left;
23361   verifyFormat("STACK_OF(int)* a;", Macros);
23362   verifyFormat("STACK_OF(int*)* a;", Macros);
23363   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
23364   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
23365   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
23366 }
23367 
23368 TEST_F(FormatTest, AtomicQualifier) {
23369   // Check that we treate _Atomic as a type and not a function call
23370   FormatStyle Google = getGoogleStyleWithColumns(0);
23371   verifyFormat("struct foo {\n"
23372                "  int a1;\n"
23373                "  _Atomic(a) a2;\n"
23374                "  _Atomic(_Atomic(int) *const) a3;\n"
23375                "};",
23376                Google);
23377   verifyFormat("_Atomic(uint64_t) a;");
23378   verifyFormat("_Atomic(uint64_t) *a;");
23379   verifyFormat("_Atomic(uint64_t const *) *a;");
23380   verifyFormat("_Atomic(uint64_t *const) *a;");
23381   verifyFormat("_Atomic(const uint64_t *) *a;");
23382   verifyFormat("_Atomic(uint64_t) a;");
23383   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
23384   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
23385   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
23386   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
23387 
23388   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
23389   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
23390   FormatStyle Style = getLLVMStyle();
23391   Style.PointerAlignment = FormatStyle::PAS_Left;
23392   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
23393   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
23394   verifyFormat("_Atomic(int)* a;", Style);
23395   verifyFormat("_Atomic(int*)* a;", Style);
23396   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
23397 
23398   Style.SpacesInCStyleCastParentheses = true;
23399   Style.SpacesInParentheses = false;
23400   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
23401   Style.SpacesInCStyleCastParentheses = false;
23402   Style.SpacesInParentheses = true;
23403   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
23404   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
23405 }
23406 
23407 TEST_F(FormatTest, AmbersandInLamda) {
23408   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
23409   FormatStyle AlignStyle = getLLVMStyle();
23410   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
23411   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23412   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
23413   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23414 }
23415 
23416 TEST_F(FormatTest, SpacesInConditionalStatement) {
23417   FormatStyle Spaces = getLLVMStyle();
23418   Spaces.IfMacros.clear();
23419   Spaces.IfMacros.push_back("MYIF");
23420   Spaces.SpacesInConditionalStatement = true;
23421   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
23422   verifyFormat("if ( !a )\n  return;", Spaces);
23423   verifyFormat("if ( a )\n  return;", Spaces);
23424   verifyFormat("if constexpr ( a )\n  return;", Spaces);
23425   verifyFormat("MYIF ( a )\n  return;", Spaces);
23426   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
23427   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
23428   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
23429   verifyFormat("while ( a )\n  return;", Spaces);
23430   verifyFormat("while ( (a && b) )\n  return;", Spaces);
23431   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
23432   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
23433   // Check that space on the left of "::" is inserted as expected at beginning
23434   // of condition.
23435   verifyFormat("while ( ::func() )\n  return;", Spaces);
23436 
23437   // Check impact of ControlStatementsExceptControlMacros is honored.
23438   Spaces.SpaceBeforeParens =
23439       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
23440   verifyFormat("MYIF( a )\n  return;", Spaces);
23441   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
23442   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
23443 }
23444 
23445 TEST_F(FormatTest, AlternativeOperators) {
23446   // Test case for ensuring alternate operators are not
23447   // combined with their right most neighbour.
23448   verifyFormat("int a and b;");
23449   verifyFormat("int a and_eq b;");
23450   verifyFormat("int a bitand b;");
23451   verifyFormat("int a bitor b;");
23452   verifyFormat("int a compl b;");
23453   verifyFormat("int a not b;");
23454   verifyFormat("int a not_eq b;");
23455   verifyFormat("int a or b;");
23456   verifyFormat("int a xor b;");
23457   verifyFormat("int a xor_eq b;");
23458   verifyFormat("return this not_eq bitand other;");
23459   verifyFormat("bool operator not_eq(const X bitand other)");
23460 
23461   verifyFormat("int a and 5;");
23462   verifyFormat("int a and_eq 5;");
23463   verifyFormat("int a bitand 5;");
23464   verifyFormat("int a bitor 5;");
23465   verifyFormat("int a compl 5;");
23466   verifyFormat("int a not 5;");
23467   verifyFormat("int a not_eq 5;");
23468   verifyFormat("int a or 5;");
23469   verifyFormat("int a xor 5;");
23470   verifyFormat("int a xor_eq 5;");
23471 
23472   verifyFormat("int a compl(5);");
23473   verifyFormat("int a not(5);");
23474 
23475   /* FIXME handle alternate tokens
23476    * https://en.cppreference.com/w/cpp/language/operator_alternative
23477   // alternative tokens
23478   verifyFormat("compl foo();");     //  ~foo();
23479   verifyFormat("foo() <%%>;");      // foo();
23480   verifyFormat("void foo() <%%>;"); // void foo(){}
23481   verifyFormat("int a <:1:>;");     // int a[1];[
23482   verifyFormat("%:define ABC abc"); // #define ABC abc
23483   verifyFormat("%:%:");             // ##
23484   */
23485 }
23486 
23487 TEST_F(FormatTest, STLWhileNotDefineChed) {
23488   verifyFormat("#if defined(while)\n"
23489                "#define while EMIT WARNING C4005\n"
23490                "#endif // while");
23491 }
23492 
23493 TEST_F(FormatTest, OperatorSpacing) {
23494   FormatStyle Style = getLLVMStyle();
23495   Style.PointerAlignment = FormatStyle::PAS_Right;
23496   verifyFormat("Foo::operator*();", Style);
23497   verifyFormat("Foo::operator void *();", Style);
23498   verifyFormat("Foo::operator void **();", Style);
23499   verifyFormat("Foo::operator void *&();", Style);
23500   verifyFormat("Foo::operator void *&&();", Style);
23501   verifyFormat("Foo::operator void const *();", Style);
23502   verifyFormat("Foo::operator void const **();", Style);
23503   verifyFormat("Foo::operator void const *&();", Style);
23504   verifyFormat("Foo::operator void const *&&();", Style);
23505   verifyFormat("Foo::operator()(void *);", Style);
23506   verifyFormat("Foo::operator*(void *);", Style);
23507   verifyFormat("Foo::operator*();", Style);
23508   verifyFormat("Foo::operator**();", Style);
23509   verifyFormat("Foo::operator&();", Style);
23510   verifyFormat("Foo::operator<int> *();", Style);
23511   verifyFormat("Foo::operator<Foo> *();", Style);
23512   verifyFormat("Foo::operator<int> **();", Style);
23513   verifyFormat("Foo::operator<Foo> **();", Style);
23514   verifyFormat("Foo::operator<int> &();", Style);
23515   verifyFormat("Foo::operator<Foo> &();", Style);
23516   verifyFormat("Foo::operator<int> &&();", Style);
23517   verifyFormat("Foo::operator<Foo> &&();", Style);
23518   verifyFormat("Foo::operator<int> *&();", Style);
23519   verifyFormat("Foo::operator<Foo> *&();", Style);
23520   verifyFormat("Foo::operator<int> *&&();", Style);
23521   verifyFormat("Foo::operator<Foo> *&&();", Style);
23522   verifyFormat("operator*(int (*)(), class Foo);", Style);
23523 
23524   verifyFormat("Foo::operator&();", Style);
23525   verifyFormat("Foo::operator void &();", Style);
23526   verifyFormat("Foo::operator void const &();", Style);
23527   verifyFormat("Foo::operator()(void &);", Style);
23528   verifyFormat("Foo::operator&(void &);", Style);
23529   verifyFormat("Foo::operator&();", Style);
23530   verifyFormat("operator&(int (&)(), class Foo);", Style);
23531   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23532 
23533   verifyFormat("Foo::operator&&();", Style);
23534   verifyFormat("Foo::operator**();", Style);
23535   verifyFormat("Foo::operator void &&();", Style);
23536   verifyFormat("Foo::operator void const &&();", Style);
23537   verifyFormat("Foo::operator()(void &&);", Style);
23538   verifyFormat("Foo::operator&&(void &&);", Style);
23539   verifyFormat("Foo::operator&&();", Style);
23540   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23541   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23542   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23543                Style);
23544   verifyFormat("operator void **()", Style);
23545   verifyFormat("operator const FooRight<Object> &()", Style);
23546   verifyFormat("operator const FooRight<Object> *()", Style);
23547   verifyFormat("operator const FooRight<Object> **()", Style);
23548   verifyFormat("operator const FooRight<Object> *&()", Style);
23549   verifyFormat("operator const FooRight<Object> *&&()", Style);
23550 
23551   Style.PointerAlignment = FormatStyle::PAS_Left;
23552   verifyFormat("Foo::operator*();", Style);
23553   verifyFormat("Foo::operator**();", Style);
23554   verifyFormat("Foo::operator void*();", Style);
23555   verifyFormat("Foo::operator void**();", Style);
23556   verifyFormat("Foo::operator void*&();", Style);
23557   verifyFormat("Foo::operator void*&&();", Style);
23558   verifyFormat("Foo::operator void const*();", Style);
23559   verifyFormat("Foo::operator void const**();", Style);
23560   verifyFormat("Foo::operator void const*&();", Style);
23561   verifyFormat("Foo::operator void const*&&();", Style);
23562   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23563   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23564   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23565   verifyFormat("Foo::operator()(void*);", Style);
23566   verifyFormat("Foo::operator*(void*);", Style);
23567   verifyFormat("Foo::operator*();", Style);
23568   verifyFormat("Foo::operator<int>*();", Style);
23569   verifyFormat("Foo::operator<Foo>*();", Style);
23570   verifyFormat("Foo::operator<int>**();", Style);
23571   verifyFormat("Foo::operator<Foo>**();", Style);
23572   verifyFormat("Foo::operator<Foo>*&();", Style);
23573   verifyFormat("Foo::operator<int>&();", Style);
23574   verifyFormat("Foo::operator<Foo>&();", Style);
23575   verifyFormat("Foo::operator<int>&&();", Style);
23576   verifyFormat("Foo::operator<Foo>&&();", Style);
23577   verifyFormat("Foo::operator<int>*&();", Style);
23578   verifyFormat("Foo::operator<Foo>*&();", Style);
23579   verifyFormat("operator*(int (*)(), class Foo);", Style);
23580 
23581   verifyFormat("Foo::operator&();", Style);
23582   verifyFormat("Foo::operator void&();", Style);
23583   verifyFormat("Foo::operator void const&();", Style);
23584   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23585   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23586   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
23587   verifyFormat("Foo::operator()(void&);", Style);
23588   verifyFormat("Foo::operator&(void&);", Style);
23589   verifyFormat("Foo::operator&();", Style);
23590   verifyFormat("operator&(int (&)(), class Foo);", Style);
23591   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23592   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23593 
23594   verifyFormat("Foo::operator&&();", Style);
23595   verifyFormat("Foo::operator void&&();", Style);
23596   verifyFormat("Foo::operator void const&&();", Style);
23597   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23598   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23599   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23600   verifyFormat("Foo::operator()(void&&);", Style);
23601   verifyFormat("Foo::operator&&(void&&);", Style);
23602   verifyFormat("Foo::operator&&();", Style);
23603   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23604   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23605   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23606                Style);
23607   verifyFormat("operator void**()", Style);
23608   verifyFormat("operator const FooLeft<Object>&()", Style);
23609   verifyFormat("operator const FooLeft<Object>*()", Style);
23610   verifyFormat("operator const FooLeft<Object>**()", Style);
23611   verifyFormat("operator const FooLeft<Object>*&()", Style);
23612   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23613 
23614   // PR45107
23615   verifyFormat("operator Vector<String>&();", Style);
23616   verifyFormat("operator const Vector<String>&();", Style);
23617   verifyFormat("operator foo::Bar*();", Style);
23618   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23619   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23620                Style);
23621 
23622   Style.PointerAlignment = FormatStyle::PAS_Middle;
23623   verifyFormat("Foo::operator*();", Style);
23624   verifyFormat("Foo::operator void *();", Style);
23625   verifyFormat("Foo::operator()(void *);", Style);
23626   verifyFormat("Foo::operator*(void *);", Style);
23627   verifyFormat("Foo::operator*();", Style);
23628   verifyFormat("operator*(int (*)(), class Foo);", Style);
23629 
23630   verifyFormat("Foo::operator&();", Style);
23631   verifyFormat("Foo::operator void &();", Style);
23632   verifyFormat("Foo::operator void const &();", Style);
23633   verifyFormat("Foo::operator()(void &);", Style);
23634   verifyFormat("Foo::operator&(void &);", Style);
23635   verifyFormat("Foo::operator&();", Style);
23636   verifyFormat("operator&(int (&)(), class Foo);", Style);
23637 
23638   verifyFormat("Foo::operator&&();", Style);
23639   verifyFormat("Foo::operator void &&();", Style);
23640   verifyFormat("Foo::operator void const &&();", Style);
23641   verifyFormat("Foo::operator()(void &&);", Style);
23642   verifyFormat("Foo::operator&&(void &&);", Style);
23643   verifyFormat("Foo::operator&&();", Style);
23644   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23645 }
23646 
23647 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23648   FormatStyle Style = getLLVMStyle();
23649   // PR46157
23650   verifyFormat("foo(operator+, -42);", Style);
23651   verifyFormat("foo(operator++, -42);", Style);
23652   verifyFormat("foo(operator--, -42);", Style);
23653   verifyFormat("foo(-42, operator--);", Style);
23654   verifyFormat("foo(-42, operator, );", Style);
23655   verifyFormat("foo(operator, , -42);", Style);
23656 }
23657 
23658 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23659   FormatStyle Style = getLLVMStyle();
23660   Style.WhitespaceSensitiveMacros.push_back("FOO");
23661 
23662   // Don't use the helpers here, since 'mess up' will change the whitespace
23663   // and these are all whitespace sensitive by definition
23664 
23665   // Newlines are important here.
23666   EXPECT_EQ("FOO(1+2  );\n", format("FOO(1+2  );\n", Style));
23667   EXPECT_EQ("FOO(1+2  )\n", format("FOO(1+2  )\n", Style));
23668 
23669   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23670             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23671   EXPECT_EQ(
23672       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23673       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23674   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23675             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23676   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23677             "       Still=Intentional);",
23678             format("FOO(String-ized&Messy+But,: :\n"
23679                    "       Still=Intentional);",
23680                    Style));
23681   Style.AlignConsecutiveAssignments.Enabled = true;
23682   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
23683             "       Still=Intentional);",
23684             format("FOO(String-ized=&Messy+But,: :\n"
23685                    "       Still=Intentional);",
23686                    Style));
23687 
23688   Style.ColumnLimit = 21;
23689   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23690             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23691 }
23692 
23693 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23694   // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
23695   // test its interaction with line wrapping
23696   FormatStyle Style = getLLVMStyleWithColumns(80);
23697   verifyFormat("namespace {\n"
23698                "int i;\n"
23699                "int j;\n"
23700                "} // namespace",
23701                Style);
23702 
23703   verifyFormat("namespace AAA {\n"
23704                "int i;\n"
23705                "int j;\n"
23706                "} // namespace AAA",
23707                Style);
23708 
23709   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23710             "int i;\n"
23711             "int j;\n"
23712             "} // namespace Averyveryveryverylongnamespace",
23713             format("namespace Averyveryveryverylongnamespace {\n"
23714                    "int i;\n"
23715                    "int j;\n"
23716                    "}",
23717                    Style));
23718 
23719   EXPECT_EQ(
23720       "namespace "
23721       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23722       "    went::mad::now {\n"
23723       "int i;\n"
23724       "int j;\n"
23725       "} // namespace\n"
23726       "  // "
23727       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23728       "went::mad::now",
23729       format("namespace "
23730              "would::it::save::you::a::lot::of::time::if_::i::"
23731              "just::gave::up::and_::went::mad::now {\n"
23732              "int i;\n"
23733              "int j;\n"
23734              "}",
23735              Style));
23736 
23737   // This used to duplicate the comment again and again on subsequent runs
23738   EXPECT_EQ(
23739       "namespace "
23740       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23741       "    went::mad::now {\n"
23742       "int i;\n"
23743       "int j;\n"
23744       "} // namespace\n"
23745       "  // "
23746       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23747       "went::mad::now",
23748       format("namespace "
23749              "would::it::save::you::a::lot::of::time::if_::i::"
23750              "just::gave::up::and_::went::mad::now {\n"
23751              "int i;\n"
23752              "int j;\n"
23753              "} // namespace\n"
23754              "  // "
23755              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23756              "and_::went::mad::now",
23757              Style));
23758 }
23759 
23760 TEST_F(FormatTest, LikelyUnlikely) {
23761   FormatStyle Style = getLLVMStyle();
23762 
23763   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23764                "  return 29;\n"
23765                "}",
23766                Style);
23767 
23768   verifyFormat("if (argc > 5) [[likely]] {\n"
23769                "  return 29;\n"
23770                "}",
23771                Style);
23772 
23773   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23774                "  return 29;\n"
23775                "} else [[likely]] {\n"
23776                "  return 42;\n"
23777                "}\n",
23778                Style);
23779 
23780   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23781                "  return 29;\n"
23782                "} else if (argc > 10) [[likely]] {\n"
23783                "  return 99;\n"
23784                "} else {\n"
23785                "  return 42;\n"
23786                "}\n",
23787                Style);
23788 
23789   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23790                "  return 29;\n"
23791                "}",
23792                Style);
23793 
23794   verifyFormat("if (argc > 5) [[unlikely]]\n"
23795                "  return 29;\n",
23796                Style);
23797   verifyFormat("if (argc > 5) [[likely]]\n"
23798                "  return 29;\n",
23799                Style);
23800 
23801   Style.AttributeMacros.push_back("UNLIKELY");
23802   Style.AttributeMacros.push_back("LIKELY");
23803   verifyFormat("if (argc > 5) UNLIKELY\n"
23804                "  return 29;\n",
23805                Style);
23806 
23807   verifyFormat("if (argc > 5) UNLIKELY {\n"
23808                "  return 29;\n"
23809                "}",
23810                Style);
23811   verifyFormat("if (argc > 5) UNLIKELY {\n"
23812                "  return 29;\n"
23813                "} else [[likely]] {\n"
23814                "  return 42;\n"
23815                "}\n",
23816                Style);
23817   verifyFormat("if (argc > 5) UNLIKELY {\n"
23818                "  return 29;\n"
23819                "} else LIKELY {\n"
23820                "  return 42;\n"
23821                "}\n",
23822                Style);
23823   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23824                "  return 29;\n"
23825                "} else LIKELY {\n"
23826                "  return 42;\n"
23827                "}\n",
23828                Style);
23829 }
23830 
23831 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23832   verifyFormat("Constructor()\n"
23833                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23834                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
23835                "aaaaaaaaaaaaaaaaaat))");
23836   verifyFormat("Constructor()\n"
23837                "    : aaaaaaaaaaaaa(aaaaaa), "
23838                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
23839 
23840   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
23841   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
23842   verifyFormat("Constructor()\n"
23843                "    : aaaaaa(aaaaaa),\n"
23844                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23845                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
23846                StyleWithWhitespacePenalty);
23847   verifyFormat("Constructor()\n"
23848                "    : aaaaaaaaaaaaa(aaaaaa), "
23849                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
23850                StyleWithWhitespacePenalty);
23851 }
23852 
23853 TEST_F(FormatTest, LLVMDefaultStyle) {
23854   FormatStyle Style = getLLVMStyle();
23855   verifyFormat("extern \"C\" {\n"
23856                "int foo();\n"
23857                "}",
23858                Style);
23859 }
23860 TEST_F(FormatTest, GNUDefaultStyle) {
23861   FormatStyle Style = getGNUStyle();
23862   verifyFormat("extern \"C\"\n"
23863                "{\n"
23864                "  int foo ();\n"
23865                "}",
23866                Style);
23867 }
23868 TEST_F(FormatTest, MozillaDefaultStyle) {
23869   FormatStyle Style = getMozillaStyle();
23870   verifyFormat("extern \"C\"\n"
23871                "{\n"
23872                "  int foo();\n"
23873                "}",
23874                Style);
23875 }
23876 TEST_F(FormatTest, GoogleDefaultStyle) {
23877   FormatStyle Style = getGoogleStyle();
23878   verifyFormat("extern \"C\" {\n"
23879                "int foo();\n"
23880                "}",
23881                Style);
23882 }
23883 TEST_F(FormatTest, ChromiumDefaultStyle) {
23884   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
23885   verifyFormat("extern \"C\" {\n"
23886                "int foo();\n"
23887                "}",
23888                Style);
23889 }
23890 TEST_F(FormatTest, MicrosoftDefaultStyle) {
23891   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
23892   verifyFormat("extern \"C\"\n"
23893                "{\n"
23894                "    int foo();\n"
23895                "}",
23896                Style);
23897 }
23898 TEST_F(FormatTest, WebKitDefaultStyle) {
23899   FormatStyle Style = getWebKitStyle();
23900   verifyFormat("extern \"C\" {\n"
23901                "int foo();\n"
23902                "}",
23903                Style);
23904 }
23905 
23906 TEST_F(FormatTest, Concepts) {
23907   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
23908             FormatStyle::BBCDS_Always);
23909   verifyFormat("template <typename T>\n"
23910                "concept True = true;");
23911 
23912   verifyFormat("template <typename T>\n"
23913                "concept C = ((false || foo()) && C2<T>) ||\n"
23914                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
23915                getLLVMStyleWithColumns(60));
23916 
23917   verifyFormat("template <typename T>\n"
23918                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
23919                "sizeof(T) <= 8;");
23920 
23921   verifyFormat("template <typename T>\n"
23922                "concept DelayedCheck = true && requires(T t) {\n"
23923                "                                 t.bar();\n"
23924                "                                 t.baz();\n"
23925                "                               } && sizeof(T) <= 8;");
23926 
23927   verifyFormat("template <typename T>\n"
23928                "concept DelayedCheck = true && requires(T t) { // Comment\n"
23929                "                                 t.bar();\n"
23930                "                                 t.baz();\n"
23931                "                               } && sizeof(T) <= 8;");
23932 
23933   verifyFormat("template <typename T>\n"
23934                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
23935                "sizeof(T) <= 8;");
23936 
23937   verifyFormat("template <typename T>\n"
23938                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
23939                "&& sizeof(T) <= 8;");
23940 
23941   verifyFormat(
23942       "template <typename T>\n"
23943       "concept DelayedCheck = static_cast<bool>(0) ||\n"
23944       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23945 
23946   verifyFormat("template <typename T>\n"
23947                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
23948                "&& sizeof(T) <= 8;");
23949 
23950   verifyFormat(
23951       "template <typename T>\n"
23952       "concept DelayedCheck = (bool)(0) ||\n"
23953       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23954 
23955   verifyFormat("template <typename T>\n"
23956                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
23957                "&& sizeof(T) <= 8;");
23958 
23959   verifyFormat("template <typename T>\n"
23960                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
23961                "sizeof(T) <= 8;");
23962 
23963   verifyFormat("template <typename T>\n"
23964                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
23965                "               requires(T t) {\n"
23966                "                 t.bar();\n"
23967                "                 t.baz();\n"
23968                "               } && sizeof(T) <= 8 && !(4 < 3);",
23969                getLLVMStyleWithColumns(60));
23970 
23971   verifyFormat("template <typename T>\n"
23972                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
23973 
23974   verifyFormat("template <typename T>\n"
23975                "concept C = foo();");
23976 
23977   verifyFormat("template <typename T>\n"
23978                "concept C = foo(T());");
23979 
23980   verifyFormat("template <typename T>\n"
23981                "concept C = foo(T{});");
23982 
23983   verifyFormat("template <typename T>\n"
23984                "concept Size = V<sizeof(T)>::Value > 5;");
23985 
23986   verifyFormat("template <typename T>\n"
23987                "concept True = S<T>::Value;");
23988 
23989   verifyFormat(
23990       "template <typename T>\n"
23991       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
23992       "            sizeof(T) <= 8;");
23993 
23994   // FIXME: This is misformatted because the fake l paren starts at bool, not at
23995   // the lambda l square.
23996   verifyFormat("template <typename T>\n"
23997                "concept C = [] -> bool { return true; }() && requires(T t) { "
23998                "t.bar(); } &&\n"
23999                "                      sizeof(T) <= 8;");
24000 
24001   verifyFormat(
24002       "template <typename T>\n"
24003       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
24004       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24005 
24006   verifyFormat("template <typename T>\n"
24007                "concept C = decltype([]() { return std::true_type{}; "
24008                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24009                getLLVMStyleWithColumns(120));
24010 
24011   verifyFormat("template <typename T>\n"
24012                "concept C = decltype([]() -> std::true_type { return {}; "
24013                "}())::value &&\n"
24014                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24015 
24016   verifyFormat("template <typename T>\n"
24017                "concept C = true;\n"
24018                "Foo Bar;");
24019 
24020   verifyFormat("template <typename T>\n"
24021                "concept Hashable = requires(T a) {\n"
24022                "                     { std::hash<T>{}(a) } -> "
24023                "std::convertible_to<std::size_t>;\n"
24024                "                   };");
24025 
24026   verifyFormat(
24027       "template <typename T>\n"
24028       "concept EqualityComparable = requires(T a, T b) {\n"
24029       "                               { a == b } -> std::same_as<bool>;\n"
24030       "                             };");
24031 
24032   verifyFormat(
24033       "template <typename T>\n"
24034       "concept EqualityComparable = requires(T a, T b) {\n"
24035       "                               { a == b } -> std::same_as<bool>;\n"
24036       "                               { a != b } -> std::same_as<bool>;\n"
24037       "                             };");
24038 
24039   verifyFormat("template <typename T>\n"
24040                "concept WeakEqualityComparable = requires(T a, T b) {\n"
24041                "                                   { a == b };\n"
24042                "                                   { a != b };\n"
24043                "                                 };");
24044 
24045   verifyFormat("template <typename T>\n"
24046                "concept HasSizeT = requires { typename T::size_t; };");
24047 
24048   verifyFormat("template <typename T>\n"
24049                "concept Semiregular =\n"
24050                "    DefaultConstructible<T> && CopyConstructible<T> && "
24051                "CopyAssignable<T> &&\n"
24052                "    requires(T a, std::size_t n) {\n"
24053                "      requires Same<T *, decltype(&a)>;\n"
24054                "      { a.~T() } noexcept;\n"
24055                "      requires Same<T *, decltype(new T)>;\n"
24056                "      requires Same<T *, decltype(new T[n])>;\n"
24057                "      { delete new T; };\n"
24058                "      { delete new T[n]; };\n"
24059                "    };");
24060 
24061   verifyFormat("template <typename T>\n"
24062                "concept Semiregular =\n"
24063                "    requires(T a, std::size_t n) {\n"
24064                "      requires Same<T *, decltype(&a)>;\n"
24065                "      { a.~T() } noexcept;\n"
24066                "      requires Same<T *, decltype(new T)>;\n"
24067                "      requires Same<T *, decltype(new T[n])>;\n"
24068                "      { delete new T; };\n"
24069                "      { delete new T[n]; };\n"
24070                "      { new T } -> std::same_as<T *>;\n"
24071                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
24072                "CopyAssignable<T>;");
24073 
24074   verifyFormat(
24075       "template <typename T>\n"
24076       "concept Semiregular =\n"
24077       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
24078       "                                 requires Same<T *, decltype(&a)>;\n"
24079       "                                 { a.~T() } noexcept;\n"
24080       "                                 requires Same<T *, decltype(new T)>;\n"
24081       "                                 requires Same<T *, decltype(new "
24082       "T[n])>;\n"
24083       "                                 { delete new T; };\n"
24084       "                                 { delete new T[n]; };\n"
24085       "                               } && CopyConstructible<T> && "
24086       "CopyAssignable<T>;");
24087 
24088   verifyFormat("template <typename T>\n"
24089                "concept Two = requires(T t) {\n"
24090                "                { t.foo() } -> std::same_as<Bar>;\n"
24091                "              } && requires(T &&t) {\n"
24092                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
24093                "                   };");
24094 
24095   verifyFormat(
24096       "template <typename T>\n"
24097       "concept C = requires(T x) {\n"
24098       "              { *x } -> std::convertible_to<typename T::inner>;\n"
24099       "              { x + 1 } noexcept -> std::same_as<int>;\n"
24100       "              { x * 1 } -> std::convertible_to<T>;\n"
24101       "            };");
24102 
24103   verifyFormat(
24104       "template <typename T, typename U = T>\n"
24105       "concept Swappable = requires(T &&t, U &&u) {\n"
24106       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
24107       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
24108       "                    };");
24109 
24110   verifyFormat("template <typename T, typename U>\n"
24111                "concept Common = requires(T &&t, U &&u) {\n"
24112                "                   typename CommonType<T, U>;\n"
24113                "                   { CommonType<T, U>(std::forward<T>(t)) };\n"
24114                "                 };");
24115 
24116   verifyFormat("template <typename T, typename U>\n"
24117                "concept Common = requires(T &&t, U &&u) {\n"
24118                "                   typename CommonType<T, U>;\n"
24119                "                   { CommonType<T, U>{std::forward<T>(t)} };\n"
24120                "                 };");
24121 
24122   verifyFormat(
24123       "template <typename T>\n"
24124       "concept C = requires(T t) {\n"
24125       "              requires Bar<T> && Foo<T>;\n"
24126       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24127       "            };");
24128 
24129   verifyFormat("template <typename T>\n"
24130                "concept HasFoo = requires(T t) {\n"
24131                "                   { t.foo() };\n"
24132                "                   t.foo();\n"
24133                "                 };\n"
24134                "template <typename T>\n"
24135                "concept HasBar = requires(T t) {\n"
24136                "                   { t.bar() };\n"
24137                "                   t.bar();\n"
24138                "                 };");
24139 
24140   verifyFormat("template <typename T>\n"
24141                "concept Large = sizeof(T) > 10;");
24142 
24143   verifyFormat("template <typename T, typename U>\n"
24144                "concept FooableWith = requires(T t, U u) {\n"
24145                "                        typename T::foo_type;\n"
24146                "                        { t.foo(u) } -> typename T::foo_type;\n"
24147                "                        t++;\n"
24148                "                      };\n"
24149                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
24150 
24151   verifyFormat("template <typename T>\n"
24152                "concept Context = is_specialization_of_v<context, T>;");
24153 
24154   verifyFormat("template <typename T>\n"
24155                "concept Node = std::is_object_v<T>;");
24156 
24157   verifyFormat("template <class T>\n"
24158                "concept integral = __is_integral(T);");
24159 
24160   verifyFormat("template <class T>\n"
24161                "concept is2D = __array_extent(T, 1) == 2;");
24162 
24163   verifyFormat("template <class T>\n"
24164                "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
24165 
24166   verifyFormat("template <class T, class T2>\n"
24167                "concept Same = __is_same_as<T, T2>;");
24168 
24169   verifyFormat(
24170       "template <class _InIt, class _OutIt>\n"
24171       "concept _Can_reread_dest =\n"
24172       "    std::forward_iterator<_OutIt> &&\n"
24173       "    std::same_as<std::iter_value_t<_InIt>, std::iter_value_t<_OutIt>>;");
24174 
24175   auto Style = getLLVMStyle();
24176   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
24177 
24178   verifyFormat(
24179       "template <typename T>\n"
24180       "concept C = requires(T t) {\n"
24181       "              requires Bar<T> && Foo<T>;\n"
24182       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24183       "            };",
24184       Style);
24185 
24186   verifyFormat("template <typename T>\n"
24187                "concept HasFoo = requires(T t) {\n"
24188                "                   { t.foo() };\n"
24189                "                   t.foo();\n"
24190                "                 };\n"
24191                "template <typename T>\n"
24192                "concept HasBar = requires(T t) {\n"
24193                "                   { t.bar() };\n"
24194                "                   t.bar();\n"
24195                "                 };",
24196                Style);
24197 
24198   verifyFormat("template <typename T> concept True = true;", Style);
24199 
24200   verifyFormat("template <typename T>\n"
24201                "concept C = decltype([]() -> std::true_type { return {}; "
24202                "}())::value &&\n"
24203                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24204                Style);
24205 
24206   verifyFormat("template <typename T>\n"
24207                "concept Semiregular =\n"
24208                "    DefaultConstructible<T> && CopyConstructible<T> && "
24209                "CopyAssignable<T> &&\n"
24210                "    requires(T a, std::size_t n) {\n"
24211                "      requires Same<T *, decltype(&a)>;\n"
24212                "      { a.~T() } noexcept;\n"
24213                "      requires Same<T *, decltype(new T)>;\n"
24214                "      requires Same<T *, decltype(new T[n])>;\n"
24215                "      { delete new T; };\n"
24216                "      { delete new T[n]; };\n"
24217                "    };",
24218                Style);
24219 
24220   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
24221 
24222   verifyFormat("template <typename T> concept C =\n"
24223                "    requires(T t) {\n"
24224                "      requires Bar<T> && Foo<T>;\n"
24225                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24226                "    };",
24227                Style);
24228 
24229   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
24230                "                                         { t.foo() };\n"
24231                "                                         t.foo();\n"
24232                "                                       };\n"
24233                "template <typename T> concept HasBar = requires(T t) {\n"
24234                "                                         { t.bar() };\n"
24235                "                                         t.bar();\n"
24236                "                                       };",
24237                Style);
24238 
24239   verifyFormat("template <typename T> concept True = true;", Style);
24240 
24241   verifyFormat(
24242       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
24243       "                                    return {};\n"
24244       "                                  }())::value &&\n"
24245       "                                  requires(T t) { t.bar(); } && "
24246       "sizeof(T) <= 8;",
24247       Style);
24248 
24249   verifyFormat("template <typename T> concept Semiregular =\n"
24250                "    DefaultConstructible<T> && CopyConstructible<T> && "
24251                "CopyAssignable<T> &&\n"
24252                "    requires(T a, std::size_t n) {\n"
24253                "      requires Same<T *, decltype(&a)>;\n"
24254                "      { a.~T() } noexcept;\n"
24255                "      requires Same<T *, decltype(new T)>;\n"
24256                "      requires Same<T *, decltype(new T[n])>;\n"
24257                "      { delete new T; };\n"
24258                "      { delete new T[n]; };\n"
24259                "    };",
24260                Style);
24261 
24262   // The following tests are invalid C++, we just want to make sure we don't
24263   // assert.
24264   verifyFormat("template <typename T>\n"
24265                "concept C = requires C2<T>;");
24266 
24267   verifyFormat("template <typename T>\n"
24268                "concept C = 5 + 4;");
24269 
24270   verifyFormat("template <typename T>\n"
24271                "concept C =\n"
24272                "class X;");
24273 
24274   verifyFormat("template <typename T>\n"
24275                "concept C = [] && true;");
24276 
24277   verifyFormat("template <typename T>\n"
24278                "concept C = [] && requires(T t) { typename T::size_type; };");
24279 }
24280 
24281 TEST_F(FormatTest, RequiresClausesPositions) {
24282   auto Style = getLLVMStyle();
24283   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
24284   EXPECT_EQ(Style.IndentRequiresClause, true);
24285 
24286   verifyFormat("template <typename T>\n"
24287                "  requires(Foo<T> && std::trait<T>)\n"
24288                "struct Bar;",
24289                Style);
24290 
24291   verifyFormat("template <typename T>\n"
24292                "  requires(Foo<T> && std::trait<T>)\n"
24293                "class Bar {\n"
24294                "public:\n"
24295                "  Bar(T t);\n"
24296                "  bool baz();\n"
24297                "};",
24298                Style);
24299 
24300   verifyFormat(
24301       "template <typename T>\n"
24302       "  requires requires(T &&t) {\n"
24303       "             typename T::I;\n"
24304       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
24305       "           }\n"
24306       "Bar(T) -> Bar<typename T::I>;",
24307       Style);
24308 
24309   verifyFormat("template <typename T>\n"
24310                "  requires(Foo<T> && std::trait<T>)\n"
24311                "constexpr T MyGlobal;",
24312                Style);
24313 
24314   verifyFormat("template <typename T>\n"
24315                "  requires Foo<T> && requires(T t) {\n"
24316                "                       { t.baz() } -> std::same_as<bool>;\n"
24317                "                       requires std::same_as<T::Factor, int>;\n"
24318                "                     }\n"
24319                "inline int bar(T t) {\n"
24320                "  return t.baz() ? T::Factor : 5;\n"
24321                "}",
24322                Style);
24323 
24324   verifyFormat("template <typename T>\n"
24325                "inline int bar(T t)\n"
24326                "  requires Foo<T> && requires(T t) {\n"
24327                "                       { t.baz() } -> std::same_as<bool>;\n"
24328                "                       requires std::same_as<T::Factor, int>;\n"
24329                "                     }\n"
24330                "{\n"
24331                "  return t.baz() ? T::Factor : 5;\n"
24332                "}",
24333                Style);
24334 
24335   verifyFormat("template <typename T>\n"
24336                "  requires F<T>\n"
24337                "int bar(T t) {\n"
24338                "  return 5;\n"
24339                "}",
24340                Style);
24341 
24342   verifyFormat("template <typename T>\n"
24343                "int bar(T t)\n"
24344                "  requires F<T>\n"
24345                "{\n"
24346                "  return 5;\n"
24347                "}",
24348                Style);
24349 
24350   verifyFormat("template <typename T>\n"
24351                "int bar(T t)\n"
24352                "  requires F<T>;",
24353                Style);
24354 
24355   Style.IndentRequiresClause = false;
24356   verifyFormat("template <typename T>\n"
24357                "requires F<T>\n"
24358                "int bar(T t) {\n"
24359                "  return 5;\n"
24360                "}",
24361                Style);
24362 
24363   verifyFormat("template <typename T>\n"
24364                "int bar(T t)\n"
24365                "requires F<T>\n"
24366                "{\n"
24367                "  return 5;\n"
24368                "}",
24369                Style);
24370 
24371   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
24372   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
24373                "template <typename T> requires Foo<T> void bar() {}\n"
24374                "template <typename T> void bar() requires Foo<T> {}\n"
24375                "template <typename T> void bar() requires Foo<T>;\n"
24376                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
24377                Style);
24378 
24379   auto ColumnStyle = Style;
24380   ColumnStyle.ColumnLimit = 40;
24381   verifyFormat("template <typename AAAAAAA>\n"
24382                "requires Foo<T> struct Bar {};\n"
24383                "template <typename AAAAAAA>\n"
24384                "requires Foo<T> void bar() {}\n"
24385                "template <typename AAAAAAA>\n"
24386                "void bar() requires Foo<T> {}\n"
24387                "template <typename AAAAAAA>\n"
24388                "requires Foo<T> Baz(T) -> Baz<T>;",
24389                ColumnStyle);
24390 
24391   verifyFormat("template <typename T>\n"
24392                "requires Foo<AAAAAAA> struct Bar {};\n"
24393                "template <typename T>\n"
24394                "requires Foo<AAAAAAA> void bar() {}\n"
24395                "template <typename T>\n"
24396                "void bar() requires Foo<AAAAAAA> {}\n"
24397                "template <typename T>\n"
24398                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
24399                ColumnStyle);
24400 
24401   verifyFormat("template <typename AAAAAAA>\n"
24402                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24403                "struct Bar {};\n"
24404                "template <typename AAAAAAA>\n"
24405                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24406                "void bar() {}\n"
24407                "template <typename AAAAAAA>\n"
24408                "void bar()\n"
24409                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24410                "template <typename AAAAAAA>\n"
24411                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24412                "template <typename AAAAAAA>\n"
24413                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24414                "Bar(T) -> Bar<T>;",
24415                ColumnStyle);
24416 
24417   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24418   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24419 
24420   verifyFormat("template <typename T>\n"
24421                "requires Foo<T> struct Bar {};\n"
24422                "template <typename T>\n"
24423                "requires Foo<T> void bar() {}\n"
24424                "template <typename T>\n"
24425                "void bar()\n"
24426                "requires Foo<T> {}\n"
24427                "template <typename T>\n"
24428                "void bar()\n"
24429                "requires Foo<T>;\n"
24430                "template <typename T>\n"
24431                "requires Foo<T> Bar(T) -> Bar<T>;",
24432                Style);
24433 
24434   verifyFormat("template <typename AAAAAAA>\n"
24435                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24436                "struct Bar {};\n"
24437                "template <typename AAAAAAA>\n"
24438                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24439                "void bar() {}\n"
24440                "template <typename AAAAAAA>\n"
24441                "void bar()\n"
24442                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24443                "template <typename AAAAAAA>\n"
24444                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24445                "template <typename AAAAAAA>\n"
24446                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24447                "Bar(T) -> Bar<T>;",
24448                ColumnStyle);
24449 
24450   Style.IndentRequiresClause = true;
24451   ColumnStyle.IndentRequiresClause = true;
24452 
24453   verifyFormat("template <typename T>\n"
24454                "  requires Foo<T> struct Bar {};\n"
24455                "template <typename T>\n"
24456                "  requires Foo<T> void bar() {}\n"
24457                "template <typename T>\n"
24458                "void bar()\n"
24459                "  requires Foo<T> {}\n"
24460                "template <typename T>\n"
24461                "  requires Foo<T> Bar(T) -> Bar<T>;",
24462                Style);
24463 
24464   verifyFormat("template <typename AAAAAAA>\n"
24465                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24466                "struct Bar {};\n"
24467                "template <typename AAAAAAA>\n"
24468                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24469                "void bar() {}\n"
24470                "template <typename AAAAAAA>\n"
24471                "void bar()\n"
24472                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24473                "template <typename AAAAAAA>\n"
24474                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
24475                "template <typename AAAAAAA>\n"
24476                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24477                "Bar(T) -> Bar<T>;",
24478                ColumnStyle);
24479 
24480   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24481   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24482 
24483   verifyFormat("template <typename T> requires Foo<T>\n"
24484                "struct Bar {};\n"
24485                "template <typename T> requires Foo<T>\n"
24486                "void bar() {}\n"
24487                "template <typename T>\n"
24488                "void bar() requires Foo<T>\n"
24489                "{}\n"
24490                "template <typename T> void bar() requires Foo<T>;\n"
24491                "template <typename T> requires Foo<T>\n"
24492                "Bar(T) -> Bar<T>;",
24493                Style);
24494 
24495   verifyFormat("template <typename AAAAAAA>\n"
24496                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24497                "struct Bar {};\n"
24498                "template <typename AAAAAAA>\n"
24499                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24500                "void bar() {}\n"
24501                "template <typename AAAAAAA>\n"
24502                "void bar()\n"
24503                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24504                "{}\n"
24505                "template <typename AAAAAAA>\n"
24506                "requires Foo<AAAAAAAA>\n"
24507                "Bar(T) -> Bar<T>;\n"
24508                "template <typename AAAAAAA>\n"
24509                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24510                "Bar(T) -> Bar<T>;",
24511                ColumnStyle);
24512 }
24513 
24514 TEST_F(FormatTest, RequiresClauses) {
24515   verifyFormat("struct [[nodiscard]] zero_t {\n"
24516                "  template <class T>\n"
24517                "    requires requires { number_zero_v<T>; }\n"
24518                "  [[nodiscard]] constexpr operator T() const {\n"
24519                "    return number_zero_v<T>;\n"
24520                "  }\n"
24521                "};");
24522 
24523   auto Style = getLLVMStyle();
24524 
24525   verifyFormat(
24526       "template <typename T>\n"
24527       "  requires is_default_constructible_v<hash<T>> and\n"
24528       "           is_copy_constructible_v<hash<T>> and\n"
24529       "           is_move_constructible_v<hash<T>> and\n"
24530       "           is_copy_assignable_v<hash<T>> and "
24531       "is_move_assignable_v<hash<T>> and\n"
24532       "           is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
24533       "           is_callable_v<hash<T>(T)> and\n"
24534       "           is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n"
24535       "           is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n"
24536       "           is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
24537       "struct S {};",
24538       Style);
24539 
24540   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
24541   verifyFormat(
24542       "template <typename T>\n"
24543       "  requires is_default_constructible_v<hash<T>>\n"
24544       "           and is_copy_constructible_v<hash<T>>\n"
24545       "           and is_move_constructible_v<hash<T>>\n"
24546       "           and is_copy_assignable_v<hash<T>> and "
24547       "is_move_assignable_v<hash<T>>\n"
24548       "           and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
24549       "           and is_callable_v<hash<T>(T)>\n"
24550       "           and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n"
24551       "           and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n"
24552       "           and is_same_v<size_t, decltype(hash<T>(declval<const T "
24553       "&>()))>\n"
24554       "struct S {};",
24555       Style);
24556 
24557   // Not a clause, but we once hit an assert.
24558   verifyFormat("#if 0\n"
24559                "#else\n"
24560                "foo();\n"
24561                "#endif\n"
24562                "bar(requires);");
24563 }
24564 
24565 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24566   FormatStyle Style = getLLVMStyle();
24567   StringRef Source = "void Foo::slot() {\n"
24568                      "  unsigned char MyChar = 'x';\n"
24569                      "  emit signal(MyChar);\n"
24570                      "  Q_EMIT signal(MyChar);\n"
24571                      "}";
24572 
24573   EXPECT_EQ(Source, format(Source, Style));
24574 
24575   Style.AlignConsecutiveDeclarations.Enabled = true;
24576   EXPECT_EQ("void Foo::slot() {\n"
24577             "  unsigned char MyChar = 'x';\n"
24578             "  emit          signal(MyChar);\n"
24579             "  Q_EMIT signal(MyChar);\n"
24580             "}",
24581             format(Source, Style));
24582 
24583   Style.StatementAttributeLikeMacros.push_back("emit");
24584   EXPECT_EQ(Source, format(Source, Style));
24585 
24586   Style.StatementAttributeLikeMacros = {};
24587   EXPECT_EQ("void Foo::slot() {\n"
24588             "  unsigned char MyChar = 'x';\n"
24589             "  emit          signal(MyChar);\n"
24590             "  Q_EMIT        signal(MyChar);\n"
24591             "}",
24592             format(Source, Style));
24593 }
24594 
24595 TEST_F(FormatTest, IndentAccessModifiers) {
24596   FormatStyle Style = getLLVMStyle();
24597   Style.IndentAccessModifiers = true;
24598   // Members are *two* levels below the record;
24599   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24600   verifyFormat("class C {\n"
24601                "    int i;\n"
24602                "};\n",
24603                Style);
24604   verifyFormat("union C {\n"
24605                "    int i;\n"
24606                "    unsigned u;\n"
24607                "};\n",
24608                Style);
24609   // Access modifiers should be indented one level below the record.
24610   verifyFormat("class C {\n"
24611                "  public:\n"
24612                "    int i;\n"
24613                "};\n",
24614                Style);
24615   verifyFormat("struct S {\n"
24616                "  private:\n"
24617                "    class C {\n"
24618                "        int j;\n"
24619                "\n"
24620                "      public:\n"
24621                "        C();\n"
24622                "    };\n"
24623                "\n"
24624                "  public:\n"
24625                "    int i;\n"
24626                "};\n",
24627                Style);
24628   // Enumerations are not records and should be unaffected.
24629   Style.AllowShortEnumsOnASingleLine = false;
24630   verifyFormat("enum class E {\n"
24631                "  A,\n"
24632                "  B\n"
24633                "};\n",
24634                Style);
24635   // Test with a different indentation width;
24636   // also proves that the result is Style.AccessModifierOffset agnostic.
24637   Style.IndentWidth = 3;
24638   verifyFormat("class C {\n"
24639                "   public:\n"
24640                "      int i;\n"
24641                "};\n",
24642                Style);
24643 }
24644 
24645 TEST_F(FormatTest, LimitlessStringsAndComments) {
24646   auto Style = getLLVMStyleWithColumns(0);
24647   constexpr StringRef Code =
24648       "/**\n"
24649       " * This is a multiline comment with quite some long lines, at least for "
24650       "the LLVM Style.\n"
24651       " * We will redo this with strings and line comments. Just to  check if "
24652       "everything is working.\n"
24653       " */\n"
24654       "bool foo() {\n"
24655       "  /* Single line multi line comment. */\n"
24656       "  const std::string String = \"This is a multiline string with quite "
24657       "some long lines, at least for the LLVM Style.\"\n"
24658       "                             \"We already did it with multi line "
24659       "comments, and we will do it with line comments. Just to check if "
24660       "everything is working.\";\n"
24661       "  // This is a line comment (block) with quite some long lines, at "
24662       "least for the LLVM Style.\n"
24663       "  // We already did this with multi line comments and strings. Just to "
24664       "check if everything is working.\n"
24665       "  const std::string SmallString = \"Hello World\";\n"
24666       "  // Small line comment\n"
24667       "  return String.size() > SmallString.size();\n"
24668       "}";
24669   EXPECT_EQ(Code, format(Code, Style));
24670 }
24671 
24672 TEST_F(FormatTest, FormatDecayCopy) {
24673   // error cases from unit tests
24674   verifyFormat("foo(auto())");
24675   verifyFormat("foo(auto{})");
24676   verifyFormat("foo(auto({}))");
24677   verifyFormat("foo(auto{{}})");
24678 
24679   verifyFormat("foo(auto(1))");
24680   verifyFormat("foo(auto{1})");
24681   verifyFormat("foo(new auto(1))");
24682   verifyFormat("foo(new auto{1})");
24683   verifyFormat("decltype(auto(1)) x;");
24684   verifyFormat("decltype(auto{1}) x;");
24685   verifyFormat("auto(x);");
24686   verifyFormat("auto{x};");
24687   verifyFormat("new auto{x};");
24688   verifyFormat("auto{x} = y;");
24689   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24690                                 // the user's own fault
24691   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24692                                          // clearly the user's own fault
24693   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24694 }
24695 
24696 TEST_F(FormatTest, Cpp20ModulesSupport) {
24697   FormatStyle Style = getLLVMStyle();
24698   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24699   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24700 
24701   verifyFormat("export import foo;", Style);
24702   verifyFormat("export import foo:bar;", Style);
24703   verifyFormat("export import foo.bar;", Style);
24704   verifyFormat("export import foo.bar:baz;", Style);
24705   verifyFormat("export import :bar;", Style);
24706   verifyFormat("export module foo:bar;", Style);
24707   verifyFormat("export module foo;", Style);
24708   verifyFormat("export module foo.bar;", Style);
24709   verifyFormat("export module foo.bar:baz;", Style);
24710   verifyFormat("export import <string_view>;", Style);
24711 
24712   verifyFormat("export type_name var;", Style);
24713   verifyFormat("template <class T> export using A = B<T>;", Style);
24714   verifyFormat("export using A = B;", Style);
24715   verifyFormat("export int func() {\n"
24716                "  foo();\n"
24717                "}",
24718                Style);
24719   verifyFormat("export struct {\n"
24720                "  int foo;\n"
24721                "};",
24722                Style);
24723   verifyFormat("export {\n"
24724                "  int foo;\n"
24725                "};",
24726                Style);
24727   verifyFormat("export export char const *hello() { return \"hello\"; }");
24728 
24729   verifyFormat("import bar;", Style);
24730   verifyFormat("import foo.bar;", Style);
24731   verifyFormat("import foo:bar;", Style);
24732   verifyFormat("import :bar;", Style);
24733   verifyFormat("import <ctime>;", Style);
24734   verifyFormat("import \"header\";", Style);
24735 
24736   verifyFormat("module foo;", Style);
24737   verifyFormat("module foo:bar;", Style);
24738   verifyFormat("module foo.bar;", Style);
24739   verifyFormat("module;", Style);
24740 
24741   verifyFormat("export namespace hi {\n"
24742                "const char *sayhi();\n"
24743                "}",
24744                Style);
24745 
24746   verifyFormat("module :private;", Style);
24747   verifyFormat("import <foo/bar.h>;", Style);
24748   verifyFormat("import foo...bar;", Style);
24749   verifyFormat("import ..........;", Style);
24750   verifyFormat("module foo:private;", Style);
24751   verifyFormat("import a", Style);
24752   verifyFormat("module a", Style);
24753   verifyFormat("export import a", Style);
24754   verifyFormat("export module a", Style);
24755 
24756   verifyFormat("import", Style);
24757   verifyFormat("module", Style);
24758   verifyFormat("export", Style);
24759 }
24760 
24761 TEST_F(FormatTest, CoroutineForCoawait) {
24762   FormatStyle Style = getLLVMStyle();
24763   verifyFormat("for co_await (auto x : range())\n  ;");
24764   verifyFormat("for (auto i : arr) {\n"
24765                "}",
24766                Style);
24767   verifyFormat("for co_await (auto i : arr) {\n"
24768                "}",
24769                Style);
24770   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24771                "}",
24772                Style);
24773 }
24774 
24775 TEST_F(FormatTest, CoroutineCoAwait) {
24776   verifyFormat("int x = co_await foo();");
24777   verifyFormat("int x = (co_await foo());");
24778   verifyFormat("co_await (42);");
24779   verifyFormat("void operator co_await(int);");
24780   verifyFormat("void operator co_await(a);");
24781   verifyFormat("co_await a;");
24782   verifyFormat("co_await missing_await_resume{};");
24783   verifyFormat("co_await a; // comment");
24784   verifyFormat("void test0() { co_await a; }");
24785   verifyFormat("co_await co_await co_await foo();");
24786   verifyFormat("co_await foo().bar();");
24787   verifyFormat("co_await [this]() -> Task { co_return x; }");
24788   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24789                "foo(); }(x, y);");
24790 
24791   FormatStyle Style = getLLVMStyleWithColumns(40);
24792   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24793                "  co_return co_await foo();\n"
24794                "}(x, y);",
24795                Style);
24796   verifyFormat("co_await;");
24797 }
24798 
24799 TEST_F(FormatTest, CoroutineCoYield) {
24800   verifyFormat("int x = co_yield foo();");
24801   verifyFormat("int x = (co_yield foo());");
24802   verifyFormat("co_yield (42);");
24803   verifyFormat("co_yield {42};");
24804   verifyFormat("co_yield 42;");
24805   verifyFormat("co_yield n++;");
24806   verifyFormat("co_yield ++n;");
24807   verifyFormat("co_yield;");
24808 }
24809 
24810 TEST_F(FormatTest, CoroutineCoReturn) {
24811   verifyFormat("co_return (42);");
24812   verifyFormat("co_return;");
24813   verifyFormat("co_return {};");
24814   verifyFormat("co_return x;");
24815   verifyFormat("co_return co_await foo();");
24816   verifyFormat("co_return co_yield foo();");
24817 }
24818 
24819 TEST_F(FormatTest, EmptyShortBlock) {
24820   auto Style = getLLVMStyle();
24821   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24822 
24823   verifyFormat("try {\n"
24824                "  doA();\n"
24825                "} catch (Exception &e) {\n"
24826                "  e.printStackTrace();\n"
24827                "}\n",
24828                Style);
24829 
24830   verifyFormat("try {\n"
24831                "  doA();\n"
24832                "} catch (Exception &e) {}\n",
24833                Style);
24834 }
24835 
24836 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
24837   auto Style = getLLVMStyle();
24838 
24839   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
24840   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
24841   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
24842   verifyFormat("struct Y<[] { return 0; }> {};", Style);
24843 
24844   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
24845   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
24846 }
24847 
24848 TEST_F(FormatTest, InsertBraces) {
24849   FormatStyle Style = getLLVMStyle();
24850   Style.InsertBraces = true;
24851 
24852   verifyFormat("// clang-format off\n"
24853                "// comment\n"
24854                "if (a) f();\n"
24855                "// clang-format on\n"
24856                "if (b) {\n"
24857                "  g();\n"
24858                "}",
24859                "// clang-format off\n"
24860                "// comment\n"
24861                "if (a) f();\n"
24862                "// clang-format on\n"
24863                "if (b) g();",
24864                Style);
24865 
24866   verifyFormat("if (a) {\n"
24867                "  switch (b) {\n"
24868                "  case 1:\n"
24869                "    c = 0;\n"
24870                "    break;\n"
24871                "  default:\n"
24872                "    c = 1;\n"
24873                "  }\n"
24874                "}",
24875                "if (a)\n"
24876                "  switch (b) {\n"
24877                "  case 1:\n"
24878                "    c = 0;\n"
24879                "    break;\n"
24880                "  default:\n"
24881                "    c = 1;\n"
24882                "  }",
24883                Style);
24884 
24885   verifyFormat("for (auto node : nodes) {\n"
24886                "  if (node) {\n"
24887                "    break;\n"
24888                "  }\n"
24889                "}",
24890                "for (auto node : nodes)\n"
24891                "  if (node)\n"
24892                "    break;",
24893                Style);
24894 
24895   verifyFormat("for (auto node : nodes) {\n"
24896                "  if (node)\n"
24897                "}",
24898                "for (auto node : nodes)\n"
24899                "  if (node)",
24900                Style);
24901 
24902   verifyFormat("do {\n"
24903                "  --a;\n"
24904                "} while (a);",
24905                "do\n"
24906                "  --a;\n"
24907                "while (a);",
24908                Style);
24909 
24910   verifyFormat("if (i) {\n"
24911                "  ++i;\n"
24912                "} else {\n"
24913                "  --i;\n"
24914                "}",
24915                "if (i)\n"
24916                "  ++i;\n"
24917                "else {\n"
24918                "  --i;\n"
24919                "}",
24920                Style);
24921 
24922   verifyFormat("void f() {\n"
24923                "  while (j--) {\n"
24924                "    while (i) {\n"
24925                "      --i;\n"
24926                "    }\n"
24927                "  }\n"
24928                "}",
24929                "void f() {\n"
24930                "  while (j--)\n"
24931                "    while (i)\n"
24932                "      --i;\n"
24933                "}",
24934                Style);
24935 
24936   verifyFormat("f({\n"
24937                "  if (a) {\n"
24938                "    g();\n"
24939                "  }\n"
24940                "});",
24941                "f({\n"
24942                "  if (a)\n"
24943                "    g();\n"
24944                "});",
24945                Style);
24946 
24947   verifyFormat("if (a) {\n"
24948                "  f();\n"
24949                "} else if (b) {\n"
24950                "  g();\n"
24951                "} else {\n"
24952                "  h();\n"
24953                "}",
24954                "if (a)\n"
24955                "  f();\n"
24956                "else if (b)\n"
24957                "  g();\n"
24958                "else\n"
24959                "  h();",
24960                Style);
24961 
24962   verifyFormat("if (a) {\n"
24963                "  f();\n"
24964                "}\n"
24965                "// comment\n"
24966                "/* comment */",
24967                "if (a)\n"
24968                "  f();\n"
24969                "// comment\n"
24970                "/* comment */",
24971                Style);
24972 
24973   verifyFormat("if (a) {\n"
24974                "  // foo\n"
24975                "  // bar\n"
24976                "  f();\n"
24977                "}",
24978                "if (a)\n"
24979                "  // foo\n"
24980                "  // bar\n"
24981                "  f();",
24982                Style);
24983 
24984   verifyFormat("if (a) { // comment\n"
24985                "  // comment\n"
24986                "  f();\n"
24987                "}",
24988                "if (a) // comment\n"
24989                "  // comment\n"
24990                "  f();",
24991                Style);
24992 
24993   verifyFormat("if (a) {\n"
24994                "  f(); // comment\n"
24995                "}",
24996                "if (a)\n"
24997                "  f(); // comment",
24998                Style);
24999 
25000   verifyFormat("if (a) {\n"
25001                "  f();\n"
25002                "}\n"
25003                "#undef A\n"
25004                "#undef B",
25005                "if (a)\n"
25006                "  f();\n"
25007                "#undef A\n"
25008                "#undef B",
25009                Style);
25010 
25011   verifyFormat("if (a)\n"
25012                "#ifdef A\n"
25013                "  f();\n"
25014                "#else\n"
25015                "  g();\n"
25016                "#endif",
25017                Style);
25018 
25019   verifyFormat("#if 0\n"
25020                "#elif 1\n"
25021                "#endif\n"
25022                "void f() {\n"
25023                "  if (a) {\n"
25024                "    g();\n"
25025                "  }\n"
25026                "}",
25027                "#if 0\n"
25028                "#elif 1\n"
25029                "#endif\n"
25030                "void f() {\n"
25031                "  if (a) g();\n"
25032                "}",
25033                Style);
25034 
25035   Style.ColumnLimit = 15;
25036 
25037   verifyFormat("#define A     \\\n"
25038                "  if (a)      \\\n"
25039                "    f();",
25040                Style);
25041 
25042   verifyFormat("if (a + b >\n"
25043                "    c) {\n"
25044                "  f();\n"
25045                "}",
25046                "if (a + b > c)\n"
25047                "  f();",
25048                Style);
25049 }
25050 
25051 TEST_F(FormatTest, RemoveBraces) {
25052   FormatStyle Style = getLLVMStyle();
25053   Style.RemoveBracesLLVM = true;
25054 
25055   // The following eight test cases are fully-braced versions of the examples at
25056   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
25057   // statement-bodies-of-if-else-loop-statements".
25058 
25059   // 1. Omit the braces, since the body is simple and clearly associated with
25060   // the if.
25061   verifyFormat("if (isa<FunctionDecl>(D))\n"
25062                "  handleFunctionDecl(D);\n"
25063                "else if (isa<VarDecl>(D))\n"
25064                "  handleVarDecl(D);",
25065                "if (isa<FunctionDecl>(D)) {\n"
25066                "  handleFunctionDecl(D);\n"
25067                "} else if (isa<VarDecl>(D)) {\n"
25068                "  handleVarDecl(D);\n"
25069                "}",
25070                Style);
25071 
25072   // 2. Here we document the condition itself and not the body.
25073   verifyFormat("if (isa<VarDecl>(D)) {\n"
25074                "  // It is necessary that we explain the situation with this\n"
25075                "  // surprisingly long comment, so it would be unclear\n"
25076                "  // without the braces whether the following statement is in\n"
25077                "  // the scope of the `if`.\n"
25078                "  // Because the condition is documented, we can't really\n"
25079                "  // hoist this comment that applies to the body above the\n"
25080                "  // if.\n"
25081                "  handleOtherDecl(D);\n"
25082                "}",
25083                Style);
25084 
25085   // 3. Use braces on the outer `if` to avoid a potential dangling else
25086   // situation.
25087   verifyFormat("if (isa<VarDecl>(D)) {\n"
25088                "  for (auto *A : D.attrs())\n"
25089                "    if (shouldProcessAttr(A))\n"
25090                "      handleAttr(A);\n"
25091                "}",
25092                "if (isa<VarDecl>(D)) {\n"
25093                "  for (auto *A : D.attrs()) {\n"
25094                "    if (shouldProcessAttr(A)) {\n"
25095                "      handleAttr(A);\n"
25096                "    }\n"
25097                "  }\n"
25098                "}",
25099                Style);
25100 
25101   // 4. Use braces for the `if` block to keep it uniform with the else block.
25102   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25103                "  handleFunctionDecl(D);\n"
25104                "} else {\n"
25105                "  // In this else case, it is necessary that we explain the\n"
25106                "  // situation with this surprisingly long comment, so it\n"
25107                "  // would be unclear without the braces whether the\n"
25108                "  // following statement is in the scope of the `if`.\n"
25109                "  handleOtherDecl(D);\n"
25110                "}",
25111                Style);
25112 
25113   // 5. This should also omit braces.  The `for` loop contains only a single
25114   // statement, so it shouldn't have braces.  The `if` also only contains a
25115   // single simple statement (the for loop), so it also should omit braces.
25116   verifyFormat("if (isa<FunctionDecl>(D))\n"
25117                "  for (auto *A : D.attrs())\n"
25118                "    handleAttr(A);",
25119                "if (isa<FunctionDecl>(D)) {\n"
25120                "  for (auto *A : D.attrs()) {\n"
25121                "    handleAttr(A);\n"
25122                "  }\n"
25123                "}",
25124                Style);
25125 
25126   // 6. Use braces for the outer `if` since the nested `for` is braced.
25127   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25128                "  for (auto *A : D.attrs()) {\n"
25129                "    // In this for loop body, it is necessary that we explain\n"
25130                "    // the situation with this surprisingly long comment,\n"
25131                "    // forcing braces on the `for` block.\n"
25132                "    handleAttr(A);\n"
25133                "  }\n"
25134                "}",
25135                Style);
25136 
25137   // 7. Use braces on the outer block because there are more than two levels of
25138   // nesting.
25139   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25140                "  for (auto *A : D.attrs())\n"
25141                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
25142                "      handleAttrOnDecl(D, A, i);\n"
25143                "}",
25144                "if (isa<FunctionDecl>(D)) {\n"
25145                "  for (auto *A : D.attrs()) {\n"
25146                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
25147                "      handleAttrOnDecl(D, A, i);\n"
25148                "    }\n"
25149                "  }\n"
25150                "}",
25151                Style);
25152 
25153   // 8. Use braces on the outer block because of a nested `if`, otherwise the
25154   // compiler would warn: `add explicit braces to avoid dangling else`
25155   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25156                "  if (shouldProcess(D))\n"
25157                "    handleVarDecl(D);\n"
25158                "  else\n"
25159                "    markAsIgnored(D);\n"
25160                "}",
25161                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25162                "  if (shouldProcess(D)) {\n"
25163                "    handleVarDecl(D);\n"
25164                "  } else {\n"
25165                "    markAsIgnored(D);\n"
25166                "  }\n"
25167                "}",
25168                Style);
25169 
25170   verifyFormat("// clang-format off\n"
25171                "// comment\n"
25172                "while (i > 0) { --i; }\n"
25173                "// clang-format on\n"
25174                "while (j < 0)\n"
25175                "  ++j;",
25176                "// clang-format off\n"
25177                "// comment\n"
25178                "while (i > 0) { --i; }\n"
25179                "// clang-format on\n"
25180                "while (j < 0) { ++j; }",
25181                Style);
25182 
25183   verifyFormat("if (a)\n"
25184                "  b; // comment\n"
25185                "else if (c)\n"
25186                "  d; /* comment */\n"
25187                "else\n"
25188                "  e;",
25189                "if (a) {\n"
25190                "  b; // comment\n"
25191                "} else if (c) {\n"
25192                "  d; /* comment */\n"
25193                "} else {\n"
25194                "  e;\n"
25195                "}",
25196                Style);
25197 
25198   verifyFormat("if (a) {\n"
25199                "  b;\n"
25200                "  c;\n"
25201                "} else if (d) {\n"
25202                "  e;\n"
25203                "}",
25204                Style);
25205 
25206   verifyFormat("if (a) {\n"
25207                "#undef NDEBUG\n"
25208                "  b;\n"
25209                "} else {\n"
25210                "  c;\n"
25211                "}",
25212                Style);
25213 
25214   verifyFormat("if (a) {\n"
25215                "  // comment\n"
25216                "} else if (b) {\n"
25217                "  c;\n"
25218                "}",
25219                Style);
25220 
25221   verifyFormat("if (a) {\n"
25222                "  b;\n"
25223                "} else {\n"
25224                "  { c; }\n"
25225                "}",
25226                Style);
25227 
25228   verifyFormat("if (a) {\n"
25229                "  if (b) // comment\n"
25230                "    c;\n"
25231                "} else if (d) {\n"
25232                "  e;\n"
25233                "}",
25234                "if (a) {\n"
25235                "  if (b) { // comment\n"
25236                "    c;\n"
25237                "  }\n"
25238                "} else if (d) {\n"
25239                "  e;\n"
25240                "}",
25241                Style);
25242 
25243   verifyFormat("if (a) {\n"
25244                "  if (b) {\n"
25245                "    c;\n"
25246                "    // comment\n"
25247                "  } else if (d) {\n"
25248                "    e;\n"
25249                "  }\n"
25250                "}",
25251                Style);
25252 
25253   verifyFormat("if (a) {\n"
25254                "  if (b)\n"
25255                "    c;\n"
25256                "}",
25257                "if (a) {\n"
25258                "  if (b) {\n"
25259                "    c;\n"
25260                "  }\n"
25261                "}",
25262                Style);
25263 
25264   verifyFormat("if (a)\n"
25265                "  if (b)\n"
25266                "    c;\n"
25267                "  else\n"
25268                "    d;\n"
25269                "else\n"
25270                "  e;",
25271                "if (a) {\n"
25272                "  if (b) {\n"
25273                "    c;\n"
25274                "  } else {\n"
25275                "    d;\n"
25276                "  }\n"
25277                "} else {\n"
25278                "  e;\n"
25279                "}",
25280                Style);
25281 
25282   verifyFormat("if (a) {\n"
25283                "  // comment\n"
25284                "  if (b)\n"
25285                "    c;\n"
25286                "  else if (d)\n"
25287                "    e;\n"
25288                "} else {\n"
25289                "  g;\n"
25290                "}",
25291                "if (a) {\n"
25292                "  // comment\n"
25293                "  if (b) {\n"
25294                "    c;\n"
25295                "  } else if (d) {\n"
25296                "    e;\n"
25297                "  }\n"
25298                "} else {\n"
25299                "  g;\n"
25300                "}",
25301                Style);
25302 
25303   verifyFormat("if (a)\n"
25304                "  b;\n"
25305                "else if (c)\n"
25306                "  d;\n"
25307                "else\n"
25308                "  e;",
25309                "if (a) {\n"
25310                "  b;\n"
25311                "} else {\n"
25312                "  if (c) {\n"
25313                "    d;\n"
25314                "  } else {\n"
25315                "    e;\n"
25316                "  }\n"
25317                "}",
25318                Style);
25319 
25320   verifyFormat("if (a) {\n"
25321                "  if (b)\n"
25322                "    c;\n"
25323                "  else if (d)\n"
25324                "    e;\n"
25325                "} else {\n"
25326                "  g;\n"
25327                "}",
25328                "if (a) {\n"
25329                "  if (b)\n"
25330                "    c;\n"
25331                "  else {\n"
25332                "    if (d)\n"
25333                "      e;\n"
25334                "  }\n"
25335                "} else {\n"
25336                "  g;\n"
25337                "}",
25338                Style);
25339 
25340   verifyFormat("if (a)\n"
25341                "  b;\n"
25342                "else if (c)\n"
25343                "  while (d)\n"
25344                "    e;\n"
25345                "// comment",
25346                "if (a)\n"
25347                "{\n"
25348                "  b;\n"
25349                "} else if (c) {\n"
25350                "  while (d) {\n"
25351                "    e;\n"
25352                "  }\n"
25353                "}\n"
25354                "// comment",
25355                Style);
25356 
25357   verifyFormat("if (a) {\n"
25358                "  b;\n"
25359                "} else if (c) {\n"
25360                "  d;\n"
25361                "} else {\n"
25362                "  e;\n"
25363                "  g;\n"
25364                "}",
25365                Style);
25366 
25367   verifyFormat("if (a) {\n"
25368                "  b;\n"
25369                "} else if (c) {\n"
25370                "  d;\n"
25371                "} else {\n"
25372                "  e;\n"
25373                "} // comment",
25374                Style);
25375 
25376   verifyFormat("int abs = [](int i) {\n"
25377                "  if (i >= 0)\n"
25378                "    return i;\n"
25379                "  return -i;\n"
25380                "};",
25381                "int abs = [](int i) {\n"
25382                "  if (i >= 0) {\n"
25383                "    return i;\n"
25384                "  }\n"
25385                "  return -i;\n"
25386                "};",
25387                Style);
25388 
25389   verifyFormat("if (a)\n"
25390                "  foo();\n"
25391                "else\n"
25392                "  bar();",
25393                "if (a)\n"
25394                "{\n"
25395                "  foo();\n"
25396                "}\n"
25397                "else\n"
25398                "{\n"
25399                "  bar();\n"
25400                "}",
25401                Style);
25402 
25403   verifyFormat("if (a)\n"
25404                "  foo();\n"
25405                "// comment\n"
25406                "else\n"
25407                "  bar();",
25408                "if (a) {\n"
25409                "  foo();\n"
25410                "}\n"
25411                "// comment\n"
25412                "else {\n"
25413                "  bar();\n"
25414                "}",
25415                Style);
25416 
25417   verifyFormat("if (a) {\n"
25418                "Label:\n"
25419                "}",
25420                Style);
25421 
25422   verifyFormat("if (a) {\n"
25423                "Label:\n"
25424                "  f();\n"
25425                "}",
25426                Style);
25427 
25428   verifyFormat("if (a) {\n"
25429                "  f();\n"
25430                "Label:\n"
25431                "}",
25432                Style);
25433 
25434   verifyFormat("if consteval {\n"
25435                "  f();\n"
25436                "} else {\n"
25437                "  g();\n"
25438                "}",
25439                Style);
25440 
25441   verifyFormat("if not consteval {\n"
25442                "  f();\n"
25443                "} else if (a) {\n"
25444                "  g();\n"
25445                "}",
25446                Style);
25447 
25448   verifyFormat("if !consteval {\n"
25449                "  g();\n"
25450                "}",
25451                Style);
25452 
25453   Style.ColumnLimit = 65;
25454 
25455   verifyFormat("if (condition) {\n"
25456                "  ff(Indices,\n"
25457                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25458                "} else {\n"
25459                "  ff(Indices,\n"
25460                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25461                "}",
25462                Style);
25463 
25464   Style.ColumnLimit = 20;
25465 
25466   verifyFormat("int ab = [](int i) {\n"
25467                "  if (i > 0) {\n"
25468                "    i = 12345678 -\n"
25469                "        i;\n"
25470                "  }\n"
25471                "  return i;\n"
25472                "};",
25473                Style);
25474 
25475   verifyFormat("if (a) {\n"
25476                "  b = c + // 1 -\n"
25477                "      d;\n"
25478                "}",
25479                Style);
25480 
25481   verifyFormat("if (a) {\n"
25482                "  b = c >= 0 ? d\n"
25483                "             : e;\n"
25484                "}",
25485                "if (a) {\n"
25486                "  b = c >= 0 ? d : e;\n"
25487                "}",
25488                Style);
25489 
25490   verifyFormat("if (a)\n"
25491                "  b = c > 0 ? d : e;",
25492                "if (a) {\n"
25493                "  b = c > 0 ? d : e;\n"
25494                "}",
25495                Style);
25496 
25497   Style.ColumnLimit = 0;
25498 
25499   verifyFormat("if (a)\n"
25500                "  b234567890223456789032345678904234567890 = "
25501                "c234567890223456789032345678904234567890;",
25502                "if (a) {\n"
25503                "  b234567890223456789032345678904234567890 = "
25504                "c234567890223456789032345678904234567890;\n"
25505                "}",
25506                Style);
25507 }
25508 
25509 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
25510   auto Style = getLLVMStyle();
25511 
25512   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
25513                     "void functionDecl(int a, int b, int c);";
25514 
25515   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25516                      "paramF, paramG, paramH, paramI);\n"
25517                      "void functionDecl(int argumentA, int argumentB, int "
25518                      "argumentC, int argumentD, int argumentE);";
25519 
25520   verifyFormat(Short, Style);
25521 
25522   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25523                       "paramF, paramG, paramH,\n"
25524                       "             paramI);\n"
25525                       "void functionDecl(int argumentA, int argumentB, int "
25526                       "argumentC, int argumentD,\n"
25527                       "                  int argumentE);";
25528 
25529   verifyFormat(NoBreak, Medium, Style);
25530   verifyFormat(NoBreak,
25531                "functionCall(\n"
25532                "    paramA,\n"
25533                "    paramB,\n"
25534                "    paramC,\n"
25535                "    paramD,\n"
25536                "    paramE,\n"
25537                "    paramF,\n"
25538                "    paramG,\n"
25539                "    paramH,\n"
25540                "    paramI\n"
25541                ");\n"
25542                "void functionDecl(\n"
25543                "    int argumentA,\n"
25544                "    int argumentB,\n"
25545                "    int argumentC,\n"
25546                "    int argumentD,\n"
25547                "    int argumentE\n"
25548                ");",
25549                Style);
25550 
25551   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
25552                "                  nestedLongFunctionCall(argument1, "
25553                "argument2, argument3,\n"
25554                "                                         argument4, "
25555                "argument5));",
25556                Style);
25557 
25558   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25559 
25560   verifyFormat(Short, Style);
25561   verifyFormat(
25562       "functionCall(\n"
25563       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25564       "paramI\n"
25565       ");\n"
25566       "void functionDecl(\n"
25567       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25568       "argumentE\n"
25569       ");",
25570       Medium, Style);
25571 
25572   Style.AllowAllArgumentsOnNextLine = false;
25573   Style.AllowAllParametersOfDeclarationOnNextLine = false;
25574 
25575   verifyFormat(Short, Style);
25576   verifyFormat(
25577       "functionCall(\n"
25578       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25579       "paramI\n"
25580       ");\n"
25581       "void functionDecl(\n"
25582       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25583       "argumentE\n"
25584       ");",
25585       Medium, Style);
25586 
25587   Style.BinPackArguments = false;
25588   Style.BinPackParameters = false;
25589 
25590   verifyFormat(Short, Style);
25591 
25592   verifyFormat("functionCall(\n"
25593                "    paramA,\n"
25594                "    paramB,\n"
25595                "    paramC,\n"
25596                "    paramD,\n"
25597                "    paramE,\n"
25598                "    paramF,\n"
25599                "    paramG,\n"
25600                "    paramH,\n"
25601                "    paramI\n"
25602                ");\n"
25603                "void functionDecl(\n"
25604                "    int argumentA,\n"
25605                "    int argumentB,\n"
25606                "    int argumentC,\n"
25607                "    int argumentD,\n"
25608                "    int argumentE\n"
25609                ");",
25610                Medium, Style);
25611 
25612   verifyFormat("outerFunctionCall(\n"
25613                "    nestedFunctionCall(argument1),\n"
25614                "    nestedLongFunctionCall(\n"
25615                "        argument1,\n"
25616                "        argument2,\n"
25617                "        argument3,\n"
25618                "        argument4,\n"
25619                "        argument5\n"
25620                "    )\n"
25621                ");",
25622                Style);
25623 
25624   verifyFormat("int a = (int)b;", Style);
25625   verifyFormat("int a = (int)b;",
25626                "int a = (\n"
25627                "    int\n"
25628                ") b;",
25629                Style);
25630 
25631   verifyFormat("return (true);", Style);
25632   verifyFormat("return (true);",
25633                "return (\n"
25634                "    true\n"
25635                ");",
25636                Style);
25637 
25638   verifyFormat("void foo();", Style);
25639   verifyFormat("void foo();",
25640                "void foo(\n"
25641                ");",
25642                Style);
25643 
25644   verifyFormat("void foo() {}", Style);
25645   verifyFormat("void foo() {}",
25646                "void foo(\n"
25647                ") {\n"
25648                "}",
25649                Style);
25650 
25651   verifyFormat("auto string = std::string();", Style);
25652   verifyFormat("auto string = std::string();",
25653                "auto string = std::string(\n"
25654                ");",
25655                Style);
25656 
25657   verifyFormat("void (*functionPointer)() = nullptr;", Style);
25658   verifyFormat("void (*functionPointer)() = nullptr;",
25659                "void (\n"
25660                "    *functionPointer\n"
25661                ")\n"
25662                "(\n"
25663                ") = nullptr;",
25664                Style);
25665 }
25666 
25667 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
25668   auto Style = getLLVMStyle();
25669 
25670   verifyFormat("if (foo()) {\n"
25671                "  return;\n"
25672                "}",
25673                Style);
25674 
25675   verifyFormat("if (quitelongarg !=\n"
25676                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25677                "comment\n"
25678                "  return;\n"
25679                "}",
25680                Style);
25681 
25682   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25683 
25684   verifyFormat("if (foo()) {\n"
25685                "  return;\n"
25686                "}",
25687                Style);
25688 
25689   verifyFormat("if (quitelongarg !=\n"
25690                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25691                "comment\n"
25692                "  return;\n"
25693                "}",
25694                Style);
25695 }
25696 
25697 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
25698   auto Style = getLLVMStyle();
25699 
25700   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25701                "  doSomething();\n"
25702                "}",
25703                Style);
25704 
25705   verifyFormat("for (int myReallyLongCountVariable = 0; "
25706                "myReallyLongCountVariable < count;\n"
25707                "     myReallyLongCountVariable++) {\n"
25708                "  doSomething();\n"
25709                "}",
25710                Style);
25711 
25712   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25713 
25714   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25715                "  doSomething();\n"
25716                "}",
25717                Style);
25718 
25719   verifyFormat("for (int myReallyLongCountVariable = 0; "
25720                "myReallyLongCountVariable < count;\n"
25721                "     myReallyLongCountVariable++) {\n"
25722                "  doSomething();\n"
25723                "}",
25724                Style);
25725 }
25726 
25727 TEST_F(FormatTest, UnderstandsDigraphs) {
25728   verifyFormat("int arr<:5:> = {};");
25729   verifyFormat("int arr[5] = <%%>;");
25730   verifyFormat("int arr<:::qualified_variable:> = {};");
25731   verifyFormat("int arr[::qualified_variable] = <%%>;");
25732   verifyFormat("%:include <header>");
25733   verifyFormat("%:define A x##y");
25734   verifyFormat("#define A x%:%:y");
25735 }
25736 
25737 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
25738   auto Style = getLLVMStyle();
25739   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
25740   Style.AlignConsecutiveAssignments.Enabled = true;
25741   Style.AlignConsecutiveDeclarations.Enabled = true;
25742 
25743   // The AlignArray code is incorrect for non square Arrays and can cause
25744   // crashes, these tests assert that the array is not changed but will
25745   // also act as regression tests for when it is properly fixed
25746   verifyFormat("struct test demo[] = {\n"
25747                "    {1, 2},\n"
25748                "    {3, 4, 5},\n"
25749                "    {6, 7, 8}\n"
25750                "};",
25751                Style);
25752   verifyFormat("struct test demo[] = {\n"
25753                "    {1, 2, 3, 4, 5},\n"
25754                "    {3, 4, 5},\n"
25755                "    {6, 7, 8}\n"
25756                "};",
25757                Style);
25758   verifyFormat("struct test demo[] = {\n"
25759                "    {1, 2, 3, 4, 5},\n"
25760                "    {3, 4, 5},\n"
25761                "    {6, 7, 8, 9, 10, 11, 12}\n"
25762                "};",
25763                Style);
25764   verifyFormat("struct test demo[] = {\n"
25765                "    {1, 2, 3},\n"
25766                "    {3, 4, 5},\n"
25767                "    {6, 7, 8, 9, 10, 11, 12}\n"
25768                "};",
25769                Style);
25770 
25771   verifyFormat("S{\n"
25772                "    {},\n"
25773                "    {},\n"
25774                "    {a, b}\n"
25775                "};",
25776                Style);
25777   verifyFormat("S{\n"
25778                "    {},\n"
25779                "    {},\n"
25780                "    {a, b},\n"
25781                "};",
25782                Style);
25783   verifyFormat("void foo() {\n"
25784                "  auto thing = test{\n"
25785                "      {\n"
25786                "       {13}, {something}, // A\n"
25787                "      }\n"
25788                "  };\n"
25789                "}",
25790                "void foo() {\n"
25791                "  auto thing = test{\n"
25792                "      {\n"
25793                "       {13},\n"
25794                "       {something}, // A\n"
25795                "      }\n"
25796                "  };\n"
25797                "}",
25798                Style);
25799 }
25800 
25801 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
25802   auto Style = getLLVMStyle();
25803   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
25804   Style.AlignConsecutiveAssignments.Enabled = true;
25805   Style.AlignConsecutiveDeclarations.Enabled = true;
25806 
25807   // The AlignArray code is incorrect for non square Arrays and can cause
25808   // crashes, these tests assert that the array is not changed but will
25809   // also act as regression tests for when it is properly fixed
25810   verifyFormat("struct test demo[] = {\n"
25811                "    {1, 2},\n"
25812                "    {3, 4, 5},\n"
25813                "    {6, 7, 8}\n"
25814                "};",
25815                Style);
25816   verifyFormat("struct test demo[] = {\n"
25817                "    {1, 2, 3, 4, 5},\n"
25818                "    {3, 4, 5},\n"
25819                "    {6, 7, 8}\n"
25820                "};",
25821                Style);
25822   verifyFormat("struct test demo[] = {\n"
25823                "    {1, 2, 3, 4, 5},\n"
25824                "    {3, 4, 5},\n"
25825                "    {6, 7, 8, 9, 10, 11, 12}\n"
25826                "};",
25827                Style);
25828   verifyFormat("struct test demo[] = {\n"
25829                "    {1, 2, 3},\n"
25830                "    {3, 4, 5},\n"
25831                "    {6, 7, 8, 9, 10, 11, 12}\n"
25832                "};",
25833                Style);
25834 
25835   verifyFormat("S{\n"
25836                "    {},\n"
25837                "    {},\n"
25838                "    {a, b}\n"
25839                "};",
25840                Style);
25841   verifyFormat("S{\n"
25842                "    {},\n"
25843                "    {},\n"
25844                "    {a, b},\n"
25845                "};",
25846                Style);
25847   verifyFormat("void foo() {\n"
25848                "  auto thing = test{\n"
25849                "      {\n"
25850                "       {13}, {something}, // A\n"
25851                "      }\n"
25852                "  };\n"
25853                "}",
25854                "void foo() {\n"
25855                "  auto thing = test{\n"
25856                "      {\n"
25857                "       {13},\n"
25858                "       {something}, // A\n"
25859                "      }\n"
25860                "  };\n"
25861                "}",
25862                Style);
25863 }
25864 
25865 TEST_F(FormatTest, FormatsVariableTemplates) {
25866   verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
25867   verifyFormat("template <typename T> "
25868                "inline bool var = is_integral_v<T> && is_signed_v<T>;");
25869 }
25870 
25871 } // namespace
25872 } // namespace format
25873 } // namespace clang
25874