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.IfMacros.push_back("MYIF");
1577   // Where line-lengths matter, a 2-letter synonym that maintains line length.
1578   // Not IF to avoid any confusion that IF is somehow special.
1579   AllowSimpleBracedStatements.IfMacros.push_back("FI");
1580   AllowSimpleBracedStatements.ColumnLimit = 40;
1581   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1582       FormatStyle::SBS_Always;
1583 
1584   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1585       FormatStyle::SIS_WithoutElse;
1586   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1587 
1588   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1589   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1590   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1591 
1592   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1593   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1594   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1595   verifyFormat("if consteval {}", AllowSimpleBracedStatements);
1596   verifyFormat("if !consteval {}", AllowSimpleBracedStatements);
1597   verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements);
1598   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1599   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1600   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1601   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1602   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1603   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1604   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1605   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1606   verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements);
1607   verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements);
1608   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1609   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1610   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1611   verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements);
1612   verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements);
1613   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1614   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1615   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1616                AllowSimpleBracedStatements);
1617   verifyFormat("if (true) {\n"
1618                "  ffffffffffffffffffffffff();\n"
1619                "}",
1620                AllowSimpleBracedStatements);
1621   verifyFormat("if (true) {\n"
1622                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1623                "}",
1624                AllowSimpleBracedStatements);
1625   verifyFormat("if (true) { //\n"
1626                "  f();\n"
1627                "}",
1628                AllowSimpleBracedStatements);
1629   verifyFormat("if (true) {\n"
1630                "  f();\n"
1631                "  f();\n"
1632                "}",
1633                AllowSimpleBracedStatements);
1634   verifyFormat("if (true) {\n"
1635                "  f();\n"
1636                "} else {\n"
1637                "  f();\n"
1638                "}",
1639                AllowSimpleBracedStatements);
1640   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1641                AllowSimpleBracedStatements);
1642   verifyFormat("MYIF (true) {\n"
1643                "  ffffffffffffffffffffffff();\n"
1644                "}",
1645                AllowSimpleBracedStatements);
1646   verifyFormat("MYIF (true) {\n"
1647                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1648                "}",
1649                AllowSimpleBracedStatements);
1650   verifyFormat("MYIF (true) { //\n"
1651                "  f();\n"
1652                "}",
1653                AllowSimpleBracedStatements);
1654   verifyFormat("MYIF (true) {\n"
1655                "  f();\n"
1656                "  f();\n"
1657                "}",
1658                AllowSimpleBracedStatements);
1659   verifyFormat("MYIF (true) {\n"
1660                "  f();\n"
1661                "} else {\n"
1662                "  f();\n"
1663                "}",
1664                AllowSimpleBracedStatements);
1665 
1666   verifyFormat("struct A2 {\n"
1667                "  int X;\n"
1668                "};",
1669                AllowSimpleBracedStatements);
1670   verifyFormat("typedef struct A2 {\n"
1671                "  int X;\n"
1672                "} A2_t;",
1673                AllowSimpleBracedStatements);
1674   verifyFormat("template <int> struct A2 {\n"
1675                "  struct B {};\n"
1676                "};",
1677                AllowSimpleBracedStatements);
1678 
1679   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1680       FormatStyle::SIS_Never;
1681   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1682   verifyFormat("if (true) {\n"
1683                "  f();\n"
1684                "}",
1685                AllowSimpleBracedStatements);
1686   verifyFormat("if (true) {\n"
1687                "  f();\n"
1688                "} else {\n"
1689                "  f();\n"
1690                "}",
1691                AllowSimpleBracedStatements);
1692   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1693   verifyFormat("MYIF (true) {\n"
1694                "  f();\n"
1695                "}",
1696                AllowSimpleBracedStatements);
1697   verifyFormat("MYIF (true) {\n"
1698                "  f();\n"
1699                "} else {\n"
1700                "  f();\n"
1701                "}",
1702                AllowSimpleBracedStatements);
1703 
1704   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1705   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1706   verifyFormat("while (true) {\n"
1707                "  f();\n"
1708                "}",
1709                AllowSimpleBracedStatements);
1710   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1711   verifyFormat("for (;;) {\n"
1712                "  f();\n"
1713                "}",
1714                AllowSimpleBracedStatements);
1715   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1716   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1717                "  f();\n"
1718                "}",
1719                AllowSimpleBracedStatements);
1720 
1721   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1722       FormatStyle::SIS_WithoutElse;
1723   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1724   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1725       FormatStyle::BWACS_Always;
1726 
1727   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1728   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1729   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1730   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1731   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1732   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1733   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1734   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1735   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1736   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1737   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1738   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1739   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1740   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1741   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1742   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1743   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1744                AllowSimpleBracedStatements);
1745   verifyFormat("if (true)\n"
1746                "{\n"
1747                "  ffffffffffffffffffffffff();\n"
1748                "}",
1749                AllowSimpleBracedStatements);
1750   verifyFormat("if (true)\n"
1751                "{\n"
1752                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1753                "}",
1754                AllowSimpleBracedStatements);
1755   verifyFormat("if (true)\n"
1756                "{ //\n"
1757                "  f();\n"
1758                "}",
1759                AllowSimpleBracedStatements);
1760   verifyFormat("if (true)\n"
1761                "{\n"
1762                "  f();\n"
1763                "  f();\n"
1764                "}",
1765                AllowSimpleBracedStatements);
1766   verifyFormat("if (true)\n"
1767                "{\n"
1768                "  f();\n"
1769                "} else\n"
1770                "{\n"
1771                "  f();\n"
1772                "}",
1773                AllowSimpleBracedStatements);
1774   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1775                AllowSimpleBracedStatements);
1776   verifyFormat("MYIF (true)\n"
1777                "{\n"
1778                "  ffffffffffffffffffffffff();\n"
1779                "}",
1780                AllowSimpleBracedStatements);
1781   verifyFormat("MYIF (true)\n"
1782                "{\n"
1783                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1784                "}",
1785                AllowSimpleBracedStatements);
1786   verifyFormat("MYIF (true)\n"
1787                "{ //\n"
1788                "  f();\n"
1789                "}",
1790                AllowSimpleBracedStatements);
1791   verifyFormat("MYIF (true)\n"
1792                "{\n"
1793                "  f();\n"
1794                "  f();\n"
1795                "}",
1796                AllowSimpleBracedStatements);
1797   verifyFormat("MYIF (true)\n"
1798                "{\n"
1799                "  f();\n"
1800                "} else\n"
1801                "{\n"
1802                "  f();\n"
1803                "}",
1804                AllowSimpleBracedStatements);
1805 
1806   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1807       FormatStyle::SIS_Never;
1808   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1809   verifyFormat("if (true)\n"
1810                "{\n"
1811                "  f();\n"
1812                "}",
1813                AllowSimpleBracedStatements);
1814   verifyFormat("if (true)\n"
1815                "{\n"
1816                "  f();\n"
1817                "} else\n"
1818                "{\n"
1819                "  f();\n"
1820                "}",
1821                AllowSimpleBracedStatements);
1822   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1823   verifyFormat("MYIF (true)\n"
1824                "{\n"
1825                "  f();\n"
1826                "}",
1827                AllowSimpleBracedStatements);
1828   verifyFormat("MYIF (true)\n"
1829                "{\n"
1830                "  f();\n"
1831                "} else\n"
1832                "{\n"
1833                "  f();\n"
1834                "}",
1835                AllowSimpleBracedStatements);
1836 
1837   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1838   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1839   verifyFormat("while (true)\n"
1840                "{\n"
1841                "  f();\n"
1842                "}",
1843                AllowSimpleBracedStatements);
1844   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1845   verifyFormat("for (;;)\n"
1846                "{\n"
1847                "  f();\n"
1848                "}",
1849                AllowSimpleBracedStatements);
1850   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1851   verifyFormat("BOOST_FOREACH (int v, vec)\n"
1852                "{\n"
1853                "  f();\n"
1854                "}",
1855                AllowSimpleBracedStatements);
1856 }
1857 
1858 TEST_F(FormatTest, UnderstandsMacros) {
1859   verifyFormat("#define A (parentheses)");
1860   verifyFormat("/* comment */ #define A (parentheses)");
1861   verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
1862   // Even the partial code should never be merged.
1863   EXPECT_EQ("/* comment */ #define A (parentheses)\n"
1864             "#",
1865             format("/* comment */ #define A (parentheses)\n"
1866                    "#"));
1867   verifyFormat("/* comment */ #define A (parentheses)\n"
1868                "#\n");
1869   verifyFormat("/* comment */ #define A (parentheses)\n"
1870                "#define B (parentheses)");
1871   verifyFormat("#define true ((int)1)");
1872   verifyFormat("#define and(x)");
1873   verifyFormat("#define if(x) x");
1874   verifyFormat("#define return(x) (x)");
1875   verifyFormat("#define while(x) for (; x;)");
1876   verifyFormat("#define xor(x) (^(x))");
1877   verifyFormat("#define __except(x)");
1878   verifyFormat("#define __try(x)");
1879 
1880   // https://llvm.org/PR54348.
1881   verifyFormat(
1882       "#define A"
1883       "                                                                      "
1884       "\\\n"
1885       "  class & {}");
1886 
1887   FormatStyle Style = getLLVMStyle();
1888   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1889   Style.BraceWrapping.AfterFunction = true;
1890   // Test that a macro definition never gets merged with the following
1891   // definition.
1892   // FIXME: The AAA macro definition probably should not be split into 3 lines.
1893   verifyFormat("#define AAA                                                    "
1894                "                \\\n"
1895                "  N                                                            "
1896                "                \\\n"
1897                "  {\n"
1898                "#define BBB }\n",
1899                Style);
1900   // verifyFormat("#define AAA N { //\n", Style);
1901 
1902   verifyFormat("MACRO(return)");
1903   verifyFormat("MACRO(co_await)");
1904   verifyFormat("MACRO(co_return)");
1905   verifyFormat("MACRO(co_yield)");
1906   verifyFormat("MACRO(return, something)");
1907   verifyFormat("MACRO(co_return, something)");
1908   verifyFormat("MACRO(something##something)");
1909   verifyFormat("MACRO(return##something)");
1910   verifyFormat("MACRO(co_return##something)");
1911 }
1912 
1913 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1914   FormatStyle Style = getLLVMStyleWithColumns(60);
1915   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1916   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1917   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1918   EXPECT_EQ("#define A                                                  \\\n"
1919             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1920             "  {                                                        \\\n"
1921             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1922             "  }\n"
1923             "X;",
1924             format("#define A \\\n"
1925                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1926                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1927                    "   }\n"
1928                    "X;",
1929                    Style));
1930 }
1931 
1932 TEST_F(FormatTest, ParseIfElse) {
1933   verifyFormat("if (true)\n"
1934                "  if (true)\n"
1935                "    if (true)\n"
1936                "      f();\n"
1937                "    else\n"
1938                "      g();\n"
1939                "  else\n"
1940                "    h();\n"
1941                "else\n"
1942                "  i();");
1943   verifyFormat("if (true)\n"
1944                "  if (true)\n"
1945                "    if (true) {\n"
1946                "      if (true)\n"
1947                "        f();\n"
1948                "    } else {\n"
1949                "      g();\n"
1950                "    }\n"
1951                "  else\n"
1952                "    h();\n"
1953                "else {\n"
1954                "  i();\n"
1955                "}");
1956   verifyFormat("if (true)\n"
1957                "  if constexpr (true)\n"
1958                "    if (true) {\n"
1959                "      if constexpr (true)\n"
1960                "        f();\n"
1961                "    } else {\n"
1962                "      g();\n"
1963                "    }\n"
1964                "  else\n"
1965                "    h();\n"
1966                "else {\n"
1967                "  i();\n"
1968                "}");
1969   verifyFormat("if (true)\n"
1970                "  if CONSTEXPR (true)\n"
1971                "    if (true) {\n"
1972                "      if CONSTEXPR (true)\n"
1973                "        f();\n"
1974                "    } else {\n"
1975                "      g();\n"
1976                "    }\n"
1977                "  else\n"
1978                "    h();\n"
1979                "else {\n"
1980                "  i();\n"
1981                "}");
1982   verifyFormat("void f() {\n"
1983                "  if (a) {\n"
1984                "  } else {\n"
1985                "  }\n"
1986                "}");
1987 }
1988 
1989 TEST_F(FormatTest, ElseIf) {
1990   verifyFormat("if (a) {\n} else if (b) {\n}");
1991   verifyFormat("if (a)\n"
1992                "  f();\n"
1993                "else if (b)\n"
1994                "  g();\n"
1995                "else\n"
1996                "  h();");
1997   verifyFormat("if (a)\n"
1998                "  f();\n"
1999                "else // comment\n"
2000                "  if (b) {\n"
2001                "    g();\n"
2002                "    h();\n"
2003                "  }");
2004   verifyFormat("if constexpr (a)\n"
2005                "  f();\n"
2006                "else if constexpr (b)\n"
2007                "  g();\n"
2008                "else\n"
2009                "  h();");
2010   verifyFormat("if CONSTEXPR (a)\n"
2011                "  f();\n"
2012                "else if CONSTEXPR (b)\n"
2013                "  g();\n"
2014                "else\n"
2015                "  h();");
2016   verifyFormat("if (a) {\n"
2017                "  f();\n"
2018                "}\n"
2019                "// or else ..\n"
2020                "else {\n"
2021                "  g()\n"
2022                "}");
2023 
2024   verifyFormat("if (a) {\n"
2025                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2026                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2027                "}");
2028   verifyFormat("if (a) {\n"
2029                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2030                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2031                "}");
2032   verifyFormat("if (a) {\n"
2033                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2034                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2035                "}");
2036   verifyFormat("if (a) {\n"
2037                "} else if (\n"
2038                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2039                "}",
2040                getLLVMStyleWithColumns(62));
2041   verifyFormat("if (a) {\n"
2042                "} else if constexpr (\n"
2043                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2044                "}",
2045                getLLVMStyleWithColumns(62));
2046   verifyFormat("if (a) {\n"
2047                "} else if CONSTEXPR (\n"
2048                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2049                "}",
2050                getLLVMStyleWithColumns(62));
2051 }
2052 
2053 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
2054   FormatStyle Style = getLLVMStyle();
2055   EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
2056   EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer);
2057   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
2058   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
2059   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
2060   verifyFormat("int *f1(int &a) const &;", Style);
2061   verifyFormat("int *f1(int &a) const & = 0;", Style);
2062   verifyFormat("int *a = f1();", Style);
2063   verifyFormat("int &b = f2();", Style);
2064   verifyFormat("int &&c = f3();", Style);
2065   verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
2066   verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2067   verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
2068   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2069   verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
2070   verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2071   verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
2072   verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
2073   verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
2074   verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
2075   verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
2076   verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
2077   verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
2078   verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
2079   verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
2080   verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
2081   verifyFormat(
2082       "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n"
2083       "                     res2 = [](int &a) { return 0000000000000; };",
2084       Style);
2085 
2086   Style.AlignConsecutiveDeclarations.Enabled = true;
2087   verifyFormat("Const unsigned int *c;\n"
2088                "const unsigned int *d;\n"
2089                "Const unsigned int &e;\n"
2090                "const unsigned int &f;\n"
2091                "const unsigned    &&g;\n"
2092                "Const unsigned      h;",
2093                Style);
2094 
2095   Style.PointerAlignment = FormatStyle::PAS_Left;
2096   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
2097   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
2098   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
2099   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
2100   verifyFormat("int* f1(int& a) const& = 0;", Style);
2101   verifyFormat("int* a = f1();", Style);
2102   verifyFormat("int& b = f2();", Style);
2103   verifyFormat("int&& c = f3();", Style);
2104   verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2105   verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2106   verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2107   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2108   verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2109   verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2110   verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2111   verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2112   verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
2113   verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
2114   verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
2115   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2116   verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
2117   verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
2118   verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
2119   verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
2120   verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
2121   verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
2122   verifyFormat(
2123       "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n"
2124       "                    res2 = [](int& a) { return 0000000000000; };",
2125       Style);
2126 
2127   Style.AlignConsecutiveDeclarations.Enabled = true;
2128   verifyFormat("Const unsigned int* c;\n"
2129                "const unsigned int* d;\n"
2130                "Const unsigned int& e;\n"
2131                "const unsigned int& f;\n"
2132                "const unsigned&&    g;\n"
2133                "Const unsigned      h;",
2134                Style);
2135 
2136   Style.PointerAlignment = FormatStyle::PAS_Right;
2137   Style.ReferenceAlignment = FormatStyle::RAS_Left;
2138   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
2139   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
2140   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
2141   verifyFormat("int *a = f1();", Style);
2142   verifyFormat("int& b = f2();", Style);
2143   verifyFormat("int&& c = f3();", Style);
2144   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2145   verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2146   verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
2147 
2148   Style.AlignConsecutiveDeclarations.Enabled = true;
2149   verifyFormat("Const unsigned int *c;\n"
2150                "const unsigned int *d;\n"
2151                "Const unsigned int& e;\n"
2152                "const unsigned int& f;\n"
2153                "const unsigned      g;\n"
2154                "Const unsigned      h;",
2155                Style);
2156 
2157   Style.PointerAlignment = FormatStyle::PAS_Left;
2158   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
2159   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
2160   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
2161   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
2162   verifyFormat("int* a = f1();", Style);
2163   verifyFormat("int & b = f2();", Style);
2164   verifyFormat("int && c = f3();", Style);
2165   verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
2166   verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
2167   verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
2168   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2169   verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
2170   verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
2171   verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
2172   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2173   verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
2174   verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
2175   verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
2176   verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
2177   verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
2178   verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
2179   verifyFormat(
2180       "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n"
2181       "                     res2 = [](int & a) { return 0000000000000; };",
2182       Style);
2183 
2184   Style.AlignConsecutiveDeclarations.Enabled = true;
2185   verifyFormat("Const unsigned int*  c;\n"
2186                "const unsigned int*  d;\n"
2187                "Const unsigned int & e;\n"
2188                "const unsigned int & f;\n"
2189                "const unsigned &&    g;\n"
2190                "Const unsigned       h;",
2191                Style);
2192 
2193   Style.PointerAlignment = FormatStyle::PAS_Middle;
2194   Style.ReferenceAlignment = FormatStyle::RAS_Right;
2195   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
2196   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
2197   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
2198   verifyFormat("int * a = f1();", Style);
2199   verifyFormat("int &b = f2();", Style);
2200   verifyFormat("int &&c = f3();", Style);
2201   verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2202   verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2203   verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
2204 
2205   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2206   // specifically handled
2207   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2208 }
2209 
2210 TEST_F(FormatTest, FormatsForLoop) {
2211   verifyFormat(
2212       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2213       "     ++VeryVeryLongLoopVariable)\n"
2214       "  ;");
2215   verifyFormat("for (;;)\n"
2216                "  f();");
2217   verifyFormat("for (;;) {\n}");
2218   verifyFormat("for (;;) {\n"
2219                "  f();\n"
2220                "}");
2221   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2222 
2223   verifyFormat(
2224       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2225       "                                          E = UnwrappedLines.end();\n"
2226       "     I != E; ++I) {\n}");
2227 
2228   verifyFormat(
2229       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2230       "     ++IIIII) {\n}");
2231   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2232                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2233                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2234   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2235                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2236                "         E = FD->getDeclsInPrototypeScope().end();\n"
2237                "     I != E; ++I) {\n}");
2238   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2239                "         I = Container.begin(),\n"
2240                "         E = Container.end();\n"
2241                "     I != E; ++I) {\n}",
2242                getLLVMStyleWithColumns(76));
2243 
2244   verifyFormat(
2245       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2246       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2247       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2248       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2249       "     ++aaaaaaaaaaa) {\n}");
2250   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2251                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2252                "     ++i) {\n}");
2253   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2254                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2255                "}");
2256   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2257                "         aaaaaaaaaa);\n"
2258                "     iter; ++iter) {\n"
2259                "}");
2260   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2261                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2262                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2263                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2264 
2265   // These should not be formatted as Objective-C for-in loops.
2266   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2267   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2268   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2269   verifyFormat(
2270       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2271 
2272   FormatStyle NoBinPacking = getLLVMStyle();
2273   NoBinPacking.BinPackParameters = false;
2274   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2275                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2276                "                                           aaaaaaaaaaaaaaaa,\n"
2277                "                                           aaaaaaaaaaaaaaaa,\n"
2278                "                                           aaaaaaaaaaaaaaaa);\n"
2279                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2280                "}",
2281                NoBinPacking);
2282   verifyFormat(
2283       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2284       "                                          E = UnwrappedLines.end();\n"
2285       "     I != E;\n"
2286       "     ++I) {\n}",
2287       NoBinPacking);
2288 
2289   FormatStyle AlignLeft = getLLVMStyle();
2290   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2291   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2292 }
2293 
2294 TEST_F(FormatTest, RangeBasedForLoops) {
2295   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2296                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2297   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2298                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2299   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2300                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2301   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2302                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2303 }
2304 
2305 TEST_F(FormatTest, ForEachLoops) {
2306   FormatStyle Style = getLLVMStyle();
2307   EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2308   EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
2309   verifyFormat("void f() {\n"
2310                "  for (;;) {\n"
2311                "  }\n"
2312                "  foreach (Item *item, itemlist) {\n"
2313                "  }\n"
2314                "  Q_FOREACH (Item *item, itemlist) {\n"
2315                "  }\n"
2316                "  BOOST_FOREACH (Item *item, itemlist) {\n"
2317                "  }\n"
2318                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2319                "}",
2320                Style);
2321   verifyFormat("void f() {\n"
2322                "  for (;;)\n"
2323                "    int j = 1;\n"
2324                "  Q_FOREACH (int v, vec)\n"
2325                "    v *= 2;\n"
2326                "  for (;;) {\n"
2327                "    int j = 1;\n"
2328                "  }\n"
2329                "  Q_FOREACH (int v, vec) {\n"
2330                "    v *= 2;\n"
2331                "  }\n"
2332                "}",
2333                Style);
2334 
2335   FormatStyle ShortBlocks = getLLVMStyle();
2336   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2337   EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
2338   verifyFormat("void f() {\n"
2339                "  for (;;)\n"
2340                "    int j = 1;\n"
2341                "  Q_FOREACH (int &v, vec)\n"
2342                "    v *= 2;\n"
2343                "  for (;;) {\n"
2344                "    int j = 1;\n"
2345                "  }\n"
2346                "  Q_FOREACH (int &v, vec) {\n"
2347                "    int j = 1;\n"
2348                "  }\n"
2349                "}",
2350                ShortBlocks);
2351 
2352   FormatStyle ShortLoops = getLLVMStyle();
2353   ShortLoops.AllowShortLoopsOnASingleLine = true;
2354   EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2355   verifyFormat("void f() {\n"
2356                "  for (;;) int j = 1;\n"
2357                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2358                "  for (;;) {\n"
2359                "    int j = 1;\n"
2360                "  }\n"
2361                "  Q_FOREACH (int &v, vec) {\n"
2362                "    int j = 1;\n"
2363                "  }\n"
2364                "}",
2365                ShortLoops);
2366 
2367   FormatStyle ShortBlocksAndLoops = getLLVMStyle();
2368   ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2369   ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true;
2370   verifyFormat("void f() {\n"
2371                "  for (;;) int j = 1;\n"
2372                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2373                "  for (;;) { int j = 1; }\n"
2374                "  Q_FOREACH (int &v, vec) { int j = 1; }\n"
2375                "}",
2376                ShortBlocksAndLoops);
2377 
2378   Style.SpaceBeforeParens =
2379       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2380   verifyFormat("void f() {\n"
2381                "  for (;;) {\n"
2382                "  }\n"
2383                "  foreach(Item *item, itemlist) {\n"
2384                "  }\n"
2385                "  Q_FOREACH(Item *item, itemlist) {\n"
2386                "  }\n"
2387                "  BOOST_FOREACH(Item *item, itemlist) {\n"
2388                "  }\n"
2389                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2390                "}",
2391                Style);
2392 
2393   // As function-like macros.
2394   verifyFormat("#define foreach(x, y)\n"
2395                "#define Q_FOREACH(x, y)\n"
2396                "#define BOOST_FOREACH(x, y)\n"
2397                "#define UNKNOWN_FOREACH(x, y)\n");
2398 
2399   // Not as function-like macros.
2400   verifyFormat("#define foreach (x, y)\n"
2401                "#define Q_FOREACH (x, y)\n"
2402                "#define BOOST_FOREACH (x, y)\n"
2403                "#define UNKNOWN_FOREACH (x, y)\n");
2404 
2405   // handle microsoft non standard extension
2406   verifyFormat("for each (char c in x->MyStringProperty)");
2407 }
2408 
2409 TEST_F(FormatTest, FormatsWhileLoop) {
2410   verifyFormat("while (true) {\n}");
2411   verifyFormat("while (true)\n"
2412                "  f();");
2413   verifyFormat("while () {\n}");
2414   verifyFormat("while () {\n"
2415                "  f();\n"
2416                "}");
2417 }
2418 
2419 TEST_F(FormatTest, FormatsDoWhile) {
2420   verifyFormat("do {\n"
2421                "  do_something();\n"
2422                "} while (something());");
2423   verifyFormat("do\n"
2424                "  do_something();\n"
2425                "while (something());");
2426 }
2427 
2428 TEST_F(FormatTest, FormatsSwitchStatement) {
2429   verifyFormat("switch (x) {\n"
2430                "case 1:\n"
2431                "  f();\n"
2432                "  break;\n"
2433                "case kFoo:\n"
2434                "case ns::kBar:\n"
2435                "case kBaz:\n"
2436                "  break;\n"
2437                "default:\n"
2438                "  g();\n"
2439                "  break;\n"
2440                "}");
2441   verifyFormat("switch (x) {\n"
2442                "case 1: {\n"
2443                "  f();\n"
2444                "  break;\n"
2445                "}\n"
2446                "case 2: {\n"
2447                "  break;\n"
2448                "}\n"
2449                "}");
2450   verifyFormat("switch (x) {\n"
2451                "case 1: {\n"
2452                "  f();\n"
2453                "  {\n"
2454                "    g();\n"
2455                "    h();\n"
2456                "  }\n"
2457                "  break;\n"
2458                "}\n"
2459                "}");
2460   verifyFormat("switch (x) {\n"
2461                "case 1: {\n"
2462                "  f();\n"
2463                "  if (foo) {\n"
2464                "    g();\n"
2465                "    h();\n"
2466                "  }\n"
2467                "  break;\n"
2468                "}\n"
2469                "}");
2470   verifyFormat("switch (x) {\n"
2471                "case 1: {\n"
2472                "  f();\n"
2473                "  g();\n"
2474                "} break;\n"
2475                "}");
2476   verifyFormat("switch (test)\n"
2477                "  ;");
2478   verifyFormat("switch (x) {\n"
2479                "default: {\n"
2480                "  // Do nothing.\n"
2481                "}\n"
2482                "}");
2483   verifyFormat("switch (x) {\n"
2484                "// comment\n"
2485                "// if 1, do f()\n"
2486                "case 1:\n"
2487                "  f();\n"
2488                "}");
2489   verifyFormat("switch (x) {\n"
2490                "case 1:\n"
2491                "  // Do amazing stuff\n"
2492                "  {\n"
2493                "    f();\n"
2494                "    g();\n"
2495                "  }\n"
2496                "  break;\n"
2497                "}");
2498   verifyFormat("#define A          \\\n"
2499                "  switch (x) {     \\\n"
2500                "  case a:          \\\n"
2501                "    foo = b;       \\\n"
2502                "  }",
2503                getLLVMStyleWithColumns(20));
2504   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2505                "  case OP_name:                        \\\n"
2506                "    return operations::Operation##name\n",
2507                getLLVMStyleWithColumns(40));
2508   verifyFormat("switch (x) {\n"
2509                "case 1:;\n"
2510                "default:;\n"
2511                "  int i;\n"
2512                "}");
2513 
2514   verifyGoogleFormat("switch (x) {\n"
2515                      "  case 1:\n"
2516                      "    f();\n"
2517                      "    break;\n"
2518                      "  case kFoo:\n"
2519                      "  case ns::kBar:\n"
2520                      "  case kBaz:\n"
2521                      "    break;\n"
2522                      "  default:\n"
2523                      "    g();\n"
2524                      "    break;\n"
2525                      "}");
2526   verifyGoogleFormat("switch (x) {\n"
2527                      "  case 1: {\n"
2528                      "    f();\n"
2529                      "    break;\n"
2530                      "  }\n"
2531                      "}");
2532   verifyGoogleFormat("switch (test)\n"
2533                      "  ;");
2534 
2535   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2536                      "  case OP_name:              \\\n"
2537                      "    return operations::Operation##name\n");
2538   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2539                      "  // Get the correction operation class.\n"
2540                      "  switch (OpCode) {\n"
2541                      "    CASE(Add);\n"
2542                      "    CASE(Subtract);\n"
2543                      "    default:\n"
2544                      "      return operations::Unknown;\n"
2545                      "  }\n"
2546                      "#undef OPERATION_CASE\n"
2547                      "}");
2548   verifyFormat("DEBUG({\n"
2549                "  switch (x) {\n"
2550                "  case A:\n"
2551                "    f();\n"
2552                "    break;\n"
2553                "    // fallthrough\n"
2554                "  case B:\n"
2555                "    g();\n"
2556                "    break;\n"
2557                "  }\n"
2558                "});");
2559   EXPECT_EQ("DEBUG({\n"
2560             "  switch (x) {\n"
2561             "  case A:\n"
2562             "    f();\n"
2563             "    break;\n"
2564             "  // On B:\n"
2565             "  case B:\n"
2566             "    g();\n"
2567             "    break;\n"
2568             "  }\n"
2569             "});",
2570             format("DEBUG({\n"
2571                    "  switch (x) {\n"
2572                    "  case A:\n"
2573                    "    f();\n"
2574                    "    break;\n"
2575                    "  // On B:\n"
2576                    "  case B:\n"
2577                    "    g();\n"
2578                    "    break;\n"
2579                    "  }\n"
2580                    "});",
2581                    getLLVMStyle()));
2582   EXPECT_EQ("switch (n) {\n"
2583             "case 0: {\n"
2584             "  return false;\n"
2585             "}\n"
2586             "default: {\n"
2587             "  return true;\n"
2588             "}\n"
2589             "}",
2590             format("switch (n)\n"
2591                    "{\n"
2592                    "case 0: {\n"
2593                    "  return false;\n"
2594                    "}\n"
2595                    "default: {\n"
2596                    "  return true;\n"
2597                    "}\n"
2598                    "}",
2599                    getLLVMStyle()));
2600   verifyFormat("switch (a) {\n"
2601                "case (b):\n"
2602                "  return;\n"
2603                "}");
2604 
2605   verifyFormat("switch (a) {\n"
2606                "case some_namespace::\n"
2607                "    some_constant:\n"
2608                "  return;\n"
2609                "}",
2610                getLLVMStyleWithColumns(34));
2611 
2612   verifyFormat("switch (a) {\n"
2613                "[[likely]] case 1:\n"
2614                "  return;\n"
2615                "}");
2616   verifyFormat("switch (a) {\n"
2617                "[[likely]] [[other::likely]] case 1:\n"
2618                "  return;\n"
2619                "}");
2620   verifyFormat("switch (x) {\n"
2621                "case 1:\n"
2622                "  return;\n"
2623                "[[likely]] case 2:\n"
2624                "  return;\n"
2625                "}");
2626   verifyFormat("switch (a) {\n"
2627                "case 1:\n"
2628                "[[likely]] case 2:\n"
2629                "  return;\n"
2630                "}");
2631   FormatStyle Attributes = getLLVMStyle();
2632   Attributes.AttributeMacros.push_back("LIKELY");
2633   Attributes.AttributeMacros.push_back("OTHER_LIKELY");
2634   verifyFormat("switch (a) {\n"
2635                "LIKELY case b:\n"
2636                "  return;\n"
2637                "}",
2638                Attributes);
2639   verifyFormat("switch (a) {\n"
2640                "LIKELY OTHER_LIKELY() case b:\n"
2641                "  return;\n"
2642                "}",
2643                Attributes);
2644   verifyFormat("switch (a) {\n"
2645                "case 1:\n"
2646                "  return;\n"
2647                "LIKELY case 2:\n"
2648                "  return;\n"
2649                "}",
2650                Attributes);
2651   verifyFormat("switch (a) {\n"
2652                "case 1:\n"
2653                "LIKELY case 2:\n"
2654                "  return;\n"
2655                "}",
2656                Attributes);
2657 
2658   FormatStyle Style = getLLVMStyle();
2659   Style.IndentCaseLabels = true;
2660   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2661   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2662   Style.BraceWrapping.AfterCaseLabel = true;
2663   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2664   EXPECT_EQ("switch (n)\n"
2665             "{\n"
2666             "  case 0:\n"
2667             "  {\n"
2668             "    return false;\n"
2669             "  }\n"
2670             "  default:\n"
2671             "  {\n"
2672             "    return true;\n"
2673             "  }\n"
2674             "}",
2675             format("switch (n) {\n"
2676                    "  case 0: {\n"
2677                    "    return false;\n"
2678                    "  }\n"
2679                    "  default: {\n"
2680                    "    return true;\n"
2681                    "  }\n"
2682                    "}",
2683                    Style));
2684   Style.BraceWrapping.AfterCaseLabel = false;
2685   EXPECT_EQ("switch (n)\n"
2686             "{\n"
2687             "  case 0: {\n"
2688             "    return false;\n"
2689             "  }\n"
2690             "  default: {\n"
2691             "    return true;\n"
2692             "  }\n"
2693             "}",
2694             format("switch (n) {\n"
2695                    "  case 0:\n"
2696                    "  {\n"
2697                    "    return false;\n"
2698                    "  }\n"
2699                    "  default:\n"
2700                    "  {\n"
2701                    "    return true;\n"
2702                    "  }\n"
2703                    "}",
2704                    Style));
2705   Style.IndentCaseLabels = false;
2706   Style.IndentCaseBlocks = true;
2707   EXPECT_EQ("switch (n)\n"
2708             "{\n"
2709             "case 0:\n"
2710             "  {\n"
2711             "    return false;\n"
2712             "  }\n"
2713             "case 1:\n"
2714             "  break;\n"
2715             "default:\n"
2716             "  {\n"
2717             "    return true;\n"
2718             "  }\n"
2719             "}",
2720             format("switch (n) {\n"
2721                    "case 0: {\n"
2722                    "  return false;\n"
2723                    "}\n"
2724                    "case 1:\n"
2725                    "  break;\n"
2726                    "default: {\n"
2727                    "  return true;\n"
2728                    "}\n"
2729                    "}",
2730                    Style));
2731   Style.IndentCaseLabels = true;
2732   Style.IndentCaseBlocks = true;
2733   EXPECT_EQ("switch (n)\n"
2734             "{\n"
2735             "  case 0:\n"
2736             "    {\n"
2737             "      return false;\n"
2738             "    }\n"
2739             "  case 1:\n"
2740             "    break;\n"
2741             "  default:\n"
2742             "    {\n"
2743             "      return true;\n"
2744             "    }\n"
2745             "}",
2746             format("switch (n) {\n"
2747                    "case 0: {\n"
2748                    "  return false;\n"
2749                    "}\n"
2750                    "case 1:\n"
2751                    "  break;\n"
2752                    "default: {\n"
2753                    "  return true;\n"
2754                    "}\n"
2755                    "}",
2756                    Style));
2757 }
2758 
2759 TEST_F(FormatTest, CaseRanges) {
2760   verifyFormat("switch (x) {\n"
2761                "case 'A' ... 'Z':\n"
2762                "case 1 ... 5:\n"
2763                "case a ... b:\n"
2764                "  break;\n"
2765                "}");
2766 }
2767 
2768 TEST_F(FormatTest, ShortEnums) {
2769   FormatStyle Style = getLLVMStyle();
2770   Style.AllowShortEnumsOnASingleLine = true;
2771   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2772   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2773   Style.AllowShortEnumsOnASingleLine = false;
2774   verifyFormat("enum {\n"
2775                "  A,\n"
2776                "  B,\n"
2777                "  C\n"
2778                "} ShortEnum1, ShortEnum2;",
2779                Style);
2780   verifyFormat("typedef enum {\n"
2781                "  A,\n"
2782                "  B,\n"
2783                "  C\n"
2784                "} ShortEnum1, ShortEnum2;",
2785                Style);
2786   verifyFormat("enum {\n"
2787                "  A,\n"
2788                "} ShortEnum1, ShortEnum2;",
2789                Style);
2790   verifyFormat("typedef enum {\n"
2791                "  A,\n"
2792                "} ShortEnum1, ShortEnum2;",
2793                Style);
2794   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2795   Style.BraceWrapping.AfterEnum = true;
2796   verifyFormat("enum\n"
2797                "{\n"
2798                "  A,\n"
2799                "  B,\n"
2800                "  C\n"
2801                "} ShortEnum1, ShortEnum2;",
2802                Style);
2803   verifyFormat("typedef enum\n"
2804                "{\n"
2805                "  A,\n"
2806                "  B,\n"
2807                "  C\n"
2808                "} ShortEnum1, ShortEnum2;",
2809                Style);
2810 }
2811 
2812 TEST_F(FormatTest, ShortCaseLabels) {
2813   FormatStyle Style = getLLVMStyle();
2814   Style.AllowShortCaseLabelsOnASingleLine = true;
2815   verifyFormat("switch (a) {\n"
2816                "case 1: x = 1; break;\n"
2817                "case 2: return;\n"
2818                "case 3:\n"
2819                "case 4:\n"
2820                "case 5: return;\n"
2821                "case 6: // comment\n"
2822                "  return;\n"
2823                "case 7:\n"
2824                "  // comment\n"
2825                "  return;\n"
2826                "case 8:\n"
2827                "  x = 8; // comment\n"
2828                "  break;\n"
2829                "default: y = 1; break;\n"
2830                "}",
2831                Style);
2832   verifyFormat("switch (a) {\n"
2833                "case 0: return; // comment\n"
2834                "case 1: break;  // comment\n"
2835                "case 2: return;\n"
2836                "// comment\n"
2837                "case 3: return;\n"
2838                "// comment 1\n"
2839                "// comment 2\n"
2840                "// comment 3\n"
2841                "case 4: break; /* comment */\n"
2842                "case 5:\n"
2843                "  // comment\n"
2844                "  break;\n"
2845                "case 6: /* comment */ x = 1; break;\n"
2846                "case 7: x = /* comment */ 1; break;\n"
2847                "case 8:\n"
2848                "  x = 1; /* comment */\n"
2849                "  break;\n"
2850                "case 9:\n"
2851                "  break; // comment line 1\n"
2852                "         // comment line 2\n"
2853                "}",
2854                Style);
2855   EXPECT_EQ("switch (a) {\n"
2856             "case 1:\n"
2857             "  x = 8;\n"
2858             "  // fall through\n"
2859             "case 2: x = 8;\n"
2860             "// comment\n"
2861             "case 3:\n"
2862             "  return; /* comment line 1\n"
2863             "           * comment line 2 */\n"
2864             "case 4: i = 8;\n"
2865             "// something else\n"
2866             "#if FOO\n"
2867             "case 5: break;\n"
2868             "#endif\n"
2869             "}",
2870             format("switch (a) {\n"
2871                    "case 1: x = 8;\n"
2872                    "  // fall through\n"
2873                    "case 2:\n"
2874                    "  x = 8;\n"
2875                    "// comment\n"
2876                    "case 3:\n"
2877                    "  return; /* comment line 1\n"
2878                    "           * comment line 2 */\n"
2879                    "case 4:\n"
2880                    "  i = 8;\n"
2881                    "// something else\n"
2882                    "#if FOO\n"
2883                    "case 5: break;\n"
2884                    "#endif\n"
2885                    "}",
2886                    Style));
2887   EXPECT_EQ("switch (a) {\n"
2888             "case 0:\n"
2889             "  return; // long long long long long long long long long long "
2890             "long long comment\n"
2891             "          // line\n"
2892             "}",
2893             format("switch (a) {\n"
2894                    "case 0: return; // long long long long long long long long "
2895                    "long long long long comment line\n"
2896                    "}",
2897                    Style));
2898   EXPECT_EQ("switch (a) {\n"
2899             "case 0:\n"
2900             "  return; /* long long long long long long long long long long "
2901             "long long comment\n"
2902             "             line */\n"
2903             "}",
2904             format("switch (a) {\n"
2905                    "case 0: return; /* long long long long long long long long "
2906                    "long long long long comment line */\n"
2907                    "}",
2908                    Style));
2909   verifyFormat("switch (a) {\n"
2910                "#if FOO\n"
2911                "case 0: return 0;\n"
2912                "#endif\n"
2913                "}",
2914                Style);
2915   verifyFormat("switch (a) {\n"
2916                "case 1: {\n"
2917                "}\n"
2918                "case 2: {\n"
2919                "  return;\n"
2920                "}\n"
2921                "case 3: {\n"
2922                "  x = 1;\n"
2923                "  return;\n"
2924                "}\n"
2925                "case 4:\n"
2926                "  if (x)\n"
2927                "    return;\n"
2928                "}",
2929                Style);
2930   Style.ColumnLimit = 21;
2931   verifyFormat("switch (a) {\n"
2932                "case 1: x = 1; break;\n"
2933                "case 2: return;\n"
2934                "case 3:\n"
2935                "case 4:\n"
2936                "case 5: return;\n"
2937                "default:\n"
2938                "  y = 1;\n"
2939                "  break;\n"
2940                "}",
2941                Style);
2942   Style.ColumnLimit = 80;
2943   Style.AllowShortCaseLabelsOnASingleLine = false;
2944   Style.IndentCaseLabels = true;
2945   EXPECT_EQ("switch (n) {\n"
2946             "  default /*comments*/:\n"
2947             "    return true;\n"
2948             "  case 0:\n"
2949             "    return false;\n"
2950             "}",
2951             format("switch (n) {\n"
2952                    "default/*comments*/:\n"
2953                    "  return true;\n"
2954                    "case 0:\n"
2955                    "  return false;\n"
2956                    "}",
2957                    Style));
2958   Style.AllowShortCaseLabelsOnASingleLine = true;
2959   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2960   Style.BraceWrapping.AfterCaseLabel = true;
2961   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2962   EXPECT_EQ("switch (n)\n"
2963             "{\n"
2964             "  case 0:\n"
2965             "  {\n"
2966             "    return false;\n"
2967             "  }\n"
2968             "  default:\n"
2969             "  {\n"
2970             "    return true;\n"
2971             "  }\n"
2972             "}",
2973             format("switch (n) {\n"
2974                    "  case 0: {\n"
2975                    "    return false;\n"
2976                    "  }\n"
2977                    "  default:\n"
2978                    "  {\n"
2979                    "    return true;\n"
2980                    "  }\n"
2981                    "}",
2982                    Style));
2983 }
2984 
2985 TEST_F(FormatTest, FormatsLabels) {
2986   verifyFormat("void f() {\n"
2987                "  some_code();\n"
2988                "test_label:\n"
2989                "  some_other_code();\n"
2990                "  {\n"
2991                "    some_more_code();\n"
2992                "  another_label:\n"
2993                "    some_more_code();\n"
2994                "  }\n"
2995                "}");
2996   verifyFormat("{\n"
2997                "  some_code();\n"
2998                "test_label:\n"
2999                "  some_other_code();\n"
3000                "}");
3001   verifyFormat("{\n"
3002                "  some_code();\n"
3003                "test_label:;\n"
3004                "  int i = 0;\n"
3005                "}");
3006   FormatStyle Style = getLLVMStyle();
3007   Style.IndentGotoLabels = false;
3008   verifyFormat("void f() {\n"
3009                "  some_code();\n"
3010                "test_label:\n"
3011                "  some_other_code();\n"
3012                "  {\n"
3013                "    some_more_code();\n"
3014                "another_label:\n"
3015                "    some_more_code();\n"
3016                "  }\n"
3017                "}",
3018                Style);
3019   verifyFormat("{\n"
3020                "  some_code();\n"
3021                "test_label:\n"
3022                "  some_other_code();\n"
3023                "}",
3024                Style);
3025   verifyFormat("{\n"
3026                "  some_code();\n"
3027                "test_label:;\n"
3028                "  int i = 0;\n"
3029                "}");
3030 }
3031 
3032 TEST_F(FormatTest, MultiLineControlStatements) {
3033   FormatStyle Style = getLLVMStyleWithColumns(20);
3034   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3035   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3036   // Short lines should keep opening brace on same line.
3037   EXPECT_EQ("if (foo) {\n"
3038             "  bar();\n"
3039             "}",
3040             format("if(foo){bar();}", Style));
3041   EXPECT_EQ("if (foo) {\n"
3042             "  bar();\n"
3043             "} else {\n"
3044             "  baz();\n"
3045             "}",
3046             format("if(foo){bar();}else{baz();}", Style));
3047   EXPECT_EQ("if (foo && bar) {\n"
3048             "  baz();\n"
3049             "}",
3050             format("if(foo&&bar){baz();}", Style));
3051   EXPECT_EQ("if (foo) {\n"
3052             "  bar();\n"
3053             "} else if (baz) {\n"
3054             "  quux();\n"
3055             "}",
3056             format("if(foo){bar();}else if(baz){quux();}", Style));
3057   EXPECT_EQ(
3058       "if (foo) {\n"
3059       "  bar();\n"
3060       "} else if (baz) {\n"
3061       "  quux();\n"
3062       "} else {\n"
3063       "  foobar();\n"
3064       "}",
3065       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
3066   EXPECT_EQ("for (;;) {\n"
3067             "  foo();\n"
3068             "}",
3069             format("for(;;){foo();}"));
3070   EXPECT_EQ("while (1) {\n"
3071             "  foo();\n"
3072             "}",
3073             format("while(1){foo();}", Style));
3074   EXPECT_EQ("switch (foo) {\n"
3075             "case bar:\n"
3076             "  return;\n"
3077             "}",
3078             format("switch(foo){case bar:return;}", Style));
3079   EXPECT_EQ("try {\n"
3080             "  foo();\n"
3081             "} catch (...) {\n"
3082             "  bar();\n"
3083             "}",
3084             format("try{foo();}catch(...){bar();}", Style));
3085   EXPECT_EQ("do {\n"
3086             "  foo();\n"
3087             "} while (bar &&\n"
3088             "         baz);",
3089             format("do{foo();}while(bar&&baz);", Style));
3090   // Long lines should put opening brace on new line.
3091   EXPECT_EQ("if (foo && bar &&\n"
3092             "    baz)\n"
3093             "{\n"
3094             "  quux();\n"
3095             "}",
3096             format("if(foo&&bar&&baz){quux();}", Style));
3097   EXPECT_EQ("if (foo && bar &&\n"
3098             "    baz)\n"
3099             "{\n"
3100             "  quux();\n"
3101             "}",
3102             format("if (foo && bar &&\n"
3103                    "    baz) {\n"
3104                    "  quux();\n"
3105                    "}",
3106                    Style));
3107   EXPECT_EQ("if (foo) {\n"
3108             "  bar();\n"
3109             "} else if (baz ||\n"
3110             "           quux)\n"
3111             "{\n"
3112             "  foobar();\n"
3113             "}",
3114             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
3115   EXPECT_EQ(
3116       "if (foo) {\n"
3117       "  bar();\n"
3118       "} else if (baz ||\n"
3119       "           quux)\n"
3120       "{\n"
3121       "  foobar();\n"
3122       "} else {\n"
3123       "  barbaz();\n"
3124       "}",
3125       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3126              Style));
3127   EXPECT_EQ("for (int i = 0;\n"
3128             "     i < 10; ++i)\n"
3129             "{\n"
3130             "  foo();\n"
3131             "}",
3132             format("for(int i=0;i<10;++i){foo();}", Style));
3133   EXPECT_EQ("foreach (int i,\n"
3134             "         list)\n"
3135             "{\n"
3136             "  foo();\n"
3137             "}",
3138             format("foreach(int i, list){foo();}", Style));
3139   Style.ColumnLimit =
3140       40; // to concentrate at brace wrapping, not line wrap due to column limit
3141   EXPECT_EQ("foreach (int i, list) {\n"
3142             "  foo();\n"
3143             "}",
3144             format("foreach(int i, list){foo();}", Style));
3145   Style.ColumnLimit =
3146       20; // to concentrate at brace wrapping, not line wrap due to column limit
3147   EXPECT_EQ("while (foo || bar ||\n"
3148             "       baz)\n"
3149             "{\n"
3150             "  quux();\n"
3151             "}",
3152             format("while(foo||bar||baz){quux();}", Style));
3153   EXPECT_EQ("switch (\n"
3154             "    foo = barbaz)\n"
3155             "{\n"
3156             "case quux:\n"
3157             "  return;\n"
3158             "}",
3159             format("switch(foo=barbaz){case quux:return;}", Style));
3160   EXPECT_EQ("try {\n"
3161             "  foo();\n"
3162             "} catch (\n"
3163             "    Exception &bar)\n"
3164             "{\n"
3165             "  baz();\n"
3166             "}",
3167             format("try{foo();}catch(Exception&bar){baz();}", Style));
3168   Style.ColumnLimit =
3169       40; // to concentrate at brace wrapping, not line wrap due to column limit
3170   EXPECT_EQ("try {\n"
3171             "  foo();\n"
3172             "} catch (Exception &bar) {\n"
3173             "  baz();\n"
3174             "}",
3175             format("try{foo();}catch(Exception&bar){baz();}", Style));
3176   Style.ColumnLimit =
3177       20; // to concentrate at brace wrapping, not line wrap due to column limit
3178 
3179   Style.BraceWrapping.BeforeElse = true;
3180   EXPECT_EQ(
3181       "if (foo) {\n"
3182       "  bar();\n"
3183       "}\n"
3184       "else if (baz ||\n"
3185       "         quux)\n"
3186       "{\n"
3187       "  foobar();\n"
3188       "}\n"
3189       "else {\n"
3190       "  barbaz();\n"
3191       "}",
3192       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3193              Style));
3194 
3195   Style.BraceWrapping.BeforeCatch = true;
3196   EXPECT_EQ("try {\n"
3197             "  foo();\n"
3198             "}\n"
3199             "catch (...) {\n"
3200             "  baz();\n"
3201             "}",
3202             format("try{foo();}catch(...){baz();}", Style));
3203 
3204   Style.BraceWrapping.AfterFunction = true;
3205   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3206   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
3207   Style.ColumnLimit = 80;
3208   verifyFormat("void shortfunction() { bar(); }", Style);
3209 
3210   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
3211   verifyFormat("void shortfunction()\n"
3212                "{\n"
3213                "  bar();\n"
3214                "}",
3215                Style);
3216 }
3217 
3218 TEST_F(FormatTest, BeforeWhile) {
3219   FormatStyle Style = getLLVMStyle();
3220   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3221 
3222   verifyFormat("do {\n"
3223                "  foo();\n"
3224                "} while (1);",
3225                Style);
3226   Style.BraceWrapping.BeforeWhile = true;
3227   verifyFormat("do {\n"
3228                "  foo();\n"
3229                "}\n"
3230                "while (1);",
3231                Style);
3232 }
3233 
3234 //===----------------------------------------------------------------------===//
3235 // Tests for classes, namespaces, etc.
3236 //===----------------------------------------------------------------------===//
3237 
3238 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
3239   verifyFormat("class A {};");
3240 }
3241 
3242 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
3243   verifyFormat("class A {\n"
3244                "public:\n"
3245                "public: // comment\n"
3246                "protected:\n"
3247                "private:\n"
3248                "  void f() {}\n"
3249                "};");
3250   verifyFormat("export class A {\n"
3251                "public:\n"
3252                "public: // comment\n"
3253                "protected:\n"
3254                "private:\n"
3255                "  void f() {}\n"
3256                "};");
3257   verifyGoogleFormat("class A {\n"
3258                      " public:\n"
3259                      " protected:\n"
3260                      " private:\n"
3261                      "  void f() {}\n"
3262                      "};");
3263   verifyGoogleFormat("export class A {\n"
3264                      " public:\n"
3265                      " protected:\n"
3266                      " private:\n"
3267                      "  void f() {}\n"
3268                      "};");
3269   verifyFormat("class A {\n"
3270                "public slots:\n"
3271                "  void f1() {}\n"
3272                "public Q_SLOTS:\n"
3273                "  void f2() {}\n"
3274                "protected slots:\n"
3275                "  void f3() {}\n"
3276                "protected Q_SLOTS:\n"
3277                "  void f4() {}\n"
3278                "private slots:\n"
3279                "  void f5() {}\n"
3280                "private Q_SLOTS:\n"
3281                "  void f6() {}\n"
3282                "signals:\n"
3283                "  void g1();\n"
3284                "Q_SIGNALS:\n"
3285                "  void g2();\n"
3286                "};");
3287 
3288   // Don't interpret 'signals' the wrong way.
3289   verifyFormat("signals.set();");
3290   verifyFormat("for (Signals signals : f()) {\n}");
3291   verifyFormat("{\n"
3292                "  signals.set(); // This needs indentation.\n"
3293                "}");
3294   verifyFormat("void f() {\n"
3295                "label:\n"
3296                "  signals.baz();\n"
3297                "}");
3298   verifyFormat("private[1];");
3299   verifyFormat("testArray[public] = 1;");
3300   verifyFormat("public();");
3301   verifyFormat("myFunc(public);");
3302   verifyFormat("std::vector<int> testVec = {private};");
3303   verifyFormat("private.p = 1;");
3304   verifyFormat("void function(private...){};");
3305   verifyFormat("if (private && public)\n");
3306   verifyFormat("private &= true;");
3307   verifyFormat("int x = private * public;");
3308   verifyFormat("public *= private;");
3309   verifyFormat("int x = public + private;");
3310   verifyFormat("private++;");
3311   verifyFormat("++private;");
3312   verifyFormat("public += private;");
3313   verifyFormat("public = public - private;");
3314   verifyFormat("public->foo();");
3315   verifyFormat("private--;");
3316   verifyFormat("--private;");
3317   verifyFormat("public -= 1;");
3318   verifyFormat("if (!private && !public)\n");
3319   verifyFormat("public != private;");
3320   verifyFormat("int x = public / private;");
3321   verifyFormat("public /= 2;");
3322   verifyFormat("public = public % 2;");
3323   verifyFormat("public %= 2;");
3324   verifyFormat("if (public < private)\n");
3325   verifyFormat("public << private;");
3326   verifyFormat("public <<= private;");
3327   verifyFormat("if (public > private)\n");
3328   verifyFormat("public >> private;");
3329   verifyFormat("public >>= private;");
3330   verifyFormat("public ^ private;");
3331   verifyFormat("public ^= private;");
3332   verifyFormat("public | private;");
3333   verifyFormat("public |= private;");
3334   verifyFormat("auto x = private ? 1 : 2;");
3335   verifyFormat("if (public == private)\n");
3336   verifyFormat("void foo(public, private)");
3337   verifyFormat("public::foo();");
3338 }
3339 
3340 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3341   EXPECT_EQ("class A {\n"
3342             "public:\n"
3343             "  void f();\n"
3344             "\n"
3345             "private:\n"
3346             "  void g() {}\n"
3347             "  // test\n"
3348             "protected:\n"
3349             "  int h;\n"
3350             "};",
3351             format("class A {\n"
3352                    "public:\n"
3353                    "void f();\n"
3354                    "private:\n"
3355                    "void g() {}\n"
3356                    "// test\n"
3357                    "protected:\n"
3358                    "int h;\n"
3359                    "};"));
3360   EXPECT_EQ("class A {\n"
3361             "protected:\n"
3362             "public:\n"
3363             "  void f();\n"
3364             "};",
3365             format("class A {\n"
3366                    "protected:\n"
3367                    "\n"
3368                    "public:\n"
3369                    "\n"
3370                    "  void f();\n"
3371                    "};"));
3372 
3373   // Even ensure proper spacing inside macros.
3374   EXPECT_EQ("#define B     \\\n"
3375             "  class A {   \\\n"
3376             "   protected: \\\n"
3377             "   public:    \\\n"
3378             "    void f(); \\\n"
3379             "  };",
3380             format("#define B     \\\n"
3381                    "  class A {   \\\n"
3382                    "   protected: \\\n"
3383                    "              \\\n"
3384                    "   public:    \\\n"
3385                    "              \\\n"
3386                    "    void f(); \\\n"
3387                    "  };",
3388                    getGoogleStyle()));
3389   // But don't remove empty lines after macros ending in access specifiers.
3390   EXPECT_EQ("#define A private:\n"
3391             "\n"
3392             "int i;",
3393             format("#define A         private:\n"
3394                    "\n"
3395                    "int              i;"));
3396 }
3397 
3398 TEST_F(FormatTest, FormatsClasses) {
3399   verifyFormat("class A : public B {};");
3400   verifyFormat("class A : public ::B {};");
3401 
3402   verifyFormat(
3403       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3404       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3405   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3406                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3407                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3408   verifyFormat(
3409       "class A : public B, public C, public D, public E, public F {};");
3410   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3411                "                     public C,\n"
3412                "                     public D,\n"
3413                "                     public E,\n"
3414                "                     public F,\n"
3415                "                     public G {};");
3416 
3417   verifyFormat("class\n"
3418                "    ReallyReallyLongClassName {\n"
3419                "  int i;\n"
3420                "};",
3421                getLLVMStyleWithColumns(32));
3422   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3423                "                           aaaaaaaaaaaaaaaa> {};");
3424   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3425                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3426                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3427   verifyFormat("template <class R, class C>\n"
3428                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3429                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3430   verifyFormat("class ::A::B {};");
3431 }
3432 
3433 TEST_F(FormatTest, BreakInheritanceStyle) {
3434   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3435   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3436       FormatStyle::BILS_BeforeComma;
3437   verifyFormat("class MyClass : public X {};",
3438                StyleWithInheritanceBreakBeforeComma);
3439   verifyFormat("class MyClass\n"
3440                "    : public X\n"
3441                "    , public Y {};",
3442                StyleWithInheritanceBreakBeforeComma);
3443   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3444                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3445                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3446                StyleWithInheritanceBreakBeforeComma);
3447   verifyFormat("struct aaaaaaaaaaaaa\n"
3448                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3449                "          aaaaaaaaaaaaaaaa> {};",
3450                StyleWithInheritanceBreakBeforeComma);
3451 
3452   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3453   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3454       FormatStyle::BILS_AfterColon;
3455   verifyFormat("class MyClass : public X {};",
3456                StyleWithInheritanceBreakAfterColon);
3457   verifyFormat("class MyClass : public X, public Y {};",
3458                StyleWithInheritanceBreakAfterColon);
3459   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3460                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3461                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3462                StyleWithInheritanceBreakAfterColon);
3463   verifyFormat("struct aaaaaaaaaaaaa :\n"
3464                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3465                "        aaaaaaaaaaaaaaaa> {};",
3466                StyleWithInheritanceBreakAfterColon);
3467 
3468   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3469   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3470       FormatStyle::BILS_AfterComma;
3471   verifyFormat("class MyClass : public X {};",
3472                StyleWithInheritanceBreakAfterComma);
3473   verifyFormat("class MyClass : public X,\n"
3474                "                public Y {};",
3475                StyleWithInheritanceBreakAfterComma);
3476   verifyFormat(
3477       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3478       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3479       "{};",
3480       StyleWithInheritanceBreakAfterComma);
3481   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3482                "                           aaaaaaaaaaaaaaaa> {};",
3483                StyleWithInheritanceBreakAfterComma);
3484   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3485                "    : public OnceBreak,\n"
3486                "      public AlwaysBreak,\n"
3487                "      EvenBasesFitInOneLine {};",
3488                StyleWithInheritanceBreakAfterComma);
3489 }
3490 
3491 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) {
3492   verifyFormat("class A {\n} a, b;");
3493   verifyFormat("struct A {\n} a, b;");
3494   verifyFormat("union A {\n} a, b;");
3495 
3496   verifyFormat("constexpr class A {\n} a, b;");
3497   verifyFormat("constexpr struct A {\n} a, b;");
3498   verifyFormat("constexpr union A {\n} a, b;");
3499 
3500   verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace");
3501   verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace");
3502   verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace");
3503 
3504   verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace");
3505   verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace");
3506   verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace");
3507 
3508   verifyFormat("namespace ns {\n"
3509                "class {\n"
3510                "} a, b;\n"
3511                "} // namespace ns");
3512   verifyFormat("namespace ns {\n"
3513                "const class {\n"
3514                "} a, b;\n"
3515                "} // namespace ns");
3516   verifyFormat("namespace ns {\n"
3517                "constexpr class C {\n"
3518                "} a, b;\n"
3519                "} // namespace ns");
3520   verifyFormat("namespace ns {\n"
3521                "class { /* comment */\n"
3522                "} a, b;\n"
3523                "} // namespace ns");
3524   verifyFormat("namespace ns {\n"
3525                "const class { /* comment */\n"
3526                "} a, b;\n"
3527                "} // namespace ns");
3528 }
3529 
3530 TEST_F(FormatTest, FormatsEnum) {
3531   verifyFormat("enum {\n"
3532                "  Zero,\n"
3533                "  One = 1,\n"
3534                "  Two = One + 1,\n"
3535                "  Three = (One + Two),\n"
3536                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3537                "  Five = (One, Two, Three, Four, 5)\n"
3538                "};");
3539   verifyGoogleFormat("enum {\n"
3540                      "  Zero,\n"
3541                      "  One = 1,\n"
3542                      "  Two = One + 1,\n"
3543                      "  Three = (One + Two),\n"
3544                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3545                      "  Five = (One, Two, Three, Four, 5)\n"
3546                      "};");
3547   verifyFormat("enum Enum {};");
3548   verifyFormat("enum {};");
3549   verifyFormat("enum X E {} d;");
3550   verifyFormat("enum __attribute__((...)) E {} d;");
3551   verifyFormat("enum __declspec__((...)) E {} d;");
3552   verifyFormat("enum {\n"
3553                "  Bar = Foo<int, int>::value\n"
3554                "};",
3555                getLLVMStyleWithColumns(30));
3556 
3557   verifyFormat("enum ShortEnum { A, B, C };");
3558   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3559 
3560   EXPECT_EQ("enum KeepEmptyLines {\n"
3561             "  ONE,\n"
3562             "\n"
3563             "  TWO,\n"
3564             "\n"
3565             "  THREE\n"
3566             "}",
3567             format("enum KeepEmptyLines {\n"
3568                    "  ONE,\n"
3569                    "\n"
3570                    "  TWO,\n"
3571                    "\n"
3572                    "\n"
3573                    "  THREE\n"
3574                    "}"));
3575   verifyFormat("enum E { // comment\n"
3576                "  ONE,\n"
3577                "  TWO\n"
3578                "};\n"
3579                "int i;");
3580 
3581   FormatStyle EightIndent = getLLVMStyle();
3582   EightIndent.IndentWidth = 8;
3583   verifyFormat("enum {\n"
3584                "        VOID,\n"
3585                "        CHAR,\n"
3586                "        SHORT,\n"
3587                "        INT,\n"
3588                "        LONG,\n"
3589                "        SIGNED,\n"
3590                "        UNSIGNED,\n"
3591                "        BOOL,\n"
3592                "        FLOAT,\n"
3593                "        DOUBLE,\n"
3594                "        COMPLEX\n"
3595                "};",
3596                EightIndent);
3597 
3598   // Not enums.
3599   verifyFormat("enum X f() {\n"
3600                "  a();\n"
3601                "  return 42;\n"
3602                "}");
3603   verifyFormat("enum X Type::f() {\n"
3604                "  a();\n"
3605                "  return 42;\n"
3606                "}");
3607   verifyFormat("enum ::X f() {\n"
3608                "  a();\n"
3609                "  return 42;\n"
3610                "}");
3611   verifyFormat("enum ns::X f() {\n"
3612                "  a();\n"
3613                "  return 42;\n"
3614                "}");
3615 }
3616 
3617 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3618   verifyFormat("enum Type {\n"
3619                "  One = 0; // These semicolons should be commas.\n"
3620                "  Two = 1;\n"
3621                "};");
3622   verifyFormat("namespace n {\n"
3623                "enum Type {\n"
3624                "  One,\n"
3625                "  Two, // missing };\n"
3626                "  int i;\n"
3627                "}\n"
3628                "void g() {}");
3629 }
3630 
3631 TEST_F(FormatTest, FormatsEnumStruct) {
3632   verifyFormat("enum struct {\n"
3633                "  Zero,\n"
3634                "  One = 1,\n"
3635                "  Two = One + 1,\n"
3636                "  Three = (One + Two),\n"
3637                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3638                "  Five = (One, Two, Three, Four, 5)\n"
3639                "};");
3640   verifyFormat("enum struct Enum {};");
3641   verifyFormat("enum struct {};");
3642   verifyFormat("enum struct X E {} d;");
3643   verifyFormat("enum struct __attribute__((...)) E {} d;");
3644   verifyFormat("enum struct __declspec__((...)) E {} d;");
3645   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3646 }
3647 
3648 TEST_F(FormatTest, FormatsEnumClass) {
3649   verifyFormat("enum class {\n"
3650                "  Zero,\n"
3651                "  One = 1,\n"
3652                "  Two = One + 1,\n"
3653                "  Three = (One + Two),\n"
3654                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3655                "  Five = (One, Two, Three, Four, 5)\n"
3656                "};");
3657   verifyFormat("enum class Enum {};");
3658   verifyFormat("enum class {};");
3659   verifyFormat("enum class X E {} d;");
3660   verifyFormat("enum class __attribute__((...)) E {} d;");
3661   verifyFormat("enum class __declspec__((...)) E {} d;");
3662   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3663 }
3664 
3665 TEST_F(FormatTest, FormatsEnumTypes) {
3666   verifyFormat("enum X : int {\n"
3667                "  A, // Force multiple lines.\n"
3668                "  B\n"
3669                "};");
3670   verifyFormat("enum X : int { A, B };");
3671   verifyFormat("enum X : std::uint32_t { A, B };");
3672 }
3673 
3674 TEST_F(FormatTest, FormatsTypedefEnum) {
3675   FormatStyle Style = getLLVMStyleWithColumns(40);
3676   verifyFormat("typedef enum {} EmptyEnum;");
3677   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3678   verifyFormat("typedef enum {\n"
3679                "  ZERO = 0,\n"
3680                "  ONE = 1,\n"
3681                "  TWO = 2,\n"
3682                "  THREE = 3\n"
3683                "} LongEnum;",
3684                Style);
3685   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3686   Style.BraceWrapping.AfterEnum = true;
3687   verifyFormat("typedef enum {} EmptyEnum;");
3688   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3689   verifyFormat("typedef enum\n"
3690                "{\n"
3691                "  ZERO = 0,\n"
3692                "  ONE = 1,\n"
3693                "  TWO = 2,\n"
3694                "  THREE = 3\n"
3695                "} LongEnum;",
3696                Style);
3697 }
3698 
3699 TEST_F(FormatTest, FormatsNSEnums) {
3700   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3701   verifyGoogleFormat(
3702       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3703   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3704                      "  // Information about someDecentlyLongValue.\n"
3705                      "  someDecentlyLongValue,\n"
3706                      "  // Information about anotherDecentlyLongValue.\n"
3707                      "  anotherDecentlyLongValue,\n"
3708                      "  // Information about aThirdDecentlyLongValue.\n"
3709                      "  aThirdDecentlyLongValue\n"
3710                      "};");
3711   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3712                      "  // Information about someDecentlyLongValue.\n"
3713                      "  someDecentlyLongValue,\n"
3714                      "  // Information about anotherDecentlyLongValue.\n"
3715                      "  anotherDecentlyLongValue,\n"
3716                      "  // Information about aThirdDecentlyLongValue.\n"
3717                      "  aThirdDecentlyLongValue\n"
3718                      "};");
3719   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3720                      "  a = 1,\n"
3721                      "  b = 2,\n"
3722                      "  c = 3,\n"
3723                      "};");
3724   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3725                      "  a = 1,\n"
3726                      "  b = 2,\n"
3727                      "  c = 3,\n"
3728                      "};");
3729   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3730                      "  a = 1,\n"
3731                      "  b = 2,\n"
3732                      "  c = 3,\n"
3733                      "};");
3734   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3735                      "  a = 1,\n"
3736                      "  b = 2,\n"
3737                      "  c = 3,\n"
3738                      "};");
3739 }
3740 
3741 TEST_F(FormatTest, FormatsBitfields) {
3742   verifyFormat("struct Bitfields {\n"
3743                "  unsigned sClass : 8;\n"
3744                "  unsigned ValueKind : 2;\n"
3745                "};");
3746   verifyFormat("struct A {\n"
3747                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3748                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3749                "};");
3750   verifyFormat("struct MyStruct {\n"
3751                "  uchar data;\n"
3752                "  uchar : 8;\n"
3753                "  uchar : 8;\n"
3754                "  uchar other;\n"
3755                "};");
3756   FormatStyle Style = getLLVMStyle();
3757   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3758   verifyFormat("struct Bitfields {\n"
3759                "  unsigned sClass:8;\n"
3760                "  unsigned ValueKind:2;\n"
3761                "  uchar other;\n"
3762                "};",
3763                Style);
3764   verifyFormat("struct A {\n"
3765                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3766                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3767                "};",
3768                Style);
3769   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3770   verifyFormat("struct Bitfields {\n"
3771                "  unsigned sClass :8;\n"
3772                "  unsigned ValueKind :2;\n"
3773                "  uchar other;\n"
3774                "};",
3775                Style);
3776   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3777   verifyFormat("struct Bitfields {\n"
3778                "  unsigned sClass: 8;\n"
3779                "  unsigned ValueKind: 2;\n"
3780                "  uchar other;\n"
3781                "};",
3782                Style);
3783 }
3784 
3785 TEST_F(FormatTest, FormatsNamespaces) {
3786   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3787   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3788 
3789   verifyFormat("namespace some_namespace {\n"
3790                "class A {};\n"
3791                "void f() { f(); }\n"
3792                "}",
3793                LLVMWithNoNamespaceFix);
3794   verifyFormat("#define M(x) x##x\n"
3795                "namespace M(x) {\n"
3796                "class A {};\n"
3797                "void f() { f(); }\n"
3798                "}",
3799                LLVMWithNoNamespaceFix);
3800   verifyFormat("#define M(x) x##x\n"
3801                "namespace N::inline M(x) {\n"
3802                "class A {};\n"
3803                "void f() { f(); }\n"
3804                "}",
3805                LLVMWithNoNamespaceFix);
3806   verifyFormat("#define M(x) x##x\n"
3807                "namespace M(x)::inline N {\n"
3808                "class A {};\n"
3809                "void f() { f(); }\n"
3810                "}",
3811                LLVMWithNoNamespaceFix);
3812   verifyFormat("#define M(x) x##x\n"
3813                "namespace N::M(x) {\n"
3814                "class A {};\n"
3815                "void f() { f(); }\n"
3816                "}",
3817                LLVMWithNoNamespaceFix);
3818   verifyFormat("#define M(x) x##x\n"
3819                "namespace M::N(x) {\n"
3820                "class A {};\n"
3821                "void f() { f(); }\n"
3822                "}",
3823                LLVMWithNoNamespaceFix);
3824   verifyFormat("namespace N::inline D {\n"
3825                "class A {};\n"
3826                "void f() { f(); }\n"
3827                "}",
3828                LLVMWithNoNamespaceFix);
3829   verifyFormat("namespace N::inline D::E {\n"
3830                "class A {};\n"
3831                "void f() { f(); }\n"
3832                "}",
3833                LLVMWithNoNamespaceFix);
3834   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3835                "class A {};\n"
3836                "void f() { f(); }\n"
3837                "}",
3838                LLVMWithNoNamespaceFix);
3839   verifyFormat("/* something */ namespace some_namespace {\n"
3840                "class A {};\n"
3841                "void f() { f(); }\n"
3842                "}",
3843                LLVMWithNoNamespaceFix);
3844   verifyFormat("namespace {\n"
3845                "class A {};\n"
3846                "void f() { f(); }\n"
3847                "}",
3848                LLVMWithNoNamespaceFix);
3849   verifyFormat("/* something */ namespace {\n"
3850                "class A {};\n"
3851                "void f() { f(); }\n"
3852                "}",
3853                LLVMWithNoNamespaceFix);
3854   verifyFormat("inline namespace X {\n"
3855                "class A {};\n"
3856                "void f() { f(); }\n"
3857                "}",
3858                LLVMWithNoNamespaceFix);
3859   verifyFormat("/* something */ inline namespace X {\n"
3860                "class A {};\n"
3861                "void f() { f(); }\n"
3862                "}",
3863                LLVMWithNoNamespaceFix);
3864   verifyFormat("export namespace X {\n"
3865                "class A {};\n"
3866                "void f() { f(); }\n"
3867                "}",
3868                LLVMWithNoNamespaceFix);
3869   verifyFormat("using namespace some_namespace;\n"
3870                "class A {};\n"
3871                "void f() { f(); }",
3872                LLVMWithNoNamespaceFix);
3873 
3874   // This code is more common than we thought; if we
3875   // layout this correctly the semicolon will go into
3876   // its own line, which is undesirable.
3877   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3878   verifyFormat("namespace {\n"
3879                "class A {};\n"
3880                "};",
3881                LLVMWithNoNamespaceFix);
3882 
3883   verifyFormat("namespace {\n"
3884                "int SomeVariable = 0; // comment\n"
3885                "} // namespace",
3886                LLVMWithNoNamespaceFix);
3887   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3888             "#define HEADER_GUARD\n"
3889             "namespace my_namespace {\n"
3890             "int i;\n"
3891             "} // my_namespace\n"
3892             "#endif // HEADER_GUARD",
3893             format("#ifndef HEADER_GUARD\n"
3894                    " #define HEADER_GUARD\n"
3895                    "   namespace my_namespace {\n"
3896                    "int i;\n"
3897                    "}    // my_namespace\n"
3898                    "#endif    // HEADER_GUARD",
3899                    LLVMWithNoNamespaceFix));
3900 
3901   EXPECT_EQ("namespace A::B {\n"
3902             "class C {};\n"
3903             "}",
3904             format("namespace A::B {\n"
3905                    "class C {};\n"
3906                    "}",
3907                    LLVMWithNoNamespaceFix));
3908 
3909   FormatStyle Style = getLLVMStyle();
3910   Style.NamespaceIndentation = FormatStyle::NI_All;
3911   EXPECT_EQ("namespace out {\n"
3912             "  int i;\n"
3913             "  namespace in {\n"
3914             "    int i;\n"
3915             "  } // namespace in\n"
3916             "} // namespace out",
3917             format("namespace out {\n"
3918                    "int i;\n"
3919                    "namespace in {\n"
3920                    "int i;\n"
3921                    "} // namespace in\n"
3922                    "} // namespace out",
3923                    Style));
3924 
3925   FormatStyle ShortInlineFunctions = getLLVMStyle();
3926   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3927   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3928       FormatStyle::SFS_Inline;
3929   verifyFormat("namespace {\n"
3930                "  void f() {\n"
3931                "    return;\n"
3932                "  }\n"
3933                "} // namespace\n",
3934                ShortInlineFunctions);
3935   verifyFormat("namespace { /* comment */\n"
3936                "  void f() {\n"
3937                "    return;\n"
3938                "  }\n"
3939                "} // namespace\n",
3940                ShortInlineFunctions);
3941   verifyFormat("namespace { // comment\n"
3942                "  void f() {\n"
3943                "    return;\n"
3944                "  }\n"
3945                "} // namespace\n",
3946                ShortInlineFunctions);
3947   verifyFormat("namespace {\n"
3948                "  int some_int;\n"
3949                "  void f() {\n"
3950                "    return;\n"
3951                "  }\n"
3952                "} // namespace\n",
3953                ShortInlineFunctions);
3954   verifyFormat("namespace interface {\n"
3955                "  void f() {\n"
3956                "    return;\n"
3957                "  }\n"
3958                "} // namespace interface\n",
3959                ShortInlineFunctions);
3960   verifyFormat("namespace {\n"
3961                "  class X {\n"
3962                "    void f() { return; }\n"
3963                "  };\n"
3964                "} // namespace\n",
3965                ShortInlineFunctions);
3966   verifyFormat("namespace {\n"
3967                "  class X { /* comment */\n"
3968                "    void f() { return; }\n"
3969                "  };\n"
3970                "} // namespace\n",
3971                ShortInlineFunctions);
3972   verifyFormat("namespace {\n"
3973                "  class X { // comment\n"
3974                "    void f() { return; }\n"
3975                "  };\n"
3976                "} // namespace\n",
3977                ShortInlineFunctions);
3978   verifyFormat("namespace {\n"
3979                "  struct X {\n"
3980                "    void f() { return; }\n"
3981                "  };\n"
3982                "} // namespace\n",
3983                ShortInlineFunctions);
3984   verifyFormat("namespace {\n"
3985                "  union X {\n"
3986                "    void f() { return; }\n"
3987                "  };\n"
3988                "} // namespace\n",
3989                ShortInlineFunctions);
3990   verifyFormat("extern \"C\" {\n"
3991                "void f() {\n"
3992                "  return;\n"
3993                "}\n"
3994                "} // namespace\n",
3995                ShortInlineFunctions);
3996   verifyFormat("namespace {\n"
3997                "  class X {\n"
3998                "    void f() { return; }\n"
3999                "  } x;\n"
4000                "} // namespace\n",
4001                ShortInlineFunctions);
4002   verifyFormat("namespace {\n"
4003                "  [[nodiscard]] class X {\n"
4004                "    void f() { return; }\n"
4005                "  };\n"
4006                "} // namespace\n",
4007                ShortInlineFunctions);
4008   verifyFormat("namespace {\n"
4009                "  static class X {\n"
4010                "    void f() { return; }\n"
4011                "  } x;\n"
4012                "} // namespace\n",
4013                ShortInlineFunctions);
4014   verifyFormat("namespace {\n"
4015                "  constexpr class X {\n"
4016                "    void f() { return; }\n"
4017                "  } x;\n"
4018                "} // namespace\n",
4019                ShortInlineFunctions);
4020 
4021   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
4022   verifyFormat("extern \"C\" {\n"
4023                "  void f() {\n"
4024                "    return;\n"
4025                "  }\n"
4026                "} // namespace\n",
4027                ShortInlineFunctions);
4028 
4029   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4030   EXPECT_EQ("namespace out {\n"
4031             "int i;\n"
4032             "namespace in {\n"
4033             "  int i;\n"
4034             "} // namespace in\n"
4035             "} // namespace out",
4036             format("namespace out {\n"
4037                    "int i;\n"
4038                    "namespace in {\n"
4039                    "int i;\n"
4040                    "} // namespace in\n"
4041                    "} // namespace out",
4042                    Style));
4043 
4044   Style.NamespaceIndentation = FormatStyle::NI_None;
4045   verifyFormat("template <class T>\n"
4046                "concept a_concept = X<>;\n"
4047                "namespace B {\n"
4048                "struct b_struct {};\n"
4049                "} // namespace B\n",
4050                Style);
4051   verifyFormat("template <int I>\n"
4052                "constexpr void foo()\n"
4053                "  requires(I == 42)\n"
4054                "{}\n"
4055                "namespace ns {\n"
4056                "void foo() {}\n"
4057                "} // namespace ns\n",
4058                Style);
4059 }
4060 
4061 TEST_F(FormatTest, NamespaceMacros) {
4062   FormatStyle Style = getLLVMStyle();
4063   Style.NamespaceMacros.push_back("TESTSUITE");
4064 
4065   verifyFormat("TESTSUITE(A) {\n"
4066                "int foo();\n"
4067                "} // TESTSUITE(A)",
4068                Style);
4069 
4070   verifyFormat("TESTSUITE(A, B) {\n"
4071                "int foo();\n"
4072                "} // TESTSUITE(A)",
4073                Style);
4074 
4075   // Properly indent according to NamespaceIndentation style
4076   Style.NamespaceIndentation = FormatStyle::NI_All;
4077   verifyFormat("TESTSUITE(A) {\n"
4078                "  int foo();\n"
4079                "} // TESTSUITE(A)",
4080                Style);
4081   verifyFormat("TESTSUITE(A) {\n"
4082                "  namespace B {\n"
4083                "    int foo();\n"
4084                "  } // namespace B\n"
4085                "} // TESTSUITE(A)",
4086                Style);
4087   verifyFormat("namespace A {\n"
4088                "  TESTSUITE(B) {\n"
4089                "    int foo();\n"
4090                "  } // TESTSUITE(B)\n"
4091                "} // namespace A",
4092                Style);
4093 
4094   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4095   verifyFormat("TESTSUITE(A) {\n"
4096                "TESTSUITE(B) {\n"
4097                "  int foo();\n"
4098                "} // TESTSUITE(B)\n"
4099                "} // TESTSUITE(A)",
4100                Style);
4101   verifyFormat("TESTSUITE(A) {\n"
4102                "namespace B {\n"
4103                "  int foo();\n"
4104                "} // namespace B\n"
4105                "} // TESTSUITE(A)",
4106                Style);
4107   verifyFormat("namespace A {\n"
4108                "TESTSUITE(B) {\n"
4109                "  int foo();\n"
4110                "} // TESTSUITE(B)\n"
4111                "} // namespace A",
4112                Style);
4113 
4114   // Properly merge namespace-macros blocks in CompactNamespaces mode
4115   Style.NamespaceIndentation = FormatStyle::NI_None;
4116   Style.CompactNamespaces = true;
4117   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
4118                "}} // TESTSUITE(A::B)",
4119                Style);
4120 
4121   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4122             "}} // TESTSUITE(out::in)",
4123             format("TESTSUITE(out) {\n"
4124                    "TESTSUITE(in) {\n"
4125                    "} // TESTSUITE(in)\n"
4126                    "} // TESTSUITE(out)",
4127                    Style));
4128 
4129   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4130             "}} // TESTSUITE(out::in)",
4131             format("TESTSUITE(out) {\n"
4132                    "TESTSUITE(in) {\n"
4133                    "} // TESTSUITE(in)\n"
4134                    "} // TESTSUITE(out)",
4135                    Style));
4136 
4137   // Do not merge different namespaces/macros
4138   EXPECT_EQ("namespace out {\n"
4139             "TESTSUITE(in) {\n"
4140             "} // TESTSUITE(in)\n"
4141             "} // namespace out",
4142             format("namespace out {\n"
4143                    "TESTSUITE(in) {\n"
4144                    "} // TESTSUITE(in)\n"
4145                    "} // namespace out",
4146                    Style));
4147   EXPECT_EQ("TESTSUITE(out) {\n"
4148             "namespace in {\n"
4149             "} // namespace in\n"
4150             "} // TESTSUITE(out)",
4151             format("TESTSUITE(out) {\n"
4152                    "namespace in {\n"
4153                    "} // namespace in\n"
4154                    "} // TESTSUITE(out)",
4155                    Style));
4156   Style.NamespaceMacros.push_back("FOOBAR");
4157   EXPECT_EQ("TESTSUITE(out) {\n"
4158             "FOOBAR(in) {\n"
4159             "} // FOOBAR(in)\n"
4160             "} // TESTSUITE(out)",
4161             format("TESTSUITE(out) {\n"
4162                    "FOOBAR(in) {\n"
4163                    "} // FOOBAR(in)\n"
4164                    "} // TESTSUITE(out)",
4165                    Style));
4166 }
4167 
4168 TEST_F(FormatTest, FormatsCompactNamespaces) {
4169   FormatStyle Style = getLLVMStyle();
4170   Style.CompactNamespaces = true;
4171   Style.NamespaceMacros.push_back("TESTSUITE");
4172 
4173   verifyFormat("namespace A { namespace B {\n"
4174                "}} // namespace A::B",
4175                Style);
4176 
4177   EXPECT_EQ("namespace out { namespace in {\n"
4178             "}} // namespace out::in",
4179             format("namespace out {\n"
4180                    "namespace in {\n"
4181                    "} // namespace in\n"
4182                    "} // namespace out",
4183                    Style));
4184 
4185   // Only namespaces which have both consecutive opening and end get compacted
4186   EXPECT_EQ("namespace out {\n"
4187             "namespace in1 {\n"
4188             "} // namespace in1\n"
4189             "namespace in2 {\n"
4190             "} // namespace in2\n"
4191             "} // namespace out",
4192             format("namespace out {\n"
4193                    "namespace in1 {\n"
4194                    "} // namespace in1\n"
4195                    "namespace in2 {\n"
4196                    "} // namespace in2\n"
4197                    "} // namespace out",
4198                    Style));
4199 
4200   EXPECT_EQ("namespace out {\n"
4201             "int i;\n"
4202             "namespace in {\n"
4203             "int j;\n"
4204             "} // namespace in\n"
4205             "int k;\n"
4206             "} // namespace out",
4207             format("namespace out { int i;\n"
4208                    "namespace in { int j; } // namespace in\n"
4209                    "int k; } // namespace out",
4210                    Style));
4211 
4212   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
4213             "}}} // namespace A::B::C\n",
4214             format("namespace A { namespace B {\n"
4215                    "namespace C {\n"
4216                    "}} // namespace B::C\n"
4217                    "} // namespace A\n",
4218                    Style));
4219 
4220   Style.ColumnLimit = 40;
4221   EXPECT_EQ("namespace aaaaaaaaaa {\n"
4222             "namespace bbbbbbbbbb {\n"
4223             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
4224             format("namespace aaaaaaaaaa {\n"
4225                    "namespace bbbbbbbbbb {\n"
4226                    "} // namespace bbbbbbbbbb\n"
4227                    "} // namespace aaaaaaaaaa",
4228                    Style));
4229 
4230   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
4231             "namespace cccccc {\n"
4232             "}}} // namespace aaaaaa::bbbbbb::cccccc",
4233             format("namespace aaaaaa {\n"
4234                    "namespace bbbbbb {\n"
4235                    "namespace cccccc {\n"
4236                    "} // namespace cccccc\n"
4237                    "} // namespace bbbbbb\n"
4238                    "} // namespace aaaaaa",
4239                    Style));
4240   Style.ColumnLimit = 80;
4241 
4242   // Extra semicolon after 'inner' closing brace prevents merging
4243   EXPECT_EQ("namespace out { namespace in {\n"
4244             "}; } // namespace out::in",
4245             format("namespace out {\n"
4246                    "namespace in {\n"
4247                    "}; // namespace in\n"
4248                    "} // namespace out",
4249                    Style));
4250 
4251   // Extra semicolon after 'outer' closing brace is conserved
4252   EXPECT_EQ("namespace out { namespace in {\n"
4253             "}}; // namespace out::in",
4254             format("namespace out {\n"
4255                    "namespace in {\n"
4256                    "} // namespace in\n"
4257                    "}; // namespace out",
4258                    Style));
4259 
4260   Style.NamespaceIndentation = FormatStyle::NI_All;
4261   EXPECT_EQ("namespace out { namespace in {\n"
4262             "  int i;\n"
4263             "}} // namespace out::in",
4264             format("namespace out {\n"
4265                    "namespace in {\n"
4266                    "int i;\n"
4267                    "} // namespace in\n"
4268                    "} // namespace out",
4269                    Style));
4270   EXPECT_EQ("namespace out { namespace mid {\n"
4271             "  namespace in {\n"
4272             "    int j;\n"
4273             "  } // namespace in\n"
4274             "  int k;\n"
4275             "}} // namespace out::mid",
4276             format("namespace out { namespace mid {\n"
4277                    "namespace in { int j; } // namespace in\n"
4278                    "int k; }} // namespace out::mid",
4279                    Style));
4280 
4281   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4282   EXPECT_EQ("namespace out { namespace in {\n"
4283             "  int i;\n"
4284             "}} // namespace out::in",
4285             format("namespace out {\n"
4286                    "namespace in {\n"
4287                    "int i;\n"
4288                    "} // namespace in\n"
4289                    "} // namespace out",
4290                    Style));
4291   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
4292             "  int i;\n"
4293             "}}} // namespace out::mid::in",
4294             format("namespace out {\n"
4295                    "namespace mid {\n"
4296                    "namespace in {\n"
4297                    "int i;\n"
4298                    "} // namespace in\n"
4299                    "} // namespace mid\n"
4300                    "} // namespace out",
4301                    Style));
4302 
4303   Style.CompactNamespaces = true;
4304   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
4305   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4306   Style.BraceWrapping.BeforeLambdaBody = true;
4307   verifyFormat("namespace out { namespace in {\n"
4308                "}} // namespace out::in",
4309                Style);
4310   EXPECT_EQ("namespace out { namespace in {\n"
4311             "}} // namespace out::in",
4312             format("namespace out {\n"
4313                    "namespace in {\n"
4314                    "} // namespace in\n"
4315                    "} // namespace out",
4316                    Style));
4317 }
4318 
4319 TEST_F(FormatTest, FormatsExternC) {
4320   verifyFormat("extern \"C\" {\nint a;");
4321   verifyFormat("extern \"C\" {}");
4322   verifyFormat("extern \"C\" {\n"
4323                "int foo();\n"
4324                "}");
4325   verifyFormat("extern \"C\" int foo() {}");
4326   verifyFormat("extern \"C\" int foo();");
4327   verifyFormat("extern \"C\" int foo() {\n"
4328                "  int i = 42;\n"
4329                "  return i;\n"
4330                "}");
4331 
4332   FormatStyle Style = getLLVMStyle();
4333   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4334   Style.BraceWrapping.AfterFunction = true;
4335   verifyFormat("extern \"C\" int foo() {}", Style);
4336   verifyFormat("extern \"C\" int foo();", Style);
4337   verifyFormat("extern \"C\" int foo()\n"
4338                "{\n"
4339                "  int i = 42;\n"
4340                "  return i;\n"
4341                "}",
4342                Style);
4343 
4344   Style.BraceWrapping.AfterExternBlock = true;
4345   Style.BraceWrapping.SplitEmptyRecord = false;
4346   verifyFormat("extern \"C\"\n"
4347                "{}",
4348                Style);
4349   verifyFormat("extern \"C\"\n"
4350                "{\n"
4351                "  int foo();\n"
4352                "}",
4353                Style);
4354 }
4355 
4356 TEST_F(FormatTest, IndentExternBlockStyle) {
4357   FormatStyle Style = getLLVMStyle();
4358   Style.IndentWidth = 2;
4359 
4360   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4361   verifyFormat("extern \"C\" { /*9*/\n"
4362                "}",
4363                Style);
4364   verifyFormat("extern \"C\" {\n"
4365                "  int foo10();\n"
4366                "}",
4367                Style);
4368 
4369   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4370   verifyFormat("extern \"C\" { /*11*/\n"
4371                "}",
4372                Style);
4373   verifyFormat("extern \"C\" {\n"
4374                "int foo12();\n"
4375                "}",
4376                Style);
4377 
4378   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4379   Style.BraceWrapping.AfterExternBlock = true;
4380   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4381   verifyFormat("extern \"C\"\n"
4382                "{ /*13*/\n"
4383                "}",
4384                Style);
4385   verifyFormat("extern \"C\"\n{\n"
4386                "  int foo14();\n"
4387                "}",
4388                Style);
4389 
4390   Style.BraceWrapping.AfterExternBlock = false;
4391   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4392   verifyFormat("extern \"C\" { /*15*/\n"
4393                "}",
4394                Style);
4395   verifyFormat("extern \"C\" {\n"
4396                "int foo16();\n"
4397                "}",
4398                Style);
4399 
4400   Style.BraceWrapping.AfterExternBlock = true;
4401   verifyFormat("extern \"C\"\n"
4402                "{ /*13*/\n"
4403                "}",
4404                Style);
4405   verifyFormat("extern \"C\"\n"
4406                "{\n"
4407                "int foo14();\n"
4408                "}",
4409                Style);
4410 
4411   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4412   verifyFormat("extern \"C\"\n"
4413                "{ /*13*/\n"
4414                "}",
4415                Style);
4416   verifyFormat("extern \"C\"\n"
4417                "{\n"
4418                "  int foo14();\n"
4419                "}",
4420                Style);
4421 }
4422 
4423 TEST_F(FormatTest, FormatsInlineASM) {
4424   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4425   verifyFormat("asm(\"nop\" ::: \"memory\");");
4426   verifyFormat(
4427       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4428       "    \"cpuid\\n\\t\"\n"
4429       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4430       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4431       "    : \"a\"(value));");
4432   EXPECT_EQ(
4433       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4434       "  __asm {\n"
4435       "        mov     edx,[that] // vtable in edx\n"
4436       "        mov     eax,methodIndex\n"
4437       "        call    [edx][eax*4] // stdcall\n"
4438       "  }\n"
4439       "}",
4440       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4441              "    __asm {\n"
4442              "        mov     edx,[that] // vtable in edx\n"
4443              "        mov     eax,methodIndex\n"
4444              "        call    [edx][eax*4] // stdcall\n"
4445              "    }\n"
4446              "}"));
4447   EXPECT_EQ("_asm {\n"
4448             "  xor eax, eax;\n"
4449             "  cpuid;\n"
4450             "}",
4451             format("_asm {\n"
4452                    "  xor eax, eax;\n"
4453                    "  cpuid;\n"
4454                    "}"));
4455   verifyFormat("void function() {\n"
4456                "  // comment\n"
4457                "  asm(\"\");\n"
4458                "}");
4459   EXPECT_EQ("__asm {\n"
4460             "}\n"
4461             "int i;",
4462             format("__asm   {\n"
4463                    "}\n"
4464                    "int   i;"));
4465 }
4466 
4467 TEST_F(FormatTest, FormatTryCatch) {
4468   verifyFormat("try {\n"
4469                "  throw a * b;\n"
4470                "} catch (int a) {\n"
4471                "  // Do nothing.\n"
4472                "} catch (...) {\n"
4473                "  exit(42);\n"
4474                "}");
4475 
4476   // Function-level try statements.
4477   verifyFormat("int f() try { return 4; } catch (...) {\n"
4478                "  return 5;\n"
4479                "}");
4480   verifyFormat("class A {\n"
4481                "  int a;\n"
4482                "  A() try : a(0) {\n"
4483                "  } catch (...) {\n"
4484                "    throw;\n"
4485                "  }\n"
4486                "};\n");
4487   verifyFormat("class A {\n"
4488                "  int a;\n"
4489                "  A() try : a(0), b{1} {\n"
4490                "  } catch (...) {\n"
4491                "    throw;\n"
4492                "  }\n"
4493                "};\n");
4494   verifyFormat("class A {\n"
4495                "  int a;\n"
4496                "  A() try : a(0), b{1}, c{2} {\n"
4497                "  } catch (...) {\n"
4498                "    throw;\n"
4499                "  }\n"
4500                "};\n");
4501   verifyFormat("class A {\n"
4502                "  int a;\n"
4503                "  A() try : a(0), b{1}, c{2} {\n"
4504                "    { // New scope.\n"
4505                "    }\n"
4506                "  } catch (...) {\n"
4507                "    throw;\n"
4508                "  }\n"
4509                "};\n");
4510 
4511   // Incomplete try-catch blocks.
4512   verifyIncompleteFormat("try {} catch (");
4513 }
4514 
4515 TEST_F(FormatTest, FormatTryAsAVariable) {
4516   verifyFormat("int try;");
4517   verifyFormat("int try, size;");
4518   verifyFormat("try = foo();");
4519   verifyFormat("if (try < size) {\n  return true;\n}");
4520 
4521   verifyFormat("int catch;");
4522   verifyFormat("int catch, size;");
4523   verifyFormat("catch = foo();");
4524   verifyFormat("if (catch < size) {\n  return true;\n}");
4525 
4526   FormatStyle Style = getLLVMStyle();
4527   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4528   Style.BraceWrapping.AfterFunction = true;
4529   Style.BraceWrapping.BeforeCatch = true;
4530   verifyFormat("try {\n"
4531                "  int bar = 1;\n"
4532                "}\n"
4533                "catch (...) {\n"
4534                "  int bar = 1;\n"
4535                "}",
4536                Style);
4537   verifyFormat("#if NO_EX\n"
4538                "try\n"
4539                "#endif\n"
4540                "{\n"
4541                "}\n"
4542                "#if NO_EX\n"
4543                "catch (...) {\n"
4544                "}",
4545                Style);
4546   verifyFormat("try /* abc */ {\n"
4547                "  int bar = 1;\n"
4548                "}\n"
4549                "catch (...) {\n"
4550                "  int bar = 1;\n"
4551                "}",
4552                Style);
4553   verifyFormat("try\n"
4554                "// abc\n"
4555                "{\n"
4556                "  int bar = 1;\n"
4557                "}\n"
4558                "catch (...) {\n"
4559                "  int bar = 1;\n"
4560                "}",
4561                Style);
4562 }
4563 
4564 TEST_F(FormatTest, FormatSEHTryCatch) {
4565   verifyFormat("__try {\n"
4566                "  int a = b * c;\n"
4567                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4568                "  // Do nothing.\n"
4569                "}");
4570 
4571   verifyFormat("__try {\n"
4572                "  int a = b * c;\n"
4573                "} __finally {\n"
4574                "  // Do nothing.\n"
4575                "}");
4576 
4577   verifyFormat("DEBUG({\n"
4578                "  __try {\n"
4579                "  } __finally {\n"
4580                "  }\n"
4581                "});\n");
4582 }
4583 
4584 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4585   verifyFormat("try {\n"
4586                "  f();\n"
4587                "} catch {\n"
4588                "  g();\n"
4589                "}");
4590   verifyFormat("try {\n"
4591                "  f();\n"
4592                "} catch (A a) MACRO(x) {\n"
4593                "  g();\n"
4594                "} catch (B b) MACRO(x) {\n"
4595                "  g();\n"
4596                "}");
4597 }
4598 
4599 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4600   FormatStyle Style = getLLVMStyle();
4601   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4602                           FormatStyle::BS_WebKit}) {
4603     Style.BreakBeforeBraces = BraceStyle;
4604     verifyFormat("try {\n"
4605                  "  // something\n"
4606                  "} catch (...) {\n"
4607                  "  // something\n"
4608                  "}",
4609                  Style);
4610   }
4611   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4612   verifyFormat("try {\n"
4613                "  // something\n"
4614                "}\n"
4615                "catch (...) {\n"
4616                "  // something\n"
4617                "}",
4618                Style);
4619   verifyFormat("__try {\n"
4620                "  // something\n"
4621                "}\n"
4622                "__finally {\n"
4623                "  // something\n"
4624                "}",
4625                Style);
4626   verifyFormat("@try {\n"
4627                "  // something\n"
4628                "}\n"
4629                "@finally {\n"
4630                "  // something\n"
4631                "}",
4632                Style);
4633   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4634   verifyFormat("try\n"
4635                "{\n"
4636                "  // something\n"
4637                "}\n"
4638                "catch (...)\n"
4639                "{\n"
4640                "  // something\n"
4641                "}",
4642                Style);
4643   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4644   verifyFormat("try\n"
4645                "  {\n"
4646                "  // something white\n"
4647                "  }\n"
4648                "catch (...)\n"
4649                "  {\n"
4650                "  // something white\n"
4651                "  }",
4652                Style);
4653   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4654   verifyFormat("try\n"
4655                "  {\n"
4656                "    // something\n"
4657                "  }\n"
4658                "catch (...)\n"
4659                "  {\n"
4660                "    // something\n"
4661                "  }",
4662                Style);
4663   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4664   Style.BraceWrapping.BeforeCatch = true;
4665   verifyFormat("try {\n"
4666                "  // something\n"
4667                "}\n"
4668                "catch (...) {\n"
4669                "  // something\n"
4670                "}",
4671                Style);
4672 }
4673 
4674 TEST_F(FormatTest, StaticInitializers) {
4675   verifyFormat("static SomeClass SC = {1, 'a'};");
4676 
4677   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4678                "    100000000, "
4679                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4680 
4681   // Here, everything other than the "}" would fit on a line.
4682   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4683                "    10000000000000000000000000};");
4684   EXPECT_EQ("S s = {a,\n"
4685             "\n"
4686             "       b};",
4687             format("S s = {\n"
4688                    "  a,\n"
4689                    "\n"
4690                    "  b\n"
4691                    "};"));
4692 
4693   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4694   // line. However, the formatting looks a bit off and this probably doesn't
4695   // happen often in practice.
4696   verifyFormat("static int Variable[1] = {\n"
4697                "    {1000000000000000000000000000000000000}};",
4698                getLLVMStyleWithColumns(40));
4699 }
4700 
4701 TEST_F(FormatTest, DesignatedInitializers) {
4702   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4703   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4704                "                    .bbbbbbbbbb = 2,\n"
4705                "                    .cccccccccc = 3,\n"
4706                "                    .dddddddddd = 4,\n"
4707                "                    .eeeeeeeeee = 5};");
4708   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4709                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4710                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4711                "    .ccccccccccccccccccccccccccc = 3,\n"
4712                "    .ddddddddddddddddddddddddddd = 4,\n"
4713                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4714 
4715   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4716 
4717   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4718   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4719                "                    [2] = bbbbbbbbbb,\n"
4720                "                    [3] = cccccccccc,\n"
4721                "                    [4] = dddddddddd,\n"
4722                "                    [5] = eeeeeeeeee};");
4723   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4724                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4725                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4726                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4727                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4728                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4729 }
4730 
4731 TEST_F(FormatTest, NestedStaticInitializers) {
4732   verifyFormat("static A x = {{{}}};\n");
4733   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4734                "               {init1, init2, init3, init4}}};",
4735                getLLVMStyleWithColumns(50));
4736 
4737   verifyFormat("somes Status::global_reps[3] = {\n"
4738                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4739                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4740                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4741                getLLVMStyleWithColumns(60));
4742   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4743                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4744                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4745                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4746   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4747                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4748                "rect.fTop}};");
4749 
4750   verifyFormat(
4751       "SomeArrayOfSomeType a = {\n"
4752       "    {{1, 2, 3},\n"
4753       "     {1, 2, 3},\n"
4754       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4755       "      333333333333333333333333333333},\n"
4756       "     {1, 2, 3},\n"
4757       "     {1, 2, 3}}};");
4758   verifyFormat(
4759       "SomeArrayOfSomeType a = {\n"
4760       "    {{1, 2, 3}},\n"
4761       "    {{1, 2, 3}},\n"
4762       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4763       "      333333333333333333333333333333}},\n"
4764       "    {{1, 2, 3}},\n"
4765       "    {{1, 2, 3}}};");
4766 
4767   verifyFormat("struct {\n"
4768                "  unsigned bit;\n"
4769                "  const char *const name;\n"
4770                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4771                "                 {kOsWin, \"Windows\"},\n"
4772                "                 {kOsLinux, \"Linux\"},\n"
4773                "                 {kOsCrOS, \"Chrome OS\"}};");
4774   verifyFormat("struct {\n"
4775                "  unsigned bit;\n"
4776                "  const char *const name;\n"
4777                "} kBitsToOs[] = {\n"
4778                "    {kOsMac, \"Mac\"},\n"
4779                "    {kOsWin, \"Windows\"},\n"
4780                "    {kOsLinux, \"Linux\"},\n"
4781                "    {kOsCrOS, \"Chrome OS\"},\n"
4782                "};");
4783 }
4784 
4785 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4786   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4787                "                      \\\n"
4788                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4789 }
4790 
4791 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4792   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4793                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4794 
4795   // Do break defaulted and deleted functions.
4796   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4797                "    default;",
4798                getLLVMStyleWithColumns(40));
4799   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4800                "    delete;",
4801                getLLVMStyleWithColumns(40));
4802 }
4803 
4804 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4805   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4806                getLLVMStyleWithColumns(40));
4807   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4808                getLLVMStyleWithColumns(40));
4809   EXPECT_EQ("#define Q                              \\\n"
4810             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4811             "  \"aaaaaaaa.cpp\"",
4812             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4813                    getLLVMStyleWithColumns(40)));
4814 }
4815 
4816 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4817   EXPECT_EQ("# 123 \"A string literal\"",
4818             format("   #     123    \"A string literal\""));
4819 }
4820 
4821 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4822   EXPECT_EQ("#;", format("#;"));
4823   verifyFormat("#\n;\n;\n;");
4824 }
4825 
4826 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4827   EXPECT_EQ("#line 42 \"test\"\n",
4828             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4829   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4830                                     getLLVMStyleWithColumns(12)));
4831 }
4832 
4833 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4834   EXPECT_EQ("#line 42 \"test\"",
4835             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4836   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4837 }
4838 
4839 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4840   verifyFormat("#define A \\x20");
4841   verifyFormat("#define A \\ x20");
4842   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4843   verifyFormat("#define A ''");
4844   verifyFormat("#define A ''qqq");
4845   verifyFormat("#define A `qqq");
4846   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4847   EXPECT_EQ("const char *c = STRINGIFY(\n"
4848             "\\na : b);",
4849             format("const char * c = STRINGIFY(\n"
4850                    "\\na : b);"));
4851 
4852   verifyFormat("a\r\\");
4853   verifyFormat("a\v\\");
4854   verifyFormat("a\f\\");
4855 }
4856 
4857 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4858   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4859   style.IndentWidth = 4;
4860   style.PPIndentWidth = 1;
4861 
4862   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4863   verifyFormat("#ifdef __linux__\n"
4864                "void foo() {\n"
4865                "    int x = 0;\n"
4866                "}\n"
4867                "#define FOO\n"
4868                "#endif\n"
4869                "void bar() {\n"
4870                "    int y = 0;\n"
4871                "}\n",
4872                style);
4873 
4874   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4875   verifyFormat("#ifdef __linux__\n"
4876                "void foo() {\n"
4877                "    int x = 0;\n"
4878                "}\n"
4879                "# define FOO foo\n"
4880                "#endif\n"
4881                "void bar() {\n"
4882                "    int y = 0;\n"
4883                "}\n",
4884                style);
4885 
4886   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4887   verifyFormat("#ifdef __linux__\n"
4888                "void foo() {\n"
4889                "    int x = 0;\n"
4890                "}\n"
4891                " #define FOO foo\n"
4892                "#endif\n"
4893                "void bar() {\n"
4894                "    int y = 0;\n"
4895                "}\n",
4896                style);
4897 }
4898 
4899 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4900   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4901   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4902   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4903   // FIXME: We never break before the macro name.
4904   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4905 
4906   verifyFormat("#define A A\n#define A A");
4907   verifyFormat("#define A(X) A\n#define A A");
4908 
4909   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4910   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4911 }
4912 
4913 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4914   EXPECT_EQ("// somecomment\n"
4915             "#include \"a.h\"\n"
4916             "#define A(  \\\n"
4917             "    A, B)\n"
4918             "#include \"b.h\"\n"
4919             "// somecomment\n",
4920             format("  // somecomment\n"
4921                    "  #include \"a.h\"\n"
4922                    "#define A(A,\\\n"
4923                    "    B)\n"
4924                    "    #include \"b.h\"\n"
4925                    " // somecomment\n",
4926                    getLLVMStyleWithColumns(13)));
4927 }
4928 
4929 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4930 
4931 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4932   EXPECT_EQ("#define A    \\\n"
4933             "  c;         \\\n"
4934             "  e;\n"
4935             "f;",
4936             format("#define A c; e;\n"
4937                    "f;",
4938                    getLLVMStyleWithColumns(14)));
4939 }
4940 
4941 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4942 
4943 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4944   EXPECT_EQ("int x,\n"
4945             "#define A\n"
4946             "    y;",
4947             format("int x,\n#define A\ny;"));
4948 }
4949 
4950 TEST_F(FormatTest, HashInMacroDefinition) {
4951   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4952   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4953   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4954   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4955   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4956   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4957   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4958   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4959   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4960   verifyFormat("#define A  \\\n"
4961                "  {        \\\n"
4962                "    f(#c); \\\n"
4963                "  }",
4964                getLLVMStyleWithColumns(11));
4965 
4966   verifyFormat("#define A(X)         \\\n"
4967                "  void function##X()",
4968                getLLVMStyleWithColumns(22));
4969 
4970   verifyFormat("#define A(a, b, c)   \\\n"
4971                "  void a##b##c()",
4972                getLLVMStyleWithColumns(22));
4973 
4974   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4975 }
4976 
4977 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4978   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4979   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4980 
4981   FormatStyle Style = getLLVMStyle();
4982   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4983   verifyFormat("#define true ((foo)1)", Style);
4984   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4985   verifyFormat("#define false((foo)0)", Style);
4986 }
4987 
4988 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4989   EXPECT_EQ("#define A b;", format("#define A \\\n"
4990                                    "          \\\n"
4991                                    "  b;",
4992                                    getLLVMStyleWithColumns(25)));
4993   EXPECT_EQ("#define A \\\n"
4994             "          \\\n"
4995             "  a;      \\\n"
4996             "  b;",
4997             format("#define A \\\n"
4998                    "          \\\n"
4999                    "  a;      \\\n"
5000                    "  b;",
5001                    getLLVMStyleWithColumns(11)));
5002   EXPECT_EQ("#define A \\\n"
5003             "  a;      \\\n"
5004             "          \\\n"
5005             "  b;",
5006             format("#define A \\\n"
5007                    "  a;      \\\n"
5008                    "          \\\n"
5009                    "  b;",
5010                    getLLVMStyleWithColumns(11)));
5011 }
5012 
5013 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
5014   verifyIncompleteFormat("#define A :");
5015   verifyFormat("#define SOMECASES  \\\n"
5016                "  case 1:          \\\n"
5017                "  case 2\n",
5018                getLLVMStyleWithColumns(20));
5019   verifyFormat("#define MACRO(a) \\\n"
5020                "  if (a)         \\\n"
5021                "    f();         \\\n"
5022                "  else           \\\n"
5023                "    g()",
5024                getLLVMStyleWithColumns(18));
5025   verifyFormat("#define A template <typename T>");
5026   verifyIncompleteFormat("#define STR(x) #x\n"
5027                          "f(STR(this_is_a_string_literal{));");
5028   verifyFormat("#pragma omp threadprivate( \\\n"
5029                "    y)), // expected-warning",
5030                getLLVMStyleWithColumns(28));
5031   verifyFormat("#d, = };");
5032   verifyFormat("#if \"a");
5033   verifyIncompleteFormat("({\n"
5034                          "#define b     \\\n"
5035                          "  }           \\\n"
5036                          "  a\n"
5037                          "a",
5038                          getLLVMStyleWithColumns(15));
5039   verifyFormat("#define A     \\\n"
5040                "  {           \\\n"
5041                "    {\n"
5042                "#define B     \\\n"
5043                "  }           \\\n"
5044                "  }",
5045                getLLVMStyleWithColumns(15));
5046   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
5047   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
5048   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
5049   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
5050 }
5051 
5052 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
5053   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
5054   EXPECT_EQ("class A : public QObject {\n"
5055             "  Q_OBJECT\n"
5056             "\n"
5057             "  A() {}\n"
5058             "};",
5059             format("class A  :  public QObject {\n"
5060                    "     Q_OBJECT\n"
5061                    "\n"
5062                    "  A() {\n}\n"
5063                    "}  ;"));
5064   EXPECT_EQ("MACRO\n"
5065             "/*static*/ int i;",
5066             format("MACRO\n"
5067                    " /*static*/ int   i;"));
5068   EXPECT_EQ("SOME_MACRO\n"
5069             "namespace {\n"
5070             "void f();\n"
5071             "} // namespace",
5072             format("SOME_MACRO\n"
5073                    "  namespace    {\n"
5074                    "void   f(  );\n"
5075                    "} // namespace"));
5076   // Only if the identifier contains at least 5 characters.
5077   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
5078   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
5079   // Only if everything is upper case.
5080   EXPECT_EQ("class A : public QObject {\n"
5081             "  Q_Object A() {}\n"
5082             "};",
5083             format("class A  :  public QObject {\n"
5084                    "     Q_Object\n"
5085                    "  A() {\n}\n"
5086                    "}  ;"));
5087 
5088   // Only if the next line can actually start an unwrapped line.
5089   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
5090             format("SOME_WEIRD_LOG_MACRO\n"
5091                    "<< SomeThing;"));
5092 
5093   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
5094                "(n, buffers))\n",
5095                getChromiumStyle(FormatStyle::LK_Cpp));
5096 
5097   // See PR41483
5098   EXPECT_EQ("/**/ FOO(a)\n"
5099             "FOO(b)",
5100             format("/**/ FOO(a)\n"
5101                    "FOO(b)"));
5102 }
5103 
5104 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
5105   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5106             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5107             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5108             "class X {};\n"
5109             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5110             "int *createScopDetectionPass() { return 0; }",
5111             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5112                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5113                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5114                    "  class X {};\n"
5115                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5116                    "  int *createScopDetectionPass() { return 0; }"));
5117   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
5118   // braces, so that inner block is indented one level more.
5119   EXPECT_EQ("int q() {\n"
5120             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5121             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5122             "  IPC_END_MESSAGE_MAP()\n"
5123             "}",
5124             format("int q() {\n"
5125                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5126                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5127                    "  IPC_END_MESSAGE_MAP()\n"
5128                    "}"));
5129 
5130   // Same inside macros.
5131   EXPECT_EQ("#define LIST(L) \\\n"
5132             "  L(A)          \\\n"
5133             "  L(B)          \\\n"
5134             "  L(C)",
5135             format("#define LIST(L) \\\n"
5136                    "  L(A) \\\n"
5137                    "  L(B) \\\n"
5138                    "  L(C)",
5139                    getGoogleStyle()));
5140 
5141   // These must not be recognized as macros.
5142   EXPECT_EQ("int q() {\n"
5143             "  f(x);\n"
5144             "  f(x) {}\n"
5145             "  f(x)->g();\n"
5146             "  f(x)->*g();\n"
5147             "  f(x).g();\n"
5148             "  f(x) = x;\n"
5149             "  f(x) += x;\n"
5150             "  f(x) -= x;\n"
5151             "  f(x) *= x;\n"
5152             "  f(x) /= x;\n"
5153             "  f(x) %= x;\n"
5154             "  f(x) &= x;\n"
5155             "  f(x) |= x;\n"
5156             "  f(x) ^= x;\n"
5157             "  f(x) >>= x;\n"
5158             "  f(x) <<= x;\n"
5159             "  f(x)[y].z();\n"
5160             "  LOG(INFO) << x;\n"
5161             "  ifstream(x) >> x;\n"
5162             "}\n",
5163             format("int q() {\n"
5164                    "  f(x)\n;\n"
5165                    "  f(x)\n {}\n"
5166                    "  f(x)\n->g();\n"
5167                    "  f(x)\n->*g();\n"
5168                    "  f(x)\n.g();\n"
5169                    "  f(x)\n = x;\n"
5170                    "  f(x)\n += x;\n"
5171                    "  f(x)\n -= x;\n"
5172                    "  f(x)\n *= x;\n"
5173                    "  f(x)\n /= x;\n"
5174                    "  f(x)\n %= x;\n"
5175                    "  f(x)\n &= x;\n"
5176                    "  f(x)\n |= x;\n"
5177                    "  f(x)\n ^= x;\n"
5178                    "  f(x)\n >>= x;\n"
5179                    "  f(x)\n <<= x;\n"
5180                    "  f(x)\n[y].z();\n"
5181                    "  LOG(INFO)\n << x;\n"
5182                    "  ifstream(x)\n >> x;\n"
5183                    "}\n"));
5184   EXPECT_EQ("int q() {\n"
5185             "  F(x)\n"
5186             "  if (1) {\n"
5187             "  }\n"
5188             "  F(x)\n"
5189             "  while (1) {\n"
5190             "  }\n"
5191             "  F(x)\n"
5192             "  G(x);\n"
5193             "  F(x)\n"
5194             "  try {\n"
5195             "    Q();\n"
5196             "  } catch (...) {\n"
5197             "  }\n"
5198             "}\n",
5199             format("int q() {\n"
5200                    "F(x)\n"
5201                    "if (1) {}\n"
5202                    "F(x)\n"
5203                    "while (1) {}\n"
5204                    "F(x)\n"
5205                    "G(x);\n"
5206                    "F(x)\n"
5207                    "try { Q(); } catch (...) {}\n"
5208                    "}\n"));
5209   EXPECT_EQ("class A {\n"
5210             "  A() : t(0) {}\n"
5211             "  A(int i) noexcept() : {}\n"
5212             "  A(X x)\n" // FIXME: function-level try blocks are broken.
5213             "  try : t(0) {\n"
5214             "  } catch (...) {\n"
5215             "  }\n"
5216             "};",
5217             format("class A {\n"
5218                    "  A()\n : t(0) {}\n"
5219                    "  A(int i)\n noexcept() : {}\n"
5220                    "  A(X x)\n"
5221                    "  try : t(0) {} catch (...) {}\n"
5222                    "};"));
5223   FormatStyle Style = getLLVMStyle();
5224   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5225   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5226   Style.BraceWrapping.AfterFunction = true;
5227   EXPECT_EQ("void f()\n"
5228             "try\n"
5229             "{\n"
5230             "}",
5231             format("void f() try {\n"
5232                    "}",
5233                    Style));
5234   EXPECT_EQ("class SomeClass {\n"
5235             "public:\n"
5236             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5237             "};",
5238             format("class SomeClass {\n"
5239                    "public:\n"
5240                    "  SomeClass()\n"
5241                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5242                    "};"));
5243   EXPECT_EQ("class SomeClass {\n"
5244             "public:\n"
5245             "  SomeClass()\n"
5246             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5247             "};",
5248             format("class SomeClass {\n"
5249                    "public:\n"
5250                    "  SomeClass()\n"
5251                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5252                    "};",
5253                    getLLVMStyleWithColumns(40)));
5254 
5255   verifyFormat("MACRO(>)");
5256 
5257   // Some macros contain an implicit semicolon.
5258   Style = getLLVMStyle();
5259   Style.StatementMacros.push_back("FOO");
5260   verifyFormat("FOO(a) int b = 0;");
5261   verifyFormat("FOO(a)\n"
5262                "int b = 0;",
5263                Style);
5264   verifyFormat("FOO(a);\n"
5265                "int b = 0;",
5266                Style);
5267   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
5268                "int b = 0;",
5269                Style);
5270   verifyFormat("FOO()\n"
5271                "int b = 0;",
5272                Style);
5273   verifyFormat("FOO\n"
5274                "int b = 0;",
5275                Style);
5276   verifyFormat("void f() {\n"
5277                "  FOO(a)\n"
5278                "  return a;\n"
5279                "}",
5280                Style);
5281   verifyFormat("FOO(a)\n"
5282                "FOO(b)",
5283                Style);
5284   verifyFormat("int a = 0;\n"
5285                "FOO(b)\n"
5286                "int c = 0;",
5287                Style);
5288   verifyFormat("int a = 0;\n"
5289                "int x = FOO(a)\n"
5290                "int b = 0;",
5291                Style);
5292   verifyFormat("void foo(int a) { FOO(a) }\n"
5293                "uint32_t bar() {}",
5294                Style);
5295 }
5296 
5297 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
5298   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
5299 
5300   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
5301                ZeroColumn);
5302 }
5303 
5304 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5305   verifyFormat("#define A \\\n"
5306                "  f({     \\\n"
5307                "    g();  \\\n"
5308                "  });",
5309                getLLVMStyleWithColumns(11));
5310 }
5311 
5312 TEST_F(FormatTest, IndentPreprocessorDirectives) {
5313   FormatStyle Style = getLLVMStyleWithColumns(40);
5314   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
5315   verifyFormat("#ifdef _WIN32\n"
5316                "#define A 0\n"
5317                "#ifdef VAR2\n"
5318                "#define B 1\n"
5319                "#include <someheader.h>\n"
5320                "#define MACRO                          \\\n"
5321                "  some_very_long_func_aaaaaaaaaa();\n"
5322                "#endif\n"
5323                "#else\n"
5324                "#define A 1\n"
5325                "#endif",
5326                Style);
5327   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
5328   verifyFormat("#ifdef _WIN32\n"
5329                "#  define A 0\n"
5330                "#  ifdef VAR2\n"
5331                "#    define B 1\n"
5332                "#    include <someheader.h>\n"
5333                "#    define MACRO                      \\\n"
5334                "      some_very_long_func_aaaaaaaaaa();\n"
5335                "#  endif\n"
5336                "#else\n"
5337                "#  define A 1\n"
5338                "#endif",
5339                Style);
5340   verifyFormat("#if A\n"
5341                "#  define MACRO                        \\\n"
5342                "    void a(int x) {                    \\\n"
5343                "      b();                             \\\n"
5344                "      c();                             \\\n"
5345                "      d();                             \\\n"
5346                "      e();                             \\\n"
5347                "      f();                             \\\n"
5348                "    }\n"
5349                "#endif",
5350                Style);
5351   // Comments before include guard.
5352   verifyFormat("// file comment\n"
5353                "// file comment\n"
5354                "#ifndef HEADER_H\n"
5355                "#define HEADER_H\n"
5356                "code();\n"
5357                "#endif",
5358                Style);
5359   // Test with include guards.
5360   verifyFormat("#ifndef HEADER_H\n"
5361                "#define HEADER_H\n"
5362                "code();\n"
5363                "#endif",
5364                Style);
5365   // Include guards must have a #define with the same variable immediately
5366   // after #ifndef.
5367   verifyFormat("#ifndef NOT_GUARD\n"
5368                "#  define FOO\n"
5369                "code();\n"
5370                "#endif",
5371                Style);
5372 
5373   // Include guards must cover the entire file.
5374   verifyFormat("code();\n"
5375                "code();\n"
5376                "#ifndef NOT_GUARD\n"
5377                "#  define NOT_GUARD\n"
5378                "code();\n"
5379                "#endif",
5380                Style);
5381   verifyFormat("#ifndef NOT_GUARD\n"
5382                "#  define NOT_GUARD\n"
5383                "code();\n"
5384                "#endif\n"
5385                "code();",
5386                Style);
5387   // Test with trailing blank lines.
5388   verifyFormat("#ifndef HEADER_H\n"
5389                "#define HEADER_H\n"
5390                "code();\n"
5391                "#endif\n",
5392                Style);
5393   // Include guards don't have #else.
5394   verifyFormat("#ifndef NOT_GUARD\n"
5395                "#  define NOT_GUARD\n"
5396                "code();\n"
5397                "#else\n"
5398                "#endif",
5399                Style);
5400   verifyFormat("#ifndef NOT_GUARD\n"
5401                "#  define NOT_GUARD\n"
5402                "code();\n"
5403                "#elif FOO\n"
5404                "#endif",
5405                Style);
5406   // Non-identifier #define after potential include guard.
5407   verifyFormat("#ifndef FOO\n"
5408                "#  define 1\n"
5409                "#endif\n",
5410                Style);
5411   // #if closes past last non-preprocessor line.
5412   verifyFormat("#ifndef FOO\n"
5413                "#define FOO\n"
5414                "#if 1\n"
5415                "int i;\n"
5416                "#  define A 0\n"
5417                "#endif\n"
5418                "#endif\n",
5419                Style);
5420   // Don't crash if there is an #elif directive without a condition.
5421   verifyFormat("#if 1\n"
5422                "int x;\n"
5423                "#elif\n"
5424                "int y;\n"
5425                "#else\n"
5426                "int z;\n"
5427                "#endif",
5428                Style);
5429   // FIXME: This doesn't handle the case where there's code between the
5430   // #ifndef and #define but all other conditions hold. This is because when
5431   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5432   // previous code line yet, so we can't detect it.
5433   EXPECT_EQ("#ifndef NOT_GUARD\n"
5434             "code();\n"
5435             "#define NOT_GUARD\n"
5436             "code();\n"
5437             "#endif",
5438             format("#ifndef NOT_GUARD\n"
5439                    "code();\n"
5440                    "#  define NOT_GUARD\n"
5441                    "code();\n"
5442                    "#endif",
5443                    Style));
5444   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5445   // be outside an include guard. Examples are #pragma once and
5446   // #pragma GCC diagnostic, or anything else that does not change the meaning
5447   // of the file if it's included multiple times.
5448   EXPECT_EQ("#ifdef WIN32\n"
5449             "#  pragma once\n"
5450             "#endif\n"
5451             "#ifndef HEADER_H\n"
5452             "#  define HEADER_H\n"
5453             "code();\n"
5454             "#endif",
5455             format("#ifdef WIN32\n"
5456                    "#  pragma once\n"
5457                    "#endif\n"
5458                    "#ifndef HEADER_H\n"
5459                    "#define HEADER_H\n"
5460                    "code();\n"
5461                    "#endif",
5462                    Style));
5463   // FIXME: This does not detect when there is a single non-preprocessor line
5464   // in front of an include-guard-like structure where other conditions hold
5465   // because ScopedLineState hides the line.
5466   EXPECT_EQ("code();\n"
5467             "#ifndef HEADER_H\n"
5468             "#define HEADER_H\n"
5469             "code();\n"
5470             "#endif",
5471             format("code();\n"
5472                    "#ifndef HEADER_H\n"
5473                    "#  define HEADER_H\n"
5474                    "code();\n"
5475                    "#endif",
5476                    Style));
5477   // Keep comments aligned with #, otherwise indent comments normally. These
5478   // tests cannot use verifyFormat because messUp manipulates leading
5479   // whitespace.
5480   {
5481     const char *Expected = ""
5482                            "void f() {\n"
5483                            "#if 1\n"
5484                            "// Preprocessor aligned.\n"
5485                            "#  define A 0\n"
5486                            "  // Code. Separated by blank line.\n"
5487                            "\n"
5488                            "#  define B 0\n"
5489                            "  // Code. Not aligned with #\n"
5490                            "#  define C 0\n"
5491                            "#endif";
5492     const char *ToFormat = ""
5493                            "void f() {\n"
5494                            "#if 1\n"
5495                            "// Preprocessor aligned.\n"
5496                            "#  define A 0\n"
5497                            "// Code. Separated by blank line.\n"
5498                            "\n"
5499                            "#  define B 0\n"
5500                            "   // Code. Not aligned with #\n"
5501                            "#  define C 0\n"
5502                            "#endif";
5503     EXPECT_EQ(Expected, format(ToFormat, Style));
5504     EXPECT_EQ(Expected, format(Expected, Style));
5505   }
5506   // Keep block quotes aligned.
5507   {
5508     const char *Expected = ""
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     const char *ToFormat = ""
5520                            "void f() {\n"
5521                            "#if 1\n"
5522                            "/* Preprocessor aligned. */\n"
5523                            "#  define A 0\n"
5524                            "/* Code. Separated by blank line. */\n"
5525                            "\n"
5526                            "#  define B 0\n"
5527                            "   /* Code. Not aligned with # */\n"
5528                            "#  define C 0\n"
5529                            "#endif";
5530     EXPECT_EQ(Expected, format(ToFormat, Style));
5531     EXPECT_EQ(Expected, format(Expected, Style));
5532   }
5533   // Keep comments aligned with un-indented directives.
5534   {
5535     const char *Expected = ""
5536                            "void f() {\n"
5537                            "// Preprocessor aligned.\n"
5538                            "#define A 0\n"
5539                            "  // Code. Separated by blank line.\n"
5540                            "\n"
5541                            "#define B 0\n"
5542                            "  // Code. Not aligned with #\n"
5543                            "#define C 0\n";
5544     const char *ToFormat = ""
5545                            "void f() {\n"
5546                            "// Preprocessor aligned.\n"
5547                            "#define A 0\n"
5548                            "// Code. Separated by blank line.\n"
5549                            "\n"
5550                            "#define B 0\n"
5551                            "   // Code. Not aligned with #\n"
5552                            "#define C 0\n";
5553     EXPECT_EQ(Expected, format(ToFormat, Style));
5554     EXPECT_EQ(Expected, format(Expected, Style));
5555   }
5556   // Test AfterHash with tabs.
5557   {
5558     FormatStyle Tabbed = Style;
5559     Tabbed.UseTab = FormatStyle::UT_Always;
5560     Tabbed.IndentWidth = 8;
5561     Tabbed.TabWidth = 8;
5562     verifyFormat("#ifdef _WIN32\n"
5563                  "#\tdefine A 0\n"
5564                  "#\tifdef VAR2\n"
5565                  "#\t\tdefine B 1\n"
5566                  "#\t\tinclude <someheader.h>\n"
5567                  "#\t\tdefine MACRO          \\\n"
5568                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5569                  "#\tendif\n"
5570                  "#else\n"
5571                  "#\tdefine A 1\n"
5572                  "#endif",
5573                  Tabbed);
5574   }
5575 
5576   // Regression test: Multiline-macro inside include guards.
5577   verifyFormat("#ifndef HEADER_H\n"
5578                "#define HEADER_H\n"
5579                "#define A()        \\\n"
5580                "  int i;           \\\n"
5581                "  int j;\n"
5582                "#endif // HEADER_H",
5583                getLLVMStyleWithColumns(20));
5584 
5585   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5586   // Basic before hash indent tests
5587   verifyFormat("#ifdef _WIN32\n"
5588                "  #define A 0\n"
5589                "  #ifdef VAR2\n"
5590                "    #define B 1\n"
5591                "    #include <someheader.h>\n"
5592                "    #define MACRO                      \\\n"
5593                "      some_very_long_func_aaaaaaaaaa();\n"
5594                "  #endif\n"
5595                "#else\n"
5596                "  #define A 1\n"
5597                "#endif",
5598                Style);
5599   verifyFormat("#if A\n"
5600                "  #define MACRO                        \\\n"
5601                "    void a(int x) {                    \\\n"
5602                "      b();                             \\\n"
5603                "      c();                             \\\n"
5604                "      d();                             \\\n"
5605                "      e();                             \\\n"
5606                "      f();                             \\\n"
5607                "    }\n"
5608                "#endif",
5609                Style);
5610   // Keep comments aligned with indented directives. These
5611   // tests cannot use verifyFormat because messUp manipulates leading
5612   // whitespace.
5613   {
5614     const char *Expected = "void f() {\n"
5615                            "// Aligned to preprocessor.\n"
5616                            "#if 1\n"
5617                            "  // Aligned to code.\n"
5618                            "  int a;\n"
5619                            "  #if 1\n"
5620                            "    // Aligned to preprocessor.\n"
5621                            "    #define A 0\n"
5622                            "  // Aligned to code.\n"
5623                            "  int b;\n"
5624                            "  #endif\n"
5625                            "#endif\n"
5626                            "}";
5627     const char *ToFormat = "void f() {\n"
5628                            "// Aligned to preprocessor.\n"
5629                            "#if 1\n"
5630                            "// Aligned to code.\n"
5631                            "int a;\n"
5632                            "#if 1\n"
5633                            "// Aligned to preprocessor.\n"
5634                            "#define A 0\n"
5635                            "// Aligned to code.\n"
5636                            "int b;\n"
5637                            "#endif\n"
5638                            "#endif\n"
5639                            "}";
5640     EXPECT_EQ(Expected, format(ToFormat, Style));
5641     EXPECT_EQ(Expected, format(Expected, Style));
5642   }
5643   {
5644     const char *Expected = "void f() {\n"
5645                            "/* Aligned to preprocessor. */\n"
5646                            "#if 1\n"
5647                            "  /* Aligned to code. */\n"
5648                            "  int a;\n"
5649                            "  #if 1\n"
5650                            "    /* Aligned to preprocessor. */\n"
5651                            "    #define A 0\n"
5652                            "  /* Aligned to code. */\n"
5653                            "  int b;\n"
5654                            "  #endif\n"
5655                            "#endif\n"
5656                            "}";
5657     const char *ToFormat = "void f() {\n"
5658                            "/* Aligned to preprocessor. */\n"
5659                            "#if 1\n"
5660                            "/* Aligned to code. */\n"
5661                            "int a;\n"
5662                            "#if 1\n"
5663                            "/* Aligned to preprocessor. */\n"
5664                            "#define A 0\n"
5665                            "/* Aligned to code. */\n"
5666                            "int b;\n"
5667                            "#endif\n"
5668                            "#endif\n"
5669                            "}";
5670     EXPECT_EQ(Expected, format(ToFormat, Style));
5671     EXPECT_EQ(Expected, format(Expected, Style));
5672   }
5673 
5674   // Test single comment before preprocessor
5675   verifyFormat("// Comment\n"
5676                "\n"
5677                "#if 1\n"
5678                "#endif",
5679                Style);
5680 }
5681 
5682 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5683   verifyFormat("{\n  { a #c; }\n}");
5684 }
5685 
5686 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5687   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5688             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5689   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5690             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5691 }
5692 
5693 TEST_F(FormatTest, EscapedNewlines) {
5694   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5695   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5696             format("#define A \\\nint i;\\\n  int j;", Narrow));
5697   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5698   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5699   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5700   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5701 
5702   FormatStyle AlignLeft = getLLVMStyle();
5703   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5704   EXPECT_EQ("#define MACRO(x) \\\n"
5705             "private:         \\\n"
5706             "  int x(int a);\n",
5707             format("#define MACRO(x) \\\n"
5708                    "private:         \\\n"
5709                    "  int x(int a);\n",
5710                    AlignLeft));
5711 
5712   // CRLF line endings
5713   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5714             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5715   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5716   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5717   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5718   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5719   EXPECT_EQ("#define MACRO(x) \\\r\n"
5720             "private:         \\\r\n"
5721             "  int x(int a);\r\n",
5722             format("#define MACRO(x) \\\r\n"
5723                    "private:         \\\r\n"
5724                    "  int x(int a);\r\n",
5725                    AlignLeft));
5726 
5727   FormatStyle DontAlign = getLLVMStyle();
5728   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5729   DontAlign.MaxEmptyLinesToKeep = 3;
5730   // FIXME: can't use verifyFormat here because the newline before
5731   // "public:" is not inserted the first time it's reformatted
5732   EXPECT_EQ("#define A \\\n"
5733             "  class Foo { \\\n"
5734             "    void bar(); \\\n"
5735             "\\\n"
5736             "\\\n"
5737             "\\\n"
5738             "  public: \\\n"
5739             "    void baz(); \\\n"
5740             "  };",
5741             format("#define A \\\n"
5742                    "  class Foo { \\\n"
5743                    "    void bar(); \\\n"
5744                    "\\\n"
5745                    "\\\n"
5746                    "\\\n"
5747                    "  public: \\\n"
5748                    "    void baz(); \\\n"
5749                    "  };",
5750                    DontAlign));
5751 }
5752 
5753 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5754   verifyFormat("#define A \\\n"
5755                "  int v(  \\\n"
5756                "      a); \\\n"
5757                "  int i;",
5758                getLLVMStyleWithColumns(11));
5759 }
5760 
5761 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5762   EXPECT_EQ(
5763       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5764       "                      \\\n"
5765       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5766       "\n"
5767       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5768       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5769       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5770              "\\\n"
5771              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5772              "  \n"
5773              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5774              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5775 }
5776 
5777 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5778   EXPECT_EQ("int\n"
5779             "#define A\n"
5780             "    a;",
5781             format("int\n#define A\na;"));
5782   verifyFormat("functionCallTo(\n"
5783                "    someOtherFunction(\n"
5784                "        withSomeParameters, whichInSequence,\n"
5785                "        areLongerThanALine(andAnotherCall,\n"
5786                "#define A B\n"
5787                "                           withMoreParamters,\n"
5788                "                           whichStronglyInfluenceTheLayout),\n"
5789                "        andMoreParameters),\n"
5790                "    trailing);",
5791                getLLVMStyleWithColumns(69));
5792   verifyFormat("Foo::Foo()\n"
5793                "#ifdef BAR\n"
5794                "    : baz(0)\n"
5795                "#endif\n"
5796                "{\n"
5797                "}");
5798   verifyFormat("void f() {\n"
5799                "  if (true)\n"
5800                "#ifdef A\n"
5801                "    f(42);\n"
5802                "  x();\n"
5803                "#else\n"
5804                "    g();\n"
5805                "  x();\n"
5806                "#endif\n"
5807                "}");
5808   verifyFormat("void f(param1, param2,\n"
5809                "       param3,\n"
5810                "#ifdef A\n"
5811                "       param4(param5,\n"
5812                "#ifdef A1\n"
5813                "              param6,\n"
5814                "#ifdef A2\n"
5815                "              param7),\n"
5816                "#else\n"
5817                "              param8),\n"
5818                "       param9,\n"
5819                "#endif\n"
5820                "       param10,\n"
5821                "#endif\n"
5822                "       param11)\n"
5823                "#else\n"
5824                "       param12)\n"
5825                "#endif\n"
5826                "{\n"
5827                "  x();\n"
5828                "}",
5829                getLLVMStyleWithColumns(28));
5830   verifyFormat("#if 1\n"
5831                "int i;");
5832   verifyFormat("#if 1\n"
5833                "#endif\n"
5834                "#if 1\n"
5835                "#else\n"
5836                "#endif\n");
5837   verifyFormat("DEBUG({\n"
5838                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5839                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5840                "});\n"
5841                "#if a\n"
5842                "#else\n"
5843                "#endif");
5844 
5845   verifyIncompleteFormat("void f(\n"
5846                          "#if A\n"
5847                          ");\n"
5848                          "#else\n"
5849                          "#endif");
5850 }
5851 
5852 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5853   verifyFormat("#endif\n"
5854                "#if B");
5855 }
5856 
5857 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5858   FormatStyle SingleLine = getLLVMStyle();
5859   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5860   verifyFormat("#if 0\n"
5861                "#elif 1\n"
5862                "#endif\n"
5863                "void foo() {\n"
5864                "  if (test) foo2();\n"
5865                "}",
5866                SingleLine);
5867 }
5868 
5869 TEST_F(FormatTest, LayoutBlockInsideParens) {
5870   verifyFormat("functionCall({ int i; });");
5871   verifyFormat("functionCall({\n"
5872                "  int i;\n"
5873                "  int j;\n"
5874                "});");
5875   verifyFormat("functionCall(\n"
5876                "    {\n"
5877                "      int i;\n"
5878                "      int j;\n"
5879                "    },\n"
5880                "    aaaa, bbbb, cccc);");
5881   verifyFormat("functionA(functionB({\n"
5882                "            int i;\n"
5883                "            int j;\n"
5884                "          }),\n"
5885                "          aaaa, bbbb, cccc);");
5886   verifyFormat("functionCall(\n"
5887                "    {\n"
5888                "      int i;\n"
5889                "      int j;\n"
5890                "    },\n"
5891                "    aaaa, bbbb, // comment\n"
5892                "    cccc);");
5893   verifyFormat("functionA(functionB({\n"
5894                "            int i;\n"
5895                "            int j;\n"
5896                "          }),\n"
5897                "          aaaa, bbbb, // comment\n"
5898                "          cccc);");
5899   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5900   verifyFormat("functionCall(aaaa, bbbb, {\n"
5901                "  int i;\n"
5902                "  int j;\n"
5903                "});");
5904   verifyFormat(
5905       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5906       "    {\n"
5907       "      int i; // break\n"
5908       "    },\n"
5909       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5910       "                                     ccccccccccccccccc));");
5911   verifyFormat("DEBUG({\n"
5912                "  if (a)\n"
5913                "    f();\n"
5914                "});");
5915 }
5916 
5917 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5918   EXPECT_EQ("SOME_MACRO { int i; }\n"
5919             "int i;",
5920             format("  SOME_MACRO  {int i;}  int i;"));
5921 }
5922 
5923 TEST_F(FormatTest, LayoutNestedBlocks) {
5924   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5925                "  struct s {\n"
5926                "    int i;\n"
5927                "  };\n"
5928                "  s kBitsToOs[] = {{10}};\n"
5929                "  for (int i = 0; i < 10; ++i)\n"
5930                "    return;\n"
5931                "}");
5932   verifyFormat("call(parameter, {\n"
5933                "  something();\n"
5934                "  // Comment using all columns.\n"
5935                "  somethingelse();\n"
5936                "});",
5937                getLLVMStyleWithColumns(40));
5938   verifyFormat("DEBUG( //\n"
5939                "    { f(); }, a);");
5940   verifyFormat("DEBUG( //\n"
5941                "    {\n"
5942                "      f(); //\n"
5943                "    },\n"
5944                "    a);");
5945 
5946   EXPECT_EQ("call(parameter, {\n"
5947             "  something();\n"
5948             "  // Comment too\n"
5949             "  // looooooooooong.\n"
5950             "  somethingElse();\n"
5951             "});",
5952             format("call(parameter, {\n"
5953                    "  something();\n"
5954                    "  // Comment too looooooooooong.\n"
5955                    "  somethingElse();\n"
5956                    "});",
5957                    getLLVMStyleWithColumns(29)));
5958   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5959   EXPECT_EQ("DEBUG({ // comment\n"
5960             "  int i;\n"
5961             "});",
5962             format("DEBUG({ // comment\n"
5963                    "int  i;\n"
5964                    "});"));
5965   EXPECT_EQ("DEBUG({\n"
5966             "  int i;\n"
5967             "\n"
5968             "  // comment\n"
5969             "  int j;\n"
5970             "});",
5971             format("DEBUG({\n"
5972                    "  int  i;\n"
5973                    "\n"
5974                    "  // comment\n"
5975                    "  int  j;\n"
5976                    "});"));
5977 
5978   verifyFormat("DEBUG({\n"
5979                "  if (a)\n"
5980                "    return;\n"
5981                "});");
5982   verifyGoogleFormat("DEBUG({\n"
5983                      "  if (a) return;\n"
5984                      "});");
5985   FormatStyle Style = getGoogleStyle();
5986   Style.ColumnLimit = 45;
5987   verifyFormat("Debug(\n"
5988                "    aaaaa,\n"
5989                "    {\n"
5990                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5991                "    },\n"
5992                "    a);",
5993                Style);
5994 
5995   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5996 
5997   verifyNoCrash("^{v^{a}}");
5998 }
5999 
6000 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
6001   EXPECT_EQ("#define MACRO()                     \\\n"
6002             "  Debug(aaa, /* force line break */ \\\n"
6003             "        {                           \\\n"
6004             "          int i;                    \\\n"
6005             "          int j;                    \\\n"
6006             "        })",
6007             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
6008                    "          {  int   i;  int  j;   })",
6009                    getGoogleStyle()));
6010 
6011   EXPECT_EQ("#define A                                       \\\n"
6012             "  [] {                                          \\\n"
6013             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
6014             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
6015             "  }",
6016             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
6017                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
6018                    getGoogleStyle()));
6019 }
6020 
6021 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
6022   EXPECT_EQ("{}", format("{}"));
6023   verifyFormat("enum E {};");
6024   verifyFormat("enum E {}");
6025   FormatStyle Style = getLLVMStyle();
6026   Style.SpaceInEmptyBlock = true;
6027   EXPECT_EQ("void f() { }", format("void f() {}", Style));
6028   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
6029   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
6030   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
6031   Style.BraceWrapping.BeforeElse = false;
6032   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
6033   verifyFormat("if (a)\n"
6034                "{\n"
6035                "} else if (b)\n"
6036                "{\n"
6037                "} else\n"
6038                "{ }",
6039                Style);
6040   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
6041   verifyFormat("if (a) {\n"
6042                "} else if (b) {\n"
6043                "} else {\n"
6044                "}",
6045                Style);
6046   Style.BraceWrapping.BeforeElse = true;
6047   verifyFormat("if (a) { }\n"
6048                "else if (b) { }\n"
6049                "else { }",
6050                Style);
6051 }
6052 
6053 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
6054   FormatStyle Style = getLLVMStyle();
6055   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
6056   Style.MacroBlockEnd = "^[A-Z_]+_END$";
6057   verifyFormat("FOO_BEGIN\n"
6058                "  FOO_ENTRY\n"
6059                "FOO_END",
6060                Style);
6061   verifyFormat("FOO_BEGIN\n"
6062                "  NESTED_FOO_BEGIN\n"
6063                "    NESTED_FOO_ENTRY\n"
6064                "  NESTED_FOO_END\n"
6065                "FOO_END",
6066                Style);
6067   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
6068                "  int x;\n"
6069                "  x = 1;\n"
6070                "FOO_END(Baz)",
6071                Style);
6072 }
6073 
6074 //===----------------------------------------------------------------------===//
6075 // Line break tests.
6076 //===----------------------------------------------------------------------===//
6077 
6078 TEST_F(FormatTest, PreventConfusingIndents) {
6079   verifyFormat(
6080       "void f() {\n"
6081       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
6082       "                         parameter, parameter, parameter)),\n"
6083       "                     SecondLongCall(parameter));\n"
6084       "}");
6085   verifyFormat(
6086       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6087       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6088       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6089       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
6090   verifyFormat(
6091       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6092       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
6093       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6094       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
6095   verifyFormat(
6096       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
6097       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
6098       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
6099       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
6100   verifyFormat("int a = bbbb && ccc &&\n"
6101                "        fffff(\n"
6102                "#define A Just forcing a new line\n"
6103                "            ddd);");
6104 }
6105 
6106 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
6107   verifyFormat(
6108       "bool aaaaaaa =\n"
6109       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
6110       "    bbbbbbbb();");
6111   verifyFormat(
6112       "bool aaaaaaa =\n"
6113       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
6114       "    bbbbbbbb();");
6115 
6116   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6117                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
6118                "    ccccccccc == ddddddddddd;");
6119   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6120                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
6121                "    ccccccccc == ddddddddddd;");
6122   verifyFormat(
6123       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6124       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
6125       "    ccccccccc == ddddddddddd;");
6126 
6127   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6128                "                 aaaaaa) &&\n"
6129                "         bbbbbb && cccccc;");
6130   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6131                "                 aaaaaa) >>\n"
6132                "         bbbbbb;");
6133   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
6134                "    SourceMgr.getSpellingColumnNumber(\n"
6135                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
6136                "    1);");
6137 
6138   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6139                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
6140                "    cccccc) {\n}");
6141   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6142                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6143                "              cccccc) {\n}");
6144   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6145                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6146                "              cccccc) {\n}");
6147   verifyFormat("b = a &&\n"
6148                "    // Comment\n"
6149                "    b.c && d;");
6150 
6151   // If the LHS of a comparison is not a binary expression itself, the
6152   // additional linebreak confuses many people.
6153   verifyFormat(
6154       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6155       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
6156       "}");
6157   verifyFormat(
6158       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6159       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6160       "}");
6161   verifyFormat(
6162       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
6163       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6164       "}");
6165   verifyFormat(
6166       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6167       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
6168       "}");
6169   // Even explicit parentheses stress the precedence enough to make the
6170   // additional break unnecessary.
6171   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6172                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6173                "}");
6174   // This cases is borderline, but with the indentation it is still readable.
6175   verifyFormat(
6176       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6177       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6178       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
6179       "}",
6180       getLLVMStyleWithColumns(75));
6181 
6182   // If the LHS is a binary expression, we should still use the additional break
6183   // as otherwise the formatting hides the operator precedence.
6184   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6185                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6186                "    5) {\n"
6187                "}");
6188   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6189                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
6190                "    5) {\n"
6191                "}");
6192 
6193   FormatStyle OnePerLine = getLLVMStyle();
6194   OnePerLine.BinPackParameters = false;
6195   verifyFormat(
6196       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6197       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6198       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
6199       OnePerLine);
6200 
6201   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
6202                "                .aaa(aaaaaaaaaaaaa) *\n"
6203                "            aaaaaaa +\n"
6204                "        aaaaaaa;",
6205                getLLVMStyleWithColumns(40));
6206 }
6207 
6208 TEST_F(FormatTest, ExpressionIndentation) {
6209   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6210                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6211                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6212                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6213                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6214                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
6215                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6216                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
6217                "                 ccccccccccccccccccccccccccccccccccccccccc;");
6218   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6219                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6220                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6221                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6222   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6223                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6224                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6225                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6226   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6227                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6228                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6229                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6230   verifyFormat("if () {\n"
6231                "} else if (aaaaa && bbbbb > // break\n"
6232                "                        ccccc) {\n"
6233                "}");
6234   verifyFormat("if () {\n"
6235                "} else if constexpr (aaaaa && bbbbb > // break\n"
6236                "                                  ccccc) {\n"
6237                "}");
6238   verifyFormat("if () {\n"
6239                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
6240                "                                  ccccc) {\n"
6241                "}");
6242   verifyFormat("if () {\n"
6243                "} else if (aaaaa &&\n"
6244                "           bbbbb > // break\n"
6245                "               ccccc &&\n"
6246                "           ddddd) {\n"
6247                "}");
6248 
6249   // Presence of a trailing comment used to change indentation of b.
6250   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
6251                "       b;\n"
6252                "return aaaaaaaaaaaaaaaaaaa +\n"
6253                "       b; //",
6254                getLLVMStyleWithColumns(30));
6255 }
6256 
6257 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
6258   // Not sure what the best system is here. Like this, the LHS can be found
6259   // immediately above an operator (everything with the same or a higher
6260   // indent). The RHS is aligned right of the operator and so compasses
6261   // everything until something with the same indent as the operator is found.
6262   // FIXME: Is this a good system?
6263   FormatStyle Style = getLLVMStyle();
6264   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6265   verifyFormat(
6266       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6267       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6268       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6269       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6270       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6271       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6272       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6273       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6274       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
6275       Style);
6276   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6277                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6278                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6279                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6280                Style);
6281   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6282                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6283                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6284                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6285                Style);
6286   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6287                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6288                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6289                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6290                Style);
6291   verifyFormat("if () {\n"
6292                "} else if (aaaaa\n"
6293                "           && bbbbb // break\n"
6294                "                  > ccccc) {\n"
6295                "}",
6296                Style);
6297   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6298                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6299                Style);
6300   verifyFormat("return (a)\n"
6301                "       // comment\n"
6302                "       + b;",
6303                Style);
6304   verifyFormat(
6305       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6306       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6307       "             + cc;",
6308       Style);
6309 
6310   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6311                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6312                Style);
6313 
6314   // Forced by comments.
6315   verifyFormat(
6316       "unsigned ContentSize =\n"
6317       "    sizeof(int16_t)   // DWARF ARange version number\n"
6318       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6319       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6320       "    + sizeof(int8_t); // Segment Size (in bytes)");
6321 
6322   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6323                "       == boost::fusion::at_c<1>(iiii).second;",
6324                Style);
6325 
6326   Style.ColumnLimit = 60;
6327   verifyFormat("zzzzzzzzzz\n"
6328                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6329                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6330                Style);
6331 
6332   Style.ColumnLimit = 80;
6333   Style.IndentWidth = 4;
6334   Style.TabWidth = 4;
6335   Style.UseTab = FormatStyle::UT_Always;
6336   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6337   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6338   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
6339             "\t&& (someOtherLongishConditionPart1\n"
6340             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
6341             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
6342                    "(someOtherLongishConditionPart1 || "
6343                    "someOtherEvenLongerNestedConditionPart2);",
6344                    Style));
6345 }
6346 
6347 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
6348   FormatStyle Style = getLLVMStyle();
6349   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6350   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
6351 
6352   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6353                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6354                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6355                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6356                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6357                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6358                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6359                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6360                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
6361                Style);
6362   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6363                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6364                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6365                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6366                Style);
6367   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6368                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6369                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6370                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6371                Style);
6372   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6373                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6374                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6375                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6376                Style);
6377   verifyFormat("if () {\n"
6378                "} else if (aaaaa\n"
6379                "           && bbbbb // break\n"
6380                "                  > ccccc) {\n"
6381                "}",
6382                Style);
6383   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6384                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6385                Style);
6386   verifyFormat("return (a)\n"
6387                "     // comment\n"
6388                "     + b;",
6389                Style);
6390   verifyFormat(
6391       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6392       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6393       "           + cc;",
6394       Style);
6395   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6396                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6397                "                        : 3333333333333333;",
6398                Style);
6399   verifyFormat(
6400       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6401       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6402       "                                             : eeeeeeeeeeeeeeeeee)\n"
6403       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6404       "                        : 3333333333333333;",
6405       Style);
6406   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6407                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6408                Style);
6409 
6410   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6411                "    == boost::fusion::at_c<1>(iiii).second;",
6412                Style);
6413 
6414   Style.ColumnLimit = 60;
6415   verifyFormat("zzzzzzzzzzzzz\n"
6416                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6417                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6418                Style);
6419 
6420   // Forced by comments.
6421   Style.ColumnLimit = 80;
6422   verifyFormat(
6423       "unsigned ContentSize\n"
6424       "    = sizeof(int16_t) // DWARF ARange version number\n"
6425       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6426       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6427       "    + sizeof(int8_t); // Segment Size (in bytes)",
6428       Style);
6429 
6430   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6431   verifyFormat(
6432       "unsigned ContentSize =\n"
6433       "    sizeof(int16_t)   // DWARF ARange version number\n"
6434       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6435       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6436       "    + sizeof(int8_t); // Segment Size (in bytes)",
6437       Style);
6438 
6439   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6440   verifyFormat(
6441       "unsigned ContentSize =\n"
6442       "    sizeof(int16_t)   // DWARF ARange version number\n"
6443       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6444       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6445       "    + sizeof(int8_t); // Segment Size (in bytes)",
6446       Style);
6447 }
6448 
6449 TEST_F(FormatTest, EnforcedOperatorWraps) {
6450   // Here we'd like to wrap after the || operators, but a comment is forcing an
6451   // earlier wrap.
6452   verifyFormat("bool x = aaaaa //\n"
6453                "         || bbbbb\n"
6454                "         //\n"
6455                "         || cccc;");
6456 }
6457 
6458 TEST_F(FormatTest, NoOperandAlignment) {
6459   FormatStyle Style = getLLVMStyle();
6460   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6461   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6462                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6463                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6464                Style);
6465   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6466   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6467                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6468                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6469                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6470                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6471                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6472                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6473                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6474                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6475                Style);
6476 
6477   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6478                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6479                "    + cc;",
6480                Style);
6481   verifyFormat("int a = aa\n"
6482                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6483                "        * cccccccccccccccccccccccccccccccccccc;\n",
6484                Style);
6485 
6486   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6487   verifyFormat("return (a > b\n"
6488                "    // comment1\n"
6489                "    // comment2\n"
6490                "    || c);",
6491                Style);
6492 }
6493 
6494 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6495   FormatStyle Style = getLLVMStyle();
6496   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6497   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6498                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6499                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6500                Style);
6501 }
6502 
6503 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6504   FormatStyle Style = getLLVMStyleWithColumns(40);
6505   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6506   Style.BinPackArguments = false;
6507   verifyFormat("void test() {\n"
6508                "  someFunction(\n"
6509                "      this + argument + is + quite\n"
6510                "      + long + so + it + gets + wrapped\n"
6511                "      + but + remains + bin - packed);\n"
6512                "}",
6513                Style);
6514   verifyFormat("void test() {\n"
6515                "  someFunction(arg1,\n"
6516                "               this + argument + is\n"
6517                "                   + quite + long + so\n"
6518                "                   + it + gets + wrapped\n"
6519                "                   + but + remains + bin\n"
6520                "                   - packed,\n"
6521                "               arg3);\n"
6522                "}",
6523                Style);
6524   verifyFormat("void test() {\n"
6525                "  someFunction(\n"
6526                "      arg1,\n"
6527                "      this + argument + has\n"
6528                "          + anotherFunc(nested,\n"
6529                "                        calls + whose\n"
6530                "                            + arguments\n"
6531                "                            + are + also\n"
6532                "                            + wrapped,\n"
6533                "                        in + addition)\n"
6534                "          + to + being + bin - packed,\n"
6535                "      arg3);\n"
6536                "}",
6537                Style);
6538 
6539   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
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 
6556 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) {
6557   auto Style = getLLVMStyleWithColumns(45);
6558   EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None);
6559   verifyFormat("bool b =\n"
6560                "    is_default_constructible_v<hash<T>> and\n"
6561                "    is_copy_constructible_v<hash<T>> and\n"
6562                "    is_move_constructible_v<hash<T>> and\n"
6563                "    is_copy_assignable_v<hash<T>> and\n"
6564                "    is_move_assignable_v<hash<T>> and\n"
6565                "    is_destructible_v<hash<T>> and\n"
6566                "    is_swappable_v<hash<T>> and\n"
6567                "    is_callable_v<hash<T>(T)>;",
6568                Style);
6569 
6570   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6571   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6572                "         and is_copy_constructible_v<hash<T>>\n"
6573                "         and is_move_constructible_v<hash<T>>\n"
6574                "         and is_copy_assignable_v<hash<T>>\n"
6575                "         and is_move_assignable_v<hash<T>>\n"
6576                "         and is_destructible_v<hash<T>>\n"
6577                "         and is_swappable_v<hash<T>>\n"
6578                "         and is_callable_v<hash<T>(T)>;",
6579                Style);
6580 
6581   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6582   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6583                "         and is_copy_constructible_v<hash<T>>\n"
6584                "         and is_move_constructible_v<hash<T>>\n"
6585                "         and is_copy_assignable_v<hash<T>>\n"
6586                "         and is_move_assignable_v<hash<T>>\n"
6587                "         and is_destructible_v<hash<T>>\n"
6588                "         and is_swappable_v<hash<T>>\n"
6589                "         and is_callable_v<hash<T>(T)>;",
6590                Style);
6591 }
6592 
6593 TEST_F(FormatTest, ConstructorInitializers) {
6594   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6595   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6596                getLLVMStyleWithColumns(45));
6597   verifyFormat("Constructor()\n"
6598                "    : Inttializer(FitsOnTheLine) {}",
6599                getLLVMStyleWithColumns(44));
6600   verifyFormat("Constructor()\n"
6601                "    : Inttializer(FitsOnTheLine) {}",
6602                getLLVMStyleWithColumns(43));
6603 
6604   verifyFormat("template <typename T>\n"
6605                "Constructor() : Initializer(FitsOnTheLine) {}",
6606                getLLVMStyleWithColumns(45));
6607 
6608   verifyFormat(
6609       "SomeClass::Constructor()\n"
6610       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6611 
6612   verifyFormat(
6613       "SomeClass::Constructor()\n"
6614       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6615       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6616   verifyFormat(
6617       "SomeClass::Constructor()\n"
6618       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6619       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6620   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6621                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6622                "    : aaaaaaaaaa(aaaaaa) {}");
6623 
6624   verifyFormat("Constructor()\n"
6625                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6626                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6627                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6628                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6629 
6630   verifyFormat("Constructor()\n"
6631                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6632                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6633 
6634   verifyFormat("Constructor(int Parameter = 0)\n"
6635                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6636                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6637   verifyFormat("Constructor()\n"
6638                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6639                "}",
6640                getLLVMStyleWithColumns(60));
6641   verifyFormat("Constructor()\n"
6642                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6643                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6644 
6645   // Here a line could be saved by splitting the second initializer onto two
6646   // lines, but that is not desirable.
6647   verifyFormat("Constructor()\n"
6648                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6649                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6650                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6651 
6652   FormatStyle OnePerLine = getLLVMStyle();
6653   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6654   verifyFormat("MyClass::MyClass()\n"
6655                "    : a(a),\n"
6656                "      b(b),\n"
6657                "      c(c) {}",
6658                OnePerLine);
6659   verifyFormat("MyClass::MyClass()\n"
6660                "    : a(a), // comment\n"
6661                "      b(b),\n"
6662                "      c(c) {}",
6663                OnePerLine);
6664   verifyFormat("MyClass::MyClass(int a)\n"
6665                "    : b(a),      // comment\n"
6666                "      c(a + 1) { // lined up\n"
6667                "}",
6668                OnePerLine);
6669   verifyFormat("Constructor()\n"
6670                "    : a(b, b, b) {}",
6671                OnePerLine);
6672   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6673   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6674   verifyFormat("SomeClass::Constructor()\n"
6675                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6676                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6677                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6678                OnePerLine);
6679   verifyFormat("SomeClass::Constructor()\n"
6680                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6681                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6682                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6683                OnePerLine);
6684   verifyFormat("MyClass::MyClass(int var)\n"
6685                "    : some_var_(var),            // 4 space indent\n"
6686                "      some_other_var_(var + 1) { // lined up\n"
6687                "}",
6688                OnePerLine);
6689   verifyFormat("Constructor()\n"
6690                "    : aaaaa(aaaaaa),\n"
6691                "      aaaaa(aaaaaa),\n"
6692                "      aaaaa(aaaaaa),\n"
6693                "      aaaaa(aaaaaa),\n"
6694                "      aaaaa(aaaaaa) {}",
6695                OnePerLine);
6696   verifyFormat("Constructor()\n"
6697                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6698                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6699                OnePerLine);
6700   OnePerLine.BinPackParameters = false;
6701   verifyFormat(
6702       "Constructor()\n"
6703       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6704       "          aaaaaaaaaaa().aaa(),\n"
6705       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6706       OnePerLine);
6707   OnePerLine.ColumnLimit = 60;
6708   verifyFormat("Constructor()\n"
6709                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6710                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6711                OnePerLine);
6712 
6713   EXPECT_EQ("Constructor()\n"
6714             "    : // Comment forcing unwanted break.\n"
6715             "      aaaa(aaaa) {}",
6716             format("Constructor() :\n"
6717                    "    // Comment forcing unwanted break.\n"
6718                    "    aaaa(aaaa) {}"));
6719 }
6720 
6721 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6722   FormatStyle Style = getLLVMStyleWithColumns(60);
6723   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6724   Style.BinPackParameters = false;
6725 
6726   for (int i = 0; i < 4; ++i) {
6727     // Test all combinations of parameters that should not have an effect.
6728     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6729     Style.AllowAllArgumentsOnNextLine = i & 2;
6730 
6731     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6732     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6733     verifyFormat("Constructor()\n"
6734                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6735                  Style);
6736     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6737 
6738     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6739     verifyFormat("Constructor()\n"
6740                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6741                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6742                  Style);
6743     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6744 
6745     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6746     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6747     verifyFormat("Constructor()\n"
6748                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6749                  Style);
6750 
6751     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6752     verifyFormat("Constructor()\n"
6753                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6754                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6755                  Style);
6756 
6757     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6758     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6759     verifyFormat("Constructor() :\n"
6760                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6761                  Style);
6762 
6763     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6764     verifyFormat("Constructor() :\n"
6765                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6766                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6767                  Style);
6768   }
6769 
6770   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6771   // AllowAllConstructorInitializersOnNextLine in all
6772   // BreakConstructorInitializers modes
6773   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6774   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6775   verifyFormat("SomeClassWithALongName::Constructor(\n"
6776                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6777                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6778                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6779                Style);
6780 
6781   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6782   verifyFormat("SomeClassWithALongName::Constructor(\n"
6783                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6784                "    int bbbbbbbbbbbbb,\n"
6785                "    int cccccccccccccccc)\n"
6786                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6787                Style);
6788 
6789   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6790   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6791   verifyFormat("SomeClassWithALongName::Constructor(\n"
6792                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6793                "    int bbbbbbbbbbbbb)\n"
6794                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6795                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6796                Style);
6797 
6798   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6799 
6800   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6801   verifyFormat("SomeClassWithALongName::Constructor(\n"
6802                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6803                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6804                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6805                Style);
6806 
6807   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6808   verifyFormat("SomeClassWithALongName::Constructor(\n"
6809                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6810                "    int bbbbbbbbbbbbb,\n"
6811                "    int cccccccccccccccc)\n"
6812                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6813                Style);
6814 
6815   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6816   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6817   verifyFormat("SomeClassWithALongName::Constructor(\n"
6818                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6819                "    int bbbbbbbbbbbbb)\n"
6820                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6821                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6822                Style);
6823 
6824   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6825   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6826   verifyFormat("SomeClassWithALongName::Constructor(\n"
6827                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6828                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6829                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6830                Style);
6831 
6832   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6833   verifyFormat("SomeClassWithALongName::Constructor(\n"
6834                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6835                "    int bbbbbbbbbbbbb,\n"
6836                "    int cccccccccccccccc) :\n"
6837                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6838                Style);
6839 
6840   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6841   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6842   verifyFormat("SomeClassWithALongName::Constructor(\n"
6843                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6844                "    int bbbbbbbbbbbbb) :\n"
6845                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6846                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6847                Style);
6848 }
6849 
6850 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6851   FormatStyle Style = getLLVMStyleWithColumns(60);
6852   Style.BinPackArguments = false;
6853   for (int i = 0; i < 4; ++i) {
6854     // Test all combinations of parameters that should not have an effect.
6855     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6856     Style.PackConstructorInitializers =
6857         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6858 
6859     Style.AllowAllArgumentsOnNextLine = true;
6860     verifyFormat("void foo() {\n"
6861                  "  FunctionCallWithReallyLongName(\n"
6862                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6863                  "}",
6864                  Style);
6865     Style.AllowAllArgumentsOnNextLine = false;
6866     verifyFormat("void foo() {\n"
6867                  "  FunctionCallWithReallyLongName(\n"
6868                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6869                  "      bbbbbbbbbbbb);\n"
6870                  "}",
6871                  Style);
6872 
6873     Style.AllowAllArgumentsOnNextLine = true;
6874     verifyFormat("void foo() {\n"
6875                  "  auto VariableWithReallyLongName = {\n"
6876                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6877                  "}",
6878                  Style);
6879     Style.AllowAllArgumentsOnNextLine = false;
6880     verifyFormat("void foo() {\n"
6881                  "  auto VariableWithReallyLongName = {\n"
6882                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6883                  "      bbbbbbbbbbbb};\n"
6884                  "}",
6885                  Style);
6886   }
6887 
6888   // This parameter should not affect declarations.
6889   Style.BinPackParameters = false;
6890   Style.AllowAllArgumentsOnNextLine = false;
6891   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6892   verifyFormat("void FunctionCallWithReallyLongName(\n"
6893                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6894                Style);
6895   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6896   verifyFormat("void FunctionCallWithReallyLongName(\n"
6897                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6898                "    int bbbbbbbbbbbb);",
6899                Style);
6900 }
6901 
6902 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6903   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6904   // and BAS_Align.
6905   FormatStyle Style = getLLVMStyleWithColumns(35);
6906   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6907                     "void functionDecl(int A, int B, int C);";
6908   Style.AllowAllArgumentsOnNextLine = false;
6909   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6910   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6911                       "    paramC);\n"
6912                       "void functionDecl(int A, int B,\n"
6913                       "    int C);"),
6914             format(Input, Style));
6915   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6916   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6917                       "             paramC);\n"
6918                       "void functionDecl(int A, int B,\n"
6919                       "                  int C);"),
6920             format(Input, Style));
6921   // However, BAS_AlwaysBreak should take precedence over
6922   // AllowAllArgumentsOnNextLine.
6923   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6924   EXPECT_EQ(StringRef("functionCall(\n"
6925                       "    paramA, paramB, paramC);\n"
6926                       "void functionDecl(\n"
6927                       "    int A, int B, int C);"),
6928             format(Input, Style));
6929 
6930   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6931   // first argument.
6932   Style.AllowAllArgumentsOnNextLine = true;
6933   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6934   EXPECT_EQ(StringRef("functionCall(\n"
6935                       "    paramA, paramB, paramC);\n"
6936                       "void functionDecl(\n"
6937                       "    int A, int B, int C);"),
6938             format(Input, Style));
6939   // It wouldn't fit on one line with aligned parameters so this setting
6940   // doesn't change anything for BAS_Align.
6941   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6942   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6943                       "             paramC);\n"
6944                       "void functionDecl(int A, int B,\n"
6945                       "                  int C);"),
6946             format(Input, Style));
6947   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6948   EXPECT_EQ(StringRef("functionCall(\n"
6949                       "    paramA, paramB, paramC);\n"
6950                       "void functionDecl(\n"
6951                       "    int A, int B, int C);"),
6952             format(Input, Style));
6953 }
6954 
6955 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6956   FormatStyle Style = getLLVMStyle();
6957   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6958 
6959   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6960   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6961                getStyleWithColumns(Style, 45));
6962   verifyFormat("Constructor() :\n"
6963                "    Initializer(FitsOnTheLine) {}",
6964                getStyleWithColumns(Style, 44));
6965   verifyFormat("Constructor() :\n"
6966                "    Initializer(FitsOnTheLine) {}",
6967                getStyleWithColumns(Style, 43));
6968 
6969   verifyFormat("template <typename T>\n"
6970                "Constructor() : Initializer(FitsOnTheLine) {}",
6971                getStyleWithColumns(Style, 50));
6972   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6973   verifyFormat(
6974       "SomeClass::Constructor() :\n"
6975       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6976       Style);
6977 
6978   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6979   verifyFormat(
6980       "SomeClass::Constructor() :\n"
6981       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6982       Style);
6983 
6984   verifyFormat(
6985       "SomeClass::Constructor() :\n"
6986       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6987       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6988       Style);
6989   verifyFormat(
6990       "SomeClass::Constructor() :\n"
6991       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6992       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6993       Style);
6994   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6995                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6996                "    aaaaaaaaaa(aaaaaa) {}",
6997                Style);
6998 
6999   verifyFormat("Constructor() :\n"
7000                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7001                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7002                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7003                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
7004                Style);
7005 
7006   verifyFormat("Constructor() :\n"
7007                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7008                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7009                Style);
7010 
7011   verifyFormat("Constructor(int Parameter = 0) :\n"
7012                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
7013                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
7014                Style);
7015   verifyFormat("Constructor() :\n"
7016                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
7017                "}",
7018                getStyleWithColumns(Style, 60));
7019   verifyFormat("Constructor() :\n"
7020                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7021                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
7022                Style);
7023 
7024   // Here a line could be saved by splitting the second initializer onto two
7025   // lines, but that is not desirable.
7026   verifyFormat("Constructor() :\n"
7027                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
7028                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
7029                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7030                Style);
7031 
7032   FormatStyle OnePerLine = Style;
7033   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
7034   verifyFormat("SomeClass::Constructor() :\n"
7035                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7036                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7037                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7038                OnePerLine);
7039   verifyFormat("SomeClass::Constructor() :\n"
7040                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
7041                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7042                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7043                OnePerLine);
7044   verifyFormat("MyClass::MyClass(int var) :\n"
7045                "    some_var_(var),            // 4 space indent\n"
7046                "    some_other_var_(var + 1) { // lined up\n"
7047                "}",
7048                OnePerLine);
7049   verifyFormat("Constructor() :\n"
7050                "    aaaaa(aaaaaa),\n"
7051                "    aaaaa(aaaaaa),\n"
7052                "    aaaaa(aaaaaa),\n"
7053                "    aaaaa(aaaaaa),\n"
7054                "    aaaaa(aaaaaa) {}",
7055                OnePerLine);
7056   verifyFormat("Constructor() :\n"
7057                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
7058                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
7059                OnePerLine);
7060   OnePerLine.BinPackParameters = false;
7061   verifyFormat("Constructor() :\n"
7062                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7063                "        aaaaaaaaaaa().aaa(),\n"
7064                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7065                OnePerLine);
7066   OnePerLine.ColumnLimit = 60;
7067   verifyFormat("Constructor() :\n"
7068                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
7069                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
7070                OnePerLine);
7071 
7072   EXPECT_EQ("Constructor() :\n"
7073             "    // Comment forcing unwanted break.\n"
7074             "    aaaa(aaaa) {}",
7075             format("Constructor() :\n"
7076                    "    // Comment forcing unwanted break.\n"
7077                    "    aaaa(aaaa) {}",
7078                    Style));
7079 
7080   Style.ColumnLimit = 0;
7081   verifyFormat("SomeClass::Constructor() :\n"
7082                "    a(a) {}",
7083                Style);
7084   verifyFormat("SomeClass::Constructor() noexcept :\n"
7085                "    a(a) {}",
7086                Style);
7087   verifyFormat("SomeClass::Constructor() :\n"
7088                "    a(a), b(b), c(c) {}",
7089                Style);
7090   verifyFormat("SomeClass::Constructor() :\n"
7091                "    a(a) {\n"
7092                "  foo();\n"
7093                "  bar();\n"
7094                "}",
7095                Style);
7096 
7097   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
7098   verifyFormat("SomeClass::Constructor() :\n"
7099                "    a(a), b(b), c(c) {\n"
7100                "}",
7101                Style);
7102   verifyFormat("SomeClass::Constructor() :\n"
7103                "    a(a) {\n"
7104                "}",
7105                Style);
7106 
7107   Style.ColumnLimit = 80;
7108   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
7109   Style.ConstructorInitializerIndentWidth = 2;
7110   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
7111   verifyFormat("SomeClass::Constructor() :\n"
7112                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7113                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
7114                Style);
7115 
7116   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
7117   // well
7118   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
7119   verifyFormat(
7120       "class SomeClass\n"
7121       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7122       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7123       Style);
7124   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
7125   verifyFormat(
7126       "class SomeClass\n"
7127       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7128       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7129       Style);
7130   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
7131   verifyFormat(
7132       "class SomeClass :\n"
7133       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7134       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7135       Style);
7136   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
7137   verifyFormat(
7138       "class SomeClass\n"
7139       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7140       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7141       Style);
7142 }
7143 
7144 #ifndef EXPENSIVE_CHECKS
7145 // Expensive checks enables libstdc++ checking which includes validating the
7146 // state of ranges used in std::priority_queue - this blows out the
7147 // runtime/scalability of the function and makes this test unacceptably slow.
7148 TEST_F(FormatTest, MemoizationTests) {
7149   // This breaks if the memoization lookup does not take \c Indent and
7150   // \c LastSpace into account.
7151   verifyFormat(
7152       "extern CFRunLoopTimerRef\n"
7153       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
7154       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
7155       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
7156       "                     CFRunLoopTimerContext *context) {}");
7157 
7158   // Deep nesting somewhat works around our memoization.
7159   verifyFormat(
7160       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7161       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7162       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7163       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7164       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
7165       getLLVMStyleWithColumns(65));
7166   verifyFormat(
7167       "aaaaa(\n"
7168       "    aaaaa,\n"
7169       "    aaaaa(\n"
7170       "        aaaaa,\n"
7171       "        aaaaa(\n"
7172       "            aaaaa,\n"
7173       "            aaaaa(\n"
7174       "                aaaaa,\n"
7175       "                aaaaa(\n"
7176       "                    aaaaa,\n"
7177       "                    aaaaa(\n"
7178       "                        aaaaa,\n"
7179       "                        aaaaa(\n"
7180       "                            aaaaa,\n"
7181       "                            aaaaa(\n"
7182       "                                aaaaa,\n"
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))))))))))));",
7192       getLLVMStyleWithColumns(65));
7193   verifyFormat(
7194       "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"
7195       "                                  a),\n"
7196       "                                a),\n"
7197       "                              a),\n"
7198       "                            a),\n"
7199       "                          a),\n"
7200       "                        a),\n"
7201       "                      a),\n"
7202       "                    a),\n"
7203       "                  a),\n"
7204       "                a),\n"
7205       "              a),\n"
7206       "            a),\n"
7207       "          a),\n"
7208       "        a),\n"
7209       "      a),\n"
7210       "    a),\n"
7211       "  a)",
7212       getLLVMStyleWithColumns(65));
7213 
7214   // This test takes VERY long when memoization is broken.
7215   FormatStyle OnePerLine = getLLVMStyle();
7216   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
7217   OnePerLine.BinPackParameters = false;
7218   std::string input = "Constructor()\n"
7219                       "    : aaaa(a,\n";
7220   for (unsigned i = 0, e = 80; i != e; ++i) {
7221     input += "           a,\n";
7222   }
7223   input += "           a) {}";
7224   verifyFormat(input, OnePerLine);
7225 }
7226 #endif
7227 
7228 TEST_F(FormatTest, BreaksAsHighAsPossible) {
7229   verifyFormat(
7230       "void f() {\n"
7231       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
7232       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
7233       "    f();\n"
7234       "}");
7235   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
7236                "    Intervals[i - 1].getRange().getLast()) {\n}");
7237 }
7238 
7239 TEST_F(FormatTest, BreaksFunctionDeclarations) {
7240   // Principially, we break function declarations in a certain order:
7241   // 1) break amongst arguments.
7242   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
7243                "                              Cccccccccccccc cccccccccccccc);");
7244   verifyFormat("template <class TemplateIt>\n"
7245                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
7246                "                            TemplateIt *stop) {}");
7247 
7248   // 2) break after return type.
7249   verifyFormat(
7250       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7251       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
7252       getGoogleStyle());
7253 
7254   // 3) break after (.
7255   verifyFormat(
7256       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
7257       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
7258       getGoogleStyle());
7259 
7260   // 4) break before after nested name specifiers.
7261   verifyFormat(
7262       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7263       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
7264       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
7265       getGoogleStyle());
7266 
7267   // However, there are exceptions, if a sufficient amount of lines can be
7268   // saved.
7269   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
7270   // more adjusting.
7271   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7272                "                                  Cccccccccccccc cccccccccc,\n"
7273                "                                  Cccccccccccccc cccccccccc,\n"
7274                "                                  Cccccccccccccc cccccccccc,\n"
7275                "                                  Cccccccccccccc cccccccccc);");
7276   verifyFormat(
7277       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7278       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7279       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7280       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
7281       getGoogleStyle());
7282   verifyFormat(
7283       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7284       "                                          Cccccccccccccc cccccccccc,\n"
7285       "                                          Cccccccccccccc cccccccccc,\n"
7286       "                                          Cccccccccccccc cccccccccc,\n"
7287       "                                          Cccccccccccccc cccccccccc,\n"
7288       "                                          Cccccccccccccc cccccccccc,\n"
7289       "                                          Cccccccccccccc cccccccccc);");
7290   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7291                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7292                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7293                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7294                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
7295 
7296   // Break after multi-line parameters.
7297   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7298                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7299                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7300                "    bbbb bbbb);");
7301   verifyFormat("void SomeLoooooooooooongFunction(\n"
7302                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
7303                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7304                "    int bbbbbbbbbbbbb);");
7305 
7306   // Treat overloaded operators like other functions.
7307   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7308                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
7309   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7310                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
7311   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7312                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
7313   verifyGoogleFormat(
7314       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
7315       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7316   verifyGoogleFormat(
7317       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
7318       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7319   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7320                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7321   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
7322                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7323   verifyGoogleFormat(
7324       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
7325       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7326       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
7327   verifyGoogleFormat("template <typename T>\n"
7328                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7329                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
7330                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
7331 
7332   FormatStyle Style = getLLVMStyle();
7333   Style.PointerAlignment = FormatStyle::PAS_Left;
7334   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7335                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
7336                Style);
7337   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
7338                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7339                Style);
7340 }
7341 
7342 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
7343   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
7344   // Prefer keeping `::` followed by `operator` together.
7345   EXPECT_EQ("const aaaa::bbbbbbb &\n"
7346             "ccccccccc::operator++() {\n"
7347             "  stuff();\n"
7348             "}",
7349             format("const aaaa::bbbbbbb\n"
7350                    "&ccccccccc::operator++() { stuff(); }",
7351                    getLLVMStyleWithColumns(40)));
7352 }
7353 
7354 TEST_F(FormatTest, TrailingReturnType) {
7355   verifyFormat("auto foo() -> int;\n");
7356   // correct trailing return type spacing
7357   verifyFormat("auto operator->() -> int;\n");
7358   verifyFormat("auto operator++(int) -> int;\n");
7359 
7360   verifyFormat("struct S {\n"
7361                "  auto bar() const -> int;\n"
7362                "};");
7363   verifyFormat("template <size_t Order, typename T>\n"
7364                "auto load_img(const std::string &filename)\n"
7365                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
7366   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
7367                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
7368   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
7369   verifyFormat("template <typename T>\n"
7370                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
7371                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
7372 
7373   // Not trailing return types.
7374   verifyFormat("void f() { auto a = b->c(); }");
7375   verifyFormat("auto a = p->foo();");
7376   verifyFormat("int a = p->foo();");
7377   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
7378 }
7379 
7380 TEST_F(FormatTest, DeductionGuides) {
7381   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
7382   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
7383   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
7384   verifyFormat(
7385       "template <class... T>\n"
7386       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
7387   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
7388   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
7389   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
7390   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
7391   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
7392   verifyFormat("template <class T> x() -> x<1>;");
7393   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
7394 
7395   // Ensure not deduction guides.
7396   verifyFormat("c()->f<int>();");
7397   verifyFormat("x()->foo<1>;");
7398   verifyFormat("x = p->foo<3>();");
7399   verifyFormat("x()->x<1>();");
7400   verifyFormat("x()->x<1>;");
7401 }
7402 
7403 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
7404   // Avoid breaking before trailing 'const' or other trailing annotations, if
7405   // they are not function-like.
7406   FormatStyle Style = getGoogleStyleWithColumns(47);
7407   verifyFormat("void someLongFunction(\n"
7408                "    int someLoooooooooooooongParameter) const {\n}",
7409                getLLVMStyleWithColumns(47));
7410   verifyFormat("LoooooongReturnType\n"
7411                "someLoooooooongFunction() const {}",
7412                getLLVMStyleWithColumns(47));
7413   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
7414                "    const {}",
7415                Style);
7416   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7417                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
7418   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7419                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
7420   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7421                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
7422   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
7423                "                   aaaaaaaaaaa aaaaa) const override;");
7424   verifyGoogleFormat(
7425       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7426       "    const override;");
7427 
7428   // Even if the first parameter has to be wrapped.
7429   verifyFormat("void someLongFunction(\n"
7430                "    int someLongParameter) const {}",
7431                getLLVMStyleWithColumns(46));
7432   verifyFormat("void someLongFunction(\n"
7433                "    int someLongParameter) const {}",
7434                Style);
7435   verifyFormat("void someLongFunction(\n"
7436                "    int someLongParameter) override {}",
7437                Style);
7438   verifyFormat("void someLongFunction(\n"
7439                "    int someLongParameter) OVERRIDE {}",
7440                Style);
7441   verifyFormat("void someLongFunction(\n"
7442                "    int someLongParameter) final {}",
7443                Style);
7444   verifyFormat("void someLongFunction(\n"
7445                "    int someLongParameter) FINAL {}",
7446                Style);
7447   verifyFormat("void someLongFunction(\n"
7448                "    int parameter) const override {}",
7449                Style);
7450 
7451   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
7452   verifyFormat("void someLongFunction(\n"
7453                "    int someLongParameter) const\n"
7454                "{\n"
7455                "}",
7456                Style);
7457 
7458   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
7459   verifyFormat("void someLongFunction(\n"
7460                "    int someLongParameter) const\n"
7461                "  {\n"
7462                "  }",
7463                Style);
7464 
7465   // Unless these are unknown annotations.
7466   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
7467                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7468                "    LONG_AND_UGLY_ANNOTATION;");
7469 
7470   // Breaking before function-like trailing annotations is fine to keep them
7471   // close to their arguments.
7472   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7473                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7474   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7475                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7476   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7477                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
7478   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
7479                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
7480   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
7481 
7482   verifyFormat(
7483       "void aaaaaaaaaaaaaaaaaa()\n"
7484       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
7485       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
7486   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7487                "    __attribute__((unused));");
7488   verifyGoogleFormat(
7489       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7490       "    GUARDED_BY(aaaaaaaaaaaa);");
7491   verifyGoogleFormat(
7492       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7493       "    GUARDED_BY(aaaaaaaaaaaa);");
7494   verifyGoogleFormat(
7495       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7496       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7497   verifyGoogleFormat(
7498       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7499       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
7500 }
7501 
7502 TEST_F(FormatTest, FunctionAnnotations) {
7503   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7504                "int OldFunction(const string &parameter) {}");
7505   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7506                "string OldFunction(const string &parameter) {}");
7507   verifyFormat("template <typename T>\n"
7508                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7509                "string OldFunction(const string &parameter) {}");
7510 
7511   // Not function annotations.
7512   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7513                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
7514   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
7515                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
7516   verifyFormat("MACRO(abc).function() // wrap\n"
7517                "    << abc;");
7518   verifyFormat("MACRO(abc)->function() // wrap\n"
7519                "    << abc;");
7520   verifyFormat("MACRO(abc)::function() // wrap\n"
7521                "    << abc;");
7522 }
7523 
7524 TEST_F(FormatTest, BreaksDesireably) {
7525   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7526                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7527                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
7528   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7529                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
7530                "}");
7531 
7532   verifyFormat(
7533       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7534       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7535 
7536   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7537                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7538                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7539 
7540   verifyFormat(
7541       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7542       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7543       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7544       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7545       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7546 
7547   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7548                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7549 
7550   verifyFormat(
7551       "void f() {\n"
7552       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7553       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7554       "}");
7555   verifyFormat(
7556       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7557       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7558   verifyFormat(
7559       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7560       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7561   verifyFormat(
7562       "aaaaaa(aaa,\n"
7563       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7564       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7565       "       aaaa);");
7566   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7567                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7568                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7569 
7570   // Indent consistently independent of call expression and unary operator.
7571   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7572                "    dddddddddddddddddddddddddddddd));");
7573   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7574                "    dddddddddddddddddddddddddddddd));");
7575   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7576                "    dddddddddddddddddddddddddddddd));");
7577 
7578   // This test case breaks on an incorrect memoization, i.e. an optimization not
7579   // taking into account the StopAt value.
7580   verifyFormat(
7581       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7582       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7583       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7584       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7585 
7586   verifyFormat("{\n  {\n    {\n"
7587                "      Annotation.SpaceRequiredBefore =\n"
7588                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7589                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7590                "    }\n  }\n}");
7591 
7592   // Break on an outer level if there was a break on an inner level.
7593   EXPECT_EQ("f(g(h(a, // comment\n"
7594             "      b, c),\n"
7595             "    d, e),\n"
7596             "  x, y);",
7597             format("f(g(h(a, // comment\n"
7598                    "    b, c), d, e), x, y);"));
7599 
7600   // Prefer breaking similar line breaks.
7601   verifyFormat(
7602       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7603       "                             NSTrackingMouseEnteredAndExited |\n"
7604       "                             NSTrackingActiveAlways;");
7605 }
7606 
7607 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7608   FormatStyle NoBinPacking = getGoogleStyle();
7609   NoBinPacking.BinPackParameters = false;
7610   NoBinPacking.BinPackArguments = true;
7611   verifyFormat("void f() {\n"
7612                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7613                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7614                "}",
7615                NoBinPacking);
7616   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7617                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7618                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7619                NoBinPacking);
7620 
7621   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7622   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7623                "                        vector<int> bbbbbbbbbbbbbbb);",
7624                NoBinPacking);
7625   // FIXME: This behavior difference is probably not wanted. However, currently
7626   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7627   // template arguments from BreakBeforeParameter being set because of the
7628   // one-per-line formatting.
7629   verifyFormat(
7630       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7631       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7632       NoBinPacking);
7633   verifyFormat(
7634       "void fffffffffff(\n"
7635       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7636       "        aaaaaaaaaa);");
7637 }
7638 
7639 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7640   FormatStyle NoBinPacking = getGoogleStyle();
7641   NoBinPacking.BinPackParameters = false;
7642   NoBinPacking.BinPackArguments = false;
7643   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7644                "  aaaaaaaaaaaaaaaaaaaa,\n"
7645                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7646                NoBinPacking);
7647   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7648                "        aaaaaaaaaaaaa,\n"
7649                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7650                NoBinPacking);
7651   verifyFormat(
7652       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7653       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7654       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7655       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7656       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7657       NoBinPacking);
7658   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7659                "    .aaaaaaaaaaaaaaaaaa();",
7660                NoBinPacking);
7661   verifyFormat("void f() {\n"
7662                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7663                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7664                "}",
7665                NoBinPacking);
7666 
7667   verifyFormat(
7668       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7669       "             aaaaaaaaaaaa,\n"
7670       "             aaaaaaaaaaaa);",
7671       NoBinPacking);
7672   verifyFormat(
7673       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7674       "                               ddddddddddddddddddddddddddddd),\n"
7675       "             test);",
7676       NoBinPacking);
7677 
7678   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7679                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7680                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7681                "    aaaaaaaaaaaaaaaaaa;",
7682                NoBinPacking);
7683   verifyFormat("a(\"a\"\n"
7684                "  \"a\",\n"
7685                "  a);");
7686 
7687   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7688   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7689                "                aaaaaaaaa,\n"
7690                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7691                NoBinPacking);
7692   verifyFormat(
7693       "void f() {\n"
7694       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7695       "      .aaaaaaa();\n"
7696       "}",
7697       NoBinPacking);
7698   verifyFormat(
7699       "template <class SomeType, class SomeOtherType>\n"
7700       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7701       NoBinPacking);
7702 }
7703 
7704 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7705   FormatStyle Style = getLLVMStyleWithColumns(15);
7706   Style.ExperimentalAutoDetectBinPacking = true;
7707   EXPECT_EQ("aaa(aaaa,\n"
7708             "    aaaa,\n"
7709             "    aaaa);\n"
7710             "aaa(aaaa,\n"
7711             "    aaaa,\n"
7712             "    aaaa);",
7713             format("aaa(aaaa,\n" // one-per-line
7714                    "  aaaa,\n"
7715                    "    aaaa  );\n"
7716                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7717                    Style));
7718   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7719             "    aaaa);\n"
7720             "aaa(aaaa, aaaa,\n"
7721             "    aaaa);",
7722             format("aaa(aaaa,  aaaa,\n" // bin-packed
7723                    "    aaaa  );\n"
7724                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7725                    Style));
7726 }
7727 
7728 TEST_F(FormatTest, FormatsBuilderPattern) {
7729   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7730                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7731                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7732                "    .StartsWith(\".init\", ORDER_INIT)\n"
7733                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7734                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7735                "    .Default(ORDER_TEXT);\n");
7736 
7737   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7738                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7739   verifyFormat("aaaaaaa->aaaaaaa\n"
7740                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7741                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7742                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7743   verifyFormat(
7744       "aaaaaaa->aaaaaaa\n"
7745       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7746       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7747   verifyFormat(
7748       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7749       "    aaaaaaaaaaaaaa);");
7750   verifyFormat(
7751       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7752       "    aaaaaa->aaaaaaaaaaaa()\n"
7753       "        ->aaaaaaaaaaaaaaaa(\n"
7754       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7755       "        ->aaaaaaaaaaaaaaaaa();");
7756   verifyGoogleFormat(
7757       "void f() {\n"
7758       "  someo->Add((new util::filetools::Handler(dir))\n"
7759       "                 ->OnEvent1(NewPermanentCallback(\n"
7760       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7761       "                 ->OnEvent2(NewPermanentCallback(\n"
7762       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7763       "                 ->OnEvent3(NewPermanentCallback(\n"
7764       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7765       "                 ->OnEvent5(NewPermanentCallback(\n"
7766       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7767       "                 ->OnEvent6(NewPermanentCallback(\n"
7768       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7769       "}");
7770 
7771   verifyFormat(
7772       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7773   verifyFormat("aaaaaaaaaaaaaaa()\n"
7774                "    .aaaaaaaaaaaaaaa()\n"
7775                "    .aaaaaaaaaaaaaaa()\n"
7776                "    .aaaaaaaaaaaaaaa()\n"
7777                "    .aaaaaaaaaaaaaaa();");
7778   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7779                "    .aaaaaaaaaaaaaaa()\n"
7780                "    .aaaaaaaaaaaaaaa()\n"
7781                "    .aaaaaaaaaaaaaaa();");
7782   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7783                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7784                "    .aaaaaaaaaaaaaaa();");
7785   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7786                "    ->aaaaaaaaaaaaaae(0)\n"
7787                "    ->aaaaaaaaaaaaaaa();");
7788 
7789   // Don't linewrap after very short segments.
7790   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7791                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7792                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7793   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7794                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7795                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7796   verifyFormat("aaa()\n"
7797                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7798                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7799                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7800 
7801   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7802                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7803                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7804   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7805                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7806                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7807 
7808   // Prefer not to break after empty parentheses.
7809   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7810                "    First->LastNewlineOffset);");
7811 
7812   // Prefer not to create "hanging" indents.
7813   verifyFormat(
7814       "return !soooooooooooooome_map\n"
7815       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7816       "            .second;");
7817   verifyFormat(
7818       "return aaaaaaaaaaaaaaaa\n"
7819       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7820       "    .aaaa(aaaaaaaaaaaaaa);");
7821   // No hanging indent here.
7822   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7823                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7824   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7825                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7826   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7827                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7828                getLLVMStyleWithColumns(60));
7829   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7830                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7831                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7832                getLLVMStyleWithColumns(59));
7833   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7834                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7835                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7836 
7837   // Dont break if only closing statements before member call
7838   verifyFormat("test() {\n"
7839                "  ([]() -> {\n"
7840                "    int b = 32;\n"
7841                "    return 3;\n"
7842                "  }).foo();\n"
7843                "}");
7844   verifyFormat("test() {\n"
7845                "  (\n"
7846                "      []() -> {\n"
7847                "        int b = 32;\n"
7848                "        return 3;\n"
7849                "      },\n"
7850                "      foo, bar)\n"
7851                "      .foo();\n"
7852                "}");
7853   verifyFormat("test() {\n"
7854                "  ([]() -> {\n"
7855                "    int b = 32;\n"
7856                "    return 3;\n"
7857                "  })\n"
7858                "      .foo()\n"
7859                "      .bar();\n"
7860                "}");
7861   verifyFormat("test() {\n"
7862                "  ([]() -> {\n"
7863                "    int b = 32;\n"
7864                "    return 3;\n"
7865                "  })\n"
7866                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7867                "           \"bbbb\");\n"
7868                "}",
7869                getLLVMStyleWithColumns(30));
7870 }
7871 
7872 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7873   verifyFormat(
7874       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7875       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7876   verifyFormat(
7877       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7878       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7879 
7880   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7881                "    ccccccccccccccccccccccccc) {\n}");
7882   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7883                "    ccccccccccccccccccccccccc) {\n}");
7884 
7885   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7886                "    ccccccccccccccccccccccccc) {\n}");
7887   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7888                "    ccccccccccccccccccccccccc) {\n}");
7889 
7890   verifyFormat(
7891       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7892       "    ccccccccccccccccccccccccc) {\n}");
7893   verifyFormat(
7894       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7895       "    ccccccccccccccccccccccccc) {\n}");
7896 
7897   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7898                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7899                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7900                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7901   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7902                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7903                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7904                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7905 
7906   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7907                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7908                "    aaaaaaaaaaaaaaa != aa) {\n}");
7909   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7910                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7911                "    aaaaaaaaaaaaaaa != aa) {\n}");
7912 }
7913 
7914 TEST_F(FormatTest, BreaksAfterAssignments) {
7915   verifyFormat(
7916       "unsigned Cost =\n"
7917       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7918       "                        SI->getPointerAddressSpaceee());\n");
7919   verifyFormat(
7920       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7921       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7922 
7923   verifyFormat(
7924       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7925       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7926   verifyFormat("unsigned OriginalStartColumn =\n"
7927                "    SourceMgr.getSpellingColumnNumber(\n"
7928                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7929                "    1;");
7930 }
7931 
7932 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7933   FormatStyle Style = getLLVMStyle();
7934   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7935                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7936                Style);
7937 
7938   Style.PenaltyBreakAssignment = 20;
7939   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7940                "                                 cccccccccccccccccccccccccc;",
7941                Style);
7942 }
7943 
7944 TEST_F(FormatTest, AlignsAfterAssignments) {
7945   verifyFormat(
7946       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7947       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7948   verifyFormat(
7949       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7950       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7951   verifyFormat(
7952       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7953       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7954   verifyFormat(
7955       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7956       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7957   verifyFormat(
7958       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7959       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7960       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7961 }
7962 
7963 TEST_F(FormatTest, AlignsAfterReturn) {
7964   verifyFormat(
7965       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7966       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7967   verifyFormat(
7968       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7969       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7970   verifyFormat(
7971       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7972       "       aaaaaaaaaaaaaaaaaaaaaa();");
7973   verifyFormat(
7974       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7975       "        aaaaaaaaaaaaaaaaaaaaaa());");
7976   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7977                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7978   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7979                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7980                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7981   verifyFormat("return\n"
7982                "    // true if code is one of a or b.\n"
7983                "    code == a || code == b;");
7984 }
7985 
7986 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7987   verifyFormat(
7988       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7989       "                                                aaaaaaaaa aaaaaaa) {}");
7990   verifyFormat(
7991       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7992       "                                               aaaaaaaaaaa aaaaaaaaa);");
7993   verifyFormat(
7994       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7995       "                                             aaaaaaaaaaaaaaaaaaaaa));");
7996   FormatStyle Style = getLLVMStyle();
7997   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7998   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7999                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
8000                Style);
8001   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8002                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
8003                Style);
8004   verifyFormat("SomeLongVariableName->someFunction(\n"
8005                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
8006                Style);
8007   verifyFormat(
8008       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
8009       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8010       Style);
8011   verifyFormat(
8012       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
8013       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8014       Style);
8015   verifyFormat(
8016       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
8017       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8018       Style);
8019 
8020   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
8021                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
8022                "        b));",
8023                Style);
8024 
8025   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8026   Style.BinPackArguments = false;
8027   Style.BinPackParameters = false;
8028   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8029                "    aaaaaaaaaaa aaaaaaaa,\n"
8030                "    aaaaaaaaa aaaaaaa,\n"
8031                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8032                Style);
8033   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8034                "    aaaaaaaaaaa aaaaaaaaa,\n"
8035                "    aaaaaaaaaaa aaaaaaaaa,\n"
8036                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8037                Style);
8038   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
8039                "    aaaaaaaaaaaaaaa,\n"
8040                "    aaaaaaaaaaaaaaaaaaaaa,\n"
8041                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8042                Style);
8043   verifyFormat(
8044       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
8045       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8046       Style);
8047   verifyFormat(
8048       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
8049       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8050       Style);
8051   verifyFormat(
8052       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8053       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8054       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
8055       "    aaaaaaaaaaaaaaaa);",
8056       Style);
8057   verifyFormat(
8058       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8059       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8060       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
8061       "    aaaaaaaaaaaaaaaa);",
8062       Style);
8063 }
8064 
8065 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
8066   FormatStyle Style = getLLVMStyleWithColumns(40);
8067   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8068                "          bbbbbbbbbbbbbbbbbbbbbb);",
8069                Style);
8070   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
8071   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8072   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8073                "          bbbbbbbbbbbbbbbbbbbbbb);",
8074                Style);
8075   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8076   Style.AlignOperands = FormatStyle::OAS_Align;
8077   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8078                "          bbbbbbbbbbbbbbbbbbbbbb);",
8079                Style);
8080   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8081   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8082   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8083                "    bbbbbbbbbbbbbbbbbbbbbb);",
8084                Style);
8085 }
8086 
8087 TEST_F(FormatTest, BreaksConditionalExpressions) {
8088   verifyFormat(
8089       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8090       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8091       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8092   verifyFormat(
8093       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8094       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8095       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8096   verifyFormat(
8097       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8098       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8099   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
8100                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8101                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8102   verifyFormat(
8103       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
8104       "                                                    : aaaaaaaaaaaaa);");
8105   verifyFormat(
8106       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8107       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8108       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8109       "                   aaaaaaaaaaaaa);");
8110   verifyFormat(
8111       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8112       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8113       "                   aaaaaaaaaaaaa);");
8114   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8115                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8116                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8117                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8118                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8119   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8120                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8121                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8122                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8123                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8124                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8125                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8126   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8127                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8128                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8129                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8130                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8131   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8132                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8133                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8134   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8135                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8136                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8137                "        : aaaaaaaaaaaaaaaa;");
8138   verifyFormat(
8139       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8140       "    ? aaaaaaaaaaaaaaa\n"
8141       "    : aaaaaaaaaaaaaaa;");
8142   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8143                "          aaaaaaaaa\n"
8144                "      ? b\n"
8145                "      : c);");
8146   verifyFormat("return aaaa == bbbb\n"
8147                "           // comment\n"
8148                "           ? aaaa\n"
8149                "           : bbbb;");
8150   verifyFormat("unsigned Indent =\n"
8151                "    format(TheLine.First,\n"
8152                "           IndentForLevel[TheLine.Level] >= 0\n"
8153                "               ? IndentForLevel[TheLine.Level]\n"
8154                "               : TheLine * 2,\n"
8155                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8156                getLLVMStyleWithColumns(60));
8157   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8158                "                  ? aaaaaaaaaaaaaaa\n"
8159                "                  : bbbbbbbbbbbbbbb //\n"
8160                "                        ? ccccccccccccccc\n"
8161                "                        : ddddddddddddddd;");
8162   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8163                "                  ? aaaaaaaaaaaaaaa\n"
8164                "                  : (bbbbbbbbbbbbbbb //\n"
8165                "                         ? ccccccccccccccc\n"
8166                "                         : ddddddddddddddd);");
8167   verifyFormat(
8168       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8169       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8170       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
8171       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
8172       "                                      : aaaaaaaaaa;");
8173   verifyFormat(
8174       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8175       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
8176       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8177 
8178   FormatStyle NoBinPacking = getLLVMStyle();
8179   NoBinPacking.BinPackArguments = false;
8180   verifyFormat(
8181       "void f() {\n"
8182       "  g(aaa,\n"
8183       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8184       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8185       "        ? aaaaaaaaaaaaaaa\n"
8186       "        : aaaaaaaaaaaaaaa);\n"
8187       "}",
8188       NoBinPacking);
8189   verifyFormat(
8190       "void f() {\n"
8191       "  g(aaa,\n"
8192       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8193       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8194       "        ?: aaaaaaaaaaaaaaa);\n"
8195       "}",
8196       NoBinPacking);
8197 
8198   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
8199                "             // comment.\n"
8200                "             ccccccccccccccccccccccccccccccccccccccc\n"
8201                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8202                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
8203 
8204   // Assignments in conditional expressions. Apparently not uncommon :-(.
8205   verifyFormat("return a != b\n"
8206                "           // comment\n"
8207                "           ? a = b\n"
8208                "           : a = b;");
8209   verifyFormat("return a != b\n"
8210                "           // comment\n"
8211                "           ? a = a != b\n"
8212                "                     // comment\n"
8213                "                     ? a = b\n"
8214                "                     : a\n"
8215                "           : a;\n");
8216   verifyFormat("return a != b\n"
8217                "           // comment\n"
8218                "           ? a\n"
8219                "           : a = a != b\n"
8220                "                     // comment\n"
8221                "                     ? a = b\n"
8222                "                     : a;");
8223 
8224   // Chained conditionals
8225   FormatStyle Style = getLLVMStyleWithColumns(70);
8226   Style.AlignOperands = FormatStyle::OAS_Align;
8227   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8228                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8229                "                        : 3333333333333333;",
8230                Style);
8231   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8232                "       : bbbbbbbbbb     ? 2222222222222222\n"
8233                "                        : 3333333333333333;",
8234                Style);
8235   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
8236                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
8237                "                          : 3333333333333333;",
8238                Style);
8239   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8240                "       : bbbbbbbbbbbbbb ? 222222\n"
8241                "                        : 333333;",
8242                Style);
8243   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8244                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8245                "       : cccccccccccccc ? 3333333333333333\n"
8246                "                        : 4444444444444444;",
8247                Style);
8248   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
8249                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8250                "                        : 3333333333333333;",
8251                Style);
8252   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8253                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8254                "                        : (aaa ? bbb : ccc);",
8255                Style);
8256   verifyFormat(
8257       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8258       "                                             : cccccccccccccccccc)\n"
8259       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8260       "                        : 3333333333333333;",
8261       Style);
8262   verifyFormat(
8263       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8264       "                                             : cccccccccccccccccc)\n"
8265       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8266       "                        : 3333333333333333;",
8267       Style);
8268   verifyFormat(
8269       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8270       "                                             : dddddddddddddddddd)\n"
8271       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8272       "                        : 3333333333333333;",
8273       Style);
8274   verifyFormat(
8275       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8276       "                                             : dddddddddddddddddd)\n"
8277       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8278       "                        : 3333333333333333;",
8279       Style);
8280   verifyFormat(
8281       "return aaaaaaaaa        ? 1111111111111111\n"
8282       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8283       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8284       "                                             : dddddddddddddddddd)\n",
8285       Style);
8286   verifyFormat(
8287       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8288       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8289       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8290       "                                             : cccccccccccccccccc);",
8291       Style);
8292   verifyFormat(
8293       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8294       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8295       "                                             : eeeeeeeeeeeeeeeeee)\n"
8296       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8297       "                        : 3333333333333333;",
8298       Style);
8299   verifyFormat(
8300       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
8301       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8302       "                                             : eeeeeeeeeeeeeeeeee)\n"
8303       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8304       "                        : 3333333333333333;",
8305       Style);
8306   verifyFormat(
8307       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8308       "                           : cccccccccccc    ? dddddddddddddddddd\n"
8309       "                                             : eeeeeeeeeeeeeeeeee)\n"
8310       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8311       "                        : 3333333333333333;",
8312       Style);
8313   verifyFormat(
8314       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8315       "                                             : cccccccccccccccccc\n"
8316       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8317       "                        : 3333333333333333;",
8318       Style);
8319   verifyFormat(
8320       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8321       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
8322       "                                             : eeeeeeeeeeeeeeeeee\n"
8323       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8324       "                        : 3333333333333333;",
8325       Style);
8326   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
8327                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
8328                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
8329                "                                   : eeeeeeeeeeeeeeeeee)\n"
8330                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8331                "                             : 3333333333333333;",
8332                Style);
8333   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
8334                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8335                "             : cccccccccccccccc ? dddddddddddddddddd\n"
8336                "                                : eeeeeeeeeeeeeeeeee\n"
8337                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8338                "                                 : 3333333333333333;",
8339                Style);
8340 
8341   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8342   Style.BreakBeforeTernaryOperators = false;
8343   // FIXME: Aligning the question marks is weird given DontAlign.
8344   // Consider disabling this alignment in this case. Also check whether this
8345   // will render the adjustment from https://reviews.llvm.org/D82199
8346   // unnecessary.
8347   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
8348                "    bbbb                ? cccccccccccccccccc :\n"
8349                "                          ddddd;\n",
8350                Style);
8351 
8352   EXPECT_EQ(
8353       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8354       "    /*\n"
8355       "     */\n"
8356       "    function() {\n"
8357       "      try {\n"
8358       "        return JJJJJJJJJJJJJJ(\n"
8359       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8360       "      }\n"
8361       "    } :\n"
8362       "    function() {};",
8363       format(
8364           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8365           "     /*\n"
8366           "      */\n"
8367           "     function() {\n"
8368           "      try {\n"
8369           "        return JJJJJJJJJJJJJJ(\n"
8370           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8371           "      }\n"
8372           "    } :\n"
8373           "    function() {};",
8374           getGoogleStyle(FormatStyle::LK_JavaScript)));
8375 }
8376 
8377 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
8378   FormatStyle Style = getLLVMStyleWithColumns(70);
8379   Style.BreakBeforeTernaryOperators = false;
8380   verifyFormat(
8381       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8382       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8383       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8384       Style);
8385   verifyFormat(
8386       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8387       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8388       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8389       Style);
8390   verifyFormat(
8391       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8392       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8393       Style);
8394   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
8395                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8396                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8397                Style);
8398   verifyFormat(
8399       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
8400       "                                                      aaaaaaaaaaaaa);",
8401       Style);
8402   verifyFormat(
8403       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8404       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8405       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8406       "                   aaaaaaaaaaaaa);",
8407       Style);
8408   verifyFormat(
8409       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8410       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8411       "                   aaaaaaaaaaaaa);",
8412       Style);
8413   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8414                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8415                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8416                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8417                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8418                Style);
8419   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8420                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8421                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8422                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8423                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8424                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8425                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8426                Style);
8427   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8428                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
8429                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8430                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8431                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8432                Style);
8433   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8434                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8435                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8436                Style);
8437   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8438                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8439                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8440                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8441                Style);
8442   verifyFormat(
8443       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8444       "    aaaaaaaaaaaaaaa :\n"
8445       "    aaaaaaaaaaaaaaa;",
8446       Style);
8447   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8448                "          aaaaaaaaa ?\n"
8449                "      b :\n"
8450                "      c);",
8451                Style);
8452   verifyFormat("unsigned Indent =\n"
8453                "    format(TheLine.First,\n"
8454                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
8455                "               IndentForLevel[TheLine.Level] :\n"
8456                "               TheLine * 2,\n"
8457                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8458                Style);
8459   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8460                "                  aaaaaaaaaaaaaaa :\n"
8461                "                  bbbbbbbbbbbbbbb ? //\n"
8462                "                      ccccccccccccccc :\n"
8463                "                      ddddddddddddddd;",
8464                Style);
8465   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8466                "                  aaaaaaaaaaaaaaa :\n"
8467                "                  (bbbbbbbbbbbbbbb ? //\n"
8468                "                       ccccccccccccccc :\n"
8469                "                       ddddddddddddddd);",
8470                Style);
8471   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8472                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
8473                "            ccccccccccccccccccccccccccc;",
8474                Style);
8475   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8476                "           aaaaa :\n"
8477                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
8478                Style);
8479 
8480   // Chained conditionals
8481   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8482                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8483                "                          3333333333333333;",
8484                Style);
8485   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8486                "       bbbbbbbbbb       ? 2222222222222222 :\n"
8487                "                          3333333333333333;",
8488                Style);
8489   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
8490                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8491                "                          3333333333333333;",
8492                Style);
8493   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8494                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
8495                "                          333333;",
8496                Style);
8497   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8498                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8499                "       cccccccccccccccc ? 3333333333333333 :\n"
8500                "                          4444444444444444;",
8501                Style);
8502   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
8503                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8504                "                          3333333333333333;",
8505                Style);
8506   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8507                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8508                "                          (aaa ? bbb : ccc);",
8509                Style);
8510   verifyFormat(
8511       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8512       "                                               cccccccccccccccccc) :\n"
8513       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8514       "                          3333333333333333;",
8515       Style);
8516   verifyFormat(
8517       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8518       "                                               cccccccccccccccccc) :\n"
8519       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8520       "                          3333333333333333;",
8521       Style);
8522   verifyFormat(
8523       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8524       "                                               dddddddddddddddddd) :\n"
8525       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8526       "                          3333333333333333;",
8527       Style);
8528   verifyFormat(
8529       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8530       "                                               dddddddddddddddddd) :\n"
8531       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8532       "                          3333333333333333;",
8533       Style);
8534   verifyFormat(
8535       "return aaaaaaaaa        ? 1111111111111111 :\n"
8536       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8537       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8538       "                                               dddddddddddddddddd)\n",
8539       Style);
8540   verifyFormat(
8541       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8542       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8543       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8544       "                                               cccccccccccccccccc);",
8545       Style);
8546   verifyFormat(
8547       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8548       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8549       "                                               eeeeeeeeeeeeeeeeee) :\n"
8550       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8551       "                          3333333333333333;",
8552       Style);
8553   verifyFormat(
8554       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8555       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8556       "                                               eeeeeeeeeeeeeeeeee) :\n"
8557       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8558       "                          3333333333333333;",
8559       Style);
8560   verifyFormat(
8561       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8562       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8563       "                                               eeeeeeeeeeeeeeeeee) :\n"
8564       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8565       "                          3333333333333333;",
8566       Style);
8567   verifyFormat(
8568       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8569       "                                               cccccccccccccccccc :\n"
8570       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8571       "                          3333333333333333;",
8572       Style);
8573   verifyFormat(
8574       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8575       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8576       "                                               eeeeeeeeeeeeeeeeee :\n"
8577       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8578       "                          3333333333333333;",
8579       Style);
8580   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8581                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8582                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8583                "                                 eeeeeeeeeeeeeeeeee) :\n"
8584                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8585                "                               3333333333333333;",
8586                Style);
8587   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8588                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8589                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8590                "                                  eeeeeeeeeeeeeeeeee :\n"
8591                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8592                "                               3333333333333333;",
8593                Style);
8594 }
8595 
8596 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8597   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8598                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8599   verifyFormat("bool a = true, b = false;");
8600 
8601   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8602                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8603                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8604                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8605   verifyFormat(
8606       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8607       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8608       "     d = e && f;");
8609   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8610                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8611   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8612                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8613   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8614                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8615 
8616   FormatStyle Style = getGoogleStyle();
8617   Style.PointerAlignment = FormatStyle::PAS_Left;
8618   Style.DerivePointerAlignment = false;
8619   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8620                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8621                "    *b = bbbbbbbbbbbbbbbbbbb;",
8622                Style);
8623   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8624                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8625                Style);
8626   verifyFormat("vector<int*> a, b;", Style);
8627   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8628   verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style);
8629   verifyFormat("if (int *p, *q; p != q) {\n  p = p->next;\n}", Style);
8630   verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n  p = p->next;\n}",
8631                Style);
8632   verifyFormat("switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8633                Style);
8634   verifyFormat(
8635       "/*comment*/ switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8636       Style);
8637 
8638   verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style);
8639   verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style);
8640   verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style);
8641   verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style);
8642   verifyFormat("switch ([](int* p, int* q) {}()) {\n  default:\n    break;\n}",
8643                Style);
8644 }
8645 
8646 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8647   verifyFormat("arr[foo ? bar : baz];");
8648   verifyFormat("f()[foo ? bar : baz];");
8649   verifyFormat("(a + b)[foo ? bar : baz];");
8650   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8651 }
8652 
8653 TEST_F(FormatTest, AlignsStringLiterals) {
8654   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8655                "                                      \"short literal\");");
8656   verifyFormat(
8657       "looooooooooooooooooooooooongFunction(\n"
8658       "    \"short literal\"\n"
8659       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8660   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8661                "             \" string literals\",\n"
8662                "             and, other, parameters);");
8663   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8664             "      \"5678\";",
8665             format("fun + \"1243\" /* comment */\n"
8666                    "    \"5678\";",
8667                    getLLVMStyleWithColumns(28)));
8668   EXPECT_EQ(
8669       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8670       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8671       "         \"aaaaaaaaaaaaaaaa\";",
8672       format("aaaaaa ="
8673              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8674              "aaaaaaaaaaaaaaaaaaaaa\" "
8675              "\"aaaaaaaaaaaaaaaa\";"));
8676   verifyFormat("a = a + \"a\"\n"
8677                "        \"a\"\n"
8678                "        \"a\";");
8679   verifyFormat("f(\"a\", \"b\"\n"
8680                "       \"c\");");
8681 
8682   verifyFormat(
8683       "#define LL_FORMAT \"ll\"\n"
8684       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8685       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8686 
8687   verifyFormat("#define A(X)          \\\n"
8688                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8689                "  \"ccccc\"",
8690                getLLVMStyleWithColumns(23));
8691   verifyFormat("#define A \"def\"\n"
8692                "f(\"abc\" A \"ghi\"\n"
8693                "  \"jkl\");");
8694 
8695   verifyFormat("f(L\"a\"\n"
8696                "  L\"b\");");
8697   verifyFormat("#define A(X)            \\\n"
8698                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8699                "  L\"ccccc\"",
8700                getLLVMStyleWithColumns(25));
8701 
8702   verifyFormat("f(@\"a\"\n"
8703                "  @\"b\");");
8704   verifyFormat("NSString s = @\"a\"\n"
8705                "             @\"b\"\n"
8706                "             @\"c\";");
8707   verifyFormat("NSString s = @\"a\"\n"
8708                "              \"b\"\n"
8709                "              \"c\";");
8710 }
8711 
8712 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8713   FormatStyle Style = getLLVMStyle();
8714   // No declarations or definitions should be moved to own line.
8715   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8716   verifyFormat("class A {\n"
8717                "  int f() { return 1; }\n"
8718                "  int g();\n"
8719                "};\n"
8720                "int f() { return 1; }\n"
8721                "int g();\n",
8722                Style);
8723 
8724   // All declarations and definitions should have the return type moved to its
8725   // own line.
8726   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8727   Style.TypenameMacros = {"LIST"};
8728   verifyFormat("SomeType\n"
8729                "funcdecl(LIST(uint64_t));",
8730                Style);
8731   verifyFormat("class E {\n"
8732                "  int\n"
8733                "  f() {\n"
8734                "    return 1;\n"
8735                "  }\n"
8736                "  int\n"
8737                "  g();\n"
8738                "};\n"
8739                "int\n"
8740                "f() {\n"
8741                "  return 1;\n"
8742                "}\n"
8743                "int\n"
8744                "g();\n",
8745                Style);
8746 
8747   // Top-level definitions, and no kinds of declarations should have the
8748   // return type moved to its own line.
8749   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8750   verifyFormat("class B {\n"
8751                "  int f() { return 1; }\n"
8752                "  int g();\n"
8753                "};\n"
8754                "int\n"
8755                "f() {\n"
8756                "  return 1;\n"
8757                "}\n"
8758                "int g();\n",
8759                Style);
8760 
8761   // Top-level definitions and declarations should have the return type moved
8762   // to its own line.
8763   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8764   verifyFormat("class C {\n"
8765                "  int f() { return 1; }\n"
8766                "  int g();\n"
8767                "};\n"
8768                "int\n"
8769                "f() {\n"
8770                "  return 1;\n"
8771                "}\n"
8772                "int\n"
8773                "g();\n",
8774                Style);
8775 
8776   // All definitions should have the return type moved to its own line, but no
8777   // kinds of declarations.
8778   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8779   verifyFormat("class D {\n"
8780                "  int\n"
8781                "  f() {\n"
8782                "    return 1;\n"
8783                "  }\n"
8784                "  int g();\n"
8785                "};\n"
8786                "int\n"
8787                "f() {\n"
8788                "  return 1;\n"
8789                "}\n"
8790                "int g();\n",
8791                Style);
8792   verifyFormat("const char *\n"
8793                "f(void) {\n" // Break here.
8794                "  return \"\";\n"
8795                "}\n"
8796                "const char *bar(void);\n", // No break here.
8797                Style);
8798   verifyFormat("template <class T>\n"
8799                "T *\n"
8800                "f(T &c) {\n" // Break here.
8801                "  return NULL;\n"
8802                "}\n"
8803                "template <class T> T *f(T &c);\n", // No break here.
8804                Style);
8805   verifyFormat("class C {\n"
8806                "  int\n"
8807                "  operator+() {\n"
8808                "    return 1;\n"
8809                "  }\n"
8810                "  int\n"
8811                "  operator()() {\n"
8812                "    return 1;\n"
8813                "  }\n"
8814                "};\n",
8815                Style);
8816   verifyFormat("void\n"
8817                "A::operator()() {}\n"
8818                "void\n"
8819                "A::operator>>() {}\n"
8820                "void\n"
8821                "A::operator+() {}\n"
8822                "void\n"
8823                "A::operator*() {}\n"
8824                "void\n"
8825                "A::operator->() {}\n"
8826                "void\n"
8827                "A::operator void *() {}\n"
8828                "void\n"
8829                "A::operator void &() {}\n"
8830                "void\n"
8831                "A::operator void &&() {}\n"
8832                "void\n"
8833                "A::operator char *() {}\n"
8834                "void\n"
8835                "A::operator[]() {}\n"
8836                "void\n"
8837                "A::operator!() {}\n"
8838                "void\n"
8839                "A::operator**() {}\n"
8840                "void\n"
8841                "A::operator<Foo> *() {}\n"
8842                "void\n"
8843                "A::operator<Foo> **() {}\n"
8844                "void\n"
8845                "A::operator<Foo> &() {}\n"
8846                "void\n"
8847                "A::operator void **() {}\n",
8848                Style);
8849   verifyFormat("constexpr auto\n"
8850                "operator()() const -> reference {}\n"
8851                "constexpr auto\n"
8852                "operator>>() const -> reference {}\n"
8853                "constexpr auto\n"
8854                "operator+() const -> reference {}\n"
8855                "constexpr auto\n"
8856                "operator*() const -> reference {}\n"
8857                "constexpr auto\n"
8858                "operator->() const -> reference {}\n"
8859                "constexpr auto\n"
8860                "operator++() const -> reference {}\n"
8861                "constexpr auto\n"
8862                "operator void *() const -> reference {}\n"
8863                "constexpr auto\n"
8864                "operator void **() const -> reference {}\n"
8865                "constexpr auto\n"
8866                "operator void *() const -> reference {}\n"
8867                "constexpr auto\n"
8868                "operator void &() const -> reference {}\n"
8869                "constexpr auto\n"
8870                "operator void &&() const -> reference {}\n"
8871                "constexpr auto\n"
8872                "operator char *() const -> reference {}\n"
8873                "constexpr auto\n"
8874                "operator!() const -> reference {}\n"
8875                "constexpr auto\n"
8876                "operator[]() const -> reference {}\n",
8877                Style);
8878   verifyFormat("void *operator new(std::size_t s);", // No break here.
8879                Style);
8880   verifyFormat("void *\n"
8881                "operator new(std::size_t s) {}",
8882                Style);
8883   verifyFormat("void *\n"
8884                "operator delete[](void *ptr) {}",
8885                Style);
8886   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8887   verifyFormat("const char *\n"
8888                "f(void)\n" // Break here.
8889                "{\n"
8890                "  return \"\";\n"
8891                "}\n"
8892                "const char *bar(void);\n", // No break here.
8893                Style);
8894   verifyFormat("template <class T>\n"
8895                "T *\n"     // Problem here: no line break
8896                "f(T &c)\n" // Break here.
8897                "{\n"
8898                "  return NULL;\n"
8899                "}\n"
8900                "template <class T> T *f(T &c);\n", // No break here.
8901                Style);
8902   verifyFormat("int\n"
8903                "foo(A<bool> a)\n"
8904                "{\n"
8905                "  return a;\n"
8906                "}\n",
8907                Style);
8908   verifyFormat("int\n"
8909                "foo(A<8> a)\n"
8910                "{\n"
8911                "  return a;\n"
8912                "}\n",
8913                Style);
8914   verifyFormat("int\n"
8915                "foo(A<B<bool>, 8> a)\n"
8916                "{\n"
8917                "  return a;\n"
8918                "}\n",
8919                Style);
8920   verifyFormat("int\n"
8921                "foo(A<B<8>, bool> a)\n"
8922                "{\n"
8923                "  return a;\n"
8924                "}\n",
8925                Style);
8926   verifyFormat("int\n"
8927                "foo(A<B<bool>, bool> a)\n"
8928                "{\n"
8929                "  return a;\n"
8930                "}\n",
8931                Style);
8932   verifyFormat("int\n"
8933                "foo(A<B<8>, 8> a)\n"
8934                "{\n"
8935                "  return a;\n"
8936                "}\n",
8937                Style);
8938 
8939   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8940   Style.BraceWrapping.AfterFunction = true;
8941   verifyFormat("int f(i);\n" // No break here.
8942                "int\n"       // Break here.
8943                "f(i)\n"
8944                "{\n"
8945                "  return i + 1;\n"
8946                "}\n"
8947                "int\n" // Break here.
8948                "f(i)\n"
8949                "{\n"
8950                "  return i + 1;\n"
8951                "};",
8952                Style);
8953   verifyFormat("int f(a, b, c);\n" // No break here.
8954                "int\n"             // Break here.
8955                "f(a, b, c)\n"      // Break here.
8956                "short a, b;\n"
8957                "float c;\n"
8958                "{\n"
8959                "  return a + b < c;\n"
8960                "}\n"
8961                "int\n"        // Break here.
8962                "f(a, b, c)\n" // Break here.
8963                "short a, b;\n"
8964                "float c;\n"
8965                "{\n"
8966                "  return a + b < c;\n"
8967                "};",
8968                Style);
8969   verifyFormat("byte *\n" // Break here.
8970                "f(a)\n"   // Break here.
8971                "byte a[];\n"
8972                "{\n"
8973                "  return a;\n"
8974                "}",
8975                Style);
8976   verifyFormat("bool f(int a, int) override;\n"
8977                "Bar g(int a, Bar) final;\n"
8978                "Bar h(a, Bar) final;",
8979                Style);
8980   verifyFormat("int\n"
8981                "f(a)",
8982                Style);
8983   verifyFormat("bool\n"
8984                "f(size_t = 0, bool b = false)\n"
8985                "{\n"
8986                "  return !b;\n"
8987                "}",
8988                Style);
8989 
8990   // The return breaking style doesn't affect:
8991   // * function and object definitions with attribute-like macros
8992   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8993                "    ABSL_GUARDED_BY(mutex) = {};",
8994                getGoogleStyleWithColumns(40));
8995   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8996                "    ABSL_GUARDED_BY(mutex);  // comment",
8997                getGoogleStyleWithColumns(40));
8998   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8999                "    ABSL_GUARDED_BY(mutex1)\n"
9000                "        ABSL_GUARDED_BY(mutex2);",
9001                getGoogleStyleWithColumns(40));
9002   verifyFormat("Tttttt f(int a, int b)\n"
9003                "    ABSL_GUARDED_BY(mutex1)\n"
9004                "        ABSL_GUARDED_BY(mutex2);",
9005                getGoogleStyleWithColumns(40));
9006   // * typedefs
9007   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
9008 
9009   Style = getGNUStyle();
9010 
9011   // Test for comments at the end of function declarations.
9012   verifyFormat("void\n"
9013                "foo (int a, /*abc*/ int b) // def\n"
9014                "{\n"
9015                "}\n",
9016                Style);
9017 
9018   verifyFormat("void\n"
9019                "foo (int a, /* abc */ int b) /* def */\n"
9020                "{\n"
9021                "}\n",
9022                Style);
9023 
9024   // Definitions that should not break after return type
9025   verifyFormat("void foo (int a, int b); // def\n", Style);
9026   verifyFormat("void foo (int a, int b); /* def */\n", Style);
9027   verifyFormat("void foo (int a, int b);\n", Style);
9028 }
9029 
9030 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
9031   FormatStyle NoBreak = getLLVMStyle();
9032   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
9033   FormatStyle Break = getLLVMStyle();
9034   Break.AlwaysBreakBeforeMultilineStrings = true;
9035   verifyFormat("aaaa = \"bbbb\"\n"
9036                "       \"cccc\";",
9037                NoBreak);
9038   verifyFormat("aaaa =\n"
9039                "    \"bbbb\"\n"
9040                "    \"cccc\";",
9041                Break);
9042   verifyFormat("aaaa(\"bbbb\"\n"
9043                "     \"cccc\");",
9044                NoBreak);
9045   verifyFormat("aaaa(\n"
9046                "    \"bbbb\"\n"
9047                "    \"cccc\");",
9048                Break);
9049   verifyFormat("aaaa(qqq, \"bbbb\"\n"
9050                "          \"cccc\");",
9051                NoBreak);
9052   verifyFormat("aaaa(qqq,\n"
9053                "     \"bbbb\"\n"
9054                "     \"cccc\");",
9055                Break);
9056   verifyFormat("aaaa(qqq,\n"
9057                "     L\"bbbb\"\n"
9058                "     L\"cccc\");",
9059                Break);
9060   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
9061                "                      \"bbbb\"));",
9062                Break);
9063   verifyFormat("string s = someFunction(\n"
9064                "    \"abc\"\n"
9065                "    \"abc\");",
9066                Break);
9067 
9068   // As we break before unary operators, breaking right after them is bad.
9069   verifyFormat("string foo = abc ? \"x\"\n"
9070                "                   \"blah blah blah blah blah blah\"\n"
9071                "                 : \"y\";",
9072                Break);
9073 
9074   // Don't break if there is no column gain.
9075   verifyFormat("f(\"aaaa\"\n"
9076                "  \"bbbb\");",
9077                Break);
9078 
9079   // Treat literals with escaped newlines like multi-line string literals.
9080   EXPECT_EQ("x = \"a\\\n"
9081             "b\\\n"
9082             "c\";",
9083             format("x = \"a\\\n"
9084                    "b\\\n"
9085                    "c\";",
9086                    NoBreak));
9087   EXPECT_EQ("xxxx =\n"
9088             "    \"a\\\n"
9089             "b\\\n"
9090             "c\";",
9091             format("xxxx = \"a\\\n"
9092                    "b\\\n"
9093                    "c\";",
9094                    Break));
9095 
9096   EXPECT_EQ("NSString *const kString =\n"
9097             "    @\"aaaa\"\n"
9098             "    @\"bbbb\";",
9099             format("NSString *const kString = @\"aaaa\"\n"
9100                    "@\"bbbb\";",
9101                    Break));
9102 
9103   Break.ColumnLimit = 0;
9104   verifyFormat("const char *hello = \"hello llvm\";", Break);
9105 }
9106 
9107 TEST_F(FormatTest, AlignsPipes) {
9108   verifyFormat(
9109       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9110       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9111       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9112   verifyFormat(
9113       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
9114       "                     << aaaaaaaaaaaaaaaaaaaa;");
9115   verifyFormat(
9116       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9117       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9118   verifyFormat(
9119       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
9120       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9121   verifyFormat(
9122       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
9123       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
9124       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
9125   verifyFormat(
9126       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9127       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9128       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9129   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9130                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9131                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9132                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9133   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
9134                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
9135   verifyFormat(
9136       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9137       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9138   verifyFormat(
9139       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
9140       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
9141 
9142   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
9143                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
9144   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9145                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9146                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
9147                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
9148   verifyFormat("LOG_IF(aaa == //\n"
9149                "       bbb)\n"
9150                "    << a << b;");
9151 
9152   // But sometimes, breaking before the first "<<" is desirable.
9153   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9154                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
9155   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
9156                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9157                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9158   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
9159                "    << BEF << IsTemplate << Description << E->getType();");
9160   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9161                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9162                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9163   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9164                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9165                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9166                "    << aaa;");
9167 
9168   verifyFormat(
9169       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9170       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9171 
9172   // Incomplete string literal.
9173   EXPECT_EQ("llvm::errs() << \"\n"
9174             "             << a;",
9175             format("llvm::errs() << \"\n<<a;"));
9176 
9177   verifyFormat("void f() {\n"
9178                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
9179                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
9180                "}");
9181 
9182   // Handle 'endl'.
9183   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
9184                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9185   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9186 
9187   // Handle '\n'.
9188   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
9189                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9190   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
9191                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
9192   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
9193                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
9194   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9195 }
9196 
9197 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
9198   verifyFormat("return out << \"somepacket = {\\n\"\n"
9199                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
9200                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
9201                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
9202                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
9203                "           << \"}\";");
9204 
9205   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9206                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9207                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
9208   verifyFormat(
9209       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
9210       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
9211       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
9212       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
9213       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
9214   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
9215                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9216   verifyFormat(
9217       "void f() {\n"
9218       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
9219       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
9220       "}");
9221 
9222   // Breaking before the first "<<" is generally not desirable.
9223   verifyFormat(
9224       "llvm::errs()\n"
9225       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9226       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9227       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9228       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9229       getLLVMStyleWithColumns(70));
9230   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9231                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9232                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9233                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9234                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9235                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9236                getLLVMStyleWithColumns(70));
9237 
9238   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9239                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9240                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
9241   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9242                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9243                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
9244   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
9245                "           (aaaa + aaaa);",
9246                getLLVMStyleWithColumns(40));
9247   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
9248                "                  (aaaaaaa + aaaaa));",
9249                getLLVMStyleWithColumns(40));
9250   verifyFormat(
9251       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
9252       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
9253       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
9254 }
9255 
9256 TEST_F(FormatTest, UnderstandsEquals) {
9257   verifyFormat(
9258       "aaaaaaaaaaaaaaaaa =\n"
9259       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9260   verifyFormat(
9261       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9262       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9263   verifyFormat(
9264       "if (a) {\n"
9265       "  f();\n"
9266       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9267       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
9268       "}");
9269 
9270   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9271                "        100000000 + 10000000) {\n}");
9272 }
9273 
9274 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
9275   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9276                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
9277 
9278   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9279                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
9280 
9281   verifyFormat(
9282       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
9283       "                                                          Parameter2);");
9284 
9285   verifyFormat(
9286       "ShortObject->shortFunction(\n"
9287       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
9288       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
9289 
9290   verifyFormat("loooooooooooooongFunction(\n"
9291                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
9292 
9293   verifyFormat(
9294       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
9295       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
9296 
9297   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9298                "    .WillRepeatedly(Return(SomeValue));");
9299   verifyFormat("void f() {\n"
9300                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9301                "      .Times(2)\n"
9302                "      .WillRepeatedly(Return(SomeValue));\n"
9303                "}");
9304   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
9305                "    ccccccccccccccccccccccc);");
9306   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9307                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9308                "          .aaaaa(aaaaa),\n"
9309                "      aaaaaaaaaaaaaaaaaaaaa);");
9310   verifyFormat("void f() {\n"
9311                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9312                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
9313                "}");
9314   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9315                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9316                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9317                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9318                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9319   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9320                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9321                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9322                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
9323                "}");
9324 
9325   // Here, it is not necessary to wrap at "." or "->".
9326   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
9327                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9328   verifyFormat(
9329       "aaaaaaaaaaa->aaaaaaaaa(\n"
9330       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9331       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
9332 
9333   verifyFormat(
9334       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9335       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
9336   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
9337                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9338   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
9339                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9340 
9341   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9342                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9343                "    .a();");
9344 
9345   FormatStyle NoBinPacking = getLLVMStyle();
9346   NoBinPacking.BinPackParameters = false;
9347   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9348                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9349                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
9350                "                         aaaaaaaaaaaaaaaaaaa,\n"
9351                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
9352                NoBinPacking);
9353 
9354   // If there is a subsequent call, change to hanging indentation.
9355   verifyFormat(
9356       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9357       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
9358       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9359   verifyFormat(
9360       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9361       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
9362   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9363                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9364                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9365   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9366                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9367                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9368 }
9369 
9370 TEST_F(FormatTest, WrapsTemplateDeclarations) {
9371   verifyFormat("template <typename T>\n"
9372                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9373   verifyFormat("template <typename T>\n"
9374                "// T should be one of {A, B}.\n"
9375                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9376   verifyFormat(
9377       "template <typename T>\n"
9378       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
9379   verifyFormat("template <typename T>\n"
9380                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
9381                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
9382   verifyFormat(
9383       "template <typename T>\n"
9384       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
9385       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
9386   verifyFormat(
9387       "template <typename T>\n"
9388       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
9389       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
9390       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9391   verifyFormat("template <typename T>\n"
9392                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9393                "    int aaaaaaaaaaaaaaaaaaaaaa);");
9394   verifyFormat(
9395       "template <typename T1, typename T2 = char, typename T3 = char,\n"
9396       "          typename T4 = char>\n"
9397       "void f();");
9398   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
9399                "          template <typename> class cccccccccccccccccccccc,\n"
9400                "          typename ddddddddddddd>\n"
9401                "class C {};");
9402   verifyFormat(
9403       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
9404       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9405 
9406   verifyFormat("void f() {\n"
9407                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
9408                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
9409                "}");
9410 
9411   verifyFormat("template <typename T> class C {};");
9412   verifyFormat("template <typename T> void f();");
9413   verifyFormat("template <typename T> void f() {}");
9414   verifyFormat(
9415       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9416       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9417       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
9418       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9419       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9420       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
9421       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
9422       getLLVMStyleWithColumns(72));
9423   EXPECT_EQ("static_cast<A< //\n"
9424             "    B> *>(\n"
9425             "\n"
9426             ");",
9427             format("static_cast<A<//\n"
9428                    "    B>*>(\n"
9429                    "\n"
9430                    "    );"));
9431   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9432                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
9433 
9434   FormatStyle AlwaysBreak = getLLVMStyle();
9435   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9436   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
9437   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
9438   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
9439   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9440                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9441                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
9442   verifyFormat("template <template <typename> class Fooooooo,\n"
9443                "          template <typename> class Baaaaaaar>\n"
9444                "struct C {};",
9445                AlwaysBreak);
9446   verifyFormat("template <typename T> // T can be A, B or C.\n"
9447                "struct C {};",
9448                AlwaysBreak);
9449   verifyFormat("template <enum E> class A {\n"
9450                "public:\n"
9451                "  E *f();\n"
9452                "};");
9453 
9454   FormatStyle NeverBreak = getLLVMStyle();
9455   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
9456   verifyFormat("template <typename T> class C {};", NeverBreak);
9457   verifyFormat("template <typename T> void f();", NeverBreak);
9458   verifyFormat("template <typename T> void f() {}", NeverBreak);
9459   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9460                "bbbbbbbbbbbbbbbbbbbb) {}",
9461                NeverBreak);
9462   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9463                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9464                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
9465                NeverBreak);
9466   verifyFormat("template <template <typename> class Fooooooo,\n"
9467                "          template <typename> class Baaaaaaar>\n"
9468                "struct C {};",
9469                NeverBreak);
9470   verifyFormat("template <typename T> // T can be A, B or C.\n"
9471                "struct C {};",
9472                NeverBreak);
9473   verifyFormat("template <enum E> class A {\n"
9474                "public:\n"
9475                "  E *f();\n"
9476                "};",
9477                NeverBreak);
9478   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
9479   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9480                "bbbbbbbbbbbbbbbbbbbb) {}",
9481                NeverBreak);
9482 }
9483 
9484 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
9485   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9486   Style.ColumnLimit = 60;
9487   EXPECT_EQ("// Baseline - no comments.\n"
9488             "template <\n"
9489             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9490             "void f() {}",
9491             format("// Baseline - no comments.\n"
9492                    "template <\n"
9493                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9494                    "void f() {}",
9495                    Style));
9496 
9497   EXPECT_EQ("template <\n"
9498             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9499             "void f() {}",
9500             format("template <\n"
9501                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9502                    "void f() {}",
9503                    Style));
9504 
9505   EXPECT_EQ(
9506       "template <\n"
9507       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
9508       "void f() {}",
9509       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
9510              "void f() {}",
9511              Style));
9512 
9513   EXPECT_EQ(
9514       "template <\n"
9515       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9516       "                                               // multiline\n"
9517       "void f() {}",
9518       format("template <\n"
9519              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9520              "                                              // multiline\n"
9521              "void f() {}",
9522              Style));
9523 
9524   EXPECT_EQ(
9525       "template <typename aaaaaaaaaa<\n"
9526       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
9527       "void f() {}",
9528       format(
9529           "template <\n"
9530           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
9531           "void f() {}",
9532           Style));
9533 }
9534 
9535 TEST_F(FormatTest, WrapsTemplateParameters) {
9536   FormatStyle Style = getLLVMStyle();
9537   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9538   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9539   verifyFormat(
9540       "template <typename... a> struct q {};\n"
9541       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9542       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9543       "    y;",
9544       Style);
9545   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9546   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9547   verifyFormat(
9548       "template <typename... a> struct r {};\n"
9549       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9550       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9551       "    y;",
9552       Style);
9553   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9554   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9555   verifyFormat("template <typename... a> struct s {};\n"
9556                "extern s<\n"
9557                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9558                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9559                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9560                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9561                "    y;",
9562                Style);
9563   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9564   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9565   verifyFormat("template <typename... a> struct t {};\n"
9566                "extern t<\n"
9567                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9568                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9569                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9570                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9571                "    y;",
9572                Style);
9573 }
9574 
9575 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9576   verifyFormat(
9577       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9578       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9579   verifyFormat(
9580       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9581       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9582       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9583 
9584   // FIXME: Should we have the extra indent after the second break?
9585   verifyFormat(
9586       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9587       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9588       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9589 
9590   verifyFormat(
9591       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9592       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9593 
9594   // Breaking at nested name specifiers is generally not desirable.
9595   verifyFormat(
9596       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9597       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9598 
9599   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9600                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9601                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9602                "                   aaaaaaaaaaaaaaaaaaaaa);",
9603                getLLVMStyleWithColumns(74));
9604 
9605   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9606                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9607                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9608 }
9609 
9610 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9611   verifyFormat("A<int> a;");
9612   verifyFormat("A<A<A<int>>> a;");
9613   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9614   verifyFormat("bool x = a < 1 || 2 > a;");
9615   verifyFormat("bool x = 5 < f<int>();");
9616   verifyFormat("bool x = f<int>() > 5;");
9617   verifyFormat("bool x = 5 < a<int>::x;");
9618   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9619   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9620 
9621   verifyGoogleFormat("A<A<int>> a;");
9622   verifyGoogleFormat("A<A<A<int>>> a;");
9623   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9624   verifyGoogleFormat("A<A<int> > a;");
9625   verifyGoogleFormat("A<A<A<int> > > a;");
9626   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9627   verifyGoogleFormat("A<::A<int>> a;");
9628   verifyGoogleFormat("A<::A> a;");
9629   verifyGoogleFormat("A< ::A> a;");
9630   verifyGoogleFormat("A< ::A<int> > a;");
9631   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9632   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9633   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9634   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9635   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9636             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9637 
9638   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9639 
9640   // template closer followed by a token that starts with > or =
9641   verifyFormat("bool b = a<1> > 1;");
9642   verifyFormat("bool b = a<1> >= 1;");
9643   verifyFormat("int i = a<1> >> 1;");
9644   FormatStyle Style = getLLVMStyle();
9645   Style.SpaceBeforeAssignmentOperators = false;
9646   verifyFormat("bool b= a<1> == 1;", Style);
9647   verifyFormat("a<int> = 1;", Style);
9648   verifyFormat("a<int> >>= 1;", Style);
9649 
9650   verifyFormat("test < a | b >> c;");
9651   verifyFormat("test<test<a | b>> c;");
9652   verifyFormat("test >> a >> b;");
9653   verifyFormat("test << a >> b;");
9654 
9655   verifyFormat("f<int>();");
9656   verifyFormat("template <typename T> void f() {}");
9657   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9658   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9659                "sizeof(char)>::type>;");
9660   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9661   verifyFormat("f(a.operator()<A>());");
9662   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9663                "      .template operator()<A>());",
9664                getLLVMStyleWithColumns(35));
9665   verifyFormat("bool_constant<a && noexcept(f())>");
9666   verifyFormat("bool_constant<a || noexcept(f())>");
9667 
9668   // Not template parameters.
9669   verifyFormat("return a < b && c > d;");
9670   verifyFormat("void f() {\n"
9671                "  while (a < b && c > d) {\n"
9672                "  }\n"
9673                "}");
9674   verifyFormat("template <typename... Types>\n"
9675                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9676 
9677   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9678                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9679                getLLVMStyleWithColumns(60));
9680   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9681   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9682   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9683   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9684 }
9685 
9686 TEST_F(FormatTest, UnderstandsShiftOperators) {
9687   verifyFormat("if (i < x >> 1)");
9688   verifyFormat("while (i < x >> 1)");
9689   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9690   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9691   verifyFormat(
9692       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9693   verifyFormat("Foo.call<Bar<Function>>()");
9694   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9695   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9696                "++i, v = v >> 1)");
9697   verifyFormat("if (w<u<v<x>>, 1>::t)");
9698 }
9699 
9700 TEST_F(FormatTest, BitshiftOperatorWidth) {
9701   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9702             "                   bar */",
9703             format("int    a=1<<2;  /* foo\n"
9704                    "                   bar */"));
9705 
9706   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9707             "                     bar */",
9708             format("int  b  =256>>1 ;  /* foo\n"
9709                    "                      bar */"));
9710 }
9711 
9712 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9713   verifyFormat("COMPARE(a, ==, b);");
9714   verifyFormat("auto s = sizeof...(Ts) - 1;");
9715 }
9716 
9717 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9718   verifyFormat("int A::*x;");
9719   verifyFormat("int (S::*func)(void *);");
9720   verifyFormat("void f() { int (S::*func)(void *); }");
9721   verifyFormat("typedef bool *(Class::*Member)() const;");
9722   verifyFormat("void f() {\n"
9723                "  (a->*f)();\n"
9724                "  a->*x;\n"
9725                "  (a.*f)();\n"
9726                "  ((*a).*f)();\n"
9727                "  a.*x;\n"
9728                "}");
9729   verifyFormat("void f() {\n"
9730                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9731                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9732                "}");
9733   verifyFormat(
9734       "(aaaaaaaaaa->*bbbbbbb)(\n"
9735       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9736   FormatStyle Style = getLLVMStyle();
9737   Style.PointerAlignment = FormatStyle::PAS_Left;
9738   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9739 }
9740 
9741 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9742   verifyFormat("int a = -2;");
9743   verifyFormat("f(-1, -2, -3);");
9744   verifyFormat("a[-1] = 5;");
9745   verifyFormat("int a = 5 + -2;");
9746   verifyFormat("if (i == -1) {\n}");
9747   verifyFormat("if (i != -1) {\n}");
9748   verifyFormat("if (i > -1) {\n}");
9749   verifyFormat("if (i < -1) {\n}");
9750   verifyFormat("++(a->f());");
9751   verifyFormat("--(a->f());");
9752   verifyFormat("(a->f())++;");
9753   verifyFormat("a[42]++;");
9754   verifyFormat("if (!(a->f())) {\n}");
9755   verifyFormat("if (!+i) {\n}");
9756   verifyFormat("~&a;");
9757 
9758   verifyFormat("a-- > b;");
9759   verifyFormat("b ? -a : c;");
9760   verifyFormat("n * sizeof char16;");
9761   verifyFormat("n * alignof char16;", getGoogleStyle());
9762   verifyFormat("sizeof(char);");
9763   verifyFormat("alignof(char);", getGoogleStyle());
9764 
9765   verifyFormat("return -1;");
9766   verifyFormat("throw -1;");
9767   verifyFormat("switch (a) {\n"
9768                "case -1:\n"
9769                "  break;\n"
9770                "}");
9771   verifyFormat("#define X -1");
9772   verifyFormat("#define X -kConstant");
9773 
9774   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9775   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9776 
9777   verifyFormat("int a = /* confusing comment */ -1;");
9778   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9779   verifyFormat("int a = i /* confusing comment */++;");
9780 
9781   verifyFormat("co_yield -1;");
9782   verifyFormat("co_return -1;");
9783 
9784   // Check that * is not treated as a binary operator when we set
9785   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9786   FormatStyle PASLeftStyle = getLLVMStyle();
9787   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9788   verifyFormat("co_return *a;", PASLeftStyle);
9789   verifyFormat("co_await *a;", PASLeftStyle);
9790   verifyFormat("co_yield *a", PASLeftStyle);
9791   verifyFormat("return *a;", PASLeftStyle);
9792 }
9793 
9794 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9795   verifyFormat("if (!aaaaaaaaaa( // break\n"
9796                "        aaaaa)) {\n"
9797                "}");
9798   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9799                "    aaaaa));");
9800   verifyFormat("*aaa = aaaaaaa( // break\n"
9801                "    bbbbbb);");
9802 }
9803 
9804 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9805   verifyFormat("bool operator<();");
9806   verifyFormat("bool operator>();");
9807   verifyFormat("bool operator=();");
9808   verifyFormat("bool operator==();");
9809   verifyFormat("bool operator!=();");
9810   verifyFormat("int operator+();");
9811   verifyFormat("int operator++();");
9812   verifyFormat("int operator++(int) volatile noexcept;");
9813   verifyFormat("bool operator,();");
9814   verifyFormat("bool operator();");
9815   verifyFormat("bool operator()();");
9816   verifyFormat("bool operator[]();");
9817   verifyFormat("operator bool();");
9818   verifyFormat("operator int();");
9819   verifyFormat("operator void *();");
9820   verifyFormat("operator SomeType<int>();");
9821   verifyFormat("operator SomeType<int, int>();");
9822   verifyFormat("operator SomeType<SomeType<int>>();");
9823   verifyFormat("operator< <>();");
9824   verifyFormat("operator<< <>();");
9825   verifyFormat("< <>");
9826 
9827   verifyFormat("void *operator new(std::size_t size);");
9828   verifyFormat("void *operator new[](std::size_t size);");
9829   verifyFormat("void operator delete(void *ptr);");
9830   verifyFormat("void operator delete[](void *ptr);");
9831   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9832                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9833   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9834                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9835 
9836   verifyFormat(
9837       "ostream &operator<<(ostream &OutputStream,\n"
9838       "                    SomeReallyLongType WithSomeReallyLongValue);");
9839   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9840                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9841                "  return left.group < right.group;\n"
9842                "}");
9843   verifyFormat("SomeType &operator=(const SomeType &S);");
9844   verifyFormat("f.template operator()<int>();");
9845 
9846   verifyGoogleFormat("operator void*();");
9847   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9848   verifyGoogleFormat("operator ::A();");
9849 
9850   verifyFormat("using A::operator+;");
9851   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9852                "int i;");
9853 
9854   // Calling an operator as a member function.
9855   verifyFormat("void f() { a.operator*(); }");
9856   verifyFormat("void f() { a.operator*(b & b); }");
9857   verifyFormat("void f() { a->operator&(a * b); }");
9858   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9859   // TODO: Calling an operator as a non-member function is hard to distinguish.
9860   // https://llvm.org/PR50629
9861   // verifyFormat("void f() { operator*(a & a); }");
9862   // verifyFormat("void f() { operator&(a, b * b); }");
9863 
9864   verifyFormat("::operator delete(foo);");
9865   verifyFormat("::operator new(n * sizeof(foo));");
9866   verifyFormat("foo() { ::operator delete(foo); }");
9867   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9868 }
9869 
9870 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9871   verifyFormat("void A::b() && {}");
9872   verifyFormat("void A::b() &&noexcept {}");
9873   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9874   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9875   verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
9876   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9877   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9878   verifyFormat("Deleted &operator=(const Deleted &) &;");
9879   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9880   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9881   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9882   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9883   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9884   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9885   verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
9886   verifyFormat("void Fn(T const &) const &;");
9887   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9888   verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
9889   verifyFormat("template <typename T>\n"
9890                "void F(T) && = delete;",
9891                getGoogleStyle());
9892   verifyFormat("template <typename T> void operator=(T) &;");
9893   verifyFormat("template <typename T> void operator=(T) const &;");
9894   verifyFormat("template <typename T> void operator=(T) &noexcept;");
9895   verifyFormat("template <typename T> void operator=(T) & = default;");
9896   verifyFormat("template <typename T> void operator=(T) &&;");
9897   verifyFormat("template <typename T> void operator=(T) && = delete;");
9898   verifyFormat("template <typename T> void operator=(T) & {}");
9899   verifyFormat("template <typename T> void operator=(T) && {}");
9900 
9901   FormatStyle AlignLeft = getLLVMStyle();
9902   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9903   verifyFormat("void A::b() && {}", AlignLeft);
9904   verifyFormat("void A::b() && noexcept {}", AlignLeft);
9905   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9906   verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
9907                AlignLeft);
9908   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9909                AlignLeft);
9910   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9911   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9912   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9913   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9914   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9915   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9916   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9917   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9918   verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
9919                AlignLeft);
9920   verifyFormat("template <typename T> void operator=(T) &;", AlignLeft);
9921   verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft);
9922   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9923                AlignLeft);
9924   verifyFormat("template <typename T> void operator=(T) & = default;",
9925                AlignLeft);
9926   verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft);
9927   verifyFormat("template <typename T> void operator=(T) && = delete;",
9928                AlignLeft);
9929   verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft);
9930   verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft);
9931 
9932   FormatStyle AlignMiddle = getLLVMStyle();
9933   AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9934   verifyFormat("void A::b() && {}", AlignMiddle);
9935   verifyFormat("void A::b() && noexcept {}", AlignMiddle);
9936   verifyFormat("Deleted & operator=(const Deleted &) & = default;",
9937                AlignMiddle);
9938   verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
9939                AlignMiddle);
9940   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
9941                AlignMiddle);
9942   verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
9943   verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
9944   verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
9945   verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
9946   verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
9947   verifyFormat("auto Function(T) & -> void;", AlignMiddle);
9948   verifyFormat("void Fn(T const &) const &;", AlignMiddle);
9949   verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
9950   verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
9951                AlignMiddle);
9952   verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle);
9953   verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle);
9954   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9955                AlignMiddle);
9956   verifyFormat("template <typename T> void operator=(T) & = default;",
9957                AlignMiddle);
9958   verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle);
9959   verifyFormat("template <typename T> void operator=(T) && = delete;",
9960                AlignMiddle);
9961   verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle);
9962   verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle);
9963 
9964   FormatStyle Spaces = getLLVMStyle();
9965   Spaces.SpacesInCStyleCastParentheses = true;
9966   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9967   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9968   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9969   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9970 
9971   Spaces.SpacesInCStyleCastParentheses = false;
9972   Spaces.SpacesInParentheses = true;
9973   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9974   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9975                Spaces);
9976   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9977   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9978 
9979   FormatStyle BreakTemplate = getLLVMStyle();
9980   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9981 
9982   verifyFormat("struct f {\n"
9983                "  template <class T>\n"
9984                "  int &foo(const std::string &str) &noexcept {}\n"
9985                "};",
9986                BreakTemplate);
9987 
9988   verifyFormat("struct f {\n"
9989                "  template <class T>\n"
9990                "  int &foo(const std::string &str) &&noexcept {}\n"
9991                "};",
9992                BreakTemplate);
9993 
9994   verifyFormat("struct f {\n"
9995                "  template <class T>\n"
9996                "  int &foo(const std::string &str) const &noexcept {}\n"
9997                "};",
9998                BreakTemplate);
9999 
10000   verifyFormat("struct f {\n"
10001                "  template <class T>\n"
10002                "  int &foo(const std::string &str) const &noexcept {}\n"
10003                "};",
10004                BreakTemplate);
10005 
10006   verifyFormat("struct f {\n"
10007                "  template <class T>\n"
10008                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
10009                "};",
10010                BreakTemplate);
10011 
10012   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
10013   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
10014       FormatStyle::BTDS_Yes;
10015   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
10016 
10017   verifyFormat("struct f {\n"
10018                "  template <class T>\n"
10019                "  int& foo(const std::string& str) & noexcept {}\n"
10020                "};",
10021                AlignLeftBreakTemplate);
10022 
10023   verifyFormat("struct f {\n"
10024                "  template <class T>\n"
10025                "  int& foo(const std::string& str) && noexcept {}\n"
10026                "};",
10027                AlignLeftBreakTemplate);
10028 
10029   verifyFormat("struct f {\n"
10030                "  template <class T>\n"
10031                "  int& foo(const std::string& str) const& noexcept {}\n"
10032                "};",
10033                AlignLeftBreakTemplate);
10034 
10035   verifyFormat("struct f {\n"
10036                "  template <class T>\n"
10037                "  int& foo(const std::string& str) const&& noexcept {}\n"
10038                "};",
10039                AlignLeftBreakTemplate);
10040 
10041   verifyFormat("struct f {\n"
10042                "  template <class T>\n"
10043                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
10044                "};",
10045                AlignLeftBreakTemplate);
10046 
10047   // The `&` in `Type&` should not be confused with a trailing `&` of
10048   // DEPRECATED(reason) member function.
10049   verifyFormat("struct f {\n"
10050                "  template <class T>\n"
10051                "  DEPRECATED(reason)\n"
10052                "  Type &foo(arguments) {}\n"
10053                "};",
10054                BreakTemplate);
10055 
10056   verifyFormat("struct f {\n"
10057                "  template <class T>\n"
10058                "  DEPRECATED(reason)\n"
10059                "  Type& foo(arguments) {}\n"
10060                "};",
10061                AlignLeftBreakTemplate);
10062 
10063   verifyFormat("void (*foopt)(int) = &func;");
10064 
10065   FormatStyle DerivePointerAlignment = getLLVMStyle();
10066   DerivePointerAlignment.DerivePointerAlignment = true;
10067   // There's always a space between the function and its trailing qualifiers.
10068   // This isn't evidence for PAS_Right (or for PAS_Left).
10069   std::string Prefix = "void a() &;\n"
10070                        "void b() &;\n";
10071   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10072   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10073   // Same if the function is an overloaded operator, and with &&.
10074   Prefix = "void operator()() &&;\n"
10075            "void operator()() &&;\n";
10076   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10077   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10078   // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
10079   Prefix = "void a() const &;\n"
10080            "void b() const &;\n";
10081   EXPECT_EQ(Prefix + "int *x;",
10082             format(Prefix + "int* x;", DerivePointerAlignment));
10083 }
10084 
10085 TEST_F(FormatTest, UnderstandsNewAndDelete) {
10086   verifyFormat("void f() {\n"
10087                "  A *a = new A;\n"
10088                "  A *a = new (placement) A;\n"
10089                "  delete a;\n"
10090                "  delete (A *)a;\n"
10091                "}");
10092   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10093                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10094   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10095                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10096                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10097   verifyFormat("delete[] h->p;");
10098   verifyFormat("delete[] (void *)p;");
10099 
10100   verifyFormat("void operator delete(void *foo) ATTRIB;");
10101   verifyFormat("void operator new(void *foo) ATTRIB;");
10102   verifyFormat("void operator delete[](void *foo) ATTRIB;");
10103   verifyFormat("void operator delete(void *ptr) noexcept;");
10104 
10105   EXPECT_EQ("void new(link p);\n"
10106             "void delete(link p);\n",
10107             format("void new (link p);\n"
10108                    "void delete (link p);\n"));
10109 }
10110 
10111 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
10112   verifyFormat("int *f(int *a) {}");
10113   verifyFormat("int main(int argc, char **argv) {}");
10114   verifyFormat("Test::Test(int b) : a(b * b) {}");
10115   verifyIndependentOfContext("f(a, *a);");
10116   verifyFormat("void g() { f(*a); }");
10117   verifyIndependentOfContext("int a = b * 10;");
10118   verifyIndependentOfContext("int a = 10 * b;");
10119   verifyIndependentOfContext("int a = b * c;");
10120   verifyIndependentOfContext("int a += b * c;");
10121   verifyIndependentOfContext("int a -= b * c;");
10122   verifyIndependentOfContext("int a *= b * c;");
10123   verifyIndependentOfContext("int a /= b * c;");
10124   verifyIndependentOfContext("int a = *b;");
10125   verifyIndependentOfContext("int a = *b * c;");
10126   verifyIndependentOfContext("int a = b * *c;");
10127   verifyIndependentOfContext("int a = b * (10);");
10128   verifyIndependentOfContext("S << b * (10);");
10129   verifyIndependentOfContext("return 10 * b;");
10130   verifyIndependentOfContext("return *b * *c;");
10131   verifyIndependentOfContext("return a & ~b;");
10132   verifyIndependentOfContext("f(b ? *c : *d);");
10133   verifyIndependentOfContext("int a = b ? *c : *d;");
10134   verifyIndependentOfContext("*b = a;");
10135   verifyIndependentOfContext("a * ~b;");
10136   verifyIndependentOfContext("a * !b;");
10137   verifyIndependentOfContext("a * +b;");
10138   verifyIndependentOfContext("a * -b;");
10139   verifyIndependentOfContext("a * ++b;");
10140   verifyIndependentOfContext("a * --b;");
10141   verifyIndependentOfContext("a[4] * b;");
10142   verifyIndependentOfContext("a[a * a] = 1;");
10143   verifyIndependentOfContext("f() * b;");
10144   verifyIndependentOfContext("a * [self dostuff];");
10145   verifyIndependentOfContext("int x = a * (a + b);");
10146   verifyIndependentOfContext("(a *)(a + b);");
10147   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
10148   verifyIndependentOfContext("int *pa = (int *)&a;");
10149   verifyIndependentOfContext("return sizeof(int **);");
10150   verifyIndependentOfContext("return sizeof(int ******);");
10151   verifyIndependentOfContext("return (int **&)a;");
10152   verifyIndependentOfContext("f((*PointerToArray)[10]);");
10153   verifyFormat("void f(Type (*parameter)[10]) {}");
10154   verifyFormat("void f(Type (&parameter)[10]) {}");
10155   verifyGoogleFormat("return sizeof(int**);");
10156   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
10157   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
10158   verifyFormat("auto a = [](int **&, int ***) {};");
10159   verifyFormat("auto PointerBinding = [](const char *S) {};");
10160   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
10161   verifyFormat("[](const decltype(*a) &value) {}");
10162   verifyFormat("[](const typeof(*a) &value) {}");
10163   verifyFormat("[](const _Atomic(a *) &value) {}");
10164   verifyFormat("[](const __underlying_type(a) &value) {}");
10165   verifyFormat("decltype(a * b) F();");
10166   verifyFormat("typeof(a * b) F();");
10167   verifyFormat("#define MACRO() [](A *a) { return 1; }");
10168   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
10169   verifyIndependentOfContext("typedef void (*f)(int *a);");
10170   verifyIndependentOfContext("int i{a * b};");
10171   verifyIndependentOfContext("aaa && aaa->f();");
10172   verifyIndependentOfContext("int x = ~*p;");
10173   verifyFormat("Constructor() : a(a), area(width * height) {}");
10174   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
10175   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
10176   verifyFormat("void f() { f(a, c * d); }");
10177   verifyFormat("void f() { f(new a(), c * d); }");
10178   verifyFormat("void f(const MyOverride &override);");
10179   verifyFormat("void f(const MyFinal &final);");
10180   verifyIndependentOfContext("bool a = f() && override.f();");
10181   verifyIndependentOfContext("bool a = f() && final.f();");
10182 
10183   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
10184 
10185   verifyIndependentOfContext("A<int *> a;");
10186   verifyIndependentOfContext("A<int **> a;");
10187   verifyIndependentOfContext("A<int *, int *> a;");
10188   verifyIndependentOfContext("A<int *[]> a;");
10189   verifyIndependentOfContext(
10190       "const char *const p = reinterpret_cast<const char *const>(q);");
10191   verifyIndependentOfContext("A<int **, int **> a;");
10192   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
10193   verifyFormat("for (char **a = b; *a; ++a) {\n}");
10194   verifyFormat("for (; a && b;) {\n}");
10195   verifyFormat("bool foo = true && [] { return false; }();");
10196 
10197   verifyFormat(
10198       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10199       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10200 
10201   verifyGoogleFormat("int const* a = &b;");
10202   verifyGoogleFormat("**outparam = 1;");
10203   verifyGoogleFormat("*outparam = a * b;");
10204   verifyGoogleFormat("int main(int argc, char** argv) {}");
10205   verifyGoogleFormat("A<int*> a;");
10206   verifyGoogleFormat("A<int**> a;");
10207   verifyGoogleFormat("A<int*, int*> a;");
10208   verifyGoogleFormat("A<int**, int**> a;");
10209   verifyGoogleFormat("f(b ? *c : *d);");
10210   verifyGoogleFormat("int a = b ? *c : *d;");
10211   verifyGoogleFormat("Type* t = **x;");
10212   verifyGoogleFormat("Type* t = *++*x;");
10213   verifyGoogleFormat("*++*x;");
10214   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
10215   verifyGoogleFormat("Type* t = x++ * y;");
10216   verifyGoogleFormat(
10217       "const char* const p = reinterpret_cast<const char* const>(q);");
10218   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
10219   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
10220   verifyGoogleFormat("template <typename T>\n"
10221                      "void f(int i = 0, SomeType** temps = NULL);");
10222 
10223   FormatStyle Left = getLLVMStyle();
10224   Left.PointerAlignment = FormatStyle::PAS_Left;
10225   verifyFormat("x = *a(x) = *a(y);", Left);
10226   verifyFormat("for (;; *a = b) {\n}", Left);
10227   verifyFormat("return *this += 1;", Left);
10228   verifyFormat("throw *x;", Left);
10229   verifyFormat("delete *x;", Left);
10230   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
10231   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
10232   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
10233   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
10234   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
10235   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
10236   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
10237   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
10238   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
10239 
10240   verifyIndependentOfContext("a = *(x + y);");
10241   verifyIndependentOfContext("a = &(x + y);");
10242   verifyIndependentOfContext("*(x + y).call();");
10243   verifyIndependentOfContext("&(x + y)->call();");
10244   verifyFormat("void f() { &(*I).first; }");
10245 
10246   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
10247   verifyFormat("f(* /* confusing comment */ foo);");
10248   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
10249   verifyFormat("void foo(int * // this is the first paramters\n"
10250                "         ,\n"
10251                "         int second);");
10252   verifyFormat("double term = a * // first\n"
10253                "              b;");
10254   verifyFormat(
10255       "int *MyValues = {\n"
10256       "    *A, // Operator detection might be confused by the '{'\n"
10257       "    *BB // Operator detection might be confused by previous comment\n"
10258       "};");
10259 
10260   verifyIndependentOfContext("if (int *a = &b)");
10261   verifyIndependentOfContext("if (int &a = *b)");
10262   verifyIndependentOfContext("if (a & b[i])");
10263   verifyIndependentOfContext("if constexpr (a & b[i])");
10264   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
10265   verifyIndependentOfContext("if (a * (b * c))");
10266   verifyIndependentOfContext("if constexpr (a * (b * c))");
10267   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
10268   verifyIndependentOfContext("if (a::b::c::d & b[i])");
10269   verifyIndependentOfContext("if (*b[i])");
10270   verifyIndependentOfContext("if (int *a = (&b))");
10271   verifyIndependentOfContext("while (int *a = &b)");
10272   verifyIndependentOfContext("while (a * (b * c))");
10273   verifyIndependentOfContext("size = sizeof *a;");
10274   verifyIndependentOfContext("if (a && (b = c))");
10275   verifyFormat("void f() {\n"
10276                "  for (const int &v : Values) {\n"
10277                "  }\n"
10278                "}");
10279   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
10280   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
10281   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
10282 
10283   verifyFormat("#define A (!a * b)");
10284   verifyFormat("#define MACRO     \\\n"
10285                "  int *i = a * b; \\\n"
10286                "  void f(a *b);",
10287                getLLVMStyleWithColumns(19));
10288 
10289   verifyIndependentOfContext("A = new SomeType *[Length];");
10290   verifyIndependentOfContext("A = new SomeType *[Length]();");
10291   verifyIndependentOfContext("T **t = new T *;");
10292   verifyIndependentOfContext("T **t = new T *();");
10293   verifyGoogleFormat("A = new SomeType*[Length]();");
10294   verifyGoogleFormat("A = new SomeType*[Length];");
10295   verifyGoogleFormat("T** t = new T*;");
10296   verifyGoogleFormat("T** t = new T*();");
10297 
10298   verifyFormat("STATIC_ASSERT((a & b) == 0);");
10299   verifyFormat("STATIC_ASSERT(0 == (a & b));");
10300   verifyFormat("template <bool a, bool b> "
10301                "typename t::if<x && y>::type f() {}");
10302   verifyFormat("template <int *y> f() {}");
10303   verifyFormat("vector<int *> v;");
10304   verifyFormat("vector<int *const> v;");
10305   verifyFormat("vector<int *const **const *> v;");
10306   verifyFormat("vector<int *volatile> v;");
10307   verifyFormat("vector<a *_Nonnull> v;");
10308   verifyFormat("vector<a *_Nullable> v;");
10309   verifyFormat("vector<a *_Null_unspecified> v;");
10310   verifyFormat("vector<a *__ptr32> v;");
10311   verifyFormat("vector<a *__ptr64> v;");
10312   verifyFormat("vector<a *__capability> v;");
10313   FormatStyle TypeMacros = getLLVMStyle();
10314   TypeMacros.TypenameMacros = {"LIST"};
10315   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
10316   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
10317   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
10318   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
10319   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
10320 
10321   FormatStyle CustomQualifier = getLLVMStyle();
10322   // Add identifiers that should not be parsed as a qualifier by default.
10323   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10324   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
10325   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
10326   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
10327   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
10328   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
10329   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
10330   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
10331   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
10332   verifyFormat("vector<a * _NotAQualifier> v;");
10333   verifyFormat("vector<a * __not_a_qualifier> v;");
10334   verifyFormat("vector<a * b> v;");
10335   verifyFormat("foo<b && false>();");
10336   verifyFormat("foo<b & 1>();");
10337   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
10338   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
10339   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
10340   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
10341   verifyFormat(
10342       "template <class T, class = typename std::enable_if<\n"
10343       "                       std::is_integral<T>::value &&\n"
10344       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
10345       "void F();",
10346       getLLVMStyleWithColumns(70));
10347   verifyFormat("template <class T,\n"
10348                "          class = typename std::enable_if<\n"
10349                "              std::is_integral<T>::value &&\n"
10350                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
10351                "          class U>\n"
10352                "void F();",
10353                getLLVMStyleWithColumns(70));
10354   verifyFormat(
10355       "template <class T,\n"
10356       "          class = typename ::std::enable_if<\n"
10357       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
10358       "void F();",
10359       getGoogleStyleWithColumns(68));
10360 
10361   verifyIndependentOfContext("MACRO(int *i);");
10362   verifyIndependentOfContext("MACRO(auto *a);");
10363   verifyIndependentOfContext("MACRO(const A *a);");
10364   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
10365   verifyIndependentOfContext("MACRO(decltype(A) *a);");
10366   verifyIndependentOfContext("MACRO(typeof(A) *a);");
10367   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
10368   verifyIndependentOfContext("MACRO(A *const a);");
10369   verifyIndependentOfContext("MACRO(A *restrict a);");
10370   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
10371   verifyIndependentOfContext("MACRO(A *__restrict a);");
10372   verifyIndependentOfContext("MACRO(A *volatile a);");
10373   verifyIndependentOfContext("MACRO(A *__volatile a);");
10374   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
10375   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
10376   verifyIndependentOfContext("MACRO(A *_Nullable a);");
10377   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
10378   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
10379   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
10380   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
10381   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
10382   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
10383   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
10384   verifyIndependentOfContext("MACRO(A *__capability);");
10385   verifyIndependentOfContext("MACRO(A &__capability);");
10386   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
10387   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
10388   // If we add __my_qualifier to AttributeMacros it should always be parsed as
10389   // a type declaration:
10390   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
10391   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
10392   // Also check that TypenameMacros prevents parsing it as multiplication:
10393   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
10394   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
10395 
10396   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
10397   verifyFormat("void f() { f(float{1}, a * a); }");
10398   verifyFormat("void f() { f(float(1), a * a); }");
10399 
10400   verifyFormat("f((void (*)(int))g);");
10401   verifyFormat("f((void (&)(int))g);");
10402   verifyFormat("f((void (^)(int))g);");
10403 
10404   // FIXME: Is there a way to make this work?
10405   // verifyIndependentOfContext("MACRO(A *a);");
10406   verifyFormat("MACRO(A &B);");
10407   verifyFormat("MACRO(A *B);");
10408   verifyFormat("void f() { MACRO(A * B); }");
10409   verifyFormat("void f() { MACRO(A & B); }");
10410 
10411   // This lambda was mis-formatted after D88956 (treating it as a binop):
10412   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
10413   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
10414   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
10415   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
10416 
10417   verifyFormat("DatumHandle const *operator->() const { return input_; }");
10418   verifyFormat("return options != nullptr && operator==(*options);");
10419 
10420   EXPECT_EQ("#define OP(x)                                    \\\n"
10421             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
10422             "    return s << a.DebugString();                 \\\n"
10423             "  }",
10424             format("#define OP(x) \\\n"
10425                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
10426                    "    return s << a.DebugString(); \\\n"
10427                    "  }",
10428                    getLLVMStyleWithColumns(50)));
10429 
10430   // FIXME: We cannot handle this case yet; we might be able to figure out that
10431   // foo<x> d > v; doesn't make sense.
10432   verifyFormat("foo<a<b && c> d> v;");
10433 
10434   FormatStyle PointerMiddle = getLLVMStyle();
10435   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10436   verifyFormat("delete *x;", PointerMiddle);
10437   verifyFormat("int * x;", PointerMiddle);
10438   verifyFormat("int *[] x;", PointerMiddle);
10439   verifyFormat("template <int * y> f() {}", PointerMiddle);
10440   verifyFormat("int * f(int * a) {}", PointerMiddle);
10441   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
10442   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10443   verifyFormat("A<int *> a;", PointerMiddle);
10444   verifyFormat("A<int **> a;", PointerMiddle);
10445   verifyFormat("A<int *, int *> a;", PointerMiddle);
10446   verifyFormat("A<int *[]> a;", PointerMiddle);
10447   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10448   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10449   verifyFormat("T ** t = new T *;", PointerMiddle);
10450 
10451   // Member function reference qualifiers aren't binary operators.
10452   verifyFormat("string // break\n"
10453                "operator()() & {}");
10454   verifyFormat("string // break\n"
10455                "operator()() && {}");
10456   verifyGoogleFormat("template <typename T>\n"
10457                      "auto x() & -> int {}");
10458 
10459   // Should be binary operators when used as an argument expression (overloaded
10460   // operator invoked as a member function).
10461   verifyFormat("void f() { a.operator()(a * a); }");
10462   verifyFormat("void f() { a->operator()(a & a); }");
10463   verifyFormat("void f() { a.operator()(*a & *a); }");
10464   verifyFormat("void f() { a->operator()(*a * *a); }");
10465 
10466   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10467   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10468 }
10469 
10470 TEST_F(FormatTest, UnderstandsAttributes) {
10471   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10472   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10473                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10474   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10475   FormatStyle AfterType = getLLVMStyle();
10476   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10477   verifyFormat("__attribute__((nodebug)) void\n"
10478                "foo() {}\n",
10479                AfterType);
10480   verifyFormat("__unused void\n"
10481                "foo() {}",
10482                AfterType);
10483 
10484   FormatStyle CustomAttrs = getLLVMStyle();
10485   CustomAttrs.AttributeMacros.push_back("__unused");
10486   CustomAttrs.AttributeMacros.push_back("__attr1");
10487   CustomAttrs.AttributeMacros.push_back("__attr2");
10488   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10489   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10490   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10491   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10492   // Check that it is parsed as a multiplication without AttributeMacros and
10493   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10494   verifyFormat("vector<SomeType * __attr1> v;");
10495   verifyFormat("vector<SomeType __attr1 *> v;");
10496   verifyFormat("vector<SomeType __attr1 *const> v;");
10497   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10498   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10499   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10500   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10501   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10502   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10503   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10504   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10505 
10506   // Check that these are not parsed as function declarations:
10507   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10508   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10509   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10510   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10511   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10512   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10513   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10514   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10515   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10516   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10517 }
10518 
10519 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10520   // Check that qualifiers on pointers don't break parsing of casts.
10521   verifyFormat("x = (foo *const)*v;");
10522   verifyFormat("x = (foo *volatile)*v;");
10523   verifyFormat("x = (foo *restrict)*v;");
10524   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10525   verifyFormat("x = (foo *_Nonnull)*v;");
10526   verifyFormat("x = (foo *_Nullable)*v;");
10527   verifyFormat("x = (foo *_Null_unspecified)*v;");
10528   verifyFormat("x = (foo *_Nonnull)*v;");
10529   verifyFormat("x = (foo *[[clang::attr]])*v;");
10530   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10531   verifyFormat("x = (foo *__ptr32)*v;");
10532   verifyFormat("x = (foo *__ptr64)*v;");
10533   verifyFormat("x = (foo *__capability)*v;");
10534 
10535   // Check that we handle multiple trailing qualifiers and skip them all to
10536   // determine that the expression is a cast to a pointer type.
10537   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10538   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10539   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10540   StringRef AllQualifiers =
10541       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10542       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10543   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10544   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10545 
10546   // Also check that address-of is not parsed as a binary bitwise-and:
10547   verifyFormat("x = (foo *const)&v;");
10548   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10549   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10550 
10551   // Check custom qualifiers:
10552   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10553   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10554   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10555   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10556   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10557                CustomQualifier);
10558   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10559                CustomQualifier);
10560 
10561   // Check that unknown identifiers result in binary operator parsing:
10562   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10563   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10564 }
10565 
10566 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10567   verifyFormat("SomeType s [[unused]] (InitValue);");
10568   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10569   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10570   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10571   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10572   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10573                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10574   verifyFormat("[[nodiscard]] bool f() { return false; }");
10575   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10576   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10577   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10578   verifyFormat("[[nodiscard]] ::qualified_type f();");
10579 
10580   // Make sure we do not mistake attributes for array subscripts.
10581   verifyFormat("int a() {}\n"
10582                "[[unused]] int b() {}\n");
10583   verifyFormat("NSArray *arr;\n"
10584                "arr[[Foo() bar]];");
10585 
10586   // On the other hand, we still need to correctly find array subscripts.
10587   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10588 
10589   // Make sure that we do not mistake Objective-C method inside array literals
10590   // as attributes, even if those method names are also keywords.
10591   verifyFormat("@[ [foo bar] ];");
10592   verifyFormat("@[ [NSArray class] ];");
10593   verifyFormat("@[ [foo enum] ];");
10594 
10595   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10596 
10597   // Make sure we do not parse attributes as lambda introducers.
10598   FormatStyle MultiLineFunctions = getLLVMStyle();
10599   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10600   verifyFormat("[[unused]] int b() {\n"
10601                "  return 42;\n"
10602                "}\n",
10603                MultiLineFunctions);
10604 }
10605 
10606 TEST_F(FormatTest, AttributeClass) {
10607   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10608   verifyFormat("class S {\n"
10609                "  S(S&&) = default;\n"
10610                "};",
10611                Style);
10612   verifyFormat("class [[nodiscard]] S {\n"
10613                "  S(S&&) = default;\n"
10614                "};",
10615                Style);
10616   verifyFormat("class __attribute((maybeunused)) S {\n"
10617                "  S(S&&) = default;\n"
10618                "};",
10619                Style);
10620   verifyFormat("struct S {\n"
10621                "  S(S&&) = default;\n"
10622                "};",
10623                Style);
10624   verifyFormat("struct [[nodiscard]] S {\n"
10625                "  S(S&&) = default;\n"
10626                "};",
10627                Style);
10628 }
10629 
10630 TEST_F(FormatTest, AttributesAfterMacro) {
10631   FormatStyle Style = getLLVMStyle();
10632   verifyFormat("MACRO;\n"
10633                "__attribute__((maybe_unused)) int foo() {\n"
10634                "  //...\n"
10635                "}");
10636 
10637   verifyFormat("MACRO;\n"
10638                "[[nodiscard]] int foo() {\n"
10639                "  //...\n"
10640                "}");
10641 
10642   EXPECT_EQ("MACRO\n\n"
10643             "__attribute__((maybe_unused)) int foo() {\n"
10644             "  //...\n"
10645             "}",
10646             format("MACRO\n\n"
10647                    "__attribute__((maybe_unused)) int foo() {\n"
10648                    "  //...\n"
10649                    "}"));
10650 
10651   EXPECT_EQ("MACRO\n\n"
10652             "[[nodiscard]] int foo() {\n"
10653             "  //...\n"
10654             "}",
10655             format("MACRO\n\n"
10656                    "[[nodiscard]] int foo() {\n"
10657                    "  //...\n"
10658                    "}"));
10659 }
10660 
10661 TEST_F(FormatTest, AttributePenaltyBreaking) {
10662   FormatStyle Style = getLLVMStyle();
10663   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10664                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10665                Style);
10666   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10667                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10668                Style);
10669   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10670                "shared_ptr<ALongTypeName> &C d) {\n}",
10671                Style);
10672 }
10673 
10674 TEST_F(FormatTest, UnderstandsEllipsis) {
10675   FormatStyle Style = getLLVMStyle();
10676   verifyFormat("int printf(const char *fmt, ...);");
10677   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10678   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10679 
10680   verifyFormat("template <int *...PP> a;", Style);
10681 
10682   Style.PointerAlignment = FormatStyle::PAS_Left;
10683   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10684 
10685   verifyFormat("template <int*... PP> a;", Style);
10686 
10687   Style.PointerAlignment = FormatStyle::PAS_Middle;
10688   verifyFormat("template <int *... PP> a;", Style);
10689 }
10690 
10691 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10692   EXPECT_EQ("int *a;\n"
10693             "int *a;\n"
10694             "int *a;",
10695             format("int *a;\n"
10696                    "int* a;\n"
10697                    "int *a;",
10698                    getGoogleStyle()));
10699   EXPECT_EQ("int* a;\n"
10700             "int* a;\n"
10701             "int* a;",
10702             format("int* a;\n"
10703                    "int* a;\n"
10704                    "int *a;",
10705                    getGoogleStyle()));
10706   EXPECT_EQ("int *a;\n"
10707             "int *a;\n"
10708             "int *a;",
10709             format("int *a;\n"
10710                    "int * a;\n"
10711                    "int *  a;",
10712                    getGoogleStyle()));
10713   EXPECT_EQ("auto x = [] {\n"
10714             "  int *a;\n"
10715             "  int *a;\n"
10716             "  int *a;\n"
10717             "};",
10718             format("auto x=[]{int *a;\n"
10719                    "int * a;\n"
10720                    "int *  a;};",
10721                    getGoogleStyle()));
10722 }
10723 
10724 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10725   verifyFormat("int f(int &&a) {}");
10726   verifyFormat("int f(int a, char &&b) {}");
10727   verifyFormat("void f() { int &&a = b; }");
10728   verifyGoogleFormat("int f(int a, char&& b) {}");
10729   verifyGoogleFormat("void f() { int&& a = b; }");
10730 
10731   verifyIndependentOfContext("A<int &&> a;");
10732   verifyIndependentOfContext("A<int &&, int &&> a;");
10733   verifyGoogleFormat("A<int&&> a;");
10734   verifyGoogleFormat("A<int&&, int&&> a;");
10735 
10736   // Not rvalue references:
10737   verifyFormat("template <bool B, bool C> class A {\n"
10738                "  static_assert(B && C, \"Something is wrong\");\n"
10739                "};");
10740   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10741   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10742   verifyFormat("#define A(a, b) (a && b)");
10743 }
10744 
10745 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10746   verifyFormat("void f() {\n"
10747                "  x[aaaaaaaaa -\n"
10748                "    b] = 23;\n"
10749                "}",
10750                getLLVMStyleWithColumns(15));
10751 }
10752 
10753 TEST_F(FormatTest, FormatsCasts) {
10754   verifyFormat("Type *A = static_cast<Type *>(P);");
10755   verifyFormat("static_cast<Type *>(P);");
10756   verifyFormat("static_cast<Type &>(Fun)(Args);");
10757   verifyFormat("static_cast<Type &>(*Fun)(Args);");
10758   verifyFormat("if (static_cast<int>(A) + B >= 0)\n  ;");
10759   // Check that static_cast<...>(...) does not require the next token to be on
10760   // the same line.
10761   verifyFormat("some_loooong_output << something_something__ << "
10762                "static_cast<const void *>(R)\n"
10763                "                    << something;");
10764   verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
10765   verifyFormat("const_cast<Type &>(*Fun)(Args);");
10766   verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
10767   verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
10768   verifyFormat("Type *A = (Type *)P;");
10769   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10770   verifyFormat("int a = (int)(2.0f);");
10771   verifyFormat("int a = (int)2.0f;");
10772   verifyFormat("x[(int32)y];");
10773   verifyFormat("x = (int32)y;");
10774   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10775   verifyFormat("int a = (int)*b;");
10776   verifyFormat("int a = (int)2.0f;");
10777   verifyFormat("int a = (int)~0;");
10778   verifyFormat("int a = (int)++a;");
10779   verifyFormat("int a = (int)sizeof(int);");
10780   verifyFormat("int a = (int)+2;");
10781   verifyFormat("my_int a = (my_int)2.0f;");
10782   verifyFormat("my_int a = (my_int)sizeof(int);");
10783   verifyFormat("return (my_int)aaa;");
10784   verifyFormat("#define x ((int)-1)");
10785   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10786   verifyFormat("#define p(q) ((int *)&q)");
10787   verifyFormat("fn(a)(b) + 1;");
10788 
10789   verifyFormat("void f() { my_int a = (my_int)*b; }");
10790   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10791   verifyFormat("my_int a = (my_int)~0;");
10792   verifyFormat("my_int a = (my_int)++a;");
10793   verifyFormat("my_int a = (my_int)-2;");
10794   verifyFormat("my_int a = (my_int)1;");
10795   verifyFormat("my_int a = (my_int *)1;");
10796   verifyFormat("my_int a = (const my_int)-1;");
10797   verifyFormat("my_int a = (const my_int *)-1;");
10798   verifyFormat("my_int a = (my_int)(my_int)-1;");
10799   verifyFormat("my_int a = (ns::my_int)-2;");
10800   verifyFormat("case (my_int)ONE:");
10801   verifyFormat("auto x = (X)this;");
10802   // Casts in Obj-C style calls used to not be recognized as such.
10803   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10804 
10805   // FIXME: single value wrapped with paren will be treated as cast.
10806   verifyFormat("void f(int i = (kValue)*kMask) {}");
10807 
10808   verifyFormat("{ (void)F; }");
10809 
10810   // Don't break after a cast's
10811   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10812                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10813                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10814 
10815   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10816   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10817   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10818   verifyFormat("bool *y = (bool *)(void *)(x);");
10819   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10820   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10821   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10822   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10823 
10824   // These are not casts.
10825   verifyFormat("void f(int *) {}");
10826   verifyFormat("f(foo)->b;");
10827   verifyFormat("f(foo).b;");
10828   verifyFormat("f(foo)(b);");
10829   verifyFormat("f(foo)[b];");
10830   verifyFormat("[](foo) { return 4; }(bar);");
10831   verifyFormat("(*funptr)(foo)[4];");
10832   verifyFormat("funptrs[4](foo)[4];");
10833   verifyFormat("void f(int *);");
10834   verifyFormat("void f(int *) = 0;");
10835   verifyFormat("void f(SmallVector<int>) {}");
10836   verifyFormat("void f(SmallVector<int>);");
10837   verifyFormat("void f(SmallVector<int>) = 0;");
10838   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10839   verifyFormat("int a = sizeof(int) * b;");
10840   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10841   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10842   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10843   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10844 
10845   // These are not casts, but at some point were confused with casts.
10846   verifyFormat("virtual void foo(int *) override;");
10847   verifyFormat("virtual void foo(char &) const;");
10848   verifyFormat("virtual void foo(int *a, char *) const;");
10849   verifyFormat("int a = sizeof(int *) + b;");
10850   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10851   verifyFormat("bool b = f(g<int>) && c;");
10852   verifyFormat("typedef void (*f)(int i) func;");
10853   verifyFormat("void operator++(int) noexcept;");
10854   verifyFormat("void operator++(int &) noexcept;");
10855   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10856                "&) noexcept;");
10857   verifyFormat(
10858       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10859   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10860   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10861   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10862   verifyFormat("void operator delete(foo &) noexcept;");
10863   verifyFormat("void operator delete(foo) noexcept;");
10864   verifyFormat("void operator delete(int) noexcept;");
10865   verifyFormat("void operator delete(int &) noexcept;");
10866   verifyFormat("void operator delete(int &) volatile noexcept;");
10867   verifyFormat("void operator delete(int &) const");
10868   verifyFormat("void operator delete(int &) = default");
10869   verifyFormat("void operator delete(int &) = delete");
10870   verifyFormat("void operator delete(int &) [[noreturn]]");
10871   verifyFormat("void operator delete(int &) throw();");
10872   verifyFormat("void operator delete(int &) throw(int);");
10873   verifyFormat("auto operator delete(int &) -> int;");
10874   verifyFormat("auto operator delete(int &) override");
10875   verifyFormat("auto operator delete(int &) final");
10876 
10877   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10878                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10879   // FIXME: The indentation here is not ideal.
10880   verifyFormat(
10881       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10882       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10883       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10884 }
10885 
10886 TEST_F(FormatTest, FormatsFunctionTypes) {
10887   verifyFormat("A<bool()> a;");
10888   verifyFormat("A<SomeType()> a;");
10889   verifyFormat("A<void (*)(int, std::string)> a;");
10890   verifyFormat("A<void *(int)>;");
10891   verifyFormat("void *(*a)(int *, SomeType *);");
10892   verifyFormat("int (*func)(void *);");
10893   verifyFormat("void f() { int (*func)(void *); }");
10894   verifyFormat("template <class CallbackClass>\n"
10895                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10896 
10897   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10898   verifyGoogleFormat("void* (*a)(int);");
10899   verifyGoogleFormat(
10900       "template <class CallbackClass>\n"
10901       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10902 
10903   // Other constructs can look somewhat like function types:
10904   verifyFormat("A<sizeof(*x)> a;");
10905   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10906   verifyFormat("some_var = function(*some_pointer_var)[0];");
10907   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10908   verifyFormat("int x = f(&h)();");
10909   verifyFormat("returnsFunction(&param1, &param2)(param);");
10910   verifyFormat("std::function<\n"
10911                "    LooooooooooongTemplatedType<\n"
10912                "        SomeType>*(\n"
10913                "        LooooooooooooooooongType type)>\n"
10914                "    function;",
10915                getGoogleStyleWithColumns(40));
10916 }
10917 
10918 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10919   verifyFormat("A (*foo_)[6];");
10920   verifyFormat("vector<int> (*foo_)[6];");
10921 }
10922 
10923 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10924   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10925                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10926   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10927                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10928   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10929                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10930 
10931   // Different ways of ()-initializiation.
10932   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10933                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10934   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10935                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10936   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10937                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10938   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10939                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10940 
10941   // Lambdas should not confuse the variable declaration heuristic.
10942   verifyFormat("LooooooooooooooooongType\n"
10943                "    variable(nullptr, [](A *a) {});",
10944                getLLVMStyleWithColumns(40));
10945 }
10946 
10947 TEST_F(FormatTest, BreaksLongDeclarations) {
10948   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10949                "    AnotherNameForTheLongType;");
10950   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10951                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10952   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10953                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10954   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10955                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10956   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10957                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10958   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10959                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10960   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10961                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10962   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10963                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10964   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10965                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10966   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10967                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10968   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10969                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10970   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10971                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10972   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10973                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10974   FormatStyle Indented = getLLVMStyle();
10975   Indented.IndentWrappedFunctionNames = true;
10976   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10977                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10978                Indented);
10979   verifyFormat(
10980       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10981       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10982       Indented);
10983   verifyFormat(
10984       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10985       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10986       Indented);
10987   verifyFormat(
10988       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10989       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10990       Indented);
10991 
10992   // FIXME: Without the comment, this breaks after "(".
10993   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10994                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10995                getGoogleStyle());
10996 
10997   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
10998                "                  int LoooooooooooooooooooongParam2) {}");
10999   verifyFormat(
11000       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
11001       "                                   SourceLocation L, IdentifierIn *II,\n"
11002       "                                   Type *T) {}");
11003   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
11004                "ReallyReaaallyLongFunctionName(\n"
11005                "    const std::string &SomeParameter,\n"
11006                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11007                "        &ReallyReallyLongParameterName,\n"
11008                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11009                "        &AnotherLongParameterName) {}");
11010   verifyFormat("template <typename A>\n"
11011                "SomeLoooooooooooooooooooooongType<\n"
11012                "    typename some_namespace::SomeOtherType<A>::Type>\n"
11013                "Function() {}");
11014 
11015   verifyGoogleFormat(
11016       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
11017       "    aaaaaaaaaaaaaaaaaaaaaaa;");
11018   verifyGoogleFormat(
11019       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
11020       "                                   SourceLocation L) {}");
11021   verifyGoogleFormat(
11022       "some_namespace::LongReturnType\n"
11023       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
11024       "    int first_long_parameter, int second_parameter) {}");
11025 
11026   verifyGoogleFormat("template <typename T>\n"
11027                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11028                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
11029   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11030                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
11031 
11032   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
11033                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11034                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11035   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11036                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11037                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
11038   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11039                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
11040                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
11041                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11042 
11043   verifyFormat("template <typename T> // Templates on own line.\n"
11044                "static int            // Some comment.\n"
11045                "MyFunction(int a);",
11046                getLLVMStyle());
11047 }
11048 
11049 TEST_F(FormatTest, FormatsAccessModifiers) {
11050   FormatStyle Style = getLLVMStyle();
11051   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
11052             FormatStyle::ELBAMS_LogicalBlock);
11053   verifyFormat("struct foo {\n"
11054                "private:\n"
11055                "  void f() {}\n"
11056                "\n"
11057                "private:\n"
11058                "  int i;\n"
11059                "\n"
11060                "protected:\n"
11061                "  int j;\n"
11062                "};\n",
11063                Style);
11064   verifyFormat("struct foo {\n"
11065                "private:\n"
11066                "  void f() {}\n"
11067                "\n"
11068                "private:\n"
11069                "  int i;\n"
11070                "\n"
11071                "protected:\n"
11072                "  int j;\n"
11073                "};\n",
11074                "struct foo {\n"
11075                "private:\n"
11076                "  void f() {}\n"
11077                "private:\n"
11078                "  int i;\n"
11079                "protected:\n"
11080                "  int j;\n"
11081                "};\n",
11082                Style);
11083   verifyFormat("struct foo { /* comment */\n"
11084                "private:\n"
11085                "  int i;\n"
11086                "  // comment\n"
11087                "private:\n"
11088                "  int j;\n"
11089                "};\n",
11090                Style);
11091   verifyFormat("struct foo {\n"
11092                "#ifdef FOO\n"
11093                "#endif\n"
11094                "private:\n"
11095                "  int i;\n"
11096                "#ifdef FOO\n"
11097                "private:\n"
11098                "#endif\n"
11099                "  int j;\n"
11100                "};\n",
11101                Style);
11102   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11103   verifyFormat("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 {\n"
11113                "private:\n"
11114                "  void f() {}\n"
11115                "private:\n"
11116                "  int i;\n"
11117                "protected:\n"
11118                "  int j;\n"
11119                "};\n",
11120                "struct foo {\n"
11121                "\n"
11122                "private:\n"
11123                "  void f() {}\n"
11124                "\n"
11125                "private:\n"
11126                "  int i;\n"
11127                "\n"
11128                "protected:\n"
11129                "  int j;\n"
11130                "};\n",
11131                Style);
11132   verifyFormat("struct foo { /* comment */\n"
11133                "private:\n"
11134                "  int i;\n"
11135                "  // comment\n"
11136                "private:\n"
11137                "  int j;\n"
11138                "};\n",
11139                "struct foo { /* comment */\n"
11140                "\n"
11141                "private:\n"
11142                "  int i;\n"
11143                "  // comment\n"
11144                "\n"
11145                "private:\n"
11146                "  int j;\n"
11147                "};\n",
11148                Style);
11149   verifyFormat("struct foo {\n"
11150                "#ifdef FOO\n"
11151                "#endif\n"
11152                "private:\n"
11153                "  int i;\n"
11154                "#ifdef FOO\n"
11155                "private:\n"
11156                "#endif\n"
11157                "  int j;\n"
11158                "};\n",
11159                "struct foo {\n"
11160                "#ifdef FOO\n"
11161                "#endif\n"
11162                "\n"
11163                "private:\n"
11164                "  int i;\n"
11165                "#ifdef FOO\n"
11166                "\n"
11167                "private:\n"
11168                "#endif\n"
11169                "  int j;\n"
11170                "};\n",
11171                Style);
11172   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11173   verifyFormat("struct foo {\n"
11174                "private:\n"
11175                "  void f() {}\n"
11176                "\n"
11177                "private:\n"
11178                "  int i;\n"
11179                "\n"
11180                "protected:\n"
11181                "  int j;\n"
11182                "};\n",
11183                Style);
11184   verifyFormat("struct foo {\n"
11185                "private:\n"
11186                "  void f() {}\n"
11187                "\n"
11188                "private:\n"
11189                "  int i;\n"
11190                "\n"
11191                "protected:\n"
11192                "  int j;\n"
11193                "};\n",
11194                "struct foo {\n"
11195                "private:\n"
11196                "  void f() {}\n"
11197                "private:\n"
11198                "  int i;\n"
11199                "protected:\n"
11200                "  int j;\n"
11201                "};\n",
11202                Style);
11203   verifyFormat("struct foo { /* comment */\n"
11204                "private:\n"
11205                "  int i;\n"
11206                "  // comment\n"
11207                "\n"
11208                "private:\n"
11209                "  int j;\n"
11210                "};\n",
11211                "struct foo { /* comment */\n"
11212                "private:\n"
11213                "  int i;\n"
11214                "  // comment\n"
11215                "\n"
11216                "private:\n"
11217                "  int j;\n"
11218                "};\n",
11219                Style);
11220   verifyFormat("struct foo {\n"
11221                "#ifdef FOO\n"
11222                "#endif\n"
11223                "\n"
11224                "private:\n"
11225                "  int i;\n"
11226                "#ifdef FOO\n"
11227                "\n"
11228                "private:\n"
11229                "#endif\n"
11230                "  int j;\n"
11231                "};\n",
11232                "struct foo {\n"
11233                "#ifdef FOO\n"
11234                "#endif\n"
11235                "private:\n"
11236                "  int i;\n"
11237                "#ifdef FOO\n"
11238                "private:\n"
11239                "#endif\n"
11240                "  int j;\n"
11241                "};\n",
11242                Style);
11243   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11244   EXPECT_EQ("struct foo {\n"
11245             "\n"
11246             "private:\n"
11247             "  void f() {}\n"
11248             "\n"
11249             "private:\n"
11250             "  int i;\n"
11251             "\n"
11252             "protected:\n"
11253             "  int j;\n"
11254             "};\n",
11255             format("struct foo {\n"
11256                    "\n"
11257                    "private:\n"
11258                    "  void f() {}\n"
11259                    "\n"
11260                    "private:\n"
11261                    "  int i;\n"
11262                    "\n"
11263                    "protected:\n"
11264                    "  int j;\n"
11265                    "};\n",
11266                    Style));
11267   verifyFormat("struct foo {\n"
11268                "private:\n"
11269                "  void f() {}\n"
11270                "private:\n"
11271                "  int i;\n"
11272                "protected:\n"
11273                "  int j;\n"
11274                "};\n",
11275                Style);
11276   EXPECT_EQ("struct foo { /* comment */\n"
11277             "\n"
11278             "private:\n"
11279             "  int i;\n"
11280             "  // comment\n"
11281             "\n"
11282             "private:\n"
11283             "  int j;\n"
11284             "};\n",
11285             format("struct foo { /* comment */\n"
11286                    "\n"
11287                    "private:\n"
11288                    "  int i;\n"
11289                    "  // comment\n"
11290                    "\n"
11291                    "private:\n"
11292                    "  int j;\n"
11293                    "};\n",
11294                    Style));
11295   verifyFormat("struct foo { /* comment */\n"
11296                "private:\n"
11297                "  int i;\n"
11298                "  // comment\n"
11299                "private:\n"
11300                "  int j;\n"
11301                "};\n",
11302                Style);
11303   EXPECT_EQ("struct foo {\n"
11304             "#ifdef FOO\n"
11305             "#endif\n"
11306             "\n"
11307             "private:\n"
11308             "  int i;\n"
11309             "#ifdef FOO\n"
11310             "\n"
11311             "private:\n"
11312             "#endif\n"
11313             "  int j;\n"
11314             "};\n",
11315             format("struct foo {\n"
11316                    "#ifdef FOO\n"
11317                    "#endif\n"
11318                    "\n"
11319                    "private:\n"
11320                    "  int i;\n"
11321                    "#ifdef FOO\n"
11322                    "\n"
11323                    "private:\n"
11324                    "#endif\n"
11325                    "  int j;\n"
11326                    "};\n",
11327                    Style));
11328   verifyFormat("struct foo {\n"
11329                "#ifdef FOO\n"
11330                "#endif\n"
11331                "private:\n"
11332                "  int i;\n"
11333                "#ifdef FOO\n"
11334                "private:\n"
11335                "#endif\n"
11336                "  int j;\n"
11337                "};\n",
11338                Style);
11339 
11340   FormatStyle NoEmptyLines = getLLVMStyle();
11341   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11342   verifyFormat("struct foo {\n"
11343                "private:\n"
11344                "  void f() {}\n"
11345                "\n"
11346                "private:\n"
11347                "  int i;\n"
11348                "\n"
11349                "public:\n"
11350                "protected:\n"
11351                "  int j;\n"
11352                "};\n",
11353                NoEmptyLines);
11354 
11355   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11356   verifyFormat("struct foo {\n"
11357                "private:\n"
11358                "  void f() {}\n"
11359                "private:\n"
11360                "  int i;\n"
11361                "public:\n"
11362                "protected:\n"
11363                "  int j;\n"
11364                "};\n",
11365                NoEmptyLines);
11366 
11367   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11368   verifyFormat("struct foo {\n"
11369                "private:\n"
11370                "  void f() {}\n"
11371                "\n"
11372                "private:\n"
11373                "  int i;\n"
11374                "\n"
11375                "public:\n"
11376                "\n"
11377                "protected:\n"
11378                "  int j;\n"
11379                "};\n",
11380                NoEmptyLines);
11381 }
11382 
11383 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
11384 
11385   FormatStyle Style = getLLVMStyle();
11386   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
11387   verifyFormat("struct foo {\n"
11388                "private:\n"
11389                "  void f() {}\n"
11390                "\n"
11391                "private:\n"
11392                "  int i;\n"
11393                "\n"
11394                "protected:\n"
11395                "  int j;\n"
11396                "};\n",
11397                Style);
11398 
11399   // Check if lines are removed.
11400   verifyFormat("struct foo {\n"
11401                "private:\n"
11402                "  void f() {}\n"
11403                "\n"
11404                "private:\n"
11405                "  int i;\n"
11406                "\n"
11407                "protected:\n"
11408                "  int j;\n"
11409                "};\n",
11410                "struct foo {\n"
11411                "private:\n"
11412                "\n"
11413                "  void f() {}\n"
11414                "\n"
11415                "private:\n"
11416                "\n"
11417                "  int i;\n"
11418                "\n"
11419                "protected:\n"
11420                "\n"
11421                "  int j;\n"
11422                "};\n",
11423                Style);
11424 
11425   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11426   verifyFormat("struct foo {\n"
11427                "private:\n"
11428                "\n"
11429                "  void f() {}\n"
11430                "\n"
11431                "private:\n"
11432                "\n"
11433                "  int i;\n"
11434                "\n"
11435                "protected:\n"
11436                "\n"
11437                "  int j;\n"
11438                "};\n",
11439                Style);
11440 
11441   // Check if lines are added.
11442   verifyFormat("struct foo {\n"
11443                "private:\n"
11444                "\n"
11445                "  void f() {}\n"
11446                "\n"
11447                "private:\n"
11448                "\n"
11449                "  int i;\n"
11450                "\n"
11451                "protected:\n"
11452                "\n"
11453                "  int j;\n"
11454                "};\n",
11455                "struct foo {\n"
11456                "private:\n"
11457                "  void f() {}\n"
11458                "\n"
11459                "private:\n"
11460                "  int i;\n"
11461                "\n"
11462                "protected:\n"
11463                "  int j;\n"
11464                "};\n",
11465                Style);
11466 
11467   // Leave tests rely on the code layout, test::messUp can not be used.
11468   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11469   Style.MaxEmptyLinesToKeep = 0u;
11470   verifyFormat("struct foo {\n"
11471                "private:\n"
11472                "  void f() {}\n"
11473                "\n"
11474                "private:\n"
11475                "  int i;\n"
11476                "\n"
11477                "protected:\n"
11478                "  int j;\n"
11479                "};\n",
11480                Style);
11481 
11482   // Check if MaxEmptyLinesToKeep is respected.
11483   EXPECT_EQ("struct foo {\n"
11484             "private:\n"
11485             "  void f() {}\n"
11486             "\n"
11487             "private:\n"
11488             "  int i;\n"
11489             "\n"
11490             "protected:\n"
11491             "  int j;\n"
11492             "};\n",
11493             format("struct foo {\n"
11494                    "private:\n"
11495                    "\n\n\n"
11496                    "  void f() {}\n"
11497                    "\n"
11498                    "private:\n"
11499                    "\n\n\n"
11500                    "  int i;\n"
11501                    "\n"
11502                    "protected:\n"
11503                    "\n\n\n"
11504                    "  int j;\n"
11505                    "};\n",
11506                    Style));
11507 
11508   Style.MaxEmptyLinesToKeep = 1u;
11509   EXPECT_EQ("struct foo {\n"
11510             "private:\n"
11511             "\n"
11512             "  void f() {}\n"
11513             "\n"
11514             "private:\n"
11515             "\n"
11516             "  int i;\n"
11517             "\n"
11518             "protected:\n"
11519             "\n"
11520             "  int j;\n"
11521             "};\n",
11522             format("struct foo {\n"
11523                    "private:\n"
11524                    "\n"
11525                    "  void f() {}\n"
11526                    "\n"
11527                    "private:\n"
11528                    "\n"
11529                    "  int i;\n"
11530                    "\n"
11531                    "protected:\n"
11532                    "\n"
11533                    "  int j;\n"
11534                    "};\n",
11535                    Style));
11536   // Check if no lines are kept.
11537   EXPECT_EQ("struct foo {\n"
11538             "private:\n"
11539             "  void f() {}\n"
11540             "\n"
11541             "private:\n"
11542             "  int i;\n"
11543             "\n"
11544             "protected:\n"
11545             "  int j;\n"
11546             "};\n",
11547             format("struct foo {\n"
11548                    "private:\n"
11549                    "  void f() {}\n"
11550                    "\n"
11551                    "private:\n"
11552                    "  int i;\n"
11553                    "\n"
11554                    "protected:\n"
11555                    "  int j;\n"
11556                    "};\n",
11557                    Style));
11558   // Check if MaxEmptyLinesToKeep is respected.
11559   EXPECT_EQ("struct foo {\n"
11560             "private:\n"
11561             "\n"
11562             "  void f() {}\n"
11563             "\n"
11564             "private:\n"
11565             "\n"
11566             "  int i;\n"
11567             "\n"
11568             "protected:\n"
11569             "\n"
11570             "  int j;\n"
11571             "};\n",
11572             format("struct foo {\n"
11573                    "private:\n"
11574                    "\n\n\n"
11575                    "  void f() {}\n"
11576                    "\n"
11577                    "private:\n"
11578                    "\n\n\n"
11579                    "  int i;\n"
11580                    "\n"
11581                    "protected:\n"
11582                    "\n\n\n"
11583                    "  int j;\n"
11584                    "};\n",
11585                    Style));
11586 
11587   Style.MaxEmptyLinesToKeep = 10u;
11588   EXPECT_EQ("struct foo {\n"
11589             "private:\n"
11590             "\n\n\n"
11591             "  void f() {}\n"
11592             "\n"
11593             "private:\n"
11594             "\n\n\n"
11595             "  int i;\n"
11596             "\n"
11597             "protected:\n"
11598             "\n\n\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   // Test with comments.
11617   Style = getLLVMStyle();
11618   verifyFormat("struct foo {\n"
11619                "private:\n"
11620                "  // comment\n"
11621                "  void f() {}\n"
11622                "\n"
11623                "private: /* comment */\n"
11624                "  int i;\n"
11625                "};\n",
11626                Style);
11627   verifyFormat("struct foo {\n"
11628                "private:\n"
11629                "  // comment\n"
11630                "  void f() {}\n"
11631                "\n"
11632                "private: /* comment */\n"
11633                "  int i;\n"
11634                "};\n",
11635                "struct foo {\n"
11636                "private:\n"
11637                "\n"
11638                "  // comment\n"
11639                "  void f() {}\n"
11640                "\n"
11641                "private: /* comment */\n"
11642                "\n"
11643                "  int i;\n"
11644                "};\n",
11645                Style);
11646 
11647   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11648   verifyFormat("struct foo {\n"
11649                "private:\n"
11650                "\n"
11651                "  // comment\n"
11652                "  void f() {}\n"
11653                "\n"
11654                "private: /* comment */\n"
11655                "\n"
11656                "  int i;\n"
11657                "};\n",
11658                "struct foo {\n"
11659                "private:\n"
11660                "  // comment\n"
11661                "  void f() {}\n"
11662                "\n"
11663                "private: /* comment */\n"
11664                "  int i;\n"
11665                "};\n",
11666                Style);
11667   verifyFormat("struct foo {\n"
11668                "private:\n"
11669                "\n"
11670                "  // comment\n"
11671                "  void f() {}\n"
11672                "\n"
11673                "private: /* comment */\n"
11674                "\n"
11675                "  int i;\n"
11676                "};\n",
11677                Style);
11678 
11679   // Test with preprocessor defines.
11680   Style = getLLVMStyle();
11681   verifyFormat("struct foo {\n"
11682                "private:\n"
11683                "#ifdef FOO\n"
11684                "#endif\n"
11685                "  void f() {}\n"
11686                "};\n",
11687                Style);
11688   verifyFormat("struct foo {\n"
11689                "private:\n"
11690                "#ifdef FOO\n"
11691                "#endif\n"
11692                "  void f() {}\n"
11693                "};\n",
11694                "struct foo {\n"
11695                "private:\n"
11696                "\n"
11697                "#ifdef FOO\n"
11698                "#endif\n"
11699                "  void f() {}\n"
11700                "};\n",
11701                Style);
11702 
11703   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11704   verifyFormat("struct foo {\n"
11705                "private:\n"
11706                "\n"
11707                "#ifdef FOO\n"
11708                "#endif\n"
11709                "  void f() {}\n"
11710                "};\n",
11711                "struct foo {\n"
11712                "private:\n"
11713                "#ifdef FOO\n"
11714                "#endif\n"
11715                "  void f() {}\n"
11716                "};\n",
11717                Style);
11718   verifyFormat("struct foo {\n"
11719                "private:\n"
11720                "\n"
11721                "#ifdef FOO\n"
11722                "#endif\n"
11723                "  void f() {}\n"
11724                "};\n",
11725                Style);
11726 }
11727 
11728 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11729   // Combined tests of EmptyLineAfterAccessModifier and
11730   // EmptyLineBeforeAccessModifier.
11731   FormatStyle Style = getLLVMStyle();
11732   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11733   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11734   verifyFormat("struct foo {\n"
11735                "private:\n"
11736                "\n"
11737                "protected:\n"
11738                "};\n",
11739                Style);
11740 
11741   Style.MaxEmptyLinesToKeep = 10u;
11742   // Both remove all new lines.
11743   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11744   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11745   verifyFormat("struct foo {\n"
11746                "private:\n"
11747                "protected:\n"
11748                "};\n",
11749                "struct foo {\n"
11750                "private:\n"
11751                "\n\n\n"
11752                "protected:\n"
11753                "};\n",
11754                Style);
11755 
11756   // Leave tests rely on the code layout, test::messUp can not be used.
11757   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11758   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11759   Style.MaxEmptyLinesToKeep = 10u;
11760   EXPECT_EQ("struct foo {\n"
11761             "private:\n"
11762             "\n\n\n"
11763             "protected:\n"
11764             "};\n",
11765             format("struct foo {\n"
11766                    "private:\n"
11767                    "\n\n\n"
11768                    "protected:\n"
11769                    "};\n",
11770                    Style));
11771   Style.MaxEmptyLinesToKeep = 3u;
11772   EXPECT_EQ("struct foo {\n"
11773             "private:\n"
11774             "\n\n\n"
11775             "protected:\n"
11776             "};\n",
11777             format("struct foo {\n"
11778                    "private:\n"
11779                    "\n\n\n"
11780                    "protected:\n"
11781                    "};\n",
11782                    Style));
11783   Style.MaxEmptyLinesToKeep = 1u;
11784   EXPECT_EQ("struct foo {\n"
11785             "private:\n"
11786             "\n\n\n"
11787             "protected:\n"
11788             "};\n",
11789             format("struct foo {\n"
11790                    "private:\n"
11791                    "\n\n\n"
11792                    "protected:\n"
11793                    "};\n",
11794                    Style)); // Based on new lines in original document and not
11795                             // on the setting.
11796 
11797   Style.MaxEmptyLinesToKeep = 10u;
11798   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11799   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11800   // Newlines are kept if they are greater than zero,
11801   // test::messUp removes all new lines which changes the logic
11802   EXPECT_EQ("struct foo {\n"
11803             "private:\n"
11804             "\n\n\n"
11805             "protected:\n"
11806             "};\n",
11807             format("struct foo {\n"
11808                    "private:\n"
11809                    "\n\n\n"
11810                    "protected:\n"
11811                    "};\n",
11812                    Style));
11813 
11814   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11815   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11816   // test::messUp removes all new lines which changes the logic
11817   EXPECT_EQ("struct foo {\n"
11818             "private:\n"
11819             "\n\n\n"
11820             "protected:\n"
11821             "};\n",
11822             format("struct foo {\n"
11823                    "private:\n"
11824                    "\n\n\n"
11825                    "protected:\n"
11826                    "};\n",
11827                    Style));
11828 
11829   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11830   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
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)); // test::messUp removes all new lines which changes
11842                             // the logic.
11843 
11844   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11845   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11846   verifyFormat("struct foo {\n"
11847                "private:\n"
11848                "protected:\n"
11849                "};\n",
11850                "struct foo {\n"
11851                "private:\n"
11852                "\n\n\n"
11853                "protected:\n"
11854                "};\n",
11855                Style);
11856 
11857   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11858   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11859   EXPECT_EQ("struct foo {\n"
11860             "private:\n"
11861             "\n\n\n"
11862             "protected:\n"
11863             "};\n",
11864             format("struct foo {\n"
11865                    "private:\n"
11866                    "\n\n\n"
11867                    "protected:\n"
11868                    "};\n",
11869                    Style)); // test::messUp removes all new lines which changes
11870                             // the logic.
11871 
11872   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11873   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11874   verifyFormat("struct foo {\n"
11875                "private:\n"
11876                "protected:\n"
11877                "};\n",
11878                "struct foo {\n"
11879                "private:\n"
11880                "\n\n\n"
11881                "protected:\n"
11882                "};\n",
11883                Style);
11884 
11885   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11886   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11887   verifyFormat("struct foo {\n"
11888                "private:\n"
11889                "protected:\n"
11890                "};\n",
11891                "struct foo {\n"
11892                "private:\n"
11893                "\n\n\n"
11894                "protected:\n"
11895                "};\n",
11896                Style);
11897 
11898   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11899   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11900   verifyFormat("struct foo {\n"
11901                "private:\n"
11902                "protected:\n"
11903                "};\n",
11904                "struct foo {\n"
11905                "private:\n"
11906                "\n\n\n"
11907                "protected:\n"
11908                "};\n",
11909                Style);
11910 
11911   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11912   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11913   verifyFormat("struct foo {\n"
11914                "private:\n"
11915                "protected:\n"
11916                "};\n",
11917                "struct foo {\n"
11918                "private:\n"
11919                "\n\n\n"
11920                "protected:\n"
11921                "};\n",
11922                Style);
11923 }
11924 
11925 TEST_F(FormatTest, FormatsArrays) {
11926   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11927                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11928   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11929                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11930   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11931                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11932   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11933                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11934   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11935                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11936   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11937                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11938                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11939   verifyFormat(
11940       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11941       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11942       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11943   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11944                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11945 
11946   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11947                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11948   verifyFormat(
11949       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11950       "                                  .aaaaaaa[0]\n"
11951       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11952   verifyFormat("a[::b::c];");
11953 
11954   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11955 
11956   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11957   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11958 }
11959 
11960 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11961   verifyFormat("(a)->b();");
11962   verifyFormat("--a;");
11963 }
11964 
11965 TEST_F(FormatTest, HandlesIncludeDirectives) {
11966   verifyFormat("#include <string>\n"
11967                "#include <a/b/c.h>\n"
11968                "#include \"a/b/string\"\n"
11969                "#include \"string.h\"\n"
11970                "#include \"string.h\"\n"
11971                "#include <a-a>\n"
11972                "#include < path with space >\n"
11973                "#include_next <test.h>"
11974                "#include \"abc.h\" // this is included for ABC\n"
11975                "#include \"some long include\" // with a comment\n"
11976                "#include \"some very long include path\"\n"
11977                "#include <some/very/long/include/path>\n",
11978                getLLVMStyleWithColumns(35));
11979   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11980   EXPECT_EQ("#include <a>", format("#include<a>"));
11981 
11982   verifyFormat("#import <string>");
11983   verifyFormat("#import <a/b/c.h>");
11984   verifyFormat("#import \"a/b/string\"");
11985   verifyFormat("#import \"string.h\"");
11986   verifyFormat("#import \"string.h\"");
11987   verifyFormat("#if __has_include(<strstream>)\n"
11988                "#include <strstream>\n"
11989                "#endif");
11990 
11991   verifyFormat("#define MY_IMPORT <a/b>");
11992 
11993   verifyFormat("#if __has_include(<a/b>)");
11994   verifyFormat("#if __has_include_next(<a/b>)");
11995   verifyFormat("#define F __has_include(<a/b>)");
11996   verifyFormat("#define F __has_include_next(<a/b>)");
11997 
11998   // Protocol buffer definition or missing "#".
11999   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
12000                getLLVMStyleWithColumns(30));
12001 
12002   FormatStyle Style = getLLVMStyle();
12003   Style.AlwaysBreakBeforeMultilineStrings = true;
12004   Style.ColumnLimit = 0;
12005   verifyFormat("#import \"abc.h\"", Style);
12006 
12007   // But 'import' might also be a regular C++ namespace.
12008   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12009                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
12010 }
12011 
12012 //===----------------------------------------------------------------------===//
12013 // Error recovery tests.
12014 //===----------------------------------------------------------------------===//
12015 
12016 TEST_F(FormatTest, IncompleteParameterLists) {
12017   FormatStyle NoBinPacking = getLLVMStyle();
12018   NoBinPacking.BinPackParameters = false;
12019   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
12020                "                        double *min_x,\n"
12021                "                        double *max_x,\n"
12022                "                        double *min_y,\n"
12023                "                        double *max_y,\n"
12024                "                        double *min_z,\n"
12025                "                        double *max_z, ) {}",
12026                NoBinPacking);
12027 }
12028 
12029 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
12030   verifyFormat("void f() { return; }\n42");
12031   verifyFormat("void f() {\n"
12032                "  if (0)\n"
12033                "    return;\n"
12034                "}\n"
12035                "42");
12036   verifyFormat("void f() { return }\n42");
12037   verifyFormat("void f() {\n"
12038                "  if (0)\n"
12039                "    return\n"
12040                "}\n"
12041                "42");
12042 }
12043 
12044 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
12045   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
12046   EXPECT_EQ("void f() {\n"
12047             "  if (a)\n"
12048             "    return\n"
12049             "}",
12050             format("void  f  (  )  {  if  ( a )  return  }"));
12051   EXPECT_EQ("namespace N {\n"
12052             "void f()\n"
12053             "}",
12054             format("namespace  N  {  void f()  }"));
12055   EXPECT_EQ("namespace N {\n"
12056             "void f() {}\n"
12057             "void g()\n"
12058             "} // namespace N",
12059             format("namespace N  { void f( ) { } void g( ) }"));
12060 }
12061 
12062 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
12063   verifyFormat("int aaaaaaaa =\n"
12064                "    // Overlylongcomment\n"
12065                "    b;",
12066                getLLVMStyleWithColumns(20));
12067   verifyFormat("function(\n"
12068                "    ShortArgument,\n"
12069                "    LoooooooooooongArgument);\n",
12070                getLLVMStyleWithColumns(20));
12071 }
12072 
12073 TEST_F(FormatTest, IncorrectAccessSpecifier) {
12074   verifyFormat("public:");
12075   verifyFormat("class A {\n"
12076                "public\n"
12077                "  void f() {}\n"
12078                "};");
12079   verifyFormat("public\n"
12080                "int qwerty;");
12081   verifyFormat("public\n"
12082                "B {}");
12083   verifyFormat("public\n"
12084                "{}");
12085   verifyFormat("public\n"
12086                "B { int x; }");
12087 }
12088 
12089 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
12090   verifyFormat("{");
12091   verifyFormat("#})");
12092   verifyNoCrash("(/**/[:!] ?[).");
12093 }
12094 
12095 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
12096   // Found by oss-fuzz:
12097   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
12098   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
12099   Style.ColumnLimit = 60;
12100   verifyNoCrash(
12101       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
12102       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
12103       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
12104       Style);
12105 }
12106 
12107 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
12108   verifyFormat("do {\n}");
12109   verifyFormat("do {\n}\n"
12110                "f();");
12111   verifyFormat("do {\n}\n"
12112                "wheeee(fun);");
12113   verifyFormat("do {\n"
12114                "  f();\n"
12115                "}");
12116 }
12117 
12118 TEST_F(FormatTest, IncorrectCodeMissingParens) {
12119   verifyFormat("if {\n  foo;\n  foo();\n}");
12120   verifyFormat("switch {\n  foo;\n  foo();\n}");
12121   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
12122   verifyIncompleteFormat("ERROR: for target;");
12123   verifyFormat("while {\n  foo;\n  foo();\n}");
12124   verifyFormat("do {\n  foo;\n  foo();\n} while;");
12125 }
12126 
12127 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
12128   verifyIncompleteFormat("namespace {\n"
12129                          "class Foo { Foo (\n"
12130                          "};\n"
12131                          "} // namespace");
12132 }
12133 
12134 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
12135   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
12136   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
12137   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
12138   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
12139 
12140   EXPECT_EQ("{\n"
12141             "  {\n"
12142             "    breakme(\n"
12143             "        qwe);\n"
12144             "  }\n",
12145             format("{\n"
12146                    "    {\n"
12147                    " breakme(qwe);\n"
12148                    "}\n",
12149                    getLLVMStyleWithColumns(10)));
12150 }
12151 
12152 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
12153   verifyFormat("int x = {\n"
12154                "    avariable,\n"
12155                "    b(alongervariable)};",
12156                getLLVMStyleWithColumns(25));
12157 }
12158 
12159 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
12160   verifyFormat("return (a)(b){1, 2, 3};");
12161 }
12162 
12163 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
12164   verifyFormat("vector<int> x{1, 2, 3, 4};");
12165   verifyFormat("vector<int> x{\n"
12166                "    1,\n"
12167                "    2,\n"
12168                "    3,\n"
12169                "    4,\n"
12170                "};");
12171   verifyFormat("vector<T> x{{}, {}, {}, {}};");
12172   verifyFormat("f({1, 2});");
12173   verifyFormat("auto v = Foo{-1};");
12174   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
12175   verifyFormat("Class::Class : member{1, 2, 3} {}");
12176   verifyFormat("new vector<int>{1, 2, 3};");
12177   verifyFormat("new int[3]{1, 2, 3};");
12178   verifyFormat("new int{1};");
12179   verifyFormat("return {arg1, arg2};");
12180   verifyFormat("return {arg1, SomeType{parameter}};");
12181   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
12182   verifyFormat("new T{arg1, arg2};");
12183   verifyFormat("f(MyMap[{composite, key}]);");
12184   verifyFormat("class Class {\n"
12185                "  T member = {arg1, arg2};\n"
12186                "};");
12187   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
12188   verifyFormat("const struct A a = {.a = 1, .b = 2};");
12189   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
12190   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
12191   verifyFormat("int a = std::is_integral<int>{} + 0;");
12192 
12193   verifyFormat("int foo(int i) { return fo1{}(i); }");
12194   verifyFormat("int foo(int i) { return fo1{}(i); }");
12195   verifyFormat("auto i = decltype(x){};");
12196   verifyFormat("auto i = typeof(x){};");
12197   verifyFormat("auto i = _Atomic(x){};");
12198   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
12199   verifyFormat("Node n{1, Node{1000}, //\n"
12200                "       2};");
12201   verifyFormat("Aaaa aaaaaaa{\n"
12202                "    {\n"
12203                "        aaaa,\n"
12204                "    },\n"
12205                "};");
12206   verifyFormat("class C : public D {\n"
12207                "  SomeClass SC{2};\n"
12208                "};");
12209   verifyFormat("class C : public A {\n"
12210                "  class D : public B {\n"
12211                "    void f() { int i{2}; }\n"
12212                "  };\n"
12213                "};");
12214   verifyFormat("#define A {a, a},");
12215   // Don't confuse braced list initializers with compound statements.
12216   verifyFormat(
12217       "class A {\n"
12218       "  A() : a{} {}\n"
12219       "  A(int b) : b(b) {}\n"
12220       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
12221       "  int a, b;\n"
12222       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
12223       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
12224       "{}\n"
12225       "};");
12226 
12227   // Avoid breaking between equal sign and opening brace
12228   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
12229   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
12230   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
12231                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
12232                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
12233                "     {\"ccccccccccccccccccccc\", 2}};",
12234                AvoidBreakingFirstArgument);
12235 
12236   // Binpacking only if there is no trailing comma
12237   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
12238                "                      cccccccccc, dddddddddd};",
12239                getLLVMStyleWithColumns(50));
12240   verifyFormat("const Aaaaaa aaaaa = {\n"
12241                "    aaaaaaaaaaa,\n"
12242                "    bbbbbbbbbbb,\n"
12243                "    ccccccccccc,\n"
12244                "    ddddddddddd,\n"
12245                "};",
12246                getLLVMStyleWithColumns(50));
12247 
12248   // Cases where distinguising braced lists and blocks is hard.
12249   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
12250   verifyFormat("void f() {\n"
12251                "  return; // comment\n"
12252                "}\n"
12253                "SomeType t;");
12254   verifyFormat("void f() {\n"
12255                "  if (a) {\n"
12256                "    f();\n"
12257                "  }\n"
12258                "}\n"
12259                "SomeType t;");
12260 
12261   // In combination with BinPackArguments = false.
12262   FormatStyle NoBinPacking = getLLVMStyle();
12263   NoBinPacking.BinPackArguments = false;
12264   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
12265                "                      bbbbb,\n"
12266                "                      ccccc,\n"
12267                "                      ddddd,\n"
12268                "                      eeeee,\n"
12269                "                      ffffff,\n"
12270                "                      ggggg,\n"
12271                "                      hhhhhh,\n"
12272                "                      iiiiii,\n"
12273                "                      jjjjjj,\n"
12274                "                      kkkkkk};",
12275                NoBinPacking);
12276   verifyFormat("const Aaaaaa aaaaa = {\n"
12277                "    aaaaa,\n"
12278                "    bbbbb,\n"
12279                "    ccccc,\n"
12280                "    ddddd,\n"
12281                "    eeeee,\n"
12282                "    ffffff,\n"
12283                "    ggggg,\n"
12284                "    hhhhhh,\n"
12285                "    iiiiii,\n"
12286                "    jjjjjj,\n"
12287                "    kkkkkk,\n"
12288                "};",
12289                NoBinPacking);
12290   verifyFormat(
12291       "const Aaaaaa aaaaa = {\n"
12292       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
12293       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
12294       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
12295       "};",
12296       NoBinPacking);
12297 
12298   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12299   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
12300             "    CDDDP83848_BMCR_REGISTER,\n"
12301             "    CDDDP83848_BMSR_REGISTER,\n"
12302             "    CDDDP83848_RBR_REGISTER};",
12303             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
12304                    "                                CDDDP83848_BMSR_REGISTER,\n"
12305                    "                                CDDDP83848_RBR_REGISTER};",
12306                    NoBinPacking));
12307 
12308   // FIXME: The alignment of these trailing comments might be bad. Then again,
12309   // this might be utterly useless in real code.
12310   verifyFormat("Constructor::Constructor()\n"
12311                "    : some_value{         //\n"
12312                "                 aaaaaaa, //\n"
12313                "                 bbbbbbb} {}");
12314 
12315   // In braced lists, the first comment is always assumed to belong to the
12316   // first element. Thus, it can be moved to the next or previous line as
12317   // appropriate.
12318   EXPECT_EQ("function({// First element:\n"
12319             "          1,\n"
12320             "          // Second element:\n"
12321             "          2});",
12322             format("function({\n"
12323                    "    // First element:\n"
12324                    "    1,\n"
12325                    "    // Second element:\n"
12326                    "    2});"));
12327   EXPECT_EQ("std::vector<int> MyNumbers{\n"
12328             "    // First element:\n"
12329             "    1,\n"
12330             "    // Second element:\n"
12331             "    2};",
12332             format("std::vector<int> MyNumbers{// First element:\n"
12333                    "                           1,\n"
12334                    "                           // Second element:\n"
12335                    "                           2};",
12336                    getLLVMStyleWithColumns(30)));
12337   // A trailing comma should still lead to an enforced line break and no
12338   // binpacking.
12339   EXPECT_EQ("vector<int> SomeVector = {\n"
12340             "    // aaa\n"
12341             "    1,\n"
12342             "    2,\n"
12343             "};",
12344             format("vector<int> SomeVector = { // aaa\n"
12345                    "    1, 2, };"));
12346 
12347   // C++11 brace initializer list l-braces should not be treated any differently
12348   // when breaking before lambda bodies is enabled
12349   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
12350   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
12351   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
12352   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
12353   verifyFormat(
12354       "std::runtime_error{\n"
12355       "    \"Long string which will force a break onto the next line...\"};",
12356       BreakBeforeLambdaBody);
12357 
12358   FormatStyle ExtraSpaces = getLLVMStyle();
12359   ExtraSpaces.Cpp11BracedListStyle = false;
12360   ExtraSpaces.ColumnLimit = 75;
12361   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
12362   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
12363   verifyFormat("f({ 1, 2 });", ExtraSpaces);
12364   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
12365   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
12366   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
12367   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
12368   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
12369   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
12370   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
12371   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
12372   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
12373   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
12374   verifyFormat("class Class {\n"
12375                "  T member = { arg1, arg2 };\n"
12376                "};",
12377                ExtraSpaces);
12378   verifyFormat(
12379       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12380       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
12381       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
12382       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
12383       ExtraSpaces);
12384   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
12385   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
12386                ExtraSpaces);
12387   verifyFormat(
12388       "someFunction(OtherParam,\n"
12389       "             BracedList{ // comment 1 (Forcing interesting break)\n"
12390       "                         param1, param2,\n"
12391       "                         // comment 2\n"
12392       "                         param3, param4 });",
12393       ExtraSpaces);
12394   verifyFormat(
12395       "std::this_thread::sleep_for(\n"
12396       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
12397       ExtraSpaces);
12398   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
12399                "    aaaaaaa,\n"
12400                "    aaaaaaaaaa,\n"
12401                "    aaaaa,\n"
12402                "    aaaaaaaaaaaaaaa,\n"
12403                "    aaa,\n"
12404                "    aaaaaaaaaa,\n"
12405                "    a,\n"
12406                "    aaaaaaaaaaaaaaaaaaaaa,\n"
12407                "    aaaaaaaaaaaa,\n"
12408                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
12409                "    aaaaaaa,\n"
12410                "    a};");
12411   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
12412   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
12413   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
12414 
12415   // Avoid breaking between initializer/equal sign and opening brace
12416   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
12417   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
12418                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12419                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12420                "  { \"ccccccccccccccccccccc\", 2 }\n"
12421                "};",
12422                ExtraSpaces);
12423   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
12424                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12425                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12426                "  { \"ccccccccccccccccccccc\", 2 }\n"
12427                "};",
12428                ExtraSpaces);
12429 
12430   FormatStyle SpaceBeforeBrace = getLLVMStyle();
12431   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
12432   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
12433   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
12434 
12435   FormatStyle SpaceBetweenBraces = getLLVMStyle();
12436   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
12437   SpaceBetweenBraces.SpacesInParentheses = true;
12438   SpaceBetweenBraces.SpacesInSquareBrackets = true;
12439   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
12440   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
12441   verifyFormat("vector< int > x{ // comment 1\n"
12442                "                 1, 2, 3, 4 };",
12443                SpaceBetweenBraces);
12444   SpaceBetweenBraces.ColumnLimit = 20;
12445   EXPECT_EQ("vector< int > x{\n"
12446             "    1, 2, 3, 4 };",
12447             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12448   SpaceBetweenBraces.ColumnLimit = 24;
12449   EXPECT_EQ("vector< int > x{ 1, 2,\n"
12450             "                 3, 4 };",
12451             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12452   EXPECT_EQ("vector< int > x{\n"
12453             "    1,\n"
12454             "    2,\n"
12455             "    3,\n"
12456             "    4,\n"
12457             "};",
12458             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12459   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12460   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12461   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12462 }
12463 
12464 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12465   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12466                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12467                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12468                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12469                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12470                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12471   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12472                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12473                "                 1, 22, 333, 4444, 55555, //\n"
12474                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12475                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12476   verifyFormat(
12477       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12478       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12479       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12480       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12481       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12482       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12483       "                 7777777};");
12484   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12485                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12486                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12487   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12488                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12489                "    // Separating comment.\n"
12490                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12491   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12492                "    // Leading comment\n"
12493                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12494                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12495   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12496                "                 1, 1, 1, 1};",
12497                getLLVMStyleWithColumns(39));
12498   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12499                "                 1, 1, 1, 1};",
12500                getLLVMStyleWithColumns(38));
12501   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12502                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12503                getLLVMStyleWithColumns(43));
12504   verifyFormat(
12505       "static unsigned SomeValues[10][3] = {\n"
12506       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12507       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12508   verifyFormat("static auto fields = new vector<string>{\n"
12509                "    \"aaaaaaaaaaaaa\",\n"
12510                "    \"aaaaaaaaaaaaa\",\n"
12511                "    \"aaaaaaaaaaaa\",\n"
12512                "    \"aaaaaaaaaaaaaa\",\n"
12513                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12514                "    \"aaaaaaaaaaaa\",\n"
12515                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12516                "};");
12517   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12518   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12519                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12520                "                 3, cccccccccccccccccccccc};",
12521                getLLVMStyleWithColumns(60));
12522 
12523   // Trailing commas.
12524   verifyFormat("vector<int> x = {\n"
12525                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12526                "};",
12527                getLLVMStyleWithColumns(39));
12528   verifyFormat("vector<int> x = {\n"
12529                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12530                "};",
12531                getLLVMStyleWithColumns(39));
12532   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12533                "                 1, 1, 1, 1,\n"
12534                "                 /**/ /**/};",
12535                getLLVMStyleWithColumns(39));
12536 
12537   // Trailing comment in the first line.
12538   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12539                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12540                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12541                "    11111111,   22222222,   333333333,   44444444};");
12542   // Trailing comment in the last line.
12543   verifyFormat("int aaaaa[] = {\n"
12544                "    1, 2, 3, // comment\n"
12545                "    4, 5, 6  // comment\n"
12546                "};");
12547 
12548   // With nested lists, we should either format one item per line or all nested
12549   // lists one on line.
12550   // FIXME: For some nested lists, we can do better.
12551   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12552                "        {aaaaaaaaaaaaaaaaaaa},\n"
12553                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12554                "        {aaaaaaaaaaaaaaaaa}};",
12555                getLLVMStyleWithColumns(60));
12556   verifyFormat(
12557       "SomeStruct my_struct_array = {\n"
12558       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12559       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12560       "    {aaa, aaa},\n"
12561       "    {aaa, aaa},\n"
12562       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12563       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12564       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12565 
12566   // No column layout should be used here.
12567   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12568                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12569 
12570   verifyNoCrash("a<,");
12571 
12572   // No braced initializer here.
12573   verifyFormat("void f() {\n"
12574                "  struct Dummy {};\n"
12575                "  f(v);\n"
12576                "}");
12577 
12578   // Long lists should be formatted in columns even if they are nested.
12579   verifyFormat(
12580       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12581       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12582       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12583       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12584       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12585       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12586 
12587   // Allow "single-column" layout even if that violates the column limit. There
12588   // isn't going to be a better way.
12589   verifyFormat("std::vector<int> a = {\n"
12590                "    aaaaaaaa,\n"
12591                "    aaaaaaaa,\n"
12592                "    aaaaaaaa,\n"
12593                "    aaaaaaaa,\n"
12594                "    aaaaaaaaaa,\n"
12595                "    aaaaaaaa,\n"
12596                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12597                getLLVMStyleWithColumns(30));
12598   verifyFormat("vector<int> aaaa = {\n"
12599                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12600                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12601                "    aaaaaa.aaaaaaa,\n"
12602                "    aaaaaa.aaaaaaa,\n"
12603                "    aaaaaa.aaaaaaa,\n"
12604                "    aaaaaa.aaaaaaa,\n"
12605                "};");
12606 
12607   // Don't create hanging lists.
12608   verifyFormat("someFunction(Param, {List1, List2,\n"
12609                "                     List3});",
12610                getLLVMStyleWithColumns(35));
12611   verifyFormat("someFunction(Param, Param,\n"
12612                "             {List1, List2,\n"
12613                "              List3});",
12614                getLLVMStyleWithColumns(35));
12615   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12616                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12617 }
12618 
12619 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12620   FormatStyle DoNotMerge = getLLVMStyle();
12621   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12622 
12623   verifyFormat("void f() { return 42; }");
12624   verifyFormat("void f() {\n"
12625                "  return 42;\n"
12626                "}",
12627                DoNotMerge);
12628   verifyFormat("void f() {\n"
12629                "  // Comment\n"
12630                "}");
12631   verifyFormat("{\n"
12632                "#error {\n"
12633                "  int a;\n"
12634                "}");
12635   verifyFormat("{\n"
12636                "  int a;\n"
12637                "#error {\n"
12638                "}");
12639   verifyFormat("void f() {} // comment");
12640   verifyFormat("void f() { int a; } // comment");
12641   verifyFormat("void f() {\n"
12642                "} // comment",
12643                DoNotMerge);
12644   verifyFormat("void f() {\n"
12645                "  int a;\n"
12646                "} // comment",
12647                DoNotMerge);
12648   verifyFormat("void f() {\n"
12649                "} // comment",
12650                getLLVMStyleWithColumns(15));
12651 
12652   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12653   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12654 
12655   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12656   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12657   verifyFormat("class C {\n"
12658                "  C()\n"
12659                "      : iiiiiiii(nullptr),\n"
12660                "        kkkkkkk(nullptr),\n"
12661                "        mmmmmmm(nullptr),\n"
12662                "        nnnnnnn(nullptr) {}\n"
12663                "};",
12664                getGoogleStyle());
12665 
12666   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12667   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12668   EXPECT_EQ("class C {\n"
12669             "  A() : b(0) {}\n"
12670             "};",
12671             format("class C{A():b(0){}};", NoColumnLimit));
12672   EXPECT_EQ("A()\n"
12673             "    : b(0) {\n"
12674             "}",
12675             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12676 
12677   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12678   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12679       FormatStyle::SFS_None;
12680   EXPECT_EQ("A()\n"
12681             "    : b(0) {\n"
12682             "}",
12683             format("A():b(0){}", DoNotMergeNoColumnLimit));
12684   EXPECT_EQ("A()\n"
12685             "    : b(0) {\n"
12686             "}",
12687             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12688 
12689   verifyFormat("#define A          \\\n"
12690                "  void f() {       \\\n"
12691                "    int i;         \\\n"
12692                "  }",
12693                getLLVMStyleWithColumns(20));
12694   verifyFormat("#define A           \\\n"
12695                "  void f() { int i; }",
12696                getLLVMStyleWithColumns(21));
12697   verifyFormat("#define A            \\\n"
12698                "  void f() {         \\\n"
12699                "    int i;           \\\n"
12700                "  }                  \\\n"
12701                "  int j;",
12702                getLLVMStyleWithColumns(22));
12703   verifyFormat("#define A             \\\n"
12704                "  void f() { int i; } \\\n"
12705                "  int j;",
12706                getLLVMStyleWithColumns(23));
12707 }
12708 
12709 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12710   FormatStyle MergeEmptyOnly = getLLVMStyle();
12711   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12712   verifyFormat("class C {\n"
12713                "  int f() {}\n"
12714                "};",
12715                MergeEmptyOnly);
12716   verifyFormat("class C {\n"
12717                "  int f() {\n"
12718                "    return 42;\n"
12719                "  }\n"
12720                "};",
12721                MergeEmptyOnly);
12722   verifyFormat("int f() {}", MergeEmptyOnly);
12723   verifyFormat("int f() {\n"
12724                "  return 42;\n"
12725                "}",
12726                MergeEmptyOnly);
12727 
12728   // Also verify behavior when BraceWrapping.AfterFunction = true
12729   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12730   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12731   verifyFormat("int f() {}", MergeEmptyOnly);
12732   verifyFormat("class C {\n"
12733                "  int f() {}\n"
12734                "};",
12735                MergeEmptyOnly);
12736 }
12737 
12738 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12739   FormatStyle MergeInlineOnly = getLLVMStyle();
12740   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12741   verifyFormat("class C {\n"
12742                "  int f() { return 42; }\n"
12743                "};",
12744                MergeInlineOnly);
12745   verifyFormat("int f() {\n"
12746                "  return 42;\n"
12747                "}",
12748                MergeInlineOnly);
12749 
12750   // SFS_Inline implies SFS_Empty
12751   verifyFormat("class C {\n"
12752                "  int f() {}\n"
12753                "};",
12754                MergeInlineOnly);
12755   verifyFormat("int f() {}", MergeInlineOnly);
12756   // https://llvm.org/PR54147
12757   verifyFormat("auto lambda = []() {\n"
12758                "  // comment\n"
12759                "  f();\n"
12760                "  g();\n"
12761                "};",
12762                MergeInlineOnly);
12763 
12764   // Also verify behavior when BraceWrapping.AfterFunction = true
12765   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12766   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12767   verifyFormat("class C {\n"
12768                "  int f() { return 42; }\n"
12769                "};",
12770                MergeInlineOnly);
12771   verifyFormat("int f()\n"
12772                "{\n"
12773                "  return 42;\n"
12774                "}",
12775                MergeInlineOnly);
12776 
12777   // SFS_Inline implies SFS_Empty
12778   verifyFormat("int f() {}", MergeInlineOnly);
12779   verifyFormat("class C {\n"
12780                "  int f() {}\n"
12781                "};",
12782                MergeInlineOnly);
12783 
12784   MergeInlineOnly.BraceWrapping.AfterClass = true;
12785   MergeInlineOnly.BraceWrapping.AfterStruct = true;
12786   verifyFormat("class C\n"
12787                "{\n"
12788                "  int f() { return 42; }\n"
12789                "};",
12790                MergeInlineOnly);
12791   verifyFormat("struct C\n"
12792                "{\n"
12793                "  int f() { return 42; }\n"
12794                "};",
12795                MergeInlineOnly);
12796   verifyFormat("int f()\n"
12797                "{\n"
12798                "  return 42;\n"
12799                "}",
12800                MergeInlineOnly);
12801   verifyFormat("int f() {}", MergeInlineOnly);
12802   verifyFormat("class C\n"
12803                "{\n"
12804                "  int f() { return 42; }\n"
12805                "};",
12806                MergeInlineOnly);
12807   verifyFormat("struct C\n"
12808                "{\n"
12809                "  int f() { return 42; }\n"
12810                "};",
12811                MergeInlineOnly);
12812   verifyFormat("struct C\n"
12813                "// comment\n"
12814                "/* comment */\n"
12815                "// comment\n"
12816                "{\n"
12817                "  int f() { return 42; }\n"
12818                "};",
12819                MergeInlineOnly);
12820   verifyFormat("/* comment */ struct C\n"
12821                "{\n"
12822                "  int f() { return 42; }\n"
12823                "};",
12824                MergeInlineOnly);
12825 }
12826 
12827 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12828   FormatStyle MergeInlineOnly = getLLVMStyle();
12829   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12830       FormatStyle::SFS_InlineOnly;
12831   verifyFormat("class C {\n"
12832                "  int f() { return 42; }\n"
12833                "};",
12834                MergeInlineOnly);
12835   verifyFormat("int f() {\n"
12836                "  return 42;\n"
12837                "}",
12838                MergeInlineOnly);
12839 
12840   // SFS_InlineOnly does not imply SFS_Empty
12841   verifyFormat("class C {\n"
12842                "  int f() {}\n"
12843                "};",
12844                MergeInlineOnly);
12845   verifyFormat("int f() {\n"
12846                "}",
12847                MergeInlineOnly);
12848 
12849   // Also verify behavior when BraceWrapping.AfterFunction = true
12850   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12851   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12852   verifyFormat("class C {\n"
12853                "  int f() { return 42; }\n"
12854                "};",
12855                MergeInlineOnly);
12856   verifyFormat("int f()\n"
12857                "{\n"
12858                "  return 42;\n"
12859                "}",
12860                MergeInlineOnly);
12861 
12862   // SFS_InlineOnly does not imply SFS_Empty
12863   verifyFormat("int f()\n"
12864                "{\n"
12865                "}",
12866                MergeInlineOnly);
12867   verifyFormat("class C {\n"
12868                "  int f() {}\n"
12869                "};",
12870                MergeInlineOnly);
12871 }
12872 
12873 TEST_F(FormatTest, SplitEmptyFunction) {
12874   FormatStyle Style = getLLVMStyleWithColumns(40);
12875   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12876   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12877   Style.BraceWrapping.AfterFunction = true;
12878   Style.BraceWrapping.SplitEmptyFunction = false;
12879 
12880   verifyFormat("int f()\n"
12881                "{}",
12882                Style);
12883   verifyFormat("int f()\n"
12884                "{\n"
12885                "  return 42;\n"
12886                "}",
12887                Style);
12888   verifyFormat("int f()\n"
12889                "{\n"
12890                "  // some comment\n"
12891                "}",
12892                Style);
12893 
12894   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12895   verifyFormat("int f() {}", Style);
12896   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12897                "{}",
12898                Style);
12899   verifyFormat("int f()\n"
12900                "{\n"
12901                "  return 0;\n"
12902                "}",
12903                Style);
12904 
12905   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12906   verifyFormat("class Foo {\n"
12907                "  int f() {}\n"
12908                "};\n",
12909                Style);
12910   verifyFormat("class Foo {\n"
12911                "  int f() { return 0; }\n"
12912                "};\n",
12913                Style);
12914   verifyFormat("class Foo {\n"
12915                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12916                "  {}\n"
12917                "};\n",
12918                Style);
12919   verifyFormat("class Foo {\n"
12920                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12921                "  {\n"
12922                "    return 0;\n"
12923                "  }\n"
12924                "};\n",
12925                Style);
12926 
12927   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12928   verifyFormat("int f() {}", Style);
12929   verifyFormat("int f() { return 0; }", Style);
12930   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12931                "{}",
12932                Style);
12933   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12934                "{\n"
12935                "  return 0;\n"
12936                "}",
12937                Style);
12938 }
12939 
12940 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12941   FormatStyle Style = getLLVMStyleWithColumns(40);
12942   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12943   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12944   Style.BraceWrapping.AfterFunction = true;
12945   Style.BraceWrapping.SplitEmptyFunction = true;
12946   Style.BraceWrapping.SplitEmptyRecord = false;
12947 
12948   verifyFormat("class C {};", Style);
12949   verifyFormat("struct C {};", Style);
12950   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12951                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12952                "{\n"
12953                "}",
12954                Style);
12955   verifyFormat("class C {\n"
12956                "  C()\n"
12957                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12958                "        bbbbbbbbbbbbbbbbbbb()\n"
12959                "  {\n"
12960                "  }\n"
12961                "  void\n"
12962                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12963                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12964                "  {\n"
12965                "  }\n"
12966                "};",
12967                Style);
12968 }
12969 
12970 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12971   FormatStyle Style = getLLVMStyle();
12972   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12973   verifyFormat("#ifdef A\n"
12974                "int f() {}\n"
12975                "#else\n"
12976                "int g() {}\n"
12977                "#endif",
12978                Style);
12979 }
12980 
12981 TEST_F(FormatTest, SplitEmptyClass) {
12982   FormatStyle Style = getLLVMStyle();
12983   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12984   Style.BraceWrapping.AfterClass = true;
12985   Style.BraceWrapping.SplitEmptyRecord = false;
12986 
12987   verifyFormat("class Foo\n"
12988                "{};",
12989                Style);
12990   verifyFormat("/* something */ class Foo\n"
12991                "{};",
12992                Style);
12993   verifyFormat("template <typename X> class Foo\n"
12994                "{};",
12995                Style);
12996   verifyFormat("class Foo\n"
12997                "{\n"
12998                "  Foo();\n"
12999                "};",
13000                Style);
13001   verifyFormat("typedef class Foo\n"
13002                "{\n"
13003                "} Foo_t;",
13004                Style);
13005 
13006   Style.BraceWrapping.SplitEmptyRecord = true;
13007   Style.BraceWrapping.AfterStruct = true;
13008   verifyFormat("class rep\n"
13009                "{\n"
13010                "};",
13011                Style);
13012   verifyFormat("struct rep\n"
13013                "{\n"
13014                "};",
13015                Style);
13016   verifyFormat("template <typename T> class rep\n"
13017                "{\n"
13018                "};",
13019                Style);
13020   verifyFormat("template <typename T> struct rep\n"
13021                "{\n"
13022                "};",
13023                Style);
13024   verifyFormat("class rep\n"
13025                "{\n"
13026                "  int x;\n"
13027                "};",
13028                Style);
13029   verifyFormat("struct rep\n"
13030                "{\n"
13031                "  int x;\n"
13032                "};",
13033                Style);
13034   verifyFormat("template <typename T> class rep\n"
13035                "{\n"
13036                "  int x;\n"
13037                "};",
13038                Style);
13039   verifyFormat("template <typename T> struct rep\n"
13040                "{\n"
13041                "  int x;\n"
13042                "};",
13043                Style);
13044   verifyFormat("template <typename T> class rep // Foo\n"
13045                "{\n"
13046                "  int x;\n"
13047                "};",
13048                Style);
13049   verifyFormat("template <typename T> struct rep // Bar\n"
13050                "{\n"
13051                "  int x;\n"
13052                "};",
13053                Style);
13054 
13055   verifyFormat("template <typename T> class rep<T>\n"
13056                "{\n"
13057                "  int x;\n"
13058                "};",
13059                Style);
13060 
13061   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13062                "{\n"
13063                "  int x;\n"
13064                "};",
13065                Style);
13066   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13067                "{\n"
13068                "};",
13069                Style);
13070 
13071   verifyFormat("#include \"stdint.h\"\n"
13072                "namespace rep {}",
13073                Style);
13074   verifyFormat("#include <stdint.h>\n"
13075                "namespace rep {}",
13076                Style);
13077   verifyFormat("#include <stdint.h>\n"
13078                "namespace rep {}",
13079                "#include <stdint.h>\n"
13080                "namespace rep {\n"
13081                "\n"
13082                "\n"
13083                "}",
13084                Style);
13085 }
13086 
13087 TEST_F(FormatTest, SplitEmptyStruct) {
13088   FormatStyle Style = getLLVMStyle();
13089   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13090   Style.BraceWrapping.AfterStruct = true;
13091   Style.BraceWrapping.SplitEmptyRecord = false;
13092 
13093   verifyFormat("struct Foo\n"
13094                "{};",
13095                Style);
13096   verifyFormat("/* something */ struct Foo\n"
13097                "{};",
13098                Style);
13099   verifyFormat("template <typename X> struct Foo\n"
13100                "{};",
13101                Style);
13102   verifyFormat("struct Foo\n"
13103                "{\n"
13104                "  Foo();\n"
13105                "};",
13106                Style);
13107   verifyFormat("typedef struct Foo\n"
13108                "{\n"
13109                "} Foo_t;",
13110                Style);
13111   // typedef struct Bar {} Bar_t;
13112 }
13113 
13114 TEST_F(FormatTest, SplitEmptyUnion) {
13115   FormatStyle Style = getLLVMStyle();
13116   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13117   Style.BraceWrapping.AfterUnion = true;
13118   Style.BraceWrapping.SplitEmptyRecord = false;
13119 
13120   verifyFormat("union Foo\n"
13121                "{};",
13122                Style);
13123   verifyFormat("/* something */ union Foo\n"
13124                "{};",
13125                Style);
13126   verifyFormat("union Foo\n"
13127                "{\n"
13128                "  A,\n"
13129                "};",
13130                Style);
13131   verifyFormat("typedef union Foo\n"
13132                "{\n"
13133                "} Foo_t;",
13134                Style);
13135 }
13136 
13137 TEST_F(FormatTest, SplitEmptyNamespace) {
13138   FormatStyle Style = getLLVMStyle();
13139   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13140   Style.BraceWrapping.AfterNamespace = true;
13141   Style.BraceWrapping.SplitEmptyNamespace = false;
13142 
13143   verifyFormat("namespace Foo\n"
13144                "{};",
13145                Style);
13146   verifyFormat("/* something */ namespace Foo\n"
13147                "{};",
13148                Style);
13149   verifyFormat("inline namespace Foo\n"
13150                "{};",
13151                Style);
13152   verifyFormat("/* something */ inline namespace Foo\n"
13153                "{};",
13154                Style);
13155   verifyFormat("export namespace Foo\n"
13156                "{};",
13157                Style);
13158   verifyFormat("namespace Foo\n"
13159                "{\n"
13160                "void Bar();\n"
13161                "};",
13162                Style);
13163 }
13164 
13165 TEST_F(FormatTest, NeverMergeShortRecords) {
13166   FormatStyle Style = getLLVMStyle();
13167 
13168   verifyFormat("class Foo {\n"
13169                "  Foo();\n"
13170                "};",
13171                Style);
13172   verifyFormat("typedef class Foo {\n"
13173                "  Foo();\n"
13174                "} Foo_t;",
13175                Style);
13176   verifyFormat("struct Foo {\n"
13177                "  Foo();\n"
13178                "};",
13179                Style);
13180   verifyFormat("typedef struct Foo {\n"
13181                "  Foo();\n"
13182                "} Foo_t;",
13183                Style);
13184   verifyFormat("union Foo {\n"
13185                "  A,\n"
13186                "};",
13187                Style);
13188   verifyFormat("typedef union Foo {\n"
13189                "  A,\n"
13190                "} Foo_t;",
13191                Style);
13192   verifyFormat("namespace Foo {\n"
13193                "void Bar();\n"
13194                "};",
13195                Style);
13196 
13197   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13198   Style.BraceWrapping.AfterClass = true;
13199   Style.BraceWrapping.AfterStruct = true;
13200   Style.BraceWrapping.AfterUnion = true;
13201   Style.BraceWrapping.AfterNamespace = true;
13202   verifyFormat("class Foo\n"
13203                "{\n"
13204                "  Foo();\n"
13205                "};",
13206                Style);
13207   verifyFormat("typedef class Foo\n"
13208                "{\n"
13209                "  Foo();\n"
13210                "} Foo_t;",
13211                Style);
13212   verifyFormat("struct Foo\n"
13213                "{\n"
13214                "  Foo();\n"
13215                "};",
13216                Style);
13217   verifyFormat("typedef struct Foo\n"
13218                "{\n"
13219                "  Foo();\n"
13220                "} Foo_t;",
13221                Style);
13222   verifyFormat("union Foo\n"
13223                "{\n"
13224                "  A,\n"
13225                "};",
13226                Style);
13227   verifyFormat("typedef union Foo\n"
13228                "{\n"
13229                "  A,\n"
13230                "} Foo_t;",
13231                Style);
13232   verifyFormat("namespace Foo\n"
13233                "{\n"
13234                "void Bar();\n"
13235                "};",
13236                Style);
13237 }
13238 
13239 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
13240   // Elaborate type variable declarations.
13241   verifyFormat("struct foo a = {bar};\nint n;");
13242   verifyFormat("class foo a = {bar};\nint n;");
13243   verifyFormat("union foo a = {bar};\nint n;");
13244 
13245   // Elaborate types inside function definitions.
13246   verifyFormat("struct foo f() {}\nint n;");
13247   verifyFormat("class foo f() {}\nint n;");
13248   verifyFormat("union foo f() {}\nint n;");
13249 
13250   // Templates.
13251   verifyFormat("template <class X> void f() {}\nint n;");
13252   verifyFormat("template <struct X> void f() {}\nint n;");
13253   verifyFormat("template <union X> void f() {}\nint n;");
13254 
13255   // Actual definitions...
13256   verifyFormat("struct {\n} n;");
13257   verifyFormat(
13258       "template <template <class T, class Y>, class Z> class X {\n} n;");
13259   verifyFormat("union Z {\n  int n;\n} x;");
13260   verifyFormat("class MACRO Z {\n} n;");
13261   verifyFormat("class MACRO(X) Z {\n} n;");
13262   verifyFormat("class __attribute__(X) Z {\n} n;");
13263   verifyFormat("class __declspec(X) Z {\n} n;");
13264   verifyFormat("class A##B##C {\n} n;");
13265   verifyFormat("class alignas(16) Z {\n} n;");
13266   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
13267   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
13268 
13269   // Redefinition from nested context:
13270   verifyFormat("class A::B::C {\n} n;");
13271 
13272   // Template definitions.
13273   verifyFormat(
13274       "template <typename F>\n"
13275       "Matcher(const Matcher<F> &Other,\n"
13276       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
13277       "                             !is_same<F, T>::value>::type * = 0)\n"
13278       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
13279 
13280   // FIXME: This is still incorrectly handled at the formatter side.
13281   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
13282   verifyFormat("int i = SomeFunction(a<b, a> b);");
13283 
13284   // FIXME:
13285   // This now gets parsed incorrectly as class definition.
13286   // verifyFormat("class A<int> f() {\n}\nint n;");
13287 
13288   // Elaborate types where incorrectly parsing the structural element would
13289   // break the indent.
13290   verifyFormat("if (true)\n"
13291                "  class X x;\n"
13292                "else\n"
13293                "  f();\n");
13294 
13295   // This is simply incomplete. Formatting is not important, but must not crash.
13296   verifyFormat("class A:");
13297 }
13298 
13299 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
13300   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
13301             format("#error Leave     all         white!!!!! space* alone!\n"));
13302   EXPECT_EQ(
13303       "#warning Leave     all         white!!!!! space* alone!\n",
13304       format("#warning Leave     all         white!!!!! space* alone!\n"));
13305   EXPECT_EQ("#error 1", format("  #  error   1"));
13306   EXPECT_EQ("#warning 1", format("  #  warning 1"));
13307 }
13308 
13309 TEST_F(FormatTest, FormatHashIfExpressions) {
13310   verifyFormat("#if AAAA && BBBB");
13311   verifyFormat("#if (AAAA && BBBB)");
13312   verifyFormat("#elif (AAAA && BBBB)");
13313   // FIXME: Come up with a better indentation for #elif.
13314   verifyFormat(
13315       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
13316       "    defined(BBBBBBBB)\n"
13317       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
13318       "    defined(BBBBBBBB)\n"
13319       "#endif",
13320       getLLVMStyleWithColumns(65));
13321 }
13322 
13323 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
13324   FormatStyle AllowsMergedIf = getGoogleStyle();
13325   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
13326       FormatStyle::SIS_WithoutElse;
13327   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
13328   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
13329   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
13330   EXPECT_EQ("if (true) return 42;",
13331             format("if (true)\nreturn 42;", AllowsMergedIf));
13332   FormatStyle ShortMergedIf = AllowsMergedIf;
13333   ShortMergedIf.ColumnLimit = 25;
13334   verifyFormat("#define A \\\n"
13335                "  if (true) return 42;",
13336                ShortMergedIf);
13337   verifyFormat("#define A \\\n"
13338                "  f();    \\\n"
13339                "  if (true)\n"
13340                "#define B",
13341                ShortMergedIf);
13342   verifyFormat("#define A \\\n"
13343                "  f();    \\\n"
13344                "  if (true)\n"
13345                "g();",
13346                ShortMergedIf);
13347   verifyFormat("{\n"
13348                "#ifdef A\n"
13349                "  // Comment\n"
13350                "  if (true) continue;\n"
13351                "#endif\n"
13352                "  // Comment\n"
13353                "  if (true) continue;\n"
13354                "}",
13355                ShortMergedIf);
13356   ShortMergedIf.ColumnLimit = 33;
13357   verifyFormat("#define A \\\n"
13358                "  if constexpr (true) return 42;",
13359                ShortMergedIf);
13360   verifyFormat("#define A \\\n"
13361                "  if CONSTEXPR (true) return 42;",
13362                ShortMergedIf);
13363   ShortMergedIf.ColumnLimit = 29;
13364   verifyFormat("#define A                   \\\n"
13365                "  if (aaaaaaaaaa) return 1; \\\n"
13366                "  return 2;",
13367                ShortMergedIf);
13368   ShortMergedIf.ColumnLimit = 28;
13369   verifyFormat("#define A         \\\n"
13370                "  if (aaaaaaaaaa) \\\n"
13371                "    return 1;     \\\n"
13372                "  return 2;",
13373                ShortMergedIf);
13374   verifyFormat("#define A                \\\n"
13375                "  if constexpr (aaaaaaa) \\\n"
13376                "    return 1;            \\\n"
13377                "  return 2;",
13378                ShortMergedIf);
13379   verifyFormat("#define A                \\\n"
13380                "  if CONSTEXPR (aaaaaaa) \\\n"
13381                "    return 1;            \\\n"
13382                "  return 2;",
13383                ShortMergedIf);
13384 }
13385 
13386 TEST_F(FormatTest, FormatStarDependingOnContext) {
13387   verifyFormat("void f(int *a);");
13388   verifyFormat("void f() { f(fint * b); }");
13389   verifyFormat("class A {\n  void f(int *a);\n};");
13390   verifyFormat("class A {\n  int *a;\n};");
13391   verifyFormat("namespace a {\n"
13392                "namespace b {\n"
13393                "class A {\n"
13394                "  void f() {}\n"
13395                "  int *a;\n"
13396                "};\n"
13397                "} // namespace b\n"
13398                "} // namespace a");
13399 }
13400 
13401 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13402   verifyFormat("while");
13403   verifyFormat("operator");
13404 }
13405 
13406 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13407   // This code would be painfully slow to format if we didn't skip it.
13408   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
13409                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13410                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13411                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13412                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13413                    "A(1, 1)\n"
13414                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
13415                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13416                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13417                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13418                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13419                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13420                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13421                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13422                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13423                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
13424   // Deeply nested part is untouched, rest is formatted.
13425   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13426             format(std::string("int    i;\n") + Code + "int    j;\n",
13427                    getLLVMStyle(), SC_ExpectIncomplete));
13428 }
13429 
13430 //===----------------------------------------------------------------------===//
13431 // Objective-C tests.
13432 //===----------------------------------------------------------------------===//
13433 
13434 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13435   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13436   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13437             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13438   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13439   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13440   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13441             format("-(NSInteger)Method3:(id)anObject;"));
13442   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13443             format("-(NSInteger)Method4:(id)anObject;"));
13444   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13445             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13446   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13447             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13448   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13449             "forAllCells:(BOOL)flag;",
13450             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13451                    "forAllCells:(BOOL)flag;"));
13452 
13453   // Very long objectiveC method declaration.
13454   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13455                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13456   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13457                "                    inRange:(NSRange)range\n"
13458                "                   outRange:(NSRange)out_range\n"
13459                "                  outRange1:(NSRange)out_range1\n"
13460                "                  outRange2:(NSRange)out_range2\n"
13461                "                  outRange3:(NSRange)out_range3\n"
13462                "                  outRange4:(NSRange)out_range4\n"
13463                "                  outRange5:(NSRange)out_range5\n"
13464                "                  outRange6:(NSRange)out_range6\n"
13465                "                  outRange7:(NSRange)out_range7\n"
13466                "                  outRange8:(NSRange)out_range8\n"
13467                "                  outRange9:(NSRange)out_range9;");
13468 
13469   // When the function name has to be wrapped.
13470   FormatStyle Style = getLLVMStyle();
13471   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13472   // and always indents instead.
13473   Style.IndentWrappedFunctionNames = false;
13474   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13475                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13476                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13477                "}",
13478                Style);
13479   Style.IndentWrappedFunctionNames = true;
13480   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13481                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13482                "               anotherName:(NSString)dddddddddddddd {\n"
13483                "}",
13484                Style);
13485 
13486   verifyFormat("- (int)sum:(vector<int>)numbers;");
13487   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13488   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13489   // protocol lists (but not for template classes):
13490   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13491 
13492   verifyFormat("- (int (*)())foo:(int (*)())f;");
13493   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13494 
13495   // If there's no return type (very rare in practice!), LLVM and Google style
13496   // agree.
13497   verifyFormat("- foo;");
13498   verifyFormat("- foo:(int)f;");
13499   verifyGoogleFormat("- foo:(int)foo;");
13500 }
13501 
13502 TEST_F(FormatTest, BreaksStringLiterals) {
13503   EXPECT_EQ("\"some text \"\n"
13504             "\"other\";",
13505             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13506   EXPECT_EQ("\"some text \"\n"
13507             "\"other\";",
13508             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13509   EXPECT_EQ(
13510       "#define A  \\\n"
13511       "  \"some \"  \\\n"
13512       "  \"text \"  \\\n"
13513       "  \"other\";",
13514       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13515   EXPECT_EQ(
13516       "#define A  \\\n"
13517       "  \"so \"    \\\n"
13518       "  \"text \"  \\\n"
13519       "  \"other\";",
13520       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13521 
13522   EXPECT_EQ("\"some text\"",
13523             format("\"some text\"", getLLVMStyleWithColumns(1)));
13524   EXPECT_EQ("\"some text\"",
13525             format("\"some text\"", getLLVMStyleWithColumns(11)));
13526   EXPECT_EQ("\"some \"\n"
13527             "\"text\"",
13528             format("\"some text\"", getLLVMStyleWithColumns(10)));
13529   EXPECT_EQ("\"some \"\n"
13530             "\"text\"",
13531             format("\"some text\"", getLLVMStyleWithColumns(7)));
13532   EXPECT_EQ("\"some\"\n"
13533             "\" tex\"\n"
13534             "\"t\"",
13535             format("\"some text\"", getLLVMStyleWithColumns(6)));
13536   EXPECT_EQ("\"some\"\n"
13537             "\" tex\"\n"
13538             "\" and\"",
13539             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13540   EXPECT_EQ("\"some\"\n"
13541             "\"/tex\"\n"
13542             "\"/and\"",
13543             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13544 
13545   EXPECT_EQ("variable =\n"
13546             "    \"long string \"\n"
13547             "    \"literal\";",
13548             format("variable = \"long string literal\";",
13549                    getLLVMStyleWithColumns(20)));
13550 
13551   EXPECT_EQ("variable = f(\n"
13552             "    \"long string \"\n"
13553             "    \"literal\",\n"
13554             "    short,\n"
13555             "    loooooooooooooooooooong);",
13556             format("variable = f(\"long string literal\", short, "
13557                    "loooooooooooooooooooong);",
13558                    getLLVMStyleWithColumns(20)));
13559 
13560   EXPECT_EQ(
13561       "f(g(\"long string \"\n"
13562       "    \"literal\"),\n"
13563       "  b);",
13564       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13565   EXPECT_EQ("f(g(\"long string \"\n"
13566             "    \"literal\",\n"
13567             "    a),\n"
13568             "  b);",
13569             format("f(g(\"long string literal\", a), b);",
13570                    getLLVMStyleWithColumns(20)));
13571   EXPECT_EQ(
13572       "f(\"one two\".split(\n"
13573       "    variable));",
13574       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13575   EXPECT_EQ("f(\"one two three four five six \"\n"
13576             "  \"seven\".split(\n"
13577             "      really_looooong_variable));",
13578             format("f(\"one two three four five six seven\"."
13579                    "split(really_looooong_variable));",
13580                    getLLVMStyleWithColumns(33)));
13581 
13582   EXPECT_EQ("f(\"some \"\n"
13583             "  \"text\",\n"
13584             "  other);",
13585             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13586 
13587   // Only break as a last resort.
13588   verifyFormat(
13589       "aaaaaaaaaaaaaaaaaaaa(\n"
13590       "    aaaaaaaaaaaaaaaaaaaa,\n"
13591       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13592 
13593   EXPECT_EQ("\"splitmea\"\n"
13594             "\"trandomp\"\n"
13595             "\"oint\"",
13596             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13597 
13598   EXPECT_EQ("\"split/\"\n"
13599             "\"pathat/\"\n"
13600             "\"slashes\"",
13601             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13602 
13603   EXPECT_EQ("\"split/\"\n"
13604             "\"pathat/\"\n"
13605             "\"slashes\"",
13606             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13607   EXPECT_EQ("\"split at \"\n"
13608             "\"spaces/at/\"\n"
13609             "\"slashes.at.any$\"\n"
13610             "\"non-alphanumeric%\"\n"
13611             "\"1111111111characte\"\n"
13612             "\"rs\"",
13613             format("\"split at "
13614                    "spaces/at/"
13615                    "slashes.at."
13616                    "any$non-"
13617                    "alphanumeric%"
13618                    "1111111111characte"
13619                    "rs\"",
13620                    getLLVMStyleWithColumns(20)));
13621 
13622   // Verify that splitting the strings understands
13623   // Style::AlwaysBreakBeforeMultilineStrings.
13624   EXPECT_EQ("aaaaaaaaaaaa(\n"
13625             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13626             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13627             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13628                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13629                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13630                    getGoogleStyle()));
13631   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13632             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13633             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13634                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13635                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13636                    getGoogleStyle()));
13637   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13638             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13639             format("llvm::outs() << "
13640                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13641                    "aaaaaaaaaaaaaaaaaaa\";"));
13642   EXPECT_EQ("ffff(\n"
13643             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13644             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13645             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13646                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13647                    getGoogleStyle()));
13648 
13649   FormatStyle Style = getLLVMStyleWithColumns(12);
13650   Style.BreakStringLiterals = false;
13651   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13652 
13653   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13654   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13655   EXPECT_EQ("#define A \\\n"
13656             "  \"some \" \\\n"
13657             "  \"text \" \\\n"
13658             "  \"other\";",
13659             format("#define A \"some text other\";", AlignLeft));
13660 }
13661 
13662 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13663   EXPECT_EQ("C a = \"some more \"\n"
13664             "      \"text\";",
13665             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13666 }
13667 
13668 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13669   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13670   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13671   EXPECT_EQ("int i = a(b());",
13672             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13673 }
13674 
13675 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13676   EXPECT_EQ(
13677       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13678       "(\n"
13679       "    \"x\t\");",
13680       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13681              "aaaaaaa("
13682              "\"x\t\");"));
13683 }
13684 
13685 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13686   EXPECT_EQ(
13687       "u8\"utf8 string \"\n"
13688       "u8\"literal\";",
13689       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13690   EXPECT_EQ(
13691       "u\"utf16 string \"\n"
13692       "u\"literal\";",
13693       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13694   EXPECT_EQ(
13695       "U\"utf32 string \"\n"
13696       "U\"literal\";",
13697       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13698   EXPECT_EQ("L\"wide string \"\n"
13699             "L\"literal\";",
13700             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13701   EXPECT_EQ("@\"NSString \"\n"
13702             "@\"literal\";",
13703             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13704   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13705 
13706   // This input makes clang-format try to split the incomplete unicode escape
13707   // sequence, which used to lead to a crasher.
13708   verifyNoCrash(
13709       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13710       getLLVMStyleWithColumns(60));
13711 }
13712 
13713 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13714   FormatStyle Style = getGoogleStyleWithColumns(15);
13715   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13716   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13717   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13718   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13719   EXPECT_EQ("u8R\"x(raw literal)x\";",
13720             format("u8R\"x(raw literal)x\";", Style));
13721 }
13722 
13723 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13724   FormatStyle Style = getLLVMStyleWithColumns(20);
13725   EXPECT_EQ(
13726       "_T(\"aaaaaaaaaaaaaa\")\n"
13727       "_T(\"aaaaaaaaaaaaaa\")\n"
13728       "_T(\"aaaaaaaaaaaa\")",
13729       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13730   EXPECT_EQ("f(x,\n"
13731             "  _T(\"aaaaaaaaaaaa\")\n"
13732             "  _T(\"aaa\"),\n"
13733             "  z);",
13734             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13735 
13736   // FIXME: Handle embedded spaces in one iteration.
13737   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13738   //            "_T(\"aaaaaaaaaaaaa\")\n"
13739   //            "_T(\"aaaaaaaaaaaaa\")\n"
13740   //            "_T(\"a\")",
13741   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13742   //                   getLLVMStyleWithColumns(20)));
13743   EXPECT_EQ(
13744       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13745       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13746   EXPECT_EQ("f(\n"
13747             "#if !TEST\n"
13748             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13749             "#endif\n"
13750             ");",
13751             format("f(\n"
13752                    "#if !TEST\n"
13753                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13754                    "#endif\n"
13755                    ");"));
13756   EXPECT_EQ("f(\n"
13757             "\n"
13758             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13759             format("f(\n"
13760                    "\n"
13761                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13762   // Regression test for accessing tokens past the end of a vector in the
13763   // TokenLexer.
13764   verifyNoCrash(R"(_T(
13765 "
13766 )
13767 )");
13768 }
13769 
13770 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13771   // In a function call with two operands, the second can be broken with no line
13772   // break before it.
13773   EXPECT_EQ(
13774       "func(a, \"long long \"\n"
13775       "        \"long long\");",
13776       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13777   // In a function call with three operands, the second must be broken with a
13778   // line break before it.
13779   EXPECT_EQ("func(a,\n"
13780             "     \"long long long \"\n"
13781             "     \"long\",\n"
13782             "     c);",
13783             format("func(a, \"long long long long\", c);",
13784                    getLLVMStyleWithColumns(24)));
13785   // In a function call with three operands, the third must be broken with a
13786   // line break before it.
13787   EXPECT_EQ("func(a, b,\n"
13788             "     \"long long long \"\n"
13789             "     \"long\");",
13790             format("func(a, b, \"long long long long\");",
13791                    getLLVMStyleWithColumns(24)));
13792   // In a function call with three operands, both the second and the third must
13793   // be broken with a line break before them.
13794   EXPECT_EQ("func(a,\n"
13795             "     \"long long long \"\n"
13796             "     \"long\",\n"
13797             "     \"long long long \"\n"
13798             "     \"long\");",
13799             format("func(a, \"long long long long\", \"long long long long\");",
13800                    getLLVMStyleWithColumns(24)));
13801   // In a chain of << with two operands, the second can be broken with no line
13802   // break before it.
13803   EXPECT_EQ("a << \"line line \"\n"
13804             "     \"line\";",
13805             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13806   // In a chain of << with three operands, the second can be broken with no line
13807   // break before it.
13808   EXPECT_EQ(
13809       "abcde << \"line \"\n"
13810       "         \"line line\"\n"
13811       "      << c;",
13812       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13813   // In a chain of << with three operands, the third must be broken with a line
13814   // break before it.
13815   EXPECT_EQ(
13816       "a << b\n"
13817       "  << \"line line \"\n"
13818       "     \"line\";",
13819       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13820   // In a chain of << with three operands, the second can be broken with no line
13821   // break before it and the third must be broken with a line break before it.
13822   EXPECT_EQ("abcd << \"line line \"\n"
13823             "        \"line\"\n"
13824             "     << \"line line \"\n"
13825             "        \"line\";",
13826             format("abcd << \"line line line\" << \"line line line\";",
13827                    getLLVMStyleWithColumns(20)));
13828   // In a chain of binary operators with two operands, the second can be broken
13829   // with no line break before it.
13830   EXPECT_EQ(
13831       "abcd + \"line line \"\n"
13832       "       \"line line\";",
13833       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13834   // In a chain of binary operators with three operands, the second must be
13835   // broken with a line break before it.
13836   EXPECT_EQ("abcd +\n"
13837             "    \"line line \"\n"
13838             "    \"line line\" +\n"
13839             "    e;",
13840             format("abcd + \"line line line line\" + e;",
13841                    getLLVMStyleWithColumns(20)));
13842   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13843   // the first must be broken with a line break before it.
13844   FormatStyle Style = getLLVMStyleWithColumns(25);
13845   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13846   EXPECT_EQ("someFunction(\n"
13847             "    \"long long long \"\n"
13848             "    \"long\",\n"
13849             "    a);",
13850             format("someFunction(\"long long long long\", a);", Style));
13851 }
13852 
13853 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13854   EXPECT_EQ(
13855       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13856       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13857       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13858       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13859              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13860              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13861 }
13862 
13863 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13864   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13865             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13866   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13867             "multiline raw string literal xxxxxxxxxxxxxx\n"
13868             ")x\",\n"
13869             "              a),\n"
13870             "            b);",
13871             format("fffffffffff(g(R\"x(\n"
13872                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13873                    ")x\", a), b);",
13874                    getGoogleStyleWithColumns(20)));
13875   EXPECT_EQ("fffffffffff(\n"
13876             "    g(R\"x(qqq\n"
13877             "multiline raw string literal xxxxxxxxxxxxxx\n"
13878             ")x\",\n"
13879             "      a),\n"
13880             "    b);",
13881             format("fffffffffff(g(R\"x(qqq\n"
13882                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13883                    ")x\", a), b);",
13884                    getGoogleStyleWithColumns(20)));
13885 
13886   EXPECT_EQ("fffffffffff(R\"x(\n"
13887             "multiline raw string literal xxxxxxxxxxxxxx\n"
13888             ")x\");",
13889             format("fffffffffff(R\"x(\n"
13890                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13891                    ")x\");",
13892                    getGoogleStyleWithColumns(20)));
13893   EXPECT_EQ("fffffffffff(R\"x(\n"
13894             "multiline raw string literal xxxxxxxxxxxxxx\n"
13895             ")x\" + bbbbbb);",
13896             format("fffffffffff(R\"x(\n"
13897                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13898                    ")x\" +   bbbbbb);",
13899                    getGoogleStyleWithColumns(20)));
13900   EXPECT_EQ("fffffffffff(\n"
13901             "    R\"x(\n"
13902             "multiline raw string literal xxxxxxxxxxxxxx\n"
13903             ")x\" +\n"
13904             "    bbbbbb);",
13905             format("fffffffffff(\n"
13906                    " R\"x(\n"
13907                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13908                    ")x\" + bbbbbb);",
13909                    getGoogleStyleWithColumns(20)));
13910   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13911             format("fffffffffff(\n"
13912                    " R\"(single line raw string)\" + bbbbbb);"));
13913 }
13914 
13915 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13916   verifyFormat("string a = \"unterminated;");
13917   EXPECT_EQ("function(\"unterminated,\n"
13918             "         OtherParameter);",
13919             format("function(  \"unterminated,\n"
13920                    "    OtherParameter);"));
13921 }
13922 
13923 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13924   FormatStyle Style = getLLVMStyle();
13925   Style.Standard = FormatStyle::LS_Cpp03;
13926   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13927             format("#define x(_a) printf(\"foo\"_a);", Style));
13928 }
13929 
13930 TEST_F(FormatTest, CppLexVersion) {
13931   FormatStyle Style = getLLVMStyle();
13932   // Formatting of x * y differs if x is a type.
13933   verifyFormat("void foo() { MACRO(a * b); }", Style);
13934   verifyFormat("void foo() { MACRO(int *b); }", Style);
13935 
13936   // LLVM style uses latest lexer.
13937   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13938   Style.Standard = FormatStyle::LS_Cpp17;
13939   // But in c++17, char8_t isn't a keyword.
13940   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13941 }
13942 
13943 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13944 
13945 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13946   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13947             "             \"ddeeefff\");",
13948             format("someFunction(\"aaabbbcccdddeeefff\");",
13949                    getLLVMStyleWithColumns(25)));
13950   EXPECT_EQ("someFunction1234567890(\n"
13951             "    \"aaabbbcccdddeeefff\");",
13952             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13953                    getLLVMStyleWithColumns(26)));
13954   EXPECT_EQ("someFunction1234567890(\n"
13955             "    \"aaabbbcccdddeeeff\"\n"
13956             "    \"f\");",
13957             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13958                    getLLVMStyleWithColumns(25)));
13959   EXPECT_EQ("someFunction1234567890(\n"
13960             "    \"aaabbbcccdddeeeff\"\n"
13961             "    \"f\");",
13962             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13963                    getLLVMStyleWithColumns(24)));
13964   EXPECT_EQ("someFunction(\n"
13965             "    \"aaabbbcc ddde \"\n"
13966             "    \"efff\");",
13967             format("someFunction(\"aaabbbcc ddde efff\");",
13968                    getLLVMStyleWithColumns(25)));
13969   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13970             "             \"ddeeefff\");",
13971             format("someFunction(\"aaabbbccc ddeeefff\");",
13972                    getLLVMStyleWithColumns(25)));
13973   EXPECT_EQ("someFunction1234567890(\n"
13974             "    \"aaabb \"\n"
13975             "    \"cccdddeeefff\");",
13976             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13977                    getLLVMStyleWithColumns(25)));
13978   EXPECT_EQ("#define A          \\\n"
13979             "  string s =       \\\n"
13980             "      \"123456789\"  \\\n"
13981             "      \"0\";         \\\n"
13982             "  int i;",
13983             format("#define A string s = \"1234567890\"; int i;",
13984                    getLLVMStyleWithColumns(20)));
13985   EXPECT_EQ("someFunction(\n"
13986             "    \"aaabbbcc \"\n"
13987             "    \"dddeeefff\");",
13988             format("someFunction(\"aaabbbcc dddeeefff\");",
13989                    getLLVMStyleWithColumns(25)));
13990 }
13991 
13992 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13993   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13994   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13995   EXPECT_EQ("\"test\"\n"
13996             "\"\\n\"",
13997             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
13998   EXPECT_EQ("\"tes\\\\\"\n"
13999             "\"n\"",
14000             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
14001   EXPECT_EQ("\"\\\\\\\\\"\n"
14002             "\"\\n\"",
14003             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
14004   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
14005   EXPECT_EQ("\"\\uff01\"\n"
14006             "\"test\"",
14007             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
14008   EXPECT_EQ("\"\\Uff01ff02\"",
14009             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
14010   EXPECT_EQ("\"\\x000000000001\"\n"
14011             "\"next\"",
14012             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
14013   EXPECT_EQ("\"\\x000000000001next\"",
14014             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
14015   EXPECT_EQ("\"\\x000000000001\"",
14016             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
14017   EXPECT_EQ("\"test\"\n"
14018             "\"\\000000\"\n"
14019             "\"000001\"",
14020             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
14021   EXPECT_EQ("\"test\\000\"\n"
14022             "\"00000000\"\n"
14023             "\"1\"",
14024             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
14025 }
14026 
14027 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
14028   verifyFormat("void f() {\n"
14029                "  return g() {}\n"
14030                "  void h() {}");
14031   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
14032                "g();\n"
14033                "}");
14034 }
14035 
14036 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
14037   verifyFormat(
14038       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
14039 }
14040 
14041 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
14042   verifyFormat("class X {\n"
14043                "  void f() {\n"
14044                "  }\n"
14045                "};",
14046                getLLVMStyleWithColumns(12));
14047 }
14048 
14049 TEST_F(FormatTest, ConfigurableIndentWidth) {
14050   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
14051   EightIndent.IndentWidth = 8;
14052   EightIndent.ContinuationIndentWidth = 8;
14053   verifyFormat("void f() {\n"
14054                "        someFunction();\n"
14055                "        if (true) {\n"
14056                "                f();\n"
14057                "        }\n"
14058                "}",
14059                EightIndent);
14060   verifyFormat("class X {\n"
14061                "        void f() {\n"
14062                "        }\n"
14063                "};",
14064                EightIndent);
14065   verifyFormat("int x[] = {\n"
14066                "        call(),\n"
14067                "        call()};",
14068                EightIndent);
14069 }
14070 
14071 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
14072   verifyFormat("double\n"
14073                "f();",
14074                getLLVMStyleWithColumns(8));
14075 }
14076 
14077 TEST_F(FormatTest, ConfigurableUseOfTab) {
14078   FormatStyle Tab = getLLVMStyleWithColumns(42);
14079   Tab.IndentWidth = 8;
14080   Tab.UseTab = FormatStyle::UT_Always;
14081   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14082 
14083   EXPECT_EQ("if (aaaaaaaa && // q\n"
14084             "    bb)\t\t// w\n"
14085             "\t;",
14086             format("if (aaaaaaaa &&// q\n"
14087                    "bb)// w\n"
14088                    ";",
14089                    Tab));
14090   EXPECT_EQ("if (aaa && bbb) // w\n"
14091             "\t;",
14092             format("if(aaa&&bbb)// w\n"
14093                    ";",
14094                    Tab));
14095 
14096   verifyFormat("class X {\n"
14097                "\tvoid f() {\n"
14098                "\t\tsomeFunction(parameter1,\n"
14099                "\t\t\t     parameter2);\n"
14100                "\t}\n"
14101                "};",
14102                Tab);
14103   verifyFormat("#define A                        \\\n"
14104                "\tvoid f() {               \\\n"
14105                "\t\tsomeFunction(    \\\n"
14106                "\t\t    parameter1,  \\\n"
14107                "\t\t    parameter2); \\\n"
14108                "\t}",
14109                Tab);
14110   verifyFormat("int a;\t      // x\n"
14111                "int bbbbbbbb; // x\n",
14112                Tab);
14113 
14114   Tab.TabWidth = 4;
14115   Tab.IndentWidth = 8;
14116   verifyFormat("class TabWidth4Indent8 {\n"
14117                "\t\tvoid f() {\n"
14118                "\t\t\t\tsomeFunction(parameter1,\n"
14119                "\t\t\t\t\t\t\t parameter2);\n"
14120                "\t\t}\n"
14121                "};",
14122                Tab);
14123 
14124   Tab.TabWidth = 4;
14125   Tab.IndentWidth = 4;
14126   verifyFormat("class TabWidth4Indent4 {\n"
14127                "\tvoid f() {\n"
14128                "\t\tsomeFunction(parameter1,\n"
14129                "\t\t\t\t\t parameter2);\n"
14130                "\t}\n"
14131                "};",
14132                Tab);
14133 
14134   Tab.TabWidth = 8;
14135   Tab.IndentWidth = 4;
14136   verifyFormat("class TabWidth8Indent4 {\n"
14137                "    void f() {\n"
14138                "\tsomeFunction(parameter1,\n"
14139                "\t\t     parameter2);\n"
14140                "    }\n"
14141                "};",
14142                Tab);
14143 
14144   Tab.TabWidth = 8;
14145   Tab.IndentWidth = 8;
14146   EXPECT_EQ("/*\n"
14147             "\t      a\t\tcomment\n"
14148             "\t      in multiple lines\n"
14149             "       */",
14150             format("   /*\t \t \n"
14151                    " \t \t a\t\tcomment\t \t\n"
14152                    " \t \t in multiple lines\t\n"
14153                    " \t  */",
14154                    Tab));
14155 
14156   Tab.UseTab = FormatStyle::UT_ForIndentation;
14157   verifyFormat("{\n"
14158                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14159                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14160                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14161                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14162                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14163                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14164                "};",
14165                Tab);
14166   verifyFormat("enum AA {\n"
14167                "\ta1, // Force multiple lines\n"
14168                "\ta2,\n"
14169                "\ta3\n"
14170                "};",
14171                Tab);
14172   EXPECT_EQ("if (aaaaaaaa && // q\n"
14173             "    bb)         // w\n"
14174             "\t;",
14175             format("if (aaaaaaaa &&// q\n"
14176                    "bb)// w\n"
14177                    ";",
14178                    Tab));
14179   verifyFormat("class X {\n"
14180                "\tvoid f() {\n"
14181                "\t\tsomeFunction(parameter1,\n"
14182                "\t\t             parameter2);\n"
14183                "\t}\n"
14184                "};",
14185                Tab);
14186   verifyFormat("{\n"
14187                "\tQ(\n"
14188                "\t    {\n"
14189                "\t\t    int a;\n"
14190                "\t\t    someFunction(aaaaaaaa,\n"
14191                "\t\t                 bbbbbbb);\n"
14192                "\t    },\n"
14193                "\t    p);\n"
14194                "}",
14195                Tab);
14196   EXPECT_EQ("{\n"
14197             "\t/* aaaa\n"
14198             "\t   bbbb */\n"
14199             "}",
14200             format("{\n"
14201                    "/* aaaa\n"
14202                    "   bbbb */\n"
14203                    "}",
14204                    Tab));
14205   EXPECT_EQ("{\n"
14206             "\t/*\n"
14207             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14208             "\t  bbbbbbbbbbbbb\n"
14209             "\t*/\n"
14210             "}",
14211             format("{\n"
14212                    "/*\n"
14213                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14214                    "*/\n"
14215                    "}",
14216                    Tab));
14217   EXPECT_EQ("{\n"
14218             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14219             "\t// bbbbbbbbbbbbb\n"
14220             "}",
14221             format("{\n"
14222                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14223                    "}",
14224                    Tab));
14225   EXPECT_EQ("{\n"
14226             "\t/*\n"
14227             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14228             "\t  bbbbbbbbbbbbb\n"
14229             "\t*/\n"
14230             "}",
14231             format("{\n"
14232                    "\t/*\n"
14233                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14234                    "\t*/\n"
14235                    "}",
14236                    Tab));
14237   EXPECT_EQ("{\n"
14238             "\t/*\n"
14239             "\n"
14240             "\t*/\n"
14241             "}",
14242             format("{\n"
14243                    "\t/*\n"
14244                    "\n"
14245                    "\t*/\n"
14246                    "}",
14247                    Tab));
14248   EXPECT_EQ("{\n"
14249             "\t/*\n"
14250             " asdf\n"
14251             "\t*/\n"
14252             "}",
14253             format("{\n"
14254                    "\t/*\n"
14255                    " asdf\n"
14256                    "\t*/\n"
14257                    "}",
14258                    Tab));
14259 
14260   verifyFormat("void f() {\n"
14261                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14262                "\t            : bbbbbbbbbbbbbbbbbb\n"
14263                "}",
14264                Tab);
14265   FormatStyle TabNoBreak = Tab;
14266   TabNoBreak.BreakBeforeTernaryOperators = false;
14267   verifyFormat("void f() {\n"
14268                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14269                "\t              bbbbbbbbbbbbbbbbbb\n"
14270                "}",
14271                TabNoBreak);
14272   verifyFormat("void f() {\n"
14273                "\treturn true ?\n"
14274                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14275                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14276                "}",
14277                TabNoBreak);
14278 
14279   Tab.UseTab = FormatStyle::UT_Never;
14280   EXPECT_EQ("/*\n"
14281             "              a\t\tcomment\n"
14282             "              in multiple lines\n"
14283             "       */",
14284             format("   /*\t \t \n"
14285                    " \t \t a\t\tcomment\t \t\n"
14286                    " \t \t in multiple lines\t\n"
14287                    " \t  */",
14288                    Tab));
14289   EXPECT_EQ("/* some\n"
14290             "   comment */",
14291             format(" \t \t /* some\n"
14292                    " \t \t    comment */",
14293                    Tab));
14294   EXPECT_EQ("int a; /* some\n"
14295             "   comment */",
14296             format(" \t \t int a; /* some\n"
14297                    " \t \t    comment */",
14298                    Tab));
14299 
14300   EXPECT_EQ("int a; /* some\n"
14301             "comment */",
14302             format(" \t \t int\ta; /* some\n"
14303                    " \t \t    comment */",
14304                    Tab));
14305   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14306             "    comment */",
14307             format(" \t \t f(\"\t\t\"); /* some\n"
14308                    " \t \t    comment */",
14309                    Tab));
14310   EXPECT_EQ("{\n"
14311             "        /*\n"
14312             "         * Comment\n"
14313             "         */\n"
14314             "        int i;\n"
14315             "}",
14316             format("{\n"
14317                    "\t/*\n"
14318                    "\t * Comment\n"
14319                    "\t */\n"
14320                    "\t int i;\n"
14321                    "}",
14322                    Tab));
14323 
14324   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14325   Tab.TabWidth = 8;
14326   Tab.IndentWidth = 8;
14327   EXPECT_EQ("if (aaaaaaaa && // q\n"
14328             "    bb)         // w\n"
14329             "\t;",
14330             format("if (aaaaaaaa &&// q\n"
14331                    "bb)// w\n"
14332                    ";",
14333                    Tab));
14334   EXPECT_EQ("if (aaa && bbb) // w\n"
14335             "\t;",
14336             format("if(aaa&&bbb)// w\n"
14337                    ";",
14338                    Tab));
14339   verifyFormat("class X {\n"
14340                "\tvoid f() {\n"
14341                "\t\tsomeFunction(parameter1,\n"
14342                "\t\t\t     parameter2);\n"
14343                "\t}\n"
14344                "};",
14345                Tab);
14346   verifyFormat("#define A                        \\\n"
14347                "\tvoid f() {               \\\n"
14348                "\t\tsomeFunction(    \\\n"
14349                "\t\t    parameter1,  \\\n"
14350                "\t\t    parameter2); \\\n"
14351                "\t}",
14352                Tab);
14353   Tab.TabWidth = 4;
14354   Tab.IndentWidth = 8;
14355   verifyFormat("class TabWidth4Indent8 {\n"
14356                "\t\tvoid f() {\n"
14357                "\t\t\t\tsomeFunction(parameter1,\n"
14358                "\t\t\t\t\t\t\t parameter2);\n"
14359                "\t\t}\n"
14360                "};",
14361                Tab);
14362   Tab.TabWidth = 4;
14363   Tab.IndentWidth = 4;
14364   verifyFormat("class TabWidth4Indent4 {\n"
14365                "\tvoid f() {\n"
14366                "\t\tsomeFunction(parameter1,\n"
14367                "\t\t\t\t\t parameter2);\n"
14368                "\t}\n"
14369                "};",
14370                Tab);
14371   Tab.TabWidth = 8;
14372   Tab.IndentWidth = 4;
14373   verifyFormat("class TabWidth8Indent4 {\n"
14374                "    void f() {\n"
14375                "\tsomeFunction(parameter1,\n"
14376                "\t\t     parameter2);\n"
14377                "    }\n"
14378                "};",
14379                Tab);
14380   Tab.TabWidth = 8;
14381   Tab.IndentWidth = 8;
14382   EXPECT_EQ("/*\n"
14383             "\t      a\t\tcomment\n"
14384             "\t      in multiple lines\n"
14385             "       */",
14386             format("   /*\t \t \n"
14387                    " \t \t a\t\tcomment\t \t\n"
14388                    " \t \t in multiple lines\t\n"
14389                    " \t  */",
14390                    Tab));
14391   verifyFormat("{\n"
14392                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14393                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14394                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14395                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14396                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14397                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14398                "};",
14399                Tab);
14400   verifyFormat("enum AA {\n"
14401                "\ta1, // Force multiple lines\n"
14402                "\ta2,\n"
14403                "\ta3\n"
14404                "};",
14405                Tab);
14406   EXPECT_EQ("if (aaaaaaaa && // q\n"
14407             "    bb)         // w\n"
14408             "\t;",
14409             format("if (aaaaaaaa &&// q\n"
14410                    "bb)// w\n"
14411                    ";",
14412                    Tab));
14413   verifyFormat("class X {\n"
14414                "\tvoid f() {\n"
14415                "\t\tsomeFunction(parameter1,\n"
14416                "\t\t\t     parameter2);\n"
14417                "\t}\n"
14418                "};",
14419                Tab);
14420   verifyFormat("{\n"
14421                "\tQ(\n"
14422                "\t    {\n"
14423                "\t\t    int a;\n"
14424                "\t\t    someFunction(aaaaaaaa,\n"
14425                "\t\t\t\t bbbbbbb);\n"
14426                "\t    },\n"
14427                "\t    p);\n"
14428                "}",
14429                Tab);
14430   EXPECT_EQ("{\n"
14431             "\t/* aaaa\n"
14432             "\t   bbbb */\n"
14433             "}",
14434             format("{\n"
14435                    "/* aaaa\n"
14436                    "   bbbb */\n"
14437                    "}",
14438                    Tab));
14439   EXPECT_EQ("{\n"
14440             "\t/*\n"
14441             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14442             "\t  bbbbbbbbbbbbb\n"
14443             "\t*/\n"
14444             "}",
14445             format("{\n"
14446                    "/*\n"
14447                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14448                    "*/\n"
14449                    "}",
14450                    Tab));
14451   EXPECT_EQ("{\n"
14452             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14453             "\t// bbbbbbbbbbbbb\n"
14454             "}",
14455             format("{\n"
14456                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14457                    "}",
14458                    Tab));
14459   EXPECT_EQ("{\n"
14460             "\t/*\n"
14461             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14462             "\t  bbbbbbbbbbbbb\n"
14463             "\t*/\n"
14464             "}",
14465             format("{\n"
14466                    "\t/*\n"
14467                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14468                    "\t*/\n"
14469                    "}",
14470                    Tab));
14471   EXPECT_EQ("{\n"
14472             "\t/*\n"
14473             "\n"
14474             "\t*/\n"
14475             "}",
14476             format("{\n"
14477                    "\t/*\n"
14478                    "\n"
14479                    "\t*/\n"
14480                    "}",
14481                    Tab));
14482   EXPECT_EQ("{\n"
14483             "\t/*\n"
14484             " asdf\n"
14485             "\t*/\n"
14486             "}",
14487             format("{\n"
14488                    "\t/*\n"
14489                    " asdf\n"
14490                    "\t*/\n"
14491                    "}",
14492                    Tab));
14493   EXPECT_EQ("/* some\n"
14494             "   comment */",
14495             format(" \t \t /* some\n"
14496                    " \t \t    comment */",
14497                    Tab));
14498   EXPECT_EQ("int a; /* some\n"
14499             "   comment */",
14500             format(" \t \t int a; /* some\n"
14501                    " \t \t    comment */",
14502                    Tab));
14503   EXPECT_EQ("int a; /* some\n"
14504             "comment */",
14505             format(" \t \t int\ta; /* some\n"
14506                    " \t \t    comment */",
14507                    Tab));
14508   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14509             "    comment */",
14510             format(" \t \t f(\"\t\t\"); /* some\n"
14511                    " \t \t    comment */",
14512                    Tab));
14513   EXPECT_EQ("{\n"
14514             "\t/*\n"
14515             "\t * Comment\n"
14516             "\t */\n"
14517             "\tint i;\n"
14518             "}",
14519             format("{\n"
14520                    "\t/*\n"
14521                    "\t * Comment\n"
14522                    "\t */\n"
14523                    "\t int i;\n"
14524                    "}",
14525                    Tab));
14526   Tab.TabWidth = 2;
14527   Tab.IndentWidth = 2;
14528   EXPECT_EQ("{\n"
14529             "\t/* aaaa\n"
14530             "\t\t bbbb */\n"
14531             "}",
14532             format("{\n"
14533                    "/* aaaa\n"
14534                    "\t bbbb */\n"
14535                    "}",
14536                    Tab));
14537   EXPECT_EQ("{\n"
14538             "\t/*\n"
14539             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14540             "\t\tbbbbbbbbbbbbb\n"
14541             "\t*/\n"
14542             "}",
14543             format("{\n"
14544                    "/*\n"
14545                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14546                    "*/\n"
14547                    "}",
14548                    Tab));
14549   Tab.AlignConsecutiveAssignments.Enabled = true;
14550   Tab.AlignConsecutiveDeclarations.Enabled = true;
14551   Tab.TabWidth = 4;
14552   Tab.IndentWidth = 4;
14553   verifyFormat("class Assign {\n"
14554                "\tvoid f() {\n"
14555                "\t\tint         x      = 123;\n"
14556                "\t\tint         random = 4;\n"
14557                "\t\tstd::string alphabet =\n"
14558                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14559                "\t}\n"
14560                "};",
14561                Tab);
14562 
14563   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14564   Tab.TabWidth = 8;
14565   Tab.IndentWidth = 8;
14566   EXPECT_EQ("if (aaaaaaaa && // q\n"
14567             "    bb)         // w\n"
14568             "\t;",
14569             format("if (aaaaaaaa &&// q\n"
14570                    "bb)// w\n"
14571                    ";",
14572                    Tab));
14573   EXPECT_EQ("if (aaa && bbb) // w\n"
14574             "\t;",
14575             format("if(aaa&&bbb)// w\n"
14576                    ";",
14577                    Tab));
14578   verifyFormat("class X {\n"
14579                "\tvoid f() {\n"
14580                "\t\tsomeFunction(parameter1,\n"
14581                "\t\t             parameter2);\n"
14582                "\t}\n"
14583                "};",
14584                Tab);
14585   verifyFormat("#define A                        \\\n"
14586                "\tvoid f() {               \\\n"
14587                "\t\tsomeFunction(    \\\n"
14588                "\t\t    parameter1,  \\\n"
14589                "\t\t    parameter2); \\\n"
14590                "\t}",
14591                Tab);
14592   Tab.TabWidth = 4;
14593   Tab.IndentWidth = 8;
14594   verifyFormat("class TabWidth4Indent8 {\n"
14595                "\t\tvoid f() {\n"
14596                "\t\t\t\tsomeFunction(parameter1,\n"
14597                "\t\t\t\t             parameter2);\n"
14598                "\t\t}\n"
14599                "};",
14600                Tab);
14601   Tab.TabWidth = 4;
14602   Tab.IndentWidth = 4;
14603   verifyFormat("class TabWidth4Indent4 {\n"
14604                "\tvoid f() {\n"
14605                "\t\tsomeFunction(parameter1,\n"
14606                "\t\t             parameter2);\n"
14607                "\t}\n"
14608                "};",
14609                Tab);
14610   Tab.TabWidth = 8;
14611   Tab.IndentWidth = 4;
14612   verifyFormat("class TabWidth8Indent4 {\n"
14613                "    void f() {\n"
14614                "\tsomeFunction(parameter1,\n"
14615                "\t             parameter2);\n"
14616                "    }\n"
14617                "};",
14618                Tab);
14619   Tab.TabWidth = 8;
14620   Tab.IndentWidth = 8;
14621   EXPECT_EQ("/*\n"
14622             "              a\t\tcomment\n"
14623             "              in multiple lines\n"
14624             "       */",
14625             format("   /*\t \t \n"
14626                    " \t \t a\t\tcomment\t \t\n"
14627                    " \t \t in multiple lines\t\n"
14628                    " \t  */",
14629                    Tab));
14630   verifyFormat("{\n"
14631                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14632                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14633                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14634                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14635                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14636                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14637                "};",
14638                Tab);
14639   verifyFormat("enum AA {\n"
14640                "\ta1, // Force multiple lines\n"
14641                "\ta2,\n"
14642                "\ta3\n"
14643                "};",
14644                Tab);
14645   EXPECT_EQ("if (aaaaaaaa && // q\n"
14646             "    bb)         // w\n"
14647             "\t;",
14648             format("if (aaaaaaaa &&// q\n"
14649                    "bb)// w\n"
14650                    ";",
14651                    Tab));
14652   verifyFormat("class X {\n"
14653                "\tvoid f() {\n"
14654                "\t\tsomeFunction(parameter1,\n"
14655                "\t\t             parameter2);\n"
14656                "\t}\n"
14657                "};",
14658                Tab);
14659   verifyFormat("{\n"
14660                "\tQ(\n"
14661                "\t    {\n"
14662                "\t\t    int a;\n"
14663                "\t\t    someFunction(aaaaaaaa,\n"
14664                "\t\t                 bbbbbbb);\n"
14665                "\t    },\n"
14666                "\t    p);\n"
14667                "}",
14668                Tab);
14669   EXPECT_EQ("{\n"
14670             "\t/* aaaa\n"
14671             "\t   bbbb */\n"
14672             "}",
14673             format("{\n"
14674                    "/* aaaa\n"
14675                    "   bbbb */\n"
14676                    "}",
14677                    Tab));
14678   EXPECT_EQ("{\n"
14679             "\t/*\n"
14680             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14681             "\t  bbbbbbbbbbbbb\n"
14682             "\t*/\n"
14683             "}",
14684             format("{\n"
14685                    "/*\n"
14686                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14687                    "*/\n"
14688                    "}",
14689                    Tab));
14690   EXPECT_EQ("{\n"
14691             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14692             "\t// bbbbbbbbbbbbb\n"
14693             "}",
14694             format("{\n"
14695                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14696                    "}",
14697                    Tab));
14698   EXPECT_EQ("{\n"
14699             "\t/*\n"
14700             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14701             "\t  bbbbbbbbbbbbb\n"
14702             "\t*/\n"
14703             "}",
14704             format("{\n"
14705                    "\t/*\n"
14706                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14707                    "\t*/\n"
14708                    "}",
14709                    Tab));
14710   EXPECT_EQ("{\n"
14711             "\t/*\n"
14712             "\n"
14713             "\t*/\n"
14714             "}",
14715             format("{\n"
14716                    "\t/*\n"
14717                    "\n"
14718                    "\t*/\n"
14719                    "}",
14720                    Tab));
14721   EXPECT_EQ("{\n"
14722             "\t/*\n"
14723             " asdf\n"
14724             "\t*/\n"
14725             "}",
14726             format("{\n"
14727                    "\t/*\n"
14728                    " asdf\n"
14729                    "\t*/\n"
14730                    "}",
14731                    Tab));
14732   EXPECT_EQ("/* some\n"
14733             "   comment */",
14734             format(" \t \t /* some\n"
14735                    " \t \t    comment */",
14736                    Tab));
14737   EXPECT_EQ("int a; /* some\n"
14738             "   comment */",
14739             format(" \t \t int a; /* some\n"
14740                    " \t \t    comment */",
14741                    Tab));
14742   EXPECT_EQ("int a; /* some\n"
14743             "comment */",
14744             format(" \t \t int\ta; /* some\n"
14745                    " \t \t    comment */",
14746                    Tab));
14747   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14748             "    comment */",
14749             format(" \t \t f(\"\t\t\"); /* some\n"
14750                    " \t \t    comment */",
14751                    Tab));
14752   EXPECT_EQ("{\n"
14753             "\t/*\n"
14754             "\t * Comment\n"
14755             "\t */\n"
14756             "\tint i;\n"
14757             "}",
14758             format("{\n"
14759                    "\t/*\n"
14760                    "\t * Comment\n"
14761                    "\t */\n"
14762                    "\t int i;\n"
14763                    "}",
14764                    Tab));
14765   Tab.TabWidth = 2;
14766   Tab.IndentWidth = 2;
14767   EXPECT_EQ("{\n"
14768             "\t/* aaaa\n"
14769             "\t   bbbb */\n"
14770             "}",
14771             format("{\n"
14772                    "/* aaaa\n"
14773                    "   bbbb */\n"
14774                    "}",
14775                    Tab));
14776   EXPECT_EQ("{\n"
14777             "\t/*\n"
14778             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14779             "\t  bbbbbbbbbbbbb\n"
14780             "\t*/\n"
14781             "}",
14782             format("{\n"
14783                    "/*\n"
14784                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14785                    "*/\n"
14786                    "}",
14787                    Tab));
14788   Tab.AlignConsecutiveAssignments.Enabled = true;
14789   Tab.AlignConsecutiveDeclarations.Enabled = true;
14790   Tab.TabWidth = 4;
14791   Tab.IndentWidth = 4;
14792   verifyFormat("class Assign {\n"
14793                "\tvoid f() {\n"
14794                "\t\tint         x      = 123;\n"
14795                "\t\tint         random = 4;\n"
14796                "\t\tstd::string alphabet =\n"
14797                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14798                "\t}\n"
14799                "};",
14800                Tab);
14801   Tab.AlignOperands = FormatStyle::OAS_Align;
14802   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14803                "                 cccccccccccccccccccc;",
14804                Tab);
14805   // no alignment
14806   verifyFormat("int aaaaaaaaaa =\n"
14807                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14808                Tab);
14809   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14810                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14811                "                        : 333333333333333;",
14812                Tab);
14813   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14814   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14815   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14816                "               + cccccccccccccccccccc;",
14817                Tab);
14818 }
14819 
14820 TEST_F(FormatTest, ZeroTabWidth) {
14821   FormatStyle Tab = getLLVMStyleWithColumns(42);
14822   Tab.IndentWidth = 8;
14823   Tab.UseTab = FormatStyle::UT_Never;
14824   Tab.TabWidth = 0;
14825   EXPECT_EQ("void a(){\n"
14826             "    // line starts with '\t'\n"
14827             "};",
14828             format("void a(){\n"
14829                    "\t// line starts with '\t'\n"
14830                    "};",
14831                    Tab));
14832 
14833   EXPECT_EQ("void a(){\n"
14834             "    // line starts with '\t'\n"
14835             "};",
14836             format("void a(){\n"
14837                    "\t\t// line starts with '\t'\n"
14838                    "};",
14839                    Tab));
14840 
14841   Tab.UseTab = FormatStyle::UT_ForIndentation;
14842   EXPECT_EQ("void a(){\n"
14843             "    // line starts with '\t'\n"
14844             "};",
14845             format("void a(){\n"
14846                    "\t// line starts with '\t'\n"
14847                    "};",
14848                    Tab));
14849 
14850   EXPECT_EQ("void a(){\n"
14851             "    // line starts with '\t'\n"
14852             "};",
14853             format("void a(){\n"
14854                    "\t\t// line starts with '\t'\n"
14855                    "};",
14856                    Tab));
14857 
14858   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14859   EXPECT_EQ("void a(){\n"
14860             "    // line starts with '\t'\n"
14861             "};",
14862             format("void a(){\n"
14863                    "\t// line starts with '\t'\n"
14864                    "};",
14865                    Tab));
14866 
14867   EXPECT_EQ("void a(){\n"
14868             "    // line starts with '\t'\n"
14869             "};",
14870             format("void a(){\n"
14871                    "\t\t// line starts with '\t'\n"
14872                    "};",
14873                    Tab));
14874 
14875   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14876   EXPECT_EQ("void a(){\n"
14877             "    // line starts with '\t'\n"
14878             "};",
14879             format("void a(){\n"
14880                    "\t// line starts with '\t'\n"
14881                    "};",
14882                    Tab));
14883 
14884   EXPECT_EQ("void a(){\n"
14885             "    // line starts with '\t'\n"
14886             "};",
14887             format("void a(){\n"
14888                    "\t\t// line starts with '\t'\n"
14889                    "};",
14890                    Tab));
14891 
14892   Tab.UseTab = FormatStyle::UT_Always;
14893   EXPECT_EQ("void a(){\n"
14894             "// line starts with '\t'\n"
14895             "};",
14896             format("void a(){\n"
14897                    "\t// line starts with '\t'\n"
14898                    "};",
14899                    Tab));
14900 
14901   EXPECT_EQ("void a(){\n"
14902             "// line starts with '\t'\n"
14903             "};",
14904             format("void a(){\n"
14905                    "\t\t// line starts with '\t'\n"
14906                    "};",
14907                    Tab));
14908 }
14909 
14910 TEST_F(FormatTest, CalculatesOriginalColumn) {
14911   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14912             "q\"; /* some\n"
14913             "       comment */",
14914             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14915                    "q\"; /* some\n"
14916                    "       comment */",
14917                    getLLVMStyle()));
14918   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14919             "/* some\n"
14920             "   comment */",
14921             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14922                    " /* some\n"
14923                    "    comment */",
14924                    getLLVMStyle()));
14925   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14926             "qqq\n"
14927             "/* some\n"
14928             "   comment */",
14929             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14930                    "qqq\n"
14931                    " /* some\n"
14932                    "    comment */",
14933                    getLLVMStyle()));
14934   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14935             "wwww; /* some\n"
14936             "         comment */",
14937             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14938                    "wwww; /* some\n"
14939                    "         comment */",
14940                    getLLVMStyle()));
14941 }
14942 
14943 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14944   FormatStyle NoSpace = getLLVMStyle();
14945   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14946 
14947   verifyFormat("while(true)\n"
14948                "  continue;",
14949                NoSpace);
14950   verifyFormat("for(;;)\n"
14951                "  continue;",
14952                NoSpace);
14953   verifyFormat("if(true)\n"
14954                "  f();\n"
14955                "else if(true)\n"
14956                "  f();",
14957                NoSpace);
14958   verifyFormat("do {\n"
14959                "  do_something();\n"
14960                "} while(something());",
14961                NoSpace);
14962   verifyFormat("switch(x) {\n"
14963                "default:\n"
14964                "  break;\n"
14965                "}",
14966                NoSpace);
14967   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14968   verifyFormat("size_t x = sizeof(x);", NoSpace);
14969   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14970   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14971   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14972   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14973   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14974   verifyFormat("alignas(128) char a[128];", NoSpace);
14975   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14976   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14977   verifyFormat("int f() throw(Deprecated);", NoSpace);
14978   verifyFormat("typedef void (*cb)(int);", NoSpace);
14979   verifyFormat("T A::operator()();", NoSpace);
14980   verifyFormat("X A::operator++(T);", NoSpace);
14981   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14982 
14983   FormatStyle Space = getLLVMStyle();
14984   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14985 
14986   verifyFormat("int f ();", Space);
14987   verifyFormat("void f (int a, T b) {\n"
14988                "  while (true)\n"
14989                "    continue;\n"
14990                "}",
14991                Space);
14992   verifyFormat("if (true)\n"
14993                "  f ();\n"
14994                "else if (true)\n"
14995                "  f ();",
14996                Space);
14997   verifyFormat("do {\n"
14998                "  do_something ();\n"
14999                "} while (something ());",
15000                Space);
15001   verifyFormat("switch (x) {\n"
15002                "default:\n"
15003                "  break;\n"
15004                "}",
15005                Space);
15006   verifyFormat("A::A () : a (1) {}", Space);
15007   verifyFormat("void f () __attribute__ ((asdf));", Space);
15008   verifyFormat("*(&a + 1);\n"
15009                "&((&a)[1]);\n"
15010                "a[(b + c) * d];\n"
15011                "(((a + 1) * 2) + 3) * 4;",
15012                Space);
15013   verifyFormat("#define A(x) x", Space);
15014   verifyFormat("#define A (x) x", Space);
15015   verifyFormat("#if defined(x)\n"
15016                "#endif",
15017                Space);
15018   verifyFormat("auto i = std::make_unique<int> (5);", Space);
15019   verifyFormat("size_t x = sizeof (x);", Space);
15020   verifyFormat("auto f (int x) -> decltype (x);", Space);
15021   verifyFormat("auto f (int x) -> typeof (x);", Space);
15022   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
15023   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
15024   verifyFormat("int f (T x) noexcept (x.create ());", Space);
15025   verifyFormat("alignas (128) char a[128];", Space);
15026   verifyFormat("size_t x = alignof (MyType);", Space);
15027   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
15028   verifyFormat("int f () throw (Deprecated);", Space);
15029   verifyFormat("typedef void (*cb) (int);", Space);
15030   // FIXME these tests regressed behaviour.
15031   // verifyFormat("T A::operator() ();", Space);
15032   // verifyFormat("X A::operator++ (T);", Space);
15033   verifyFormat("auto lambda = [] () { return 0; };", Space);
15034   verifyFormat("int x = int (y);", Space);
15035 
15036   FormatStyle SomeSpace = getLLVMStyle();
15037   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
15038 
15039   verifyFormat("[]() -> float {}", SomeSpace);
15040   verifyFormat("[] (auto foo) {}", SomeSpace);
15041   verifyFormat("[foo]() -> int {}", SomeSpace);
15042   verifyFormat("int f();", SomeSpace);
15043   verifyFormat("void f (int a, T b) {\n"
15044                "  while (true)\n"
15045                "    continue;\n"
15046                "}",
15047                SomeSpace);
15048   verifyFormat("if (true)\n"
15049                "  f();\n"
15050                "else if (true)\n"
15051                "  f();",
15052                SomeSpace);
15053   verifyFormat("do {\n"
15054                "  do_something();\n"
15055                "} while (something());",
15056                SomeSpace);
15057   verifyFormat("switch (x) {\n"
15058                "default:\n"
15059                "  break;\n"
15060                "}",
15061                SomeSpace);
15062   verifyFormat("A::A() : a (1) {}", SomeSpace);
15063   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
15064   verifyFormat("*(&a + 1);\n"
15065                "&((&a)[1]);\n"
15066                "a[(b + c) * d];\n"
15067                "(((a + 1) * 2) + 3) * 4;",
15068                SomeSpace);
15069   verifyFormat("#define A(x) x", SomeSpace);
15070   verifyFormat("#define A (x) x", SomeSpace);
15071   verifyFormat("#if defined(x)\n"
15072                "#endif",
15073                SomeSpace);
15074   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
15075   verifyFormat("size_t x = sizeof (x);", SomeSpace);
15076   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
15077   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
15078   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
15079   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
15080   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
15081   verifyFormat("alignas (128) char a[128];", SomeSpace);
15082   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
15083   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15084                SomeSpace);
15085   verifyFormat("int f() throw (Deprecated);", SomeSpace);
15086   verifyFormat("typedef void (*cb) (int);", SomeSpace);
15087   verifyFormat("T A::operator()();", SomeSpace);
15088   // FIXME these tests regressed behaviour.
15089   // verifyFormat("X A::operator++ (T);", SomeSpace);
15090   verifyFormat("int x = int (y);", SomeSpace);
15091   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
15092 
15093   FormatStyle SpaceControlStatements = getLLVMStyle();
15094   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15095   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
15096 
15097   verifyFormat("while (true)\n"
15098                "  continue;",
15099                SpaceControlStatements);
15100   verifyFormat("if (true)\n"
15101                "  f();\n"
15102                "else if (true)\n"
15103                "  f();",
15104                SpaceControlStatements);
15105   verifyFormat("for (;;) {\n"
15106                "  do_something();\n"
15107                "}",
15108                SpaceControlStatements);
15109   verifyFormat("do {\n"
15110                "  do_something();\n"
15111                "} while (something());",
15112                SpaceControlStatements);
15113   verifyFormat("switch (x) {\n"
15114                "default:\n"
15115                "  break;\n"
15116                "}",
15117                SpaceControlStatements);
15118 
15119   FormatStyle SpaceFuncDecl = getLLVMStyle();
15120   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15121   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
15122 
15123   verifyFormat("int f ();", SpaceFuncDecl);
15124   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
15125   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
15126   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
15127   verifyFormat("#define A(x) x", SpaceFuncDecl);
15128   verifyFormat("#define A (x) x", SpaceFuncDecl);
15129   verifyFormat("#if defined(x)\n"
15130                "#endif",
15131                SpaceFuncDecl);
15132   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
15133   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
15134   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
15135   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
15136   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
15137   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
15138   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
15139   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
15140   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
15141   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15142                SpaceFuncDecl);
15143   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
15144   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
15145   // FIXME these tests regressed behaviour.
15146   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
15147   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
15148   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
15149   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
15150   verifyFormat("int x = int(y);", SpaceFuncDecl);
15151   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15152                SpaceFuncDecl);
15153 
15154   FormatStyle SpaceFuncDef = getLLVMStyle();
15155   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15156   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
15157 
15158   verifyFormat("int f();", SpaceFuncDef);
15159   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
15160   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
15161   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
15162   verifyFormat("#define A(x) x", SpaceFuncDef);
15163   verifyFormat("#define A (x) x", SpaceFuncDef);
15164   verifyFormat("#if defined(x)\n"
15165                "#endif",
15166                SpaceFuncDef);
15167   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
15168   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
15169   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
15170   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
15171   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
15172   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
15173   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
15174   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
15175   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
15176   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15177                SpaceFuncDef);
15178   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
15179   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
15180   verifyFormat("T A::operator()();", SpaceFuncDef);
15181   verifyFormat("X A::operator++(T);", SpaceFuncDef);
15182   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
15183   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
15184   verifyFormat("int x = int(y);", SpaceFuncDef);
15185   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15186                SpaceFuncDef);
15187 
15188   FormatStyle SpaceIfMacros = getLLVMStyle();
15189   SpaceIfMacros.IfMacros.clear();
15190   SpaceIfMacros.IfMacros.push_back("MYIF");
15191   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15192   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
15193   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
15194   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
15195   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
15196 
15197   FormatStyle SpaceForeachMacros = getLLVMStyle();
15198   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
15199             FormatStyle::SBS_Never);
15200   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
15201   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15202   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
15203   verifyFormat("for (;;) {\n"
15204                "}",
15205                SpaceForeachMacros);
15206   verifyFormat("foreach (Item *item, itemlist) {\n"
15207                "}",
15208                SpaceForeachMacros);
15209   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15210                "}",
15211                SpaceForeachMacros);
15212   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15213                "}",
15214                SpaceForeachMacros);
15215   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15216 
15217   FormatStyle SomeSpace2 = getLLVMStyle();
15218   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15219   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15220   verifyFormat("[]() -> float {}", SomeSpace2);
15221   verifyFormat("[] (auto foo) {}", SomeSpace2);
15222   verifyFormat("[foo]() -> int {}", SomeSpace2);
15223   verifyFormat("int f();", SomeSpace2);
15224   verifyFormat("void f (int a, T b) {\n"
15225                "  while (true)\n"
15226                "    continue;\n"
15227                "}",
15228                SomeSpace2);
15229   verifyFormat("if (true)\n"
15230                "  f();\n"
15231                "else if (true)\n"
15232                "  f();",
15233                SomeSpace2);
15234   verifyFormat("do {\n"
15235                "  do_something();\n"
15236                "} while (something());",
15237                SomeSpace2);
15238   verifyFormat("switch (x) {\n"
15239                "default:\n"
15240                "  break;\n"
15241                "}",
15242                SomeSpace2);
15243   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15244   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15245   verifyFormat("*(&a + 1);\n"
15246                "&((&a)[1]);\n"
15247                "a[(b + c) * d];\n"
15248                "(((a + 1) * 2) + 3) * 4;",
15249                SomeSpace2);
15250   verifyFormat("#define A(x) x", SomeSpace2);
15251   verifyFormat("#define A (x) x", SomeSpace2);
15252   verifyFormat("#if defined(x)\n"
15253                "#endif",
15254                SomeSpace2);
15255   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15256   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15257   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15258   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15259   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15260   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15261   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15262   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15263   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15264   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15265                SomeSpace2);
15266   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15267   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15268   verifyFormat("T A::operator()();", SomeSpace2);
15269   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15270   verifyFormat("int x = int (y);", SomeSpace2);
15271   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15272 
15273   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15274   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15275   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15276       .AfterOverloadedOperator = true;
15277 
15278   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15279   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15280   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15281   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15282 
15283   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15284       .AfterOverloadedOperator = false;
15285 
15286   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15287   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15288   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15289   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15290 
15291   auto SpaceAfterRequires = getLLVMStyle();
15292   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15293   EXPECT_FALSE(
15294       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15295   EXPECT_FALSE(
15296       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15297   verifyFormat("void f(auto x)\n"
15298                "  requires requires(int i) { x + i; }\n"
15299                "{}",
15300                SpaceAfterRequires);
15301   verifyFormat("void f(auto x)\n"
15302                "  requires(requires(int i) { x + i; })\n"
15303                "{}",
15304                SpaceAfterRequires);
15305   verifyFormat("if (requires(int i) { x + i; })\n"
15306                "  return;",
15307                SpaceAfterRequires);
15308   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15309   verifyFormat("template <typename T>\n"
15310                "  requires(Foo<T>)\n"
15311                "class Bar;",
15312                SpaceAfterRequires);
15313 
15314   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15315   verifyFormat("void f(auto x)\n"
15316                "  requires requires(int i) { x + i; }\n"
15317                "{}",
15318                SpaceAfterRequires);
15319   verifyFormat("void f(auto x)\n"
15320                "  requires (requires(int i) { x + i; })\n"
15321                "{}",
15322                SpaceAfterRequires);
15323   verifyFormat("if (requires(int i) { x + i; })\n"
15324                "  return;",
15325                SpaceAfterRequires);
15326   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15327   verifyFormat("template <typename T>\n"
15328                "  requires (Foo<T>)\n"
15329                "class Bar;",
15330                SpaceAfterRequires);
15331 
15332   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15333   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15334   verifyFormat("void f(auto x)\n"
15335                "  requires requires (int i) { x + i; }\n"
15336                "{}",
15337                SpaceAfterRequires);
15338   verifyFormat("void f(auto x)\n"
15339                "  requires(requires (int i) { x + i; })\n"
15340                "{}",
15341                SpaceAfterRequires);
15342   verifyFormat("if (requires (int i) { x + i; })\n"
15343                "  return;",
15344                SpaceAfterRequires);
15345   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15346   verifyFormat("template <typename T>\n"
15347                "  requires(Foo<T>)\n"
15348                "class Bar;",
15349                SpaceAfterRequires);
15350 
15351   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15352   verifyFormat("void f(auto x)\n"
15353                "  requires requires (int i) { x + i; }\n"
15354                "{}",
15355                SpaceAfterRequires);
15356   verifyFormat("void f(auto x)\n"
15357                "  requires (requires (int i) { x + i; })\n"
15358                "{}",
15359                SpaceAfterRequires);
15360   verifyFormat("if (requires (int i) { x + i; })\n"
15361                "  return;",
15362                SpaceAfterRequires);
15363   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15364   verifyFormat("template <typename T>\n"
15365                "  requires (Foo<T>)\n"
15366                "class Bar;",
15367                SpaceAfterRequires);
15368 }
15369 
15370 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15371   FormatStyle Spaces = getLLVMStyle();
15372   Spaces.SpaceAfterLogicalNot = true;
15373 
15374   verifyFormat("bool x = ! y", Spaces);
15375   verifyFormat("if (! isFailure())", Spaces);
15376   verifyFormat("if (! (a && b))", Spaces);
15377   verifyFormat("\"Error!\"", Spaces);
15378   verifyFormat("! ! x", Spaces);
15379 }
15380 
15381 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15382   FormatStyle Spaces = getLLVMStyle();
15383 
15384   Spaces.SpacesInParentheses = true;
15385   verifyFormat("do_something( ::globalVar );", Spaces);
15386   verifyFormat("call( x, y, z );", Spaces);
15387   verifyFormat("call();", Spaces);
15388   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15389   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15390                Spaces);
15391   verifyFormat("while ( (bool)1 )\n"
15392                "  continue;",
15393                Spaces);
15394   verifyFormat("for ( ;; )\n"
15395                "  continue;",
15396                Spaces);
15397   verifyFormat("if ( true )\n"
15398                "  f();\n"
15399                "else if ( true )\n"
15400                "  f();",
15401                Spaces);
15402   verifyFormat("do {\n"
15403                "  do_something( (int)i );\n"
15404                "} while ( something() );",
15405                Spaces);
15406   verifyFormat("switch ( x ) {\n"
15407                "default:\n"
15408                "  break;\n"
15409                "}",
15410                Spaces);
15411 
15412   Spaces.SpacesInParentheses = false;
15413   Spaces.SpacesInCStyleCastParentheses = true;
15414   verifyFormat("Type *A = ( Type * )P;", Spaces);
15415   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15416   verifyFormat("x = ( int32 )y;", Spaces);
15417   verifyFormat("int a = ( int )(2.0f);", Spaces);
15418   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15419   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15420   verifyFormat("#define x (( int )-1)", Spaces);
15421 
15422   // Run the first set of tests again with:
15423   Spaces.SpacesInParentheses = false;
15424   Spaces.SpaceInEmptyParentheses = true;
15425   Spaces.SpacesInCStyleCastParentheses = true;
15426   verifyFormat("call(x, y, z);", Spaces);
15427   verifyFormat("call( );", Spaces);
15428   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15429   verifyFormat("while (( bool )1)\n"
15430                "  continue;",
15431                Spaces);
15432   verifyFormat("for (;;)\n"
15433                "  continue;",
15434                Spaces);
15435   verifyFormat("if (true)\n"
15436                "  f( );\n"
15437                "else if (true)\n"
15438                "  f( );",
15439                Spaces);
15440   verifyFormat("do {\n"
15441                "  do_something(( int )i);\n"
15442                "} while (something( ));",
15443                Spaces);
15444   verifyFormat("switch (x) {\n"
15445                "default:\n"
15446                "  break;\n"
15447                "}",
15448                Spaces);
15449 
15450   // Run the first set of tests again with:
15451   Spaces.SpaceAfterCStyleCast = true;
15452   verifyFormat("call(x, y, z);", Spaces);
15453   verifyFormat("call( );", Spaces);
15454   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15455   verifyFormat("while (( bool ) 1)\n"
15456                "  continue;",
15457                Spaces);
15458   verifyFormat("for (;;)\n"
15459                "  continue;",
15460                Spaces);
15461   verifyFormat("if (true)\n"
15462                "  f( );\n"
15463                "else if (true)\n"
15464                "  f( );",
15465                Spaces);
15466   verifyFormat("do {\n"
15467                "  do_something(( int ) i);\n"
15468                "} while (something( ));",
15469                Spaces);
15470   verifyFormat("switch (x) {\n"
15471                "default:\n"
15472                "  break;\n"
15473                "}",
15474                Spaces);
15475   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15476   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15477   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15478   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15479   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15480 
15481   // Run subset of tests again with:
15482   Spaces.SpacesInCStyleCastParentheses = false;
15483   Spaces.SpaceAfterCStyleCast = true;
15484   verifyFormat("while ((bool) 1)\n"
15485                "  continue;",
15486                Spaces);
15487   verifyFormat("do {\n"
15488                "  do_something((int) i);\n"
15489                "} while (something( ));",
15490                Spaces);
15491 
15492   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15493   verifyFormat("size_t idx = (size_t) a;", Spaces);
15494   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15495   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15496   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15497   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15498   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15499   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15500   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15501   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15502   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15503   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15504   Spaces.ColumnLimit = 80;
15505   Spaces.IndentWidth = 4;
15506   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15507   verifyFormat("void foo( ) {\n"
15508                "    size_t foo = (*(function))(\n"
15509                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15510                "BarrrrrrrrrrrrLong,\n"
15511                "        FoooooooooLooooong);\n"
15512                "}",
15513                Spaces);
15514   Spaces.SpaceAfterCStyleCast = false;
15515   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15516   verifyFormat("size_t idx = (size_t)a;", Spaces);
15517   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15518   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15519   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15520   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15521   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15522 
15523   verifyFormat("void foo( ) {\n"
15524                "    size_t foo = (*(function))(\n"
15525                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15526                "BarrrrrrrrrrrrLong,\n"
15527                "        FoooooooooLooooong);\n"
15528                "}",
15529                Spaces);
15530 }
15531 
15532 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15533   verifyFormat("int a[5];");
15534   verifyFormat("a[3] += 42;");
15535 
15536   FormatStyle Spaces = getLLVMStyle();
15537   Spaces.SpacesInSquareBrackets = true;
15538   // Not lambdas.
15539   verifyFormat("int a[ 5 ];", Spaces);
15540   verifyFormat("a[ 3 ] += 42;", Spaces);
15541   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15542   verifyFormat("double &operator[](int i) { return 0; }\n"
15543                "int i;",
15544                Spaces);
15545   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15546   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15547   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15548   // Lambdas.
15549   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15550   verifyFormat("return [ i, args... ] {};", Spaces);
15551   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15552   verifyFormat("int foo = [ = ]() {};", Spaces);
15553   verifyFormat("int foo = [ & ]() {};", Spaces);
15554   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15555   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15556 }
15557 
15558 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15559   FormatStyle NoSpaceStyle = getLLVMStyle();
15560   verifyFormat("int a[5];", NoSpaceStyle);
15561   verifyFormat("a[3] += 42;", NoSpaceStyle);
15562 
15563   verifyFormat("int a[1];", NoSpaceStyle);
15564   verifyFormat("int 1 [a];", NoSpaceStyle);
15565   verifyFormat("int a[1][2];", NoSpaceStyle);
15566   verifyFormat("a[7] = 5;", NoSpaceStyle);
15567   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15568   verifyFormat("f([] {})", NoSpaceStyle);
15569 
15570   FormatStyle Space = getLLVMStyle();
15571   Space.SpaceBeforeSquareBrackets = true;
15572   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15573   verifyFormat("return [i, args...] {};", Space);
15574 
15575   verifyFormat("int a [5];", Space);
15576   verifyFormat("a [3] += 42;", Space);
15577   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15578   verifyFormat("double &operator[](int i) { return 0; }\n"
15579                "int i;",
15580                Space);
15581   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15582   verifyFormat("int i = a [a][a]->f();", Space);
15583   verifyFormat("int i = (*b) [a]->f();", Space);
15584 
15585   verifyFormat("int a [1];", Space);
15586   verifyFormat("int 1 [a];", Space);
15587   verifyFormat("int a [1][2];", Space);
15588   verifyFormat("a [7] = 5;", Space);
15589   verifyFormat("int a = (f()) [23];", Space);
15590   verifyFormat("f([] {})", Space);
15591 }
15592 
15593 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15594   verifyFormat("int a = 5;");
15595   verifyFormat("a += 42;");
15596   verifyFormat("a or_eq 8;");
15597 
15598   FormatStyle Spaces = getLLVMStyle();
15599   Spaces.SpaceBeforeAssignmentOperators = false;
15600   verifyFormat("int a= 5;", Spaces);
15601   verifyFormat("a+= 42;", Spaces);
15602   verifyFormat("a or_eq 8;", Spaces);
15603 }
15604 
15605 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15606   verifyFormat("class Foo : public Bar {};");
15607   verifyFormat("Foo::Foo() : foo(1) {}");
15608   verifyFormat("for (auto a : b) {\n}");
15609   verifyFormat("int x = a ? b : c;");
15610   verifyFormat("{\n"
15611                "label0:\n"
15612                "  int x = 0;\n"
15613                "}");
15614   verifyFormat("switch (x) {\n"
15615                "case 1:\n"
15616                "default:\n"
15617                "}");
15618   verifyFormat("switch (allBraces) {\n"
15619                "case 1: {\n"
15620                "  break;\n"
15621                "}\n"
15622                "case 2: {\n"
15623                "  [[fallthrough]];\n"
15624                "}\n"
15625                "default: {\n"
15626                "  break;\n"
15627                "}\n"
15628                "}");
15629 
15630   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15631   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15632   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15633   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15634   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15635   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15636   verifyFormat("{\n"
15637                "label1:\n"
15638                "  int x = 0;\n"
15639                "}",
15640                CtorInitializerStyle);
15641   verifyFormat("switch (x) {\n"
15642                "case 1:\n"
15643                "default:\n"
15644                "}",
15645                CtorInitializerStyle);
15646   verifyFormat("switch (allBraces) {\n"
15647                "case 1: {\n"
15648                "  break;\n"
15649                "}\n"
15650                "case 2: {\n"
15651                "  [[fallthrough]];\n"
15652                "}\n"
15653                "default: {\n"
15654                "  break;\n"
15655                "}\n"
15656                "}",
15657                CtorInitializerStyle);
15658   CtorInitializerStyle.BreakConstructorInitializers =
15659       FormatStyle::BCIS_AfterColon;
15660   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15661                "    aaaaaaaaaaaaaaaa(1),\n"
15662                "    bbbbbbbbbbbbbbbb(2) {}",
15663                CtorInitializerStyle);
15664   CtorInitializerStyle.BreakConstructorInitializers =
15665       FormatStyle::BCIS_BeforeComma;
15666   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15667                "    : aaaaaaaaaaaaaaaa(1)\n"
15668                "    , bbbbbbbbbbbbbbbb(2) {}",
15669                CtorInitializerStyle);
15670   CtorInitializerStyle.BreakConstructorInitializers =
15671       FormatStyle::BCIS_BeforeColon;
15672   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15673                "    : aaaaaaaaaaaaaaaa(1),\n"
15674                "      bbbbbbbbbbbbbbbb(2) {}",
15675                CtorInitializerStyle);
15676   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15677   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15678                ": aaaaaaaaaaaaaaaa(1),\n"
15679                "  bbbbbbbbbbbbbbbb(2) {}",
15680                CtorInitializerStyle);
15681 
15682   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15683   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15684   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15685   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15686   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15687   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15688   verifyFormat("{\n"
15689                "label2:\n"
15690                "  int x = 0;\n"
15691                "}",
15692                InheritanceStyle);
15693   verifyFormat("switch (x) {\n"
15694                "case 1:\n"
15695                "default:\n"
15696                "}",
15697                InheritanceStyle);
15698   verifyFormat("switch (allBraces) {\n"
15699                "case 1: {\n"
15700                "  break;\n"
15701                "}\n"
15702                "case 2: {\n"
15703                "  [[fallthrough]];\n"
15704                "}\n"
15705                "default: {\n"
15706                "  break;\n"
15707                "}\n"
15708                "}",
15709                InheritanceStyle);
15710   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15711   verifyFormat("class Foooooooooooooooooooooo\n"
15712                "    : public aaaaaaaaaaaaaaaaaa,\n"
15713                "      public bbbbbbbbbbbbbbbbbb {\n"
15714                "}",
15715                InheritanceStyle);
15716   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15717   verifyFormat("class Foooooooooooooooooooooo:\n"
15718                "    public aaaaaaaaaaaaaaaaaa,\n"
15719                "    public bbbbbbbbbbbbbbbbbb {\n"
15720                "}",
15721                InheritanceStyle);
15722   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15723   verifyFormat("class Foooooooooooooooooooooo\n"
15724                "    : public aaaaaaaaaaaaaaaaaa\n"
15725                "    , public bbbbbbbbbbbbbbbbbb {\n"
15726                "}",
15727                InheritanceStyle);
15728   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15729   verifyFormat("class Foooooooooooooooooooooo\n"
15730                "    : public aaaaaaaaaaaaaaaaaa,\n"
15731                "      public bbbbbbbbbbbbbbbbbb {\n"
15732                "}",
15733                InheritanceStyle);
15734   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15735   verifyFormat("class Foooooooooooooooooooooo\n"
15736                ": public aaaaaaaaaaaaaaaaaa,\n"
15737                "  public bbbbbbbbbbbbbbbbbb {}",
15738                InheritanceStyle);
15739 
15740   FormatStyle ForLoopStyle = getLLVMStyle();
15741   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15742   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15743   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15744   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15745   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15746   verifyFormat("{\n"
15747                "label2:\n"
15748                "  int x = 0;\n"
15749                "}",
15750                ForLoopStyle);
15751   verifyFormat("switch (x) {\n"
15752                "case 1:\n"
15753                "default:\n"
15754                "}",
15755                ForLoopStyle);
15756   verifyFormat("switch (allBraces) {\n"
15757                "case 1: {\n"
15758                "  break;\n"
15759                "}\n"
15760                "case 2: {\n"
15761                "  [[fallthrough]];\n"
15762                "}\n"
15763                "default: {\n"
15764                "  break;\n"
15765                "}\n"
15766                "}",
15767                ForLoopStyle);
15768 
15769   FormatStyle CaseStyle = getLLVMStyle();
15770   CaseStyle.SpaceBeforeCaseColon = true;
15771   verifyFormat("class Foo : public Bar {};", CaseStyle);
15772   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15773   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15774   verifyFormat("int x = a ? b : c;", CaseStyle);
15775   verifyFormat("switch (x) {\n"
15776                "case 1 :\n"
15777                "default :\n"
15778                "}",
15779                CaseStyle);
15780   verifyFormat("switch (allBraces) {\n"
15781                "case 1 : {\n"
15782                "  break;\n"
15783                "}\n"
15784                "case 2 : {\n"
15785                "  [[fallthrough]];\n"
15786                "}\n"
15787                "default : {\n"
15788                "  break;\n"
15789                "}\n"
15790                "}",
15791                CaseStyle);
15792 
15793   FormatStyle NoSpaceStyle = getLLVMStyle();
15794   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15795   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15796   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15797   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15798   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15799   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15800   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15801   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15802   verifyFormat("{\n"
15803                "label3:\n"
15804                "  int x = 0;\n"
15805                "}",
15806                NoSpaceStyle);
15807   verifyFormat("switch (x) {\n"
15808                "case 1:\n"
15809                "default:\n"
15810                "}",
15811                NoSpaceStyle);
15812   verifyFormat("switch (allBraces) {\n"
15813                "case 1: {\n"
15814                "  break;\n"
15815                "}\n"
15816                "case 2: {\n"
15817                "  [[fallthrough]];\n"
15818                "}\n"
15819                "default: {\n"
15820                "  break;\n"
15821                "}\n"
15822                "}",
15823                NoSpaceStyle);
15824 
15825   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15826   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15827   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15828   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15829   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15830   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15831   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15832   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15833   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15834   verifyFormat("{\n"
15835                "label3:\n"
15836                "  int x = 0;\n"
15837                "}",
15838                InvertedSpaceStyle);
15839   verifyFormat("switch (x) {\n"
15840                "case 1 :\n"
15841                "case 2 : {\n"
15842                "  break;\n"
15843                "}\n"
15844                "default :\n"
15845                "  break;\n"
15846                "}",
15847                InvertedSpaceStyle);
15848   verifyFormat("switch (allBraces) {\n"
15849                "case 1 : {\n"
15850                "  break;\n"
15851                "}\n"
15852                "case 2 : {\n"
15853                "  [[fallthrough]];\n"
15854                "}\n"
15855                "default : {\n"
15856                "  break;\n"
15857                "}\n"
15858                "}",
15859                InvertedSpaceStyle);
15860 }
15861 
15862 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15863   FormatStyle Style = getLLVMStyle();
15864 
15865   Style.PointerAlignment = FormatStyle::PAS_Left;
15866   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15867   verifyFormat("void* const* x = NULL;", Style);
15868 
15869 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15870   do {                                                                         \
15871     Style.PointerAlignment = FormatStyle::Pointers;                            \
15872     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15873     verifyFormat(Code, Style);                                                 \
15874   } while (false)
15875 
15876   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15877   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15878   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15879 
15880   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15881   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15882   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15883 
15884   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15885   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15886   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15887 
15888   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15889   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15890   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15891 
15892   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15893   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15894                         SAPQ_Default);
15895   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15896                         SAPQ_Default);
15897 
15898   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15899   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15900                         SAPQ_Before);
15901   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15902                         SAPQ_Before);
15903 
15904   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15905   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15906   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15907                         SAPQ_After);
15908 
15909   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15910   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15911   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15912 
15913 #undef verifyQualifierSpaces
15914 
15915   FormatStyle Spaces = getLLVMStyle();
15916   Spaces.AttributeMacros.push_back("qualified");
15917   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15918   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15919   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15920   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15921   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15922   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15923   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15924   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15925   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15926   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15927   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15928   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15929   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15930 
15931   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15932   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15933   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15934   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15935   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15936   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15937   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15938   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15939   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15940   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15941   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15942   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15943   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15944   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15945   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15946 
15947   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15948   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15949   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15950   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15951   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15952   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15953   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15954   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15955 }
15956 
15957 TEST_F(FormatTest, AlignConsecutiveMacros) {
15958   FormatStyle Style = getLLVMStyle();
15959   Style.AlignConsecutiveAssignments.Enabled = true;
15960   Style.AlignConsecutiveDeclarations.Enabled = true;
15961 
15962   verifyFormat("#define a 3\n"
15963                "#define bbbb 4\n"
15964                "#define ccc (5)",
15965                Style);
15966 
15967   verifyFormat("#define f(x) (x * x)\n"
15968                "#define fff(x, y, z) (x * y + z)\n"
15969                "#define ffff(x, y) (x - y)",
15970                Style);
15971 
15972   verifyFormat("#define foo(x, y) (x + y)\n"
15973                "#define bar (5, 6)(2 + 2)",
15974                Style);
15975 
15976   verifyFormat("#define a 3\n"
15977                "#define bbbb 4\n"
15978                "#define ccc (5)\n"
15979                "#define f(x) (x * x)\n"
15980                "#define fff(x, y, z) (x * y + z)\n"
15981                "#define ffff(x, y) (x - y)",
15982                Style);
15983 
15984   Style.AlignConsecutiveMacros.Enabled = true;
15985   verifyFormat("#define a    3\n"
15986                "#define bbbb 4\n"
15987                "#define ccc  (5)",
15988                Style);
15989 
15990   verifyFormat("#define f(x)         (x * x)\n"
15991                "#define fff(x, y, z) (x * y + z)\n"
15992                "#define ffff(x, y)   (x - y)",
15993                Style);
15994 
15995   verifyFormat("#define foo(x, y) (x + y)\n"
15996                "#define bar       (5, 6)(2 + 2)",
15997                Style);
15998 
15999   verifyFormat("#define a            3\n"
16000                "#define bbbb         4\n"
16001                "#define ccc          (5)\n"
16002                "#define f(x)         (x * x)\n"
16003                "#define fff(x, y, z) (x * y + z)\n"
16004                "#define ffff(x, y)   (x - y)",
16005                Style);
16006 
16007   verifyFormat("#define a         5\n"
16008                "#define foo(x, y) (x + y)\n"
16009                "#define CCC       (6)\n"
16010                "auto lambda = []() {\n"
16011                "  auto  ii = 0;\n"
16012                "  float j  = 0;\n"
16013                "  return 0;\n"
16014                "};\n"
16015                "int   i  = 0;\n"
16016                "float i2 = 0;\n"
16017                "auto  v  = type{\n"
16018                "    i = 1,   //\n"
16019                "    (i = 2), //\n"
16020                "    i = 3    //\n"
16021                "};",
16022                Style);
16023 
16024   Style.AlignConsecutiveMacros.Enabled = false;
16025   Style.ColumnLimit = 20;
16026 
16027   verifyFormat("#define a          \\\n"
16028                "  \"aabbbbbbbbbbbb\"\n"
16029                "#define D          \\\n"
16030                "  \"aabbbbbbbbbbbb\" \\\n"
16031                "  \"ccddeeeeeeeee\"\n"
16032                "#define B          \\\n"
16033                "  \"QQQQQQQQQQQQQ\"  \\\n"
16034                "  \"FFFFFFFFFFFFF\"  \\\n"
16035                "  \"LLLLLLLL\"\n",
16036                Style);
16037 
16038   Style.AlignConsecutiveMacros.Enabled = true;
16039   verifyFormat("#define a          \\\n"
16040                "  \"aabbbbbbbbbbbb\"\n"
16041                "#define D          \\\n"
16042                "  \"aabbbbbbbbbbbb\" \\\n"
16043                "  \"ccddeeeeeeeee\"\n"
16044                "#define B          \\\n"
16045                "  \"QQQQQQQQQQQQQ\"  \\\n"
16046                "  \"FFFFFFFFFFFFF\"  \\\n"
16047                "  \"LLLLLLLL\"\n",
16048                Style);
16049 
16050   // Test across comments
16051   Style.MaxEmptyLinesToKeep = 10;
16052   Style.ReflowComments = false;
16053   Style.AlignConsecutiveMacros.AcrossComments = true;
16054   EXPECT_EQ("#define a    3\n"
16055             "// line comment\n"
16056             "#define bbbb 4\n"
16057             "#define ccc  (5)",
16058             format("#define a 3\n"
16059                    "// line comment\n"
16060                    "#define bbbb 4\n"
16061                    "#define ccc (5)",
16062                    Style));
16063 
16064   EXPECT_EQ("#define a    3\n"
16065             "/* block comment */\n"
16066             "#define bbbb 4\n"
16067             "#define ccc  (5)",
16068             format("#define a  3\n"
16069                    "/* block comment */\n"
16070                    "#define bbbb 4\n"
16071                    "#define ccc (5)",
16072                    Style));
16073 
16074   EXPECT_EQ("#define a    3\n"
16075             "/* multi-line *\n"
16076             " * block comment */\n"
16077             "#define bbbb 4\n"
16078             "#define ccc  (5)",
16079             format("#define a 3\n"
16080                    "/* multi-line *\n"
16081                    " * block comment */\n"
16082                    "#define bbbb 4\n"
16083                    "#define ccc (5)",
16084                    Style));
16085 
16086   EXPECT_EQ("#define a    3\n"
16087             "// multi-line line comment\n"
16088             "//\n"
16089             "#define bbbb 4\n"
16090             "#define ccc  (5)",
16091             format("#define a  3\n"
16092                    "// multi-line line comment\n"
16093                    "//\n"
16094                    "#define bbbb 4\n"
16095                    "#define ccc (5)",
16096                    Style));
16097 
16098   EXPECT_EQ("#define a 3\n"
16099             "// empty lines still break.\n"
16100             "\n"
16101             "#define bbbb 4\n"
16102             "#define ccc  (5)",
16103             format("#define a     3\n"
16104                    "// empty lines still break.\n"
16105                    "\n"
16106                    "#define bbbb     4\n"
16107                    "#define ccc  (5)",
16108                    Style));
16109 
16110   // Test across empty lines
16111   Style.AlignConsecutiveMacros.AcrossComments = false;
16112   Style.AlignConsecutiveMacros.AcrossEmptyLines = true;
16113   EXPECT_EQ("#define a    3\n"
16114             "\n"
16115             "#define bbbb 4\n"
16116             "#define ccc  (5)",
16117             format("#define a 3\n"
16118                    "\n"
16119                    "#define bbbb 4\n"
16120                    "#define ccc (5)",
16121                    Style));
16122 
16123   EXPECT_EQ("#define a    3\n"
16124             "\n"
16125             "\n"
16126             "\n"
16127             "#define bbbb 4\n"
16128             "#define ccc  (5)",
16129             format("#define a        3\n"
16130                    "\n"
16131                    "\n"
16132                    "\n"
16133                    "#define bbbb 4\n"
16134                    "#define ccc (5)",
16135                    Style));
16136 
16137   EXPECT_EQ("#define a 3\n"
16138             "// comments should break alignment\n"
16139             "//\n"
16140             "#define bbbb 4\n"
16141             "#define ccc  (5)",
16142             format("#define a        3\n"
16143                    "// comments should break alignment\n"
16144                    "//\n"
16145                    "#define bbbb 4\n"
16146                    "#define ccc (5)",
16147                    Style));
16148 
16149   // Test across empty lines and comments
16150   Style.AlignConsecutiveMacros.AcrossComments = true;
16151   verifyFormat("#define a    3\n"
16152                "\n"
16153                "// line comment\n"
16154                "#define bbbb 4\n"
16155                "#define ccc  (5)",
16156                Style);
16157 
16158   EXPECT_EQ("#define a    3\n"
16159             "\n"
16160             "\n"
16161             "/* multi-line *\n"
16162             " * block comment */\n"
16163             "\n"
16164             "\n"
16165             "#define bbbb 4\n"
16166             "#define ccc  (5)",
16167             format("#define a 3\n"
16168                    "\n"
16169                    "\n"
16170                    "/* multi-line *\n"
16171                    " * block comment */\n"
16172                    "\n"
16173                    "\n"
16174                    "#define bbbb 4\n"
16175                    "#define ccc (5)",
16176                    Style));
16177 
16178   EXPECT_EQ("#define a    3\n"
16179             "\n"
16180             "\n"
16181             "/* multi-line *\n"
16182             " * block comment */\n"
16183             "\n"
16184             "\n"
16185             "#define bbbb 4\n"
16186             "#define ccc  (5)",
16187             format("#define a 3\n"
16188                    "\n"
16189                    "\n"
16190                    "/* multi-line *\n"
16191                    " * block comment */\n"
16192                    "\n"
16193                    "\n"
16194                    "#define bbbb 4\n"
16195                    "#define ccc       (5)",
16196                    Style));
16197 }
16198 
16199 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
16200   FormatStyle Alignment = getLLVMStyle();
16201   Alignment.AlignConsecutiveMacros.Enabled = true;
16202   Alignment.AlignConsecutiveAssignments.Enabled = true;
16203   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16204 
16205   Alignment.MaxEmptyLinesToKeep = 10;
16206   /* Test alignment across empty lines */
16207   EXPECT_EQ("int a           = 5;\n"
16208             "\n"
16209             "int oneTwoThree = 123;",
16210             format("int a       = 5;\n"
16211                    "\n"
16212                    "int oneTwoThree= 123;",
16213                    Alignment));
16214   EXPECT_EQ("int a           = 5;\n"
16215             "int one         = 1;\n"
16216             "\n"
16217             "int oneTwoThree = 123;",
16218             format("int a = 5;\n"
16219                    "int one = 1;\n"
16220                    "\n"
16221                    "int oneTwoThree = 123;",
16222                    Alignment));
16223   EXPECT_EQ("int a           = 5;\n"
16224             "int one         = 1;\n"
16225             "\n"
16226             "int oneTwoThree = 123;\n"
16227             "int oneTwo      = 12;",
16228             format("int a = 5;\n"
16229                    "int one = 1;\n"
16230                    "\n"
16231                    "int oneTwoThree = 123;\n"
16232                    "int oneTwo = 12;",
16233                    Alignment));
16234 
16235   /* Test across comments */
16236   EXPECT_EQ("int a = 5;\n"
16237             "/* block comment */\n"
16238             "int oneTwoThree = 123;",
16239             format("int a = 5;\n"
16240                    "/* block comment */\n"
16241                    "int oneTwoThree=123;",
16242                    Alignment));
16243 
16244   EXPECT_EQ("int a = 5;\n"
16245             "// line comment\n"
16246             "int oneTwoThree = 123;",
16247             format("int a = 5;\n"
16248                    "// line comment\n"
16249                    "int oneTwoThree=123;",
16250                    Alignment));
16251 
16252   /* Test across comments and newlines */
16253   EXPECT_EQ("int a = 5;\n"
16254             "\n"
16255             "/* block comment */\n"
16256             "int oneTwoThree = 123;",
16257             format("int a = 5;\n"
16258                    "\n"
16259                    "/* block comment */\n"
16260                    "int oneTwoThree=123;",
16261                    Alignment));
16262 
16263   EXPECT_EQ("int a = 5;\n"
16264             "\n"
16265             "// line comment\n"
16266             "int oneTwoThree = 123;",
16267             format("int a = 5;\n"
16268                    "\n"
16269                    "// line comment\n"
16270                    "int oneTwoThree=123;",
16271                    Alignment));
16272 }
16273 
16274 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16275   FormatStyle Alignment = getLLVMStyle();
16276   Alignment.AlignConsecutiveDeclarations.Enabled = true;
16277   Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true;
16278   Alignment.AlignConsecutiveDeclarations.AcrossComments = true;
16279 
16280   Alignment.MaxEmptyLinesToKeep = 10;
16281   /* Test alignment across empty lines */
16282   EXPECT_EQ("int         a = 5;\n"
16283             "\n"
16284             "float const oneTwoThree = 123;",
16285             format("int a = 5;\n"
16286                    "\n"
16287                    "float const oneTwoThree = 123;",
16288                    Alignment));
16289   EXPECT_EQ("int         a = 5;\n"
16290             "float const one = 1;\n"
16291             "\n"
16292             "int         oneTwoThree = 123;",
16293             format("int a = 5;\n"
16294                    "float const one = 1;\n"
16295                    "\n"
16296                    "int oneTwoThree = 123;",
16297                    Alignment));
16298 
16299   /* Test across comments */
16300   EXPECT_EQ("float const a = 5;\n"
16301             "/* block comment */\n"
16302             "int         oneTwoThree = 123;",
16303             format("float const a = 5;\n"
16304                    "/* block comment */\n"
16305                    "int oneTwoThree=123;",
16306                    Alignment));
16307 
16308   EXPECT_EQ("float const a = 5;\n"
16309             "// line comment\n"
16310             "int         oneTwoThree = 123;",
16311             format("float const a = 5;\n"
16312                    "// line comment\n"
16313                    "int oneTwoThree=123;",
16314                    Alignment));
16315 
16316   /* Test across comments and newlines */
16317   EXPECT_EQ("float const a = 5;\n"
16318             "\n"
16319             "/* block comment */\n"
16320             "int         oneTwoThree = 123;",
16321             format("float const a = 5;\n"
16322                    "\n"
16323                    "/* block comment */\n"
16324                    "int         oneTwoThree=123;",
16325                    Alignment));
16326 
16327   EXPECT_EQ("float const a = 5;\n"
16328             "\n"
16329             "// line comment\n"
16330             "int         oneTwoThree = 123;",
16331             format("float const a = 5;\n"
16332                    "\n"
16333                    "// line comment\n"
16334                    "int oneTwoThree=123;",
16335                    Alignment));
16336 }
16337 
16338 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16339   FormatStyle Alignment = getLLVMStyle();
16340   Alignment.AlignConsecutiveBitFields.Enabled = true;
16341   Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true;
16342   Alignment.AlignConsecutiveBitFields.AcrossComments = true;
16343 
16344   Alignment.MaxEmptyLinesToKeep = 10;
16345   /* Test alignment across empty lines */
16346   EXPECT_EQ("int a            : 5;\n"
16347             "\n"
16348             "int longbitfield : 6;",
16349             format("int a : 5;\n"
16350                    "\n"
16351                    "int longbitfield : 6;",
16352                    Alignment));
16353   EXPECT_EQ("int a            : 5;\n"
16354             "int one          : 1;\n"
16355             "\n"
16356             "int longbitfield : 6;",
16357             format("int a : 5;\n"
16358                    "int one : 1;\n"
16359                    "\n"
16360                    "int longbitfield : 6;",
16361                    Alignment));
16362 
16363   /* Test across comments */
16364   EXPECT_EQ("int a            : 5;\n"
16365             "/* block comment */\n"
16366             "int longbitfield : 6;",
16367             format("int a : 5;\n"
16368                    "/* block comment */\n"
16369                    "int longbitfield : 6;",
16370                    Alignment));
16371   EXPECT_EQ("int a            : 5;\n"
16372             "int one          : 1;\n"
16373             "// line comment\n"
16374             "int longbitfield : 6;",
16375             format("int a : 5;\n"
16376                    "int one : 1;\n"
16377                    "// line comment\n"
16378                    "int longbitfield : 6;",
16379                    Alignment));
16380 
16381   /* Test across comments and newlines */
16382   EXPECT_EQ("int a            : 5;\n"
16383             "/* block comment */\n"
16384             "\n"
16385             "int longbitfield : 6;",
16386             format("int a : 5;\n"
16387                    "/* block comment */\n"
16388                    "\n"
16389                    "int longbitfield : 6;",
16390                    Alignment));
16391   EXPECT_EQ("int a            : 5;\n"
16392             "int one          : 1;\n"
16393             "\n"
16394             "// line comment\n"
16395             "\n"
16396             "int longbitfield : 6;",
16397             format("int a : 5;\n"
16398                    "int one : 1;\n"
16399                    "\n"
16400                    "// line comment \n"
16401                    "\n"
16402                    "int longbitfield : 6;",
16403                    Alignment));
16404 }
16405 
16406 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16407   FormatStyle Alignment = getLLVMStyle();
16408   Alignment.AlignConsecutiveMacros.Enabled = true;
16409   Alignment.AlignConsecutiveAssignments.Enabled = true;
16410   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16411 
16412   Alignment.MaxEmptyLinesToKeep = 10;
16413   /* Test alignment across empty lines */
16414   EXPECT_EQ("int a = 5;\n"
16415             "\n"
16416             "int oneTwoThree = 123;",
16417             format("int a       = 5;\n"
16418                    "\n"
16419                    "int oneTwoThree= 123;",
16420                    Alignment));
16421   EXPECT_EQ("int a   = 5;\n"
16422             "int one = 1;\n"
16423             "\n"
16424             "int oneTwoThree = 123;",
16425             format("int a = 5;\n"
16426                    "int one = 1;\n"
16427                    "\n"
16428                    "int oneTwoThree = 123;",
16429                    Alignment));
16430 
16431   /* Test across comments */
16432   EXPECT_EQ("int a           = 5;\n"
16433             "/* block comment */\n"
16434             "int oneTwoThree = 123;",
16435             format("int a = 5;\n"
16436                    "/* block comment */\n"
16437                    "int oneTwoThree=123;",
16438                    Alignment));
16439 
16440   EXPECT_EQ("int a           = 5;\n"
16441             "// line comment\n"
16442             "int oneTwoThree = 123;",
16443             format("int a = 5;\n"
16444                    "// line comment\n"
16445                    "int oneTwoThree=123;",
16446                    Alignment));
16447 
16448   EXPECT_EQ("int a           = 5;\n"
16449             "/*\n"
16450             " * multi-line block comment\n"
16451             " */\n"
16452             "int oneTwoThree = 123;",
16453             format("int a = 5;\n"
16454                    "/*\n"
16455                    " * multi-line block comment\n"
16456                    " */\n"
16457                    "int oneTwoThree=123;",
16458                    Alignment));
16459 
16460   EXPECT_EQ("int a           = 5;\n"
16461             "//\n"
16462             "// multi-line line comment\n"
16463             "//\n"
16464             "int oneTwoThree = 123;",
16465             format("int a = 5;\n"
16466                    "//\n"
16467                    "// multi-line line comment\n"
16468                    "//\n"
16469                    "int oneTwoThree=123;",
16470                    Alignment));
16471 
16472   /* Test across comments and newlines */
16473   EXPECT_EQ("int a = 5;\n"
16474             "\n"
16475             "/* block comment */\n"
16476             "int oneTwoThree = 123;",
16477             format("int a = 5;\n"
16478                    "\n"
16479                    "/* block comment */\n"
16480                    "int oneTwoThree=123;",
16481                    Alignment));
16482 
16483   EXPECT_EQ("int a = 5;\n"
16484             "\n"
16485             "// line comment\n"
16486             "int oneTwoThree = 123;",
16487             format("int a = 5;\n"
16488                    "\n"
16489                    "// line comment\n"
16490                    "int oneTwoThree=123;",
16491                    Alignment));
16492 }
16493 
16494 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16495   FormatStyle Alignment = getLLVMStyle();
16496   Alignment.AlignConsecutiveMacros.Enabled = true;
16497   Alignment.AlignConsecutiveAssignments.Enabled = true;
16498   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16499   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16500   verifyFormat("int a           = 5;\n"
16501                "int oneTwoThree = 123;",
16502                Alignment);
16503   verifyFormat("int a           = method();\n"
16504                "int oneTwoThree = 133;",
16505                Alignment);
16506   verifyFormat("a &= 5;\n"
16507                "bcd *= 5;\n"
16508                "ghtyf += 5;\n"
16509                "dvfvdb -= 5;\n"
16510                "a /= 5;\n"
16511                "vdsvsv %= 5;\n"
16512                "sfdbddfbdfbb ^= 5;\n"
16513                "dvsdsv |= 5;\n"
16514                "int dsvvdvsdvvv = 123;",
16515                Alignment);
16516   verifyFormat("int i = 1, j = 10;\n"
16517                "something = 2000;",
16518                Alignment);
16519   verifyFormat("something = 2000;\n"
16520                "int i = 1, j = 10;\n",
16521                Alignment);
16522   verifyFormat("something = 2000;\n"
16523                "another   = 911;\n"
16524                "int i = 1, j = 10;\n"
16525                "oneMore = 1;\n"
16526                "i       = 2;",
16527                Alignment);
16528   verifyFormat("int a   = 5;\n"
16529                "int one = 1;\n"
16530                "method();\n"
16531                "int oneTwoThree = 123;\n"
16532                "int oneTwo      = 12;",
16533                Alignment);
16534   verifyFormat("int oneTwoThree = 123;\n"
16535                "int oneTwo      = 12;\n"
16536                "method();\n",
16537                Alignment);
16538   verifyFormat("int oneTwoThree = 123; // comment\n"
16539                "int oneTwo      = 12;  // comment",
16540                Alignment);
16541 
16542   // Bug 25167
16543   /* Uncomment when fixed
16544     verifyFormat("#if A\n"
16545                  "#else\n"
16546                  "int aaaaaaaa = 12;\n"
16547                  "#endif\n"
16548                  "#if B\n"
16549                  "#else\n"
16550                  "int a = 12;\n"
16551                  "#endif\n",
16552                  Alignment);
16553     verifyFormat("enum foo {\n"
16554                  "#if A\n"
16555                  "#else\n"
16556                  "  aaaaaaaa = 12;\n"
16557                  "#endif\n"
16558                  "#if B\n"
16559                  "#else\n"
16560                  "  a = 12;\n"
16561                  "#endif\n"
16562                  "};\n",
16563                  Alignment);
16564   */
16565 
16566   Alignment.MaxEmptyLinesToKeep = 10;
16567   /* Test alignment across empty lines */
16568   EXPECT_EQ("int a           = 5;\n"
16569             "\n"
16570             "int oneTwoThree = 123;",
16571             format("int a       = 5;\n"
16572                    "\n"
16573                    "int oneTwoThree= 123;",
16574                    Alignment));
16575   EXPECT_EQ("int a           = 5;\n"
16576             "int one         = 1;\n"
16577             "\n"
16578             "int oneTwoThree = 123;",
16579             format("int a = 5;\n"
16580                    "int one = 1;\n"
16581                    "\n"
16582                    "int oneTwoThree = 123;",
16583                    Alignment));
16584   EXPECT_EQ("int a           = 5;\n"
16585             "int one         = 1;\n"
16586             "\n"
16587             "int oneTwoThree = 123;\n"
16588             "int oneTwo      = 12;",
16589             format("int a = 5;\n"
16590                    "int one = 1;\n"
16591                    "\n"
16592                    "int oneTwoThree = 123;\n"
16593                    "int oneTwo = 12;",
16594                    Alignment));
16595 
16596   /* Test across comments */
16597   EXPECT_EQ("int a           = 5;\n"
16598             "/* block comment */\n"
16599             "int oneTwoThree = 123;",
16600             format("int a = 5;\n"
16601                    "/* block comment */\n"
16602                    "int oneTwoThree=123;",
16603                    Alignment));
16604 
16605   EXPECT_EQ("int a           = 5;\n"
16606             "// line comment\n"
16607             "int oneTwoThree = 123;",
16608             format("int a = 5;\n"
16609                    "// line comment\n"
16610                    "int oneTwoThree=123;",
16611                    Alignment));
16612 
16613   /* Test across comments and newlines */
16614   EXPECT_EQ("int a           = 5;\n"
16615             "\n"
16616             "/* block comment */\n"
16617             "int oneTwoThree = 123;",
16618             format("int a = 5;\n"
16619                    "\n"
16620                    "/* block comment */\n"
16621                    "int oneTwoThree=123;",
16622                    Alignment));
16623 
16624   EXPECT_EQ("int a           = 5;\n"
16625             "\n"
16626             "// line comment\n"
16627             "int oneTwoThree = 123;",
16628             format("int a = 5;\n"
16629                    "\n"
16630                    "// line comment\n"
16631                    "int oneTwoThree=123;",
16632                    Alignment));
16633 
16634   EXPECT_EQ("int a           = 5;\n"
16635             "//\n"
16636             "// multi-line line comment\n"
16637             "//\n"
16638             "int oneTwoThree = 123;",
16639             format("int a = 5;\n"
16640                    "//\n"
16641                    "// multi-line line comment\n"
16642                    "//\n"
16643                    "int oneTwoThree=123;",
16644                    Alignment));
16645 
16646   EXPECT_EQ("int a           = 5;\n"
16647             "/*\n"
16648             " *  multi-line block comment\n"
16649             " */\n"
16650             "int oneTwoThree = 123;",
16651             format("int a = 5;\n"
16652                    "/*\n"
16653                    " *  multi-line block comment\n"
16654                    " */\n"
16655                    "int oneTwoThree=123;",
16656                    Alignment));
16657 
16658   EXPECT_EQ("int a           = 5;\n"
16659             "\n"
16660             "/* block comment */\n"
16661             "\n"
16662             "\n"
16663             "\n"
16664             "int oneTwoThree = 123;",
16665             format("int a = 5;\n"
16666                    "\n"
16667                    "/* block comment */\n"
16668                    "\n"
16669                    "\n"
16670                    "\n"
16671                    "int oneTwoThree=123;",
16672                    Alignment));
16673 
16674   EXPECT_EQ("int a           = 5;\n"
16675             "\n"
16676             "// line comment\n"
16677             "\n"
16678             "\n"
16679             "\n"
16680             "int oneTwoThree = 123;",
16681             format("int a = 5;\n"
16682                    "\n"
16683                    "// line comment\n"
16684                    "\n"
16685                    "\n"
16686                    "\n"
16687                    "int oneTwoThree=123;",
16688                    Alignment));
16689 
16690   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16691   verifyFormat("#define A \\\n"
16692                "  int aaaa       = 12; \\\n"
16693                "  int b          = 23; \\\n"
16694                "  int ccc        = 234; \\\n"
16695                "  int dddddddddd = 2345;",
16696                Alignment);
16697   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16698   verifyFormat("#define A               \\\n"
16699                "  int aaaa       = 12;  \\\n"
16700                "  int b          = 23;  \\\n"
16701                "  int ccc        = 234; \\\n"
16702                "  int dddddddddd = 2345;",
16703                Alignment);
16704   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16705   verifyFormat("#define A                                                      "
16706                "                \\\n"
16707                "  int aaaa       = 12;                                         "
16708                "                \\\n"
16709                "  int b          = 23;                                         "
16710                "                \\\n"
16711                "  int ccc        = 234;                                        "
16712                "                \\\n"
16713                "  int dddddddddd = 2345;",
16714                Alignment);
16715   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16716                "k = 4, int l = 5,\n"
16717                "                  int m = 6) {\n"
16718                "  int j      = 10;\n"
16719                "  otherThing = 1;\n"
16720                "}",
16721                Alignment);
16722   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16723                "  int i   = 1;\n"
16724                "  int j   = 2;\n"
16725                "  int big = 10000;\n"
16726                "}",
16727                Alignment);
16728   verifyFormat("class C {\n"
16729                "public:\n"
16730                "  int i            = 1;\n"
16731                "  virtual void f() = 0;\n"
16732                "};",
16733                Alignment);
16734   verifyFormat("int i = 1;\n"
16735                "if (SomeType t = getSomething()) {\n"
16736                "}\n"
16737                "int j   = 2;\n"
16738                "int big = 10000;",
16739                Alignment);
16740   verifyFormat("int j = 7;\n"
16741                "for (int k = 0; k < N; ++k) {\n"
16742                "}\n"
16743                "int j   = 2;\n"
16744                "int big = 10000;\n"
16745                "}",
16746                Alignment);
16747   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16748   verifyFormat("int i = 1;\n"
16749                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16750                "    = someLooooooooooooooooongFunction();\n"
16751                "int j = 2;",
16752                Alignment);
16753   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16754   verifyFormat("int i = 1;\n"
16755                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16756                "    someLooooooooooooooooongFunction();\n"
16757                "int j = 2;",
16758                Alignment);
16759 
16760   verifyFormat("auto lambda = []() {\n"
16761                "  auto i = 0;\n"
16762                "  return 0;\n"
16763                "};\n"
16764                "int i  = 0;\n"
16765                "auto v = type{\n"
16766                "    i = 1,   //\n"
16767                "    (i = 2), //\n"
16768                "    i = 3    //\n"
16769                "};",
16770                Alignment);
16771 
16772   verifyFormat(
16773       "int i      = 1;\n"
16774       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16775       "                          loooooooooooooooooooooongParameterB);\n"
16776       "int j      = 2;",
16777       Alignment);
16778 
16779   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16780                "          typename B   = very_long_type_name_1,\n"
16781                "          typename T_2 = very_long_type_name_2>\n"
16782                "auto foo() {}\n",
16783                Alignment);
16784   verifyFormat("int a, b = 1;\n"
16785                "int c  = 2;\n"
16786                "int dd = 3;\n",
16787                Alignment);
16788   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16789                "float b[1][] = {{3.f}};\n",
16790                Alignment);
16791   verifyFormat("for (int i = 0; i < 1; i++)\n"
16792                "  int x = 1;\n",
16793                Alignment);
16794   verifyFormat("for (i = 0; i < 1; i++)\n"
16795                "  x = 1;\n"
16796                "y = 1;\n",
16797                Alignment);
16798 
16799   Alignment.ReflowComments = true;
16800   Alignment.ColumnLimit = 50;
16801   EXPECT_EQ("int x   = 0;\n"
16802             "int yy  = 1; /// specificlennospace\n"
16803             "int zzz = 2;\n",
16804             format("int x   = 0;\n"
16805                    "int yy  = 1; ///specificlennospace\n"
16806                    "int zzz = 2;\n",
16807                    Alignment));
16808 }
16809 
16810 TEST_F(FormatTest, AlignCompoundAssignments) {
16811   FormatStyle Alignment = getLLVMStyle();
16812   Alignment.AlignConsecutiveAssignments.Enabled = true;
16813   Alignment.AlignConsecutiveAssignments.AlignCompound = true;
16814   Alignment.AlignConsecutiveAssignments.PadOperators = false;
16815   verifyFormat("sfdbddfbdfbb    = 5;\n"
16816                "dvsdsv          = 5;\n"
16817                "int dsvvdvsdvvv = 123;",
16818                Alignment);
16819   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16820                "dvsdsv         |= 5;\n"
16821                "int dsvvdvsdvvv = 123;",
16822                Alignment);
16823   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16824                "dvsdsv        <<= 5;\n"
16825                "int dsvvdvsdvvv = 123;",
16826                Alignment);
16827   // Test that `<=` is not treated as a compound assignment.
16828   verifyFormat("aa &= 5;\n"
16829                "b <= 10;\n"
16830                "c = 15;",
16831                Alignment);
16832   Alignment.AlignConsecutiveAssignments.PadOperators = true;
16833   verifyFormat("sfdbddfbdfbb    = 5;\n"
16834                "dvsdsv          = 5;\n"
16835                "int dsvvdvsdvvv = 123;",
16836                Alignment);
16837   verifyFormat("sfdbddfbdfbb    ^= 5;\n"
16838                "dvsdsv          |= 5;\n"
16839                "int dsvvdvsdvvv  = 123;",
16840                Alignment);
16841   verifyFormat("sfdbddfbdfbb     ^= 5;\n"
16842                "dvsdsv          <<= 5;\n"
16843                "int dsvvdvsdvvv   = 123;",
16844                Alignment);
16845   EXPECT_EQ("a   += 5;\n"
16846             "one  = 1;\n"
16847             "\n"
16848             "oneTwoThree = 123;\n",
16849             format("a += 5;\n"
16850                    "one = 1;\n"
16851                    "\n"
16852                    "oneTwoThree = 123;\n",
16853                    Alignment));
16854   EXPECT_EQ("a   += 5;\n"
16855             "one  = 1;\n"
16856             "//\n"
16857             "oneTwoThree = 123;\n",
16858             format("a += 5;\n"
16859                    "one = 1;\n"
16860                    "//\n"
16861                    "oneTwoThree = 123;\n",
16862                    Alignment));
16863   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16864   EXPECT_EQ("a           += 5;\n"
16865             "one          = 1;\n"
16866             "\n"
16867             "oneTwoThree  = 123;\n",
16868             format("a += 5;\n"
16869                    "one = 1;\n"
16870                    "\n"
16871                    "oneTwoThree = 123;\n",
16872                    Alignment));
16873   EXPECT_EQ("a   += 5;\n"
16874             "one  = 1;\n"
16875             "//\n"
16876             "oneTwoThree = 123;\n",
16877             format("a += 5;\n"
16878                    "one = 1;\n"
16879                    "//\n"
16880                    "oneTwoThree = 123;\n",
16881                    Alignment));
16882   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false;
16883   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16884   EXPECT_EQ("a   += 5;\n"
16885             "one  = 1;\n"
16886             "\n"
16887             "oneTwoThree = 123;\n",
16888             format("a += 5;\n"
16889                    "one = 1;\n"
16890                    "\n"
16891                    "oneTwoThree = 123;\n",
16892                    Alignment));
16893   EXPECT_EQ("a           += 5;\n"
16894             "one          = 1;\n"
16895             "//\n"
16896             "oneTwoThree  = 123;\n",
16897             format("a += 5;\n"
16898                    "one = 1;\n"
16899                    "//\n"
16900                    "oneTwoThree = 123;\n",
16901                    Alignment));
16902   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16903   EXPECT_EQ("a            += 5;\n"
16904             "one         >>= 1;\n"
16905             "\n"
16906             "oneTwoThree   = 123;\n",
16907             format("a += 5;\n"
16908                    "one >>= 1;\n"
16909                    "\n"
16910                    "oneTwoThree = 123;\n",
16911                    Alignment));
16912   EXPECT_EQ("a            += 5;\n"
16913             "one           = 1;\n"
16914             "//\n"
16915             "oneTwoThree <<= 123;\n",
16916             format("a += 5;\n"
16917                    "one = 1;\n"
16918                    "//\n"
16919                    "oneTwoThree <<= 123;\n",
16920                    Alignment));
16921 }
16922 
16923 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16924   FormatStyle Alignment = getLLVMStyle();
16925   Alignment.AlignConsecutiveMacros.Enabled = true;
16926   verifyFormat("int a = 5;\n"
16927                "int oneTwoThree = 123;",
16928                Alignment);
16929   verifyFormat("int a = 5;\n"
16930                "int oneTwoThree = 123;",
16931                Alignment);
16932 
16933   Alignment.AlignConsecutiveAssignments.Enabled = true;
16934   verifyFormat("int a           = 5;\n"
16935                "int oneTwoThree = 123;",
16936                Alignment);
16937   verifyFormat("int a           = method();\n"
16938                "int oneTwoThree = 133;",
16939                Alignment);
16940   verifyFormat("aa <= 5;\n"
16941                "a &= 5;\n"
16942                "bcd *= 5;\n"
16943                "ghtyf += 5;\n"
16944                "dvfvdb -= 5;\n"
16945                "a /= 5;\n"
16946                "vdsvsv %= 5;\n"
16947                "sfdbddfbdfbb ^= 5;\n"
16948                "dvsdsv |= 5;\n"
16949                "int dsvvdvsdvvv = 123;",
16950                Alignment);
16951   verifyFormat("int i = 1, j = 10;\n"
16952                "something = 2000;",
16953                Alignment);
16954   verifyFormat("something = 2000;\n"
16955                "int i = 1, j = 10;\n",
16956                Alignment);
16957   verifyFormat("something = 2000;\n"
16958                "another   = 911;\n"
16959                "int i = 1, j = 10;\n"
16960                "oneMore = 1;\n"
16961                "i       = 2;",
16962                Alignment);
16963   verifyFormat("int a   = 5;\n"
16964                "int one = 1;\n"
16965                "method();\n"
16966                "int oneTwoThree = 123;\n"
16967                "int oneTwo      = 12;",
16968                Alignment);
16969   verifyFormat("int oneTwoThree = 123;\n"
16970                "int oneTwo      = 12;\n"
16971                "method();\n",
16972                Alignment);
16973   verifyFormat("int oneTwoThree = 123; // comment\n"
16974                "int oneTwo      = 12;  // comment",
16975                Alignment);
16976   verifyFormat("int f()         = default;\n"
16977                "int &operator() = default;\n"
16978                "int &operator=() {",
16979                Alignment);
16980   verifyFormat("int f()         = delete;\n"
16981                "int &operator() = delete;\n"
16982                "int &operator=() {",
16983                Alignment);
16984   verifyFormat("int f()         = default; // comment\n"
16985                "int &operator() = default; // comment\n"
16986                "int &operator=() {",
16987                Alignment);
16988   verifyFormat("int f()         = default;\n"
16989                "int &operator() = default;\n"
16990                "int &operator==() {",
16991                Alignment);
16992   verifyFormat("int f()         = default;\n"
16993                "int &operator() = default;\n"
16994                "int &operator<=() {",
16995                Alignment);
16996   verifyFormat("int f()         = default;\n"
16997                "int &operator() = default;\n"
16998                "int &operator!=() {",
16999                Alignment);
17000   verifyFormat("int f()         = default;\n"
17001                "int &operator() = default;\n"
17002                "int &operator=();",
17003                Alignment);
17004   verifyFormat("int f()         = delete;\n"
17005                "int &operator() = delete;\n"
17006                "int &operator=();",
17007                Alignment);
17008   verifyFormat("/* long long padding */ int f() = default;\n"
17009                "int &operator()                 = default;\n"
17010                "int &operator/**/ =();",
17011                Alignment);
17012   // https://llvm.org/PR33697
17013   FormatStyle AlignmentWithPenalty = getLLVMStyle();
17014   AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true;
17015   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
17016   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
17017                "  void f() = delete;\n"
17018                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
17019                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
17020                "};\n",
17021                AlignmentWithPenalty);
17022 
17023   // Bug 25167
17024   /* Uncomment when fixed
17025     verifyFormat("#if A\n"
17026                  "#else\n"
17027                  "int aaaaaaaa = 12;\n"
17028                  "#endif\n"
17029                  "#if B\n"
17030                  "#else\n"
17031                  "int a = 12;\n"
17032                  "#endif\n",
17033                  Alignment);
17034     verifyFormat("enum foo {\n"
17035                  "#if A\n"
17036                  "#else\n"
17037                  "  aaaaaaaa = 12;\n"
17038                  "#endif\n"
17039                  "#if B\n"
17040                  "#else\n"
17041                  "  a = 12;\n"
17042                  "#endif\n"
17043                  "};\n",
17044                  Alignment);
17045   */
17046 
17047   EXPECT_EQ("int a = 5;\n"
17048             "\n"
17049             "int oneTwoThree = 123;",
17050             format("int a       = 5;\n"
17051                    "\n"
17052                    "int oneTwoThree= 123;",
17053                    Alignment));
17054   EXPECT_EQ("int a   = 5;\n"
17055             "int one = 1;\n"
17056             "\n"
17057             "int oneTwoThree = 123;",
17058             format("int a = 5;\n"
17059                    "int one = 1;\n"
17060                    "\n"
17061                    "int oneTwoThree = 123;",
17062                    Alignment));
17063   EXPECT_EQ("int a   = 5;\n"
17064             "int one = 1;\n"
17065             "\n"
17066             "int oneTwoThree = 123;\n"
17067             "int oneTwo      = 12;",
17068             format("int a = 5;\n"
17069                    "int one = 1;\n"
17070                    "\n"
17071                    "int oneTwoThree = 123;\n"
17072                    "int oneTwo = 12;",
17073                    Alignment));
17074   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17075   verifyFormat("#define A \\\n"
17076                "  int aaaa       = 12; \\\n"
17077                "  int b          = 23; \\\n"
17078                "  int ccc        = 234; \\\n"
17079                "  int dddddddddd = 2345;",
17080                Alignment);
17081   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17082   verifyFormat("#define A               \\\n"
17083                "  int aaaa       = 12;  \\\n"
17084                "  int b          = 23;  \\\n"
17085                "  int ccc        = 234; \\\n"
17086                "  int dddddddddd = 2345;",
17087                Alignment);
17088   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17089   verifyFormat("#define A                                                      "
17090                "                \\\n"
17091                "  int aaaa       = 12;                                         "
17092                "                \\\n"
17093                "  int b          = 23;                                         "
17094                "                \\\n"
17095                "  int ccc        = 234;                                        "
17096                "                \\\n"
17097                "  int dddddddddd = 2345;",
17098                Alignment);
17099   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17100                "k = 4, int l = 5,\n"
17101                "                  int m = 6) {\n"
17102                "  int j      = 10;\n"
17103                "  otherThing = 1;\n"
17104                "}",
17105                Alignment);
17106   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17107                "  int i   = 1;\n"
17108                "  int j   = 2;\n"
17109                "  int big = 10000;\n"
17110                "}",
17111                Alignment);
17112   verifyFormat("class C {\n"
17113                "public:\n"
17114                "  int i            = 1;\n"
17115                "  virtual void f() = 0;\n"
17116                "};",
17117                Alignment);
17118   verifyFormat("int i = 1;\n"
17119                "if (SomeType t = getSomething()) {\n"
17120                "}\n"
17121                "int j   = 2;\n"
17122                "int big = 10000;",
17123                Alignment);
17124   verifyFormat("int j = 7;\n"
17125                "for (int k = 0; k < N; ++k) {\n"
17126                "}\n"
17127                "int j   = 2;\n"
17128                "int big = 10000;\n"
17129                "}",
17130                Alignment);
17131   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17132   verifyFormat("int i = 1;\n"
17133                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17134                "    = someLooooooooooooooooongFunction();\n"
17135                "int j = 2;",
17136                Alignment);
17137   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17138   verifyFormat("int i = 1;\n"
17139                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17140                "    someLooooooooooooooooongFunction();\n"
17141                "int j = 2;",
17142                Alignment);
17143 
17144   verifyFormat("auto lambda = []() {\n"
17145                "  auto i = 0;\n"
17146                "  return 0;\n"
17147                "};\n"
17148                "int i  = 0;\n"
17149                "auto v = type{\n"
17150                "    i = 1,   //\n"
17151                "    (i = 2), //\n"
17152                "    i = 3    //\n"
17153                "};",
17154                Alignment);
17155 
17156   verifyFormat(
17157       "int i      = 1;\n"
17158       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17159       "                          loooooooooooooooooooooongParameterB);\n"
17160       "int j      = 2;",
17161       Alignment);
17162 
17163   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17164                "          typename B   = very_long_type_name_1,\n"
17165                "          typename T_2 = very_long_type_name_2>\n"
17166                "auto foo() {}\n",
17167                Alignment);
17168   verifyFormat("int a, b = 1;\n"
17169                "int c  = 2;\n"
17170                "int dd = 3;\n",
17171                Alignment);
17172   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17173                "float b[1][] = {{3.f}};\n",
17174                Alignment);
17175   verifyFormat("for (int i = 0; i < 1; i++)\n"
17176                "  int x = 1;\n",
17177                Alignment);
17178   verifyFormat("for (i = 0; i < 1; i++)\n"
17179                "  x = 1;\n"
17180                "y = 1;\n",
17181                Alignment);
17182 
17183   EXPECT_EQ(Alignment.ReflowComments, true);
17184   Alignment.ColumnLimit = 50;
17185   EXPECT_EQ("int x   = 0;\n"
17186             "int yy  = 1; /// specificlennospace\n"
17187             "int zzz = 2;\n",
17188             format("int x   = 0;\n"
17189                    "int yy  = 1; ///specificlennospace\n"
17190                    "int zzz = 2;\n",
17191                    Alignment));
17192 
17193   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17194                "auto b                     = [] {\n"
17195                "  f();\n"
17196                "  return;\n"
17197                "};",
17198                Alignment);
17199   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17200                "auto b                     = g([] {\n"
17201                "  f();\n"
17202                "  return;\n"
17203                "});",
17204                Alignment);
17205   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17206                "auto b                     = g(param, [] {\n"
17207                "  f();\n"
17208                "  return;\n"
17209                "});",
17210                Alignment);
17211   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17212                "auto b                     = [] {\n"
17213                "  if (condition) {\n"
17214                "    return;\n"
17215                "  }\n"
17216                "};",
17217                Alignment);
17218 
17219   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17220                "           ccc ? aaaaa : bbbbb,\n"
17221                "           dddddddddddddddddddddddddd);",
17222                Alignment);
17223   // FIXME: https://llvm.org/PR53497
17224   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
17225   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17226   //              "    ccc ? aaaaa : bbbbb,\n"
17227   //              "    dddddddddddddddddddddddddd);",
17228   //              Alignment);
17229 }
17230 
17231 TEST_F(FormatTest, AlignConsecutiveBitFields) {
17232   FormatStyle Alignment = getLLVMStyle();
17233   Alignment.AlignConsecutiveBitFields.Enabled = true;
17234   verifyFormat("int const a     : 5;\n"
17235                "int oneTwoThree : 23;",
17236                Alignment);
17237 
17238   // Initializers are allowed starting with c++2a
17239   verifyFormat("int const a     : 5 = 1;\n"
17240                "int oneTwoThree : 23 = 0;",
17241                Alignment);
17242 
17243   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17244   verifyFormat("int const a           : 5;\n"
17245                "int       oneTwoThree : 23;",
17246                Alignment);
17247 
17248   verifyFormat("int const a           : 5;  // comment\n"
17249                "int       oneTwoThree : 23; // comment",
17250                Alignment);
17251 
17252   verifyFormat("int const a           : 5 = 1;\n"
17253                "int       oneTwoThree : 23 = 0;",
17254                Alignment);
17255 
17256   Alignment.AlignConsecutiveAssignments.Enabled = true;
17257   verifyFormat("int const a           : 5  = 1;\n"
17258                "int       oneTwoThree : 23 = 0;",
17259                Alignment);
17260   verifyFormat("int const a           : 5  = {1};\n"
17261                "int       oneTwoThree : 23 = 0;",
17262                Alignment);
17263 
17264   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
17265   verifyFormat("int const a          :5;\n"
17266                "int       oneTwoThree:23;",
17267                Alignment);
17268 
17269   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
17270   verifyFormat("int const a           :5;\n"
17271                "int       oneTwoThree :23;",
17272                Alignment);
17273 
17274   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
17275   verifyFormat("int const a          : 5;\n"
17276                "int       oneTwoThree: 23;",
17277                Alignment);
17278 
17279   // Known limitations: ':' is only recognized as a bitfield colon when
17280   // followed by a number.
17281   /*
17282   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
17283                "int a           : 5;",
17284                Alignment);
17285   */
17286 }
17287 
17288 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
17289   FormatStyle Alignment = getLLVMStyle();
17290   Alignment.AlignConsecutiveMacros.Enabled = true;
17291   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17292   verifyFormat("float const a = 5;\n"
17293                "int oneTwoThree = 123;",
17294                Alignment);
17295   verifyFormat("int a = 5;\n"
17296                "float const oneTwoThree = 123;",
17297                Alignment);
17298 
17299   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17300   verifyFormat("float const a = 5;\n"
17301                "int         oneTwoThree = 123;",
17302                Alignment);
17303   verifyFormat("int         a = method();\n"
17304                "float const oneTwoThree = 133;",
17305                Alignment);
17306   verifyFormat("int i = 1, j = 10;\n"
17307                "something = 2000;",
17308                Alignment);
17309   verifyFormat("something = 2000;\n"
17310                "int i = 1, j = 10;\n",
17311                Alignment);
17312   verifyFormat("float      something = 2000;\n"
17313                "double     another = 911;\n"
17314                "int        i = 1, j = 10;\n"
17315                "const int *oneMore = 1;\n"
17316                "unsigned   i = 2;",
17317                Alignment);
17318   verifyFormat("float a = 5;\n"
17319                "int   one = 1;\n"
17320                "method();\n"
17321                "const double       oneTwoThree = 123;\n"
17322                "const unsigned int oneTwo = 12;",
17323                Alignment);
17324   verifyFormat("int      oneTwoThree{0}; // comment\n"
17325                "unsigned oneTwo;         // comment",
17326                Alignment);
17327   verifyFormat("unsigned int       *a;\n"
17328                "int                *b;\n"
17329                "unsigned int Const *c;\n"
17330                "unsigned int const *d;\n"
17331                "unsigned int Const &e;\n"
17332                "unsigned int const &f;",
17333                Alignment);
17334   verifyFormat("Const unsigned int *c;\n"
17335                "const unsigned int *d;\n"
17336                "Const unsigned int &e;\n"
17337                "const unsigned int &f;\n"
17338                "const unsigned      g;\n"
17339                "Const unsigned      h;",
17340                Alignment);
17341   EXPECT_EQ("float const a = 5;\n"
17342             "\n"
17343             "int oneTwoThree = 123;",
17344             format("float const   a = 5;\n"
17345                    "\n"
17346                    "int           oneTwoThree= 123;",
17347                    Alignment));
17348   EXPECT_EQ("float a = 5;\n"
17349             "int   one = 1;\n"
17350             "\n"
17351             "unsigned oneTwoThree = 123;",
17352             format("float    a = 5;\n"
17353                    "int      one = 1;\n"
17354                    "\n"
17355                    "unsigned oneTwoThree = 123;",
17356                    Alignment));
17357   EXPECT_EQ("float a = 5;\n"
17358             "int   one = 1;\n"
17359             "\n"
17360             "unsigned oneTwoThree = 123;\n"
17361             "int      oneTwo = 12;",
17362             format("float    a = 5;\n"
17363                    "int one = 1;\n"
17364                    "\n"
17365                    "unsigned oneTwoThree = 123;\n"
17366                    "int oneTwo = 12;",
17367                    Alignment));
17368   // Function prototype alignment
17369   verifyFormat("int    a();\n"
17370                "double b();",
17371                Alignment);
17372   verifyFormat("int    a(int x);\n"
17373                "double b();",
17374                Alignment);
17375   unsigned OldColumnLimit = Alignment.ColumnLimit;
17376   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17377   // otherwise the function parameters will be re-flowed onto a single line.
17378   Alignment.ColumnLimit = 0;
17379   EXPECT_EQ("int    a(int   x,\n"
17380             "         float y);\n"
17381             "double b(int    x,\n"
17382             "         double y);",
17383             format("int a(int x,\n"
17384                    " float y);\n"
17385                    "double b(int x,\n"
17386                    " double y);",
17387                    Alignment));
17388   // This ensures that function parameters of function declarations are
17389   // correctly indented when their owning functions are indented.
17390   // The failure case here is for 'double y' to not be indented enough.
17391   EXPECT_EQ("double a(int x);\n"
17392             "int    b(int    y,\n"
17393             "         double z);",
17394             format("double a(int x);\n"
17395                    "int b(int y,\n"
17396                    " double z);",
17397                    Alignment));
17398   // Set ColumnLimit low so that we induce wrapping immediately after
17399   // the function name and opening paren.
17400   Alignment.ColumnLimit = 13;
17401   verifyFormat("int function(\n"
17402                "    int  x,\n"
17403                "    bool y);",
17404                Alignment);
17405   Alignment.ColumnLimit = OldColumnLimit;
17406   // Ensure function pointers don't screw up recursive alignment
17407   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17408                "double b();",
17409                Alignment);
17410   Alignment.AlignConsecutiveAssignments.Enabled = true;
17411   // Ensure recursive alignment is broken by function braces, so that the
17412   // "a = 1" does not align with subsequent assignments inside the function
17413   // body.
17414   verifyFormat("int func(int a = 1) {\n"
17415                "  int b  = 2;\n"
17416                "  int cc = 3;\n"
17417                "}",
17418                Alignment);
17419   verifyFormat("float      something = 2000;\n"
17420                "double     another   = 911;\n"
17421                "int        i = 1, j = 10;\n"
17422                "const int *oneMore = 1;\n"
17423                "unsigned   i       = 2;",
17424                Alignment);
17425   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17426                "unsigned oneTwo      = 0;   // comment",
17427                Alignment);
17428   // Make sure that scope is correctly tracked, in the absence of braces
17429   verifyFormat("for (int i = 0; i < n; i++)\n"
17430                "  j = i;\n"
17431                "double x = 1;\n",
17432                Alignment);
17433   verifyFormat("if (int i = 0)\n"
17434                "  j = i;\n"
17435                "double x = 1;\n",
17436                Alignment);
17437   // Ensure operator[] and operator() are comprehended
17438   verifyFormat("struct test {\n"
17439                "  long long int foo();\n"
17440                "  int           operator[](int a);\n"
17441                "  double        bar();\n"
17442                "};\n",
17443                Alignment);
17444   verifyFormat("struct test {\n"
17445                "  long long int foo();\n"
17446                "  int           operator()(int a);\n"
17447                "  double        bar();\n"
17448                "};\n",
17449                Alignment);
17450   // http://llvm.org/PR52914
17451   verifyFormat("char *a[]     = {\"a\", // comment\n"
17452                "                 \"bb\"};\n"
17453                "int   bbbbbbb = 0;",
17454                Alignment);
17455 
17456   // PAS_Right
17457   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17458             "  int const i   = 1;\n"
17459             "  int      *j   = 2;\n"
17460             "  int       big = 10000;\n"
17461             "\n"
17462             "  unsigned oneTwoThree = 123;\n"
17463             "  int      oneTwo      = 12;\n"
17464             "  method();\n"
17465             "  float k  = 2;\n"
17466             "  int   ll = 10000;\n"
17467             "}",
17468             format("void SomeFunction(int parameter= 0) {\n"
17469                    " int const  i= 1;\n"
17470                    "  int *j=2;\n"
17471                    " int big  =  10000;\n"
17472                    "\n"
17473                    "unsigned oneTwoThree  =123;\n"
17474                    "int oneTwo = 12;\n"
17475                    "  method();\n"
17476                    "float k= 2;\n"
17477                    "int ll=10000;\n"
17478                    "}",
17479                    Alignment));
17480   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17481             "  int const i   = 1;\n"
17482             "  int     **j   = 2, ***k;\n"
17483             "  int      &k   = i;\n"
17484             "  int     &&l   = i + j;\n"
17485             "  int       big = 10000;\n"
17486             "\n"
17487             "  unsigned oneTwoThree = 123;\n"
17488             "  int      oneTwo      = 12;\n"
17489             "  method();\n"
17490             "  float k  = 2;\n"
17491             "  int   ll = 10000;\n"
17492             "}",
17493             format("void SomeFunction(int parameter= 0) {\n"
17494                    " int const  i= 1;\n"
17495                    "  int **j=2,***k;\n"
17496                    "int &k=i;\n"
17497                    "int &&l=i+j;\n"
17498                    " int big  =  10000;\n"
17499                    "\n"
17500                    "unsigned oneTwoThree  =123;\n"
17501                    "int oneTwo = 12;\n"
17502                    "  method();\n"
17503                    "float k= 2;\n"
17504                    "int ll=10000;\n"
17505                    "}",
17506                    Alignment));
17507   // variables are aligned at their name, pointers are at the right most
17508   // position
17509   verifyFormat("int   *a;\n"
17510                "int  **b;\n"
17511                "int ***c;\n"
17512                "int    foobar;\n",
17513                Alignment);
17514 
17515   // PAS_Left
17516   FormatStyle AlignmentLeft = Alignment;
17517   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17518   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17519             "  int const i   = 1;\n"
17520             "  int*      j   = 2;\n"
17521             "  int       big = 10000;\n"
17522             "\n"
17523             "  unsigned oneTwoThree = 123;\n"
17524             "  int      oneTwo      = 12;\n"
17525             "  method();\n"
17526             "  float k  = 2;\n"
17527             "  int   ll = 10000;\n"
17528             "}",
17529             format("void SomeFunction(int parameter= 0) {\n"
17530                    " int const  i= 1;\n"
17531                    "  int *j=2;\n"
17532                    " int big  =  10000;\n"
17533                    "\n"
17534                    "unsigned oneTwoThree  =123;\n"
17535                    "int oneTwo = 12;\n"
17536                    "  method();\n"
17537                    "float k= 2;\n"
17538                    "int ll=10000;\n"
17539                    "}",
17540                    AlignmentLeft));
17541   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17542             "  int const i   = 1;\n"
17543             "  int**     j   = 2;\n"
17544             "  int&      k   = i;\n"
17545             "  int&&     l   = i + j;\n"
17546             "  int       big = 10000;\n"
17547             "\n"
17548             "  unsigned oneTwoThree = 123;\n"
17549             "  int      oneTwo      = 12;\n"
17550             "  method();\n"
17551             "  float k  = 2;\n"
17552             "  int   ll = 10000;\n"
17553             "}",
17554             format("void SomeFunction(int parameter= 0) {\n"
17555                    " int const  i= 1;\n"
17556                    "  int **j=2;\n"
17557                    "int &k=i;\n"
17558                    "int &&l=i+j;\n"
17559                    " int big  =  10000;\n"
17560                    "\n"
17561                    "unsigned oneTwoThree  =123;\n"
17562                    "int oneTwo = 12;\n"
17563                    "  method();\n"
17564                    "float k= 2;\n"
17565                    "int ll=10000;\n"
17566                    "}",
17567                    AlignmentLeft));
17568   // variables are aligned at their name, pointers are at the left most position
17569   verifyFormat("int*   a;\n"
17570                "int**  b;\n"
17571                "int*** c;\n"
17572                "int    foobar;\n",
17573                AlignmentLeft);
17574 
17575   // PAS_Middle
17576   FormatStyle AlignmentMiddle = Alignment;
17577   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17578   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17579             "  int const i   = 1;\n"
17580             "  int *     j   = 2;\n"
17581             "  int       big = 10000;\n"
17582             "\n"
17583             "  unsigned oneTwoThree = 123;\n"
17584             "  int      oneTwo      = 12;\n"
17585             "  method();\n"
17586             "  float k  = 2;\n"
17587             "  int   ll = 10000;\n"
17588             "}",
17589             format("void SomeFunction(int parameter= 0) {\n"
17590                    " int const  i= 1;\n"
17591                    "  int *j=2;\n"
17592                    " int big  =  10000;\n"
17593                    "\n"
17594                    "unsigned oneTwoThree  =123;\n"
17595                    "int oneTwo = 12;\n"
17596                    "  method();\n"
17597                    "float k= 2;\n"
17598                    "int ll=10000;\n"
17599                    "}",
17600                    AlignmentMiddle));
17601   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17602             "  int const i   = 1;\n"
17603             "  int **    j   = 2, ***k;\n"
17604             "  int &     k   = i;\n"
17605             "  int &&    l   = i + j;\n"
17606             "  int       big = 10000;\n"
17607             "\n"
17608             "  unsigned oneTwoThree = 123;\n"
17609             "  int      oneTwo      = 12;\n"
17610             "  method();\n"
17611             "  float k  = 2;\n"
17612             "  int   ll = 10000;\n"
17613             "}",
17614             format("void SomeFunction(int parameter= 0) {\n"
17615                    " int const  i= 1;\n"
17616                    "  int **j=2,***k;\n"
17617                    "int &k=i;\n"
17618                    "int &&l=i+j;\n"
17619                    " int big  =  10000;\n"
17620                    "\n"
17621                    "unsigned oneTwoThree  =123;\n"
17622                    "int oneTwo = 12;\n"
17623                    "  method();\n"
17624                    "float k= 2;\n"
17625                    "int ll=10000;\n"
17626                    "}",
17627                    AlignmentMiddle));
17628   // variables are aligned at their name, pointers are in the middle
17629   verifyFormat("int *   a;\n"
17630                "int *   b;\n"
17631                "int *** c;\n"
17632                "int     foobar;\n",
17633                AlignmentMiddle);
17634 
17635   Alignment.AlignConsecutiveAssignments.Enabled = false;
17636   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17637   verifyFormat("#define A \\\n"
17638                "  int       aaaa = 12; \\\n"
17639                "  float     b = 23; \\\n"
17640                "  const int ccc = 234; \\\n"
17641                "  unsigned  dddddddddd = 2345;",
17642                Alignment);
17643   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17644   verifyFormat("#define A              \\\n"
17645                "  int       aaaa = 12; \\\n"
17646                "  float     b = 23;    \\\n"
17647                "  const int ccc = 234; \\\n"
17648                "  unsigned  dddddddddd = 2345;",
17649                Alignment);
17650   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17651   Alignment.ColumnLimit = 30;
17652   verifyFormat("#define A                    \\\n"
17653                "  int       aaaa = 12;       \\\n"
17654                "  float     b = 23;          \\\n"
17655                "  const int ccc = 234;       \\\n"
17656                "  int       dddddddddd = 2345;",
17657                Alignment);
17658   Alignment.ColumnLimit = 80;
17659   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17660                "k = 4, int l = 5,\n"
17661                "                  int m = 6) {\n"
17662                "  const int j = 10;\n"
17663                "  otherThing = 1;\n"
17664                "}",
17665                Alignment);
17666   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17667                "  int const i = 1;\n"
17668                "  int      *j = 2;\n"
17669                "  int       big = 10000;\n"
17670                "}",
17671                Alignment);
17672   verifyFormat("class C {\n"
17673                "public:\n"
17674                "  int          i = 1;\n"
17675                "  virtual void f() = 0;\n"
17676                "};",
17677                Alignment);
17678   verifyFormat("float i = 1;\n"
17679                "if (SomeType t = getSomething()) {\n"
17680                "}\n"
17681                "const unsigned j = 2;\n"
17682                "int            big = 10000;",
17683                Alignment);
17684   verifyFormat("float j = 7;\n"
17685                "for (int k = 0; k < N; ++k) {\n"
17686                "}\n"
17687                "unsigned j = 2;\n"
17688                "int      big = 10000;\n"
17689                "}",
17690                Alignment);
17691   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17692   verifyFormat("float              i = 1;\n"
17693                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17694                "    = someLooooooooooooooooongFunction();\n"
17695                "int j = 2;",
17696                Alignment);
17697   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17698   verifyFormat("int                i = 1;\n"
17699                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17700                "    someLooooooooooooooooongFunction();\n"
17701                "int j = 2;",
17702                Alignment);
17703 
17704   Alignment.AlignConsecutiveAssignments.Enabled = true;
17705   verifyFormat("auto lambda = []() {\n"
17706                "  auto  ii = 0;\n"
17707                "  float j  = 0;\n"
17708                "  return 0;\n"
17709                "};\n"
17710                "int   i  = 0;\n"
17711                "float i2 = 0;\n"
17712                "auto  v  = type{\n"
17713                "    i = 1,   //\n"
17714                "    (i = 2), //\n"
17715                "    i = 3    //\n"
17716                "};",
17717                Alignment);
17718   Alignment.AlignConsecutiveAssignments.Enabled = false;
17719 
17720   verifyFormat(
17721       "int      i = 1;\n"
17722       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17723       "                          loooooooooooooooooooooongParameterB);\n"
17724       "int      j = 2;",
17725       Alignment);
17726 
17727   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17728   // We expect declarations and assignments to align, as long as it doesn't
17729   // exceed the column limit, starting a new alignment sequence whenever it
17730   // happens.
17731   Alignment.AlignConsecutiveAssignments.Enabled = true;
17732   Alignment.ColumnLimit = 30;
17733   verifyFormat("float    ii              = 1;\n"
17734                "unsigned j               = 2;\n"
17735                "int someVerylongVariable = 1;\n"
17736                "AnotherLongType  ll = 123456;\n"
17737                "VeryVeryLongType k  = 2;\n"
17738                "int              myvar = 1;",
17739                Alignment);
17740   Alignment.ColumnLimit = 80;
17741   Alignment.AlignConsecutiveAssignments.Enabled = false;
17742 
17743   verifyFormat(
17744       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17745       "          typename LongType, typename B>\n"
17746       "auto foo() {}\n",
17747       Alignment);
17748   verifyFormat("float a, b = 1;\n"
17749                "int   c = 2;\n"
17750                "int   dd = 3;\n",
17751                Alignment);
17752   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17753                "float b[1][] = {{3.f}};\n",
17754                Alignment);
17755   Alignment.AlignConsecutiveAssignments.Enabled = true;
17756   verifyFormat("float a, b = 1;\n"
17757                "int   c  = 2;\n"
17758                "int   dd = 3;\n",
17759                Alignment);
17760   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17761                "float b[1][] = {{3.f}};\n",
17762                Alignment);
17763   Alignment.AlignConsecutiveAssignments.Enabled = false;
17764 
17765   Alignment.ColumnLimit = 30;
17766   Alignment.BinPackParameters = false;
17767   verifyFormat("void foo(float     a,\n"
17768                "         float     b,\n"
17769                "         int       c,\n"
17770                "         uint32_t *d) {\n"
17771                "  int   *e = 0;\n"
17772                "  float  f = 0;\n"
17773                "  double g = 0;\n"
17774                "}\n"
17775                "void bar(ino_t     a,\n"
17776                "         int       b,\n"
17777                "         uint32_t *c,\n"
17778                "         bool      d) {}\n",
17779                Alignment);
17780   Alignment.BinPackParameters = true;
17781   Alignment.ColumnLimit = 80;
17782 
17783   // Bug 33507
17784   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17785   verifyFormat(
17786       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
17787       "  static const Version verVs2017;\n"
17788       "  return true;\n"
17789       "});\n",
17790       Alignment);
17791   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17792 
17793   // See llvm.org/PR35641
17794   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17795   verifyFormat("int func() { //\n"
17796                "  int      b;\n"
17797                "  unsigned c;\n"
17798                "}",
17799                Alignment);
17800 
17801   // See PR37175
17802   FormatStyle Style = getMozillaStyle();
17803   Style.AlignConsecutiveDeclarations.Enabled = true;
17804   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
17805             "foo(int a);",
17806             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
17807 
17808   Alignment.PointerAlignment = FormatStyle::PAS_Left;
17809   verifyFormat("unsigned int*       a;\n"
17810                "int*                b;\n"
17811                "unsigned int Const* c;\n"
17812                "unsigned int const* d;\n"
17813                "unsigned int Const& e;\n"
17814                "unsigned int const& f;",
17815                Alignment);
17816   verifyFormat("Const unsigned int* c;\n"
17817                "const unsigned int* d;\n"
17818                "Const unsigned int& e;\n"
17819                "const unsigned int& f;\n"
17820                "const unsigned      g;\n"
17821                "Const unsigned      h;",
17822                Alignment);
17823 
17824   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17825   verifyFormat("unsigned int *       a;\n"
17826                "int *                b;\n"
17827                "unsigned int Const * c;\n"
17828                "unsigned int const * d;\n"
17829                "unsigned int Const & e;\n"
17830                "unsigned int const & f;",
17831                Alignment);
17832   verifyFormat("Const unsigned int * c;\n"
17833                "const unsigned int * d;\n"
17834                "Const unsigned int & e;\n"
17835                "const unsigned int & f;\n"
17836                "const unsigned       g;\n"
17837                "Const unsigned       h;",
17838                Alignment);
17839 
17840   // See PR46529
17841   FormatStyle BracedAlign = getLLVMStyle();
17842   BracedAlign.AlignConsecutiveDeclarations.Enabled = true;
17843   verifyFormat("const auto result{[]() {\n"
17844                "  const auto something = 1;\n"
17845                "  return 2;\n"
17846                "}};",
17847                BracedAlign);
17848   verifyFormat("int foo{[]() {\n"
17849                "  int bar{0};\n"
17850                "  return 0;\n"
17851                "}()};",
17852                BracedAlign);
17853   BracedAlign.Cpp11BracedListStyle = false;
17854   verifyFormat("const auto result{ []() {\n"
17855                "  const auto something = 1;\n"
17856                "  return 2;\n"
17857                "} };",
17858                BracedAlign);
17859   verifyFormat("int foo{ []() {\n"
17860                "  int bar{ 0 };\n"
17861                "  return 0;\n"
17862                "}() };",
17863                BracedAlign);
17864 }
17865 
17866 TEST_F(FormatTest, AlignWithLineBreaks) {
17867   auto Style = getLLVMStyleWithColumns(120);
17868 
17869   EXPECT_EQ(Style.AlignConsecutiveAssignments,
17870             FormatStyle::AlignConsecutiveStyle(
17871                 {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
17872                  /*AcrossComments=*/false, /*AlignCompound=*/false,
17873                  /*PadOperators=*/true}));
17874   EXPECT_EQ(Style.AlignConsecutiveDeclarations,
17875             FormatStyle::AlignConsecutiveStyle({}));
17876   verifyFormat("void foo() {\n"
17877                "  int myVar = 5;\n"
17878                "  double x = 3.14;\n"
17879                "  auto str = \"Hello \"\n"
17880                "             \"World\";\n"
17881                "  auto s = \"Hello \"\n"
17882                "           \"Again\";\n"
17883                "}",
17884                Style);
17885 
17886   // clang-format off
17887   verifyFormat("void foo() {\n"
17888                "  const int capacityBefore = Entries.capacity();\n"
17889                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17890                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17891                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17892                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17893                "}",
17894                Style);
17895   // clang-format on
17896 
17897   Style.AlignConsecutiveAssignments.Enabled = true;
17898   verifyFormat("void foo() {\n"
17899                "  int myVar = 5;\n"
17900                "  double x  = 3.14;\n"
17901                "  auto str  = \"Hello \"\n"
17902                "              \"World\";\n"
17903                "  auto s    = \"Hello \"\n"
17904                "              \"Again\";\n"
17905                "}",
17906                Style);
17907 
17908   // clang-format off
17909   verifyFormat("void foo() {\n"
17910                "  const int capacityBefore = Entries.capacity();\n"
17911                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17912                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17913                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17914                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17915                "}",
17916                Style);
17917   // clang-format on
17918 
17919   Style.AlignConsecutiveAssignments.Enabled = false;
17920   Style.AlignConsecutiveDeclarations.Enabled = true;
17921   verifyFormat("void foo() {\n"
17922                "  int    myVar = 5;\n"
17923                "  double x = 3.14;\n"
17924                "  auto   str = \"Hello \"\n"
17925                "               \"World\";\n"
17926                "  auto   s = \"Hello \"\n"
17927                "             \"Again\";\n"
17928                "}",
17929                Style);
17930 
17931   // clang-format off
17932   verifyFormat("void foo() {\n"
17933                "  const int  capacityBefore = Entries.capacity();\n"
17934                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17935                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17936                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17937                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17938                "}",
17939                Style);
17940   // clang-format on
17941 
17942   Style.AlignConsecutiveAssignments.Enabled = true;
17943   Style.AlignConsecutiveDeclarations.Enabled = true;
17944 
17945   verifyFormat("void foo() {\n"
17946                "  int    myVar = 5;\n"
17947                "  double x     = 3.14;\n"
17948                "  auto   str   = \"Hello \"\n"
17949                "                 \"World\";\n"
17950                "  auto   s     = \"Hello \"\n"
17951                "                 \"Again\";\n"
17952                "}",
17953                Style);
17954 
17955   // clang-format off
17956   verifyFormat("void foo() {\n"
17957                "  const int  capacityBefore = Entries.capacity();\n"
17958                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17959                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17960                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17961                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17962                "}",
17963                Style);
17964   // clang-format on
17965 
17966   Style = getLLVMStyleWithColumns(120);
17967   Style.AlignConsecutiveAssignments.Enabled = true;
17968   Style.ContinuationIndentWidth = 4;
17969   Style.IndentWidth = 4;
17970 
17971   // clang-format off
17972   verifyFormat("void SomeFunc() {\n"
17973                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17974                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17975                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17976                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17977                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17978                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17979                "}",
17980                Style);
17981   // clang-format on
17982 
17983   Style.BinPackArguments = false;
17984 
17985   // clang-format off
17986   verifyFormat("void SomeFunc() {\n"
17987                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
17988                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17989                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
17990                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17991                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
17992                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17993                "}",
17994                Style);
17995   // clang-format on
17996 }
17997 
17998 TEST_F(FormatTest, AlignWithInitializerPeriods) {
17999   auto Style = getLLVMStyleWithColumns(60);
18000 
18001   verifyFormat("void foo1(void) {\n"
18002                "  BYTE p[1] = 1;\n"
18003                "  A B = {.one_foooooooooooooooo = 2,\n"
18004                "         .two_fooooooooooooo = 3,\n"
18005                "         .three_fooooooooooooo = 4};\n"
18006                "  BYTE payload = 2;\n"
18007                "}",
18008                Style);
18009 
18010   Style.AlignConsecutiveAssignments.Enabled = true;
18011   Style.AlignConsecutiveDeclarations.Enabled = false;
18012   verifyFormat("void foo2(void) {\n"
18013                "  BYTE p[1]    = 1;\n"
18014                "  A B          = {.one_foooooooooooooooo = 2,\n"
18015                "                  .two_fooooooooooooo    = 3,\n"
18016                "                  .three_fooooooooooooo  = 4};\n"
18017                "  BYTE payload = 2;\n"
18018                "}",
18019                Style);
18020 
18021   Style.AlignConsecutiveAssignments.Enabled = false;
18022   Style.AlignConsecutiveDeclarations.Enabled = true;
18023   verifyFormat("void foo3(void) {\n"
18024                "  BYTE p[1] = 1;\n"
18025                "  A    B = {.one_foooooooooooooooo = 2,\n"
18026                "            .two_fooooooooooooo = 3,\n"
18027                "            .three_fooooooooooooo = 4};\n"
18028                "  BYTE payload = 2;\n"
18029                "}",
18030                Style);
18031 
18032   Style.AlignConsecutiveAssignments.Enabled = true;
18033   Style.AlignConsecutiveDeclarations.Enabled = true;
18034   verifyFormat("void foo4(void) {\n"
18035                "  BYTE p[1]    = 1;\n"
18036                "  A    B       = {.one_foooooooooooooooo = 2,\n"
18037                "                  .two_fooooooooooooo    = 3,\n"
18038                "                  .three_fooooooooooooo  = 4};\n"
18039                "  BYTE payload = 2;\n"
18040                "}",
18041                Style);
18042 }
18043 
18044 TEST_F(FormatTest, LinuxBraceBreaking) {
18045   FormatStyle LinuxBraceStyle = getLLVMStyle();
18046   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
18047   verifyFormat("namespace a\n"
18048                "{\n"
18049                "class A\n"
18050                "{\n"
18051                "  void f()\n"
18052                "  {\n"
18053                "    if (true) {\n"
18054                "      a();\n"
18055                "      b();\n"
18056                "    } else {\n"
18057                "      a();\n"
18058                "    }\n"
18059                "  }\n"
18060                "  void g() { return; }\n"
18061                "};\n"
18062                "struct B {\n"
18063                "  int x;\n"
18064                "};\n"
18065                "} // namespace a\n",
18066                LinuxBraceStyle);
18067   verifyFormat("enum X {\n"
18068                "  Y = 0,\n"
18069                "}\n",
18070                LinuxBraceStyle);
18071   verifyFormat("struct S {\n"
18072                "  int Type;\n"
18073                "  union {\n"
18074                "    int x;\n"
18075                "    double y;\n"
18076                "  } Value;\n"
18077                "  class C\n"
18078                "  {\n"
18079                "    MyFavoriteType Value;\n"
18080                "  } Class;\n"
18081                "}\n",
18082                LinuxBraceStyle);
18083 }
18084 
18085 TEST_F(FormatTest, MozillaBraceBreaking) {
18086   FormatStyle MozillaBraceStyle = getLLVMStyle();
18087   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
18088   MozillaBraceStyle.FixNamespaceComments = false;
18089   verifyFormat("namespace a {\n"
18090                "class A\n"
18091                "{\n"
18092                "  void f()\n"
18093                "  {\n"
18094                "    if (true) {\n"
18095                "      a();\n"
18096                "      b();\n"
18097                "    }\n"
18098                "  }\n"
18099                "  void g() { return; }\n"
18100                "};\n"
18101                "enum E\n"
18102                "{\n"
18103                "  A,\n"
18104                "  // foo\n"
18105                "  B,\n"
18106                "  C\n"
18107                "};\n"
18108                "struct B\n"
18109                "{\n"
18110                "  int x;\n"
18111                "};\n"
18112                "}\n",
18113                MozillaBraceStyle);
18114   verifyFormat("struct S\n"
18115                "{\n"
18116                "  int Type;\n"
18117                "  union\n"
18118                "  {\n"
18119                "    int x;\n"
18120                "    double y;\n"
18121                "  } Value;\n"
18122                "  class C\n"
18123                "  {\n"
18124                "    MyFavoriteType Value;\n"
18125                "  } Class;\n"
18126                "}\n",
18127                MozillaBraceStyle);
18128 }
18129 
18130 TEST_F(FormatTest, StroustrupBraceBreaking) {
18131   FormatStyle StroustrupBraceStyle = getLLVMStyle();
18132   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18133   verifyFormat("namespace a {\n"
18134                "class A {\n"
18135                "  void f()\n"
18136                "  {\n"
18137                "    if (true) {\n"
18138                "      a();\n"
18139                "      b();\n"
18140                "    }\n"
18141                "  }\n"
18142                "  void g() { return; }\n"
18143                "};\n"
18144                "struct B {\n"
18145                "  int x;\n"
18146                "};\n"
18147                "} // namespace a\n",
18148                StroustrupBraceStyle);
18149 
18150   verifyFormat("void foo()\n"
18151                "{\n"
18152                "  if (a) {\n"
18153                "    a();\n"
18154                "  }\n"
18155                "  else {\n"
18156                "    b();\n"
18157                "  }\n"
18158                "}\n",
18159                StroustrupBraceStyle);
18160 
18161   verifyFormat("#ifdef _DEBUG\n"
18162                "int foo(int i = 0)\n"
18163                "#else\n"
18164                "int foo(int i = 5)\n"
18165                "#endif\n"
18166                "{\n"
18167                "  return i;\n"
18168                "}",
18169                StroustrupBraceStyle);
18170 
18171   verifyFormat("void foo() {}\n"
18172                "void bar()\n"
18173                "#ifdef _DEBUG\n"
18174                "{\n"
18175                "  foo();\n"
18176                "}\n"
18177                "#else\n"
18178                "{\n"
18179                "}\n"
18180                "#endif",
18181                StroustrupBraceStyle);
18182 
18183   verifyFormat("void foobar() { int i = 5; }\n"
18184                "#ifdef _DEBUG\n"
18185                "void bar() {}\n"
18186                "#else\n"
18187                "void bar() { foobar(); }\n"
18188                "#endif",
18189                StroustrupBraceStyle);
18190 }
18191 
18192 TEST_F(FormatTest, AllmanBraceBreaking) {
18193   FormatStyle AllmanBraceStyle = getLLVMStyle();
18194   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
18195 
18196   EXPECT_EQ("namespace a\n"
18197             "{\n"
18198             "void f();\n"
18199             "void g();\n"
18200             "} // namespace a\n",
18201             format("namespace a\n"
18202                    "{\n"
18203                    "void f();\n"
18204                    "void g();\n"
18205                    "}\n",
18206                    AllmanBraceStyle));
18207 
18208   verifyFormat("namespace a\n"
18209                "{\n"
18210                "class A\n"
18211                "{\n"
18212                "  void f()\n"
18213                "  {\n"
18214                "    if (true)\n"
18215                "    {\n"
18216                "      a();\n"
18217                "      b();\n"
18218                "    }\n"
18219                "  }\n"
18220                "  void g() { return; }\n"
18221                "};\n"
18222                "struct B\n"
18223                "{\n"
18224                "  int x;\n"
18225                "};\n"
18226                "union C\n"
18227                "{\n"
18228                "};\n"
18229                "} // namespace a",
18230                AllmanBraceStyle);
18231 
18232   verifyFormat("void f()\n"
18233                "{\n"
18234                "  if (true)\n"
18235                "  {\n"
18236                "    a();\n"
18237                "  }\n"
18238                "  else if (false)\n"
18239                "  {\n"
18240                "    b();\n"
18241                "  }\n"
18242                "  else\n"
18243                "  {\n"
18244                "    c();\n"
18245                "  }\n"
18246                "}\n",
18247                AllmanBraceStyle);
18248 
18249   verifyFormat("void f()\n"
18250                "{\n"
18251                "  for (int i = 0; i < 10; ++i)\n"
18252                "  {\n"
18253                "    a();\n"
18254                "  }\n"
18255                "  while (false)\n"
18256                "  {\n"
18257                "    b();\n"
18258                "  }\n"
18259                "  do\n"
18260                "  {\n"
18261                "    c();\n"
18262                "  } while (false)\n"
18263                "}\n",
18264                AllmanBraceStyle);
18265 
18266   verifyFormat("void f(int a)\n"
18267                "{\n"
18268                "  switch (a)\n"
18269                "  {\n"
18270                "  case 0:\n"
18271                "    break;\n"
18272                "  case 1:\n"
18273                "  {\n"
18274                "    break;\n"
18275                "  }\n"
18276                "  case 2:\n"
18277                "  {\n"
18278                "  }\n"
18279                "  break;\n"
18280                "  default:\n"
18281                "    break;\n"
18282                "  }\n"
18283                "}\n",
18284                AllmanBraceStyle);
18285 
18286   verifyFormat("enum X\n"
18287                "{\n"
18288                "  Y = 0,\n"
18289                "}\n",
18290                AllmanBraceStyle);
18291   verifyFormat("enum X\n"
18292                "{\n"
18293                "  Y = 0\n"
18294                "}\n",
18295                AllmanBraceStyle);
18296 
18297   verifyFormat("@interface BSApplicationController ()\n"
18298                "{\n"
18299                "@private\n"
18300                "  id _extraIvar;\n"
18301                "}\n"
18302                "@end\n",
18303                AllmanBraceStyle);
18304 
18305   verifyFormat("#ifdef _DEBUG\n"
18306                "int foo(int i = 0)\n"
18307                "#else\n"
18308                "int foo(int i = 5)\n"
18309                "#endif\n"
18310                "{\n"
18311                "  return i;\n"
18312                "}",
18313                AllmanBraceStyle);
18314 
18315   verifyFormat("void foo() {}\n"
18316                "void bar()\n"
18317                "#ifdef _DEBUG\n"
18318                "{\n"
18319                "  foo();\n"
18320                "}\n"
18321                "#else\n"
18322                "{\n"
18323                "}\n"
18324                "#endif",
18325                AllmanBraceStyle);
18326 
18327   verifyFormat("void foobar() { int i = 5; }\n"
18328                "#ifdef _DEBUG\n"
18329                "void bar() {}\n"
18330                "#else\n"
18331                "void bar() { foobar(); }\n"
18332                "#endif",
18333                AllmanBraceStyle);
18334 
18335   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18336             FormatStyle::SLS_All);
18337 
18338   verifyFormat("[](int i) { return i + 2; };\n"
18339                "[](int i, int j)\n"
18340                "{\n"
18341                "  auto x = i + j;\n"
18342                "  auto y = i * j;\n"
18343                "  return x ^ y;\n"
18344                "};\n"
18345                "void foo()\n"
18346                "{\n"
18347                "  auto shortLambda = [](int i) { return i + 2; };\n"
18348                "  auto longLambda = [](int i, int j)\n"
18349                "  {\n"
18350                "    auto x = i + j;\n"
18351                "    auto y = i * j;\n"
18352                "    return x ^ y;\n"
18353                "  };\n"
18354                "}",
18355                AllmanBraceStyle);
18356 
18357   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18358 
18359   verifyFormat("[](int i)\n"
18360                "{\n"
18361                "  return i + 2;\n"
18362                "};\n"
18363                "[](int i, int j)\n"
18364                "{\n"
18365                "  auto x = i + j;\n"
18366                "  auto y = i * j;\n"
18367                "  return x ^ y;\n"
18368                "};\n"
18369                "void foo()\n"
18370                "{\n"
18371                "  auto shortLambda = [](int i)\n"
18372                "  {\n"
18373                "    return i + 2;\n"
18374                "  };\n"
18375                "  auto longLambda = [](int i, int j)\n"
18376                "  {\n"
18377                "    auto x = i + j;\n"
18378                "    auto y = i * j;\n"
18379                "    return x ^ y;\n"
18380                "  };\n"
18381                "}",
18382                AllmanBraceStyle);
18383 
18384   // Reset
18385   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18386 
18387   // This shouldn't affect ObjC blocks..
18388   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18389                "  // ...\n"
18390                "  int i;\n"
18391                "}];",
18392                AllmanBraceStyle);
18393   verifyFormat("void (^block)(void) = ^{\n"
18394                "  // ...\n"
18395                "  int i;\n"
18396                "};",
18397                AllmanBraceStyle);
18398   // .. or dict literals.
18399   verifyFormat("void f()\n"
18400                "{\n"
18401                "  // ...\n"
18402                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18403                "}",
18404                AllmanBraceStyle);
18405   verifyFormat("void f()\n"
18406                "{\n"
18407                "  // ...\n"
18408                "  [object someMethod:@{a : @\"b\"}];\n"
18409                "}",
18410                AllmanBraceStyle);
18411   verifyFormat("int f()\n"
18412                "{ // comment\n"
18413                "  return 42;\n"
18414                "}",
18415                AllmanBraceStyle);
18416 
18417   AllmanBraceStyle.ColumnLimit = 19;
18418   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18419   AllmanBraceStyle.ColumnLimit = 18;
18420   verifyFormat("void f()\n"
18421                "{\n"
18422                "  int i;\n"
18423                "}",
18424                AllmanBraceStyle);
18425   AllmanBraceStyle.ColumnLimit = 80;
18426 
18427   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18428   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18429       FormatStyle::SIS_WithoutElse;
18430   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18431   verifyFormat("void f(bool b)\n"
18432                "{\n"
18433                "  if (b)\n"
18434                "  {\n"
18435                "    return;\n"
18436                "  }\n"
18437                "}\n",
18438                BreakBeforeBraceShortIfs);
18439   verifyFormat("void f(bool b)\n"
18440                "{\n"
18441                "  if constexpr (b)\n"
18442                "  {\n"
18443                "    return;\n"
18444                "  }\n"
18445                "}\n",
18446                BreakBeforeBraceShortIfs);
18447   verifyFormat("void f(bool b)\n"
18448                "{\n"
18449                "  if CONSTEXPR (b)\n"
18450                "  {\n"
18451                "    return;\n"
18452                "  }\n"
18453                "}\n",
18454                BreakBeforeBraceShortIfs);
18455   verifyFormat("void f(bool b)\n"
18456                "{\n"
18457                "  if (b) return;\n"
18458                "}\n",
18459                BreakBeforeBraceShortIfs);
18460   verifyFormat("void f(bool b)\n"
18461                "{\n"
18462                "  if constexpr (b) return;\n"
18463                "}\n",
18464                BreakBeforeBraceShortIfs);
18465   verifyFormat("void f(bool b)\n"
18466                "{\n"
18467                "  if CONSTEXPR (b) return;\n"
18468                "}\n",
18469                BreakBeforeBraceShortIfs);
18470   verifyFormat("void f(bool b)\n"
18471                "{\n"
18472                "  while (b)\n"
18473                "  {\n"
18474                "    return;\n"
18475                "  }\n"
18476                "}\n",
18477                BreakBeforeBraceShortIfs);
18478 }
18479 
18480 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18481   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18482   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18483 
18484   // Make a few changes to the style for testing purposes
18485   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18486       FormatStyle::SFS_Empty;
18487   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18488 
18489   // FIXME: this test case can't decide whether there should be a blank line
18490   // after the ~D() line or not. It adds one if one doesn't exist in the test
18491   // and it removes the line if one exists.
18492   /*
18493   verifyFormat("class A;\n"
18494                "namespace B\n"
18495                "  {\n"
18496                "class C;\n"
18497                "// Comment\n"
18498                "class D\n"
18499                "  {\n"
18500                "public:\n"
18501                "  D();\n"
18502                "  ~D() {}\n"
18503                "private:\n"
18504                "  enum E\n"
18505                "    {\n"
18506                "    F\n"
18507                "    }\n"
18508                "  };\n"
18509                "  } // namespace B\n",
18510                WhitesmithsBraceStyle);
18511   */
18512 
18513   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18514   verifyFormat("namespace a\n"
18515                "  {\n"
18516                "class A\n"
18517                "  {\n"
18518                "  void f()\n"
18519                "    {\n"
18520                "    if (true)\n"
18521                "      {\n"
18522                "      a();\n"
18523                "      b();\n"
18524                "      }\n"
18525                "    }\n"
18526                "  void g()\n"
18527                "    {\n"
18528                "    return;\n"
18529                "    }\n"
18530                "  };\n"
18531                "struct B\n"
18532                "  {\n"
18533                "  int x;\n"
18534                "  };\n"
18535                "  } // namespace a",
18536                WhitesmithsBraceStyle);
18537 
18538   verifyFormat("namespace a\n"
18539                "  {\n"
18540                "namespace b\n"
18541                "  {\n"
18542                "class A\n"
18543                "  {\n"
18544                "  void f()\n"
18545                "    {\n"
18546                "    if (true)\n"
18547                "      {\n"
18548                "      a();\n"
18549                "      b();\n"
18550                "      }\n"
18551                "    }\n"
18552                "  void g()\n"
18553                "    {\n"
18554                "    return;\n"
18555                "    }\n"
18556                "  };\n"
18557                "struct B\n"
18558                "  {\n"
18559                "  int x;\n"
18560                "  };\n"
18561                "  } // namespace b\n"
18562                "  } // namespace a",
18563                WhitesmithsBraceStyle);
18564 
18565   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18566   verifyFormat("namespace a\n"
18567                "  {\n"
18568                "namespace b\n"
18569                "  {\n"
18570                "  class A\n"
18571                "    {\n"
18572                "    void f()\n"
18573                "      {\n"
18574                "      if (true)\n"
18575                "        {\n"
18576                "        a();\n"
18577                "        b();\n"
18578                "        }\n"
18579                "      }\n"
18580                "    void g()\n"
18581                "      {\n"
18582                "      return;\n"
18583                "      }\n"
18584                "    };\n"
18585                "  struct B\n"
18586                "    {\n"
18587                "    int x;\n"
18588                "    };\n"
18589                "  } // namespace b\n"
18590                "  } // namespace a",
18591                WhitesmithsBraceStyle);
18592 
18593   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18594   verifyFormat("namespace a\n"
18595                "  {\n"
18596                "  namespace b\n"
18597                "    {\n"
18598                "    class A\n"
18599                "      {\n"
18600                "      void f()\n"
18601                "        {\n"
18602                "        if (true)\n"
18603                "          {\n"
18604                "          a();\n"
18605                "          b();\n"
18606                "          }\n"
18607                "        }\n"
18608                "      void g()\n"
18609                "        {\n"
18610                "        return;\n"
18611                "        }\n"
18612                "      };\n"
18613                "    struct B\n"
18614                "      {\n"
18615                "      int x;\n"
18616                "      };\n"
18617                "    } // namespace b\n"
18618                "  }   // namespace a",
18619                WhitesmithsBraceStyle);
18620 
18621   verifyFormat("void f()\n"
18622                "  {\n"
18623                "  if (true)\n"
18624                "    {\n"
18625                "    a();\n"
18626                "    }\n"
18627                "  else if (false)\n"
18628                "    {\n"
18629                "    b();\n"
18630                "    }\n"
18631                "  else\n"
18632                "    {\n"
18633                "    c();\n"
18634                "    }\n"
18635                "  }\n",
18636                WhitesmithsBraceStyle);
18637 
18638   verifyFormat("void f()\n"
18639                "  {\n"
18640                "  for (int i = 0; i < 10; ++i)\n"
18641                "    {\n"
18642                "    a();\n"
18643                "    }\n"
18644                "  while (false)\n"
18645                "    {\n"
18646                "    b();\n"
18647                "    }\n"
18648                "  do\n"
18649                "    {\n"
18650                "    c();\n"
18651                "    } while (false)\n"
18652                "  }\n",
18653                WhitesmithsBraceStyle);
18654 
18655   WhitesmithsBraceStyle.IndentCaseLabels = true;
18656   verifyFormat("void switchTest1(int a)\n"
18657                "  {\n"
18658                "  switch (a)\n"
18659                "    {\n"
18660                "    case 2:\n"
18661                "      {\n"
18662                "      }\n"
18663                "      break;\n"
18664                "    }\n"
18665                "  }\n",
18666                WhitesmithsBraceStyle);
18667 
18668   verifyFormat("void switchTest2(int a)\n"
18669                "  {\n"
18670                "  switch (a)\n"
18671                "    {\n"
18672                "    case 0:\n"
18673                "      break;\n"
18674                "    case 1:\n"
18675                "      {\n"
18676                "      break;\n"
18677                "      }\n"
18678                "    case 2:\n"
18679                "      {\n"
18680                "      }\n"
18681                "      break;\n"
18682                "    default:\n"
18683                "      break;\n"
18684                "    }\n"
18685                "  }\n",
18686                WhitesmithsBraceStyle);
18687 
18688   verifyFormat("void switchTest3(int a)\n"
18689                "  {\n"
18690                "  switch (a)\n"
18691                "    {\n"
18692                "    case 0:\n"
18693                "      {\n"
18694                "      foo(x);\n"
18695                "      }\n"
18696                "      break;\n"
18697                "    default:\n"
18698                "      {\n"
18699                "      foo(1);\n"
18700                "      }\n"
18701                "      break;\n"
18702                "    }\n"
18703                "  }\n",
18704                WhitesmithsBraceStyle);
18705 
18706   WhitesmithsBraceStyle.IndentCaseLabels = false;
18707 
18708   verifyFormat("void switchTest4(int a)\n"
18709                "  {\n"
18710                "  switch (a)\n"
18711                "    {\n"
18712                "  case 2:\n"
18713                "    {\n"
18714                "    }\n"
18715                "    break;\n"
18716                "    }\n"
18717                "  }\n",
18718                WhitesmithsBraceStyle);
18719 
18720   verifyFormat("void switchTest5(int a)\n"
18721                "  {\n"
18722                "  switch (a)\n"
18723                "    {\n"
18724                "  case 0:\n"
18725                "    break;\n"
18726                "  case 1:\n"
18727                "    {\n"
18728                "    foo();\n"
18729                "    break;\n"
18730                "    }\n"
18731                "  case 2:\n"
18732                "    {\n"
18733                "    }\n"
18734                "    break;\n"
18735                "  default:\n"
18736                "    break;\n"
18737                "    }\n"
18738                "  }\n",
18739                WhitesmithsBraceStyle);
18740 
18741   verifyFormat("void switchTest6(int a)\n"
18742                "  {\n"
18743                "  switch (a)\n"
18744                "    {\n"
18745                "  case 0:\n"
18746                "    {\n"
18747                "    foo(x);\n"
18748                "    }\n"
18749                "    break;\n"
18750                "  default:\n"
18751                "    {\n"
18752                "    foo(1);\n"
18753                "    }\n"
18754                "    break;\n"
18755                "    }\n"
18756                "  }\n",
18757                WhitesmithsBraceStyle);
18758 
18759   verifyFormat("enum X\n"
18760                "  {\n"
18761                "  Y = 0, // testing\n"
18762                "  }\n",
18763                WhitesmithsBraceStyle);
18764 
18765   verifyFormat("enum X\n"
18766                "  {\n"
18767                "  Y = 0\n"
18768                "  }\n",
18769                WhitesmithsBraceStyle);
18770   verifyFormat("enum X\n"
18771                "  {\n"
18772                "  Y = 0,\n"
18773                "  Z = 1\n"
18774                "  };\n",
18775                WhitesmithsBraceStyle);
18776 
18777   verifyFormat("@interface BSApplicationController ()\n"
18778                "  {\n"
18779                "@private\n"
18780                "  id _extraIvar;\n"
18781                "  }\n"
18782                "@end\n",
18783                WhitesmithsBraceStyle);
18784 
18785   verifyFormat("#ifdef _DEBUG\n"
18786                "int foo(int i = 0)\n"
18787                "#else\n"
18788                "int foo(int i = 5)\n"
18789                "#endif\n"
18790                "  {\n"
18791                "  return i;\n"
18792                "  }",
18793                WhitesmithsBraceStyle);
18794 
18795   verifyFormat("void foo() {}\n"
18796                "void bar()\n"
18797                "#ifdef _DEBUG\n"
18798                "  {\n"
18799                "  foo();\n"
18800                "  }\n"
18801                "#else\n"
18802                "  {\n"
18803                "  }\n"
18804                "#endif",
18805                WhitesmithsBraceStyle);
18806 
18807   verifyFormat("void foobar()\n"
18808                "  {\n"
18809                "  int i = 5;\n"
18810                "  }\n"
18811                "#ifdef _DEBUG\n"
18812                "void bar()\n"
18813                "  {\n"
18814                "  }\n"
18815                "#else\n"
18816                "void bar()\n"
18817                "  {\n"
18818                "  foobar();\n"
18819                "  }\n"
18820                "#endif",
18821                WhitesmithsBraceStyle);
18822 
18823   // This shouldn't affect ObjC blocks..
18824   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18825                "  // ...\n"
18826                "  int i;\n"
18827                "}];",
18828                WhitesmithsBraceStyle);
18829   verifyFormat("void (^block)(void) = ^{\n"
18830                "  // ...\n"
18831                "  int i;\n"
18832                "};",
18833                WhitesmithsBraceStyle);
18834   // .. or dict literals.
18835   verifyFormat("void f()\n"
18836                "  {\n"
18837                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18838                "  }",
18839                WhitesmithsBraceStyle);
18840 
18841   verifyFormat("int f()\n"
18842                "  { // comment\n"
18843                "  return 42;\n"
18844                "  }",
18845                WhitesmithsBraceStyle);
18846 
18847   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
18848   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18849       FormatStyle::SIS_OnlyFirstIf;
18850   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18851   verifyFormat("void f(bool b)\n"
18852                "  {\n"
18853                "  if (b)\n"
18854                "    {\n"
18855                "    return;\n"
18856                "    }\n"
18857                "  }\n",
18858                BreakBeforeBraceShortIfs);
18859   verifyFormat("void f(bool b)\n"
18860                "  {\n"
18861                "  if (b) return;\n"
18862                "  }\n",
18863                BreakBeforeBraceShortIfs);
18864   verifyFormat("void f(bool b)\n"
18865                "  {\n"
18866                "  while (b)\n"
18867                "    {\n"
18868                "    return;\n"
18869                "    }\n"
18870                "  }\n",
18871                BreakBeforeBraceShortIfs);
18872 }
18873 
18874 TEST_F(FormatTest, GNUBraceBreaking) {
18875   FormatStyle GNUBraceStyle = getLLVMStyle();
18876   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
18877   verifyFormat("namespace a\n"
18878                "{\n"
18879                "class A\n"
18880                "{\n"
18881                "  void f()\n"
18882                "  {\n"
18883                "    int a;\n"
18884                "    {\n"
18885                "      int b;\n"
18886                "    }\n"
18887                "    if (true)\n"
18888                "      {\n"
18889                "        a();\n"
18890                "        b();\n"
18891                "      }\n"
18892                "  }\n"
18893                "  void g() { return; }\n"
18894                "}\n"
18895                "} // namespace a",
18896                GNUBraceStyle);
18897 
18898   verifyFormat("void f()\n"
18899                "{\n"
18900                "  if (true)\n"
18901                "    {\n"
18902                "      a();\n"
18903                "    }\n"
18904                "  else if (false)\n"
18905                "    {\n"
18906                "      b();\n"
18907                "    }\n"
18908                "  else\n"
18909                "    {\n"
18910                "      c();\n"
18911                "    }\n"
18912                "}\n",
18913                GNUBraceStyle);
18914 
18915   verifyFormat("void f()\n"
18916                "{\n"
18917                "  for (int i = 0; i < 10; ++i)\n"
18918                "    {\n"
18919                "      a();\n"
18920                "    }\n"
18921                "  while (false)\n"
18922                "    {\n"
18923                "      b();\n"
18924                "    }\n"
18925                "  do\n"
18926                "    {\n"
18927                "      c();\n"
18928                "    }\n"
18929                "  while (false);\n"
18930                "}\n",
18931                GNUBraceStyle);
18932 
18933   verifyFormat("void f(int a)\n"
18934                "{\n"
18935                "  switch (a)\n"
18936                "    {\n"
18937                "    case 0:\n"
18938                "      break;\n"
18939                "    case 1:\n"
18940                "      {\n"
18941                "        break;\n"
18942                "      }\n"
18943                "    case 2:\n"
18944                "      {\n"
18945                "      }\n"
18946                "      break;\n"
18947                "    default:\n"
18948                "      break;\n"
18949                "    }\n"
18950                "}\n",
18951                GNUBraceStyle);
18952 
18953   verifyFormat("enum X\n"
18954                "{\n"
18955                "  Y = 0,\n"
18956                "}\n",
18957                GNUBraceStyle);
18958 
18959   verifyFormat("@interface BSApplicationController ()\n"
18960                "{\n"
18961                "@private\n"
18962                "  id _extraIvar;\n"
18963                "}\n"
18964                "@end\n",
18965                GNUBraceStyle);
18966 
18967   verifyFormat("#ifdef _DEBUG\n"
18968                "int foo(int i = 0)\n"
18969                "#else\n"
18970                "int foo(int i = 5)\n"
18971                "#endif\n"
18972                "{\n"
18973                "  return i;\n"
18974                "}",
18975                GNUBraceStyle);
18976 
18977   verifyFormat("void foo() {}\n"
18978                "void bar()\n"
18979                "#ifdef _DEBUG\n"
18980                "{\n"
18981                "  foo();\n"
18982                "}\n"
18983                "#else\n"
18984                "{\n"
18985                "}\n"
18986                "#endif",
18987                GNUBraceStyle);
18988 
18989   verifyFormat("void foobar() { int i = 5; }\n"
18990                "#ifdef _DEBUG\n"
18991                "void bar() {}\n"
18992                "#else\n"
18993                "void bar() { foobar(); }\n"
18994                "#endif",
18995                GNUBraceStyle);
18996 }
18997 
18998 TEST_F(FormatTest, WebKitBraceBreaking) {
18999   FormatStyle WebKitBraceStyle = getLLVMStyle();
19000   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
19001   WebKitBraceStyle.FixNamespaceComments = false;
19002   verifyFormat("namespace a {\n"
19003                "class A {\n"
19004                "  void f()\n"
19005                "  {\n"
19006                "    if (true) {\n"
19007                "      a();\n"
19008                "      b();\n"
19009                "    }\n"
19010                "  }\n"
19011                "  void g() { return; }\n"
19012                "};\n"
19013                "enum E {\n"
19014                "  A,\n"
19015                "  // foo\n"
19016                "  B,\n"
19017                "  C\n"
19018                "};\n"
19019                "struct B {\n"
19020                "  int x;\n"
19021                "};\n"
19022                "}\n",
19023                WebKitBraceStyle);
19024   verifyFormat("struct S {\n"
19025                "  int Type;\n"
19026                "  union {\n"
19027                "    int x;\n"
19028                "    double y;\n"
19029                "  } Value;\n"
19030                "  class C {\n"
19031                "    MyFavoriteType Value;\n"
19032                "  } Class;\n"
19033                "};\n",
19034                WebKitBraceStyle);
19035 }
19036 
19037 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
19038   verifyFormat("void f() {\n"
19039                "  try {\n"
19040                "  } catch (const Exception &e) {\n"
19041                "  }\n"
19042                "}\n",
19043                getLLVMStyle());
19044 }
19045 
19046 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
19047   auto Style = getLLVMStyle();
19048   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19049   Style.AlignConsecutiveAssignments.Enabled = true;
19050   Style.AlignConsecutiveDeclarations.Enabled = true;
19051   verifyFormat("struct test demo[] = {\n"
19052                "    {56,    23, \"hello\"},\n"
19053                "    {-1, 93463, \"world\"},\n"
19054                "    { 7,     5,    \"!!\"}\n"
19055                "};\n",
19056                Style);
19057 
19058   verifyFormat("struct test demo[] = {\n"
19059                "    {56,    23, \"hello\"}, // first line\n"
19060                "    {-1, 93463, \"world\"}, // second line\n"
19061                "    { 7,     5,    \"!!\"}  // third line\n"
19062                "};\n",
19063                Style);
19064 
19065   verifyFormat("struct test demo[4] = {\n"
19066                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19067                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19068                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19069                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19070                "};\n",
19071                Style);
19072 
19073   verifyFormat("struct test demo[3] = {\n"
19074                "    {56,    23, \"hello\"},\n"
19075                "    {-1, 93463, \"world\"},\n"
19076                "    { 7,     5,    \"!!\"}\n"
19077                "};\n",
19078                Style);
19079 
19080   verifyFormat("struct test demo[3] = {\n"
19081                "    {int{56},    23, \"hello\"},\n"
19082                "    {int{-1}, 93463, \"world\"},\n"
19083                "    { int{7},     5,    \"!!\"}\n"
19084                "};\n",
19085                Style);
19086 
19087   verifyFormat("struct test demo[] = {\n"
19088                "    {56,    23, \"hello\"},\n"
19089                "    {-1, 93463, \"world\"},\n"
19090                "    { 7,     5,    \"!!\"},\n"
19091                "};\n",
19092                Style);
19093 
19094   verifyFormat("test demo[] = {\n"
19095                "    {56,    23, \"hello\"},\n"
19096                "    {-1, 93463, \"world\"},\n"
19097                "    { 7,     5,    \"!!\"},\n"
19098                "};\n",
19099                Style);
19100 
19101   verifyFormat("demo = std::array<struct test, 3>{\n"
19102                "    test{56,    23, \"hello\"},\n"
19103                "    test{-1, 93463, \"world\"},\n"
19104                "    test{ 7,     5,    \"!!\"},\n"
19105                "};\n",
19106                Style);
19107 
19108   verifyFormat("test demo[] = {\n"
19109                "    {56,    23, \"hello\"},\n"
19110                "#if X\n"
19111                "    {-1, 93463, \"world\"},\n"
19112                "#endif\n"
19113                "    { 7,     5,    \"!!\"}\n"
19114                "};\n",
19115                Style);
19116 
19117   verifyFormat(
19118       "test demo[] = {\n"
19119       "    { 7,    23,\n"
19120       "     \"hello world i am a very long line that really, in any\"\n"
19121       "     \"just world, ought to be split over multiple lines\"},\n"
19122       "    {-1, 93463,                                  \"world\"},\n"
19123       "    {56,     5,                                     \"!!\"}\n"
19124       "};\n",
19125       Style);
19126 
19127   verifyFormat("return GradForUnaryCwise(g, {\n"
19128                "                                {{\"sign\"}, \"Sign\",  "
19129                "  {\"x\", \"dy\"}},\n"
19130                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
19131                ", \"sign\"}},\n"
19132                "});\n",
19133                Style);
19134 
19135   Style.ColumnLimit = 0;
19136   EXPECT_EQ(
19137       "test demo[] = {\n"
19138       "    {56,    23, \"hello world i am a very long line that really, "
19139       "in any just world, ought to be split over multiple lines\"},\n"
19140       "    {-1, 93463,                                                  "
19141       "                                                 \"world\"},\n"
19142       "    { 7,     5,                                                  "
19143       "                                                    \"!!\"},\n"
19144       "};",
19145       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19146              "that really, in any just world, ought to be split over multiple "
19147              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19148              Style));
19149 
19150   Style.ColumnLimit = 80;
19151   verifyFormat("test demo[] = {\n"
19152                "    {56,    23, /* a comment */ \"hello\"},\n"
19153                "    {-1, 93463,                 \"world\"},\n"
19154                "    { 7,     5,                    \"!!\"}\n"
19155                "};\n",
19156                Style);
19157 
19158   verifyFormat("test demo[] = {\n"
19159                "    {56,    23,                    \"hello\"},\n"
19160                "    {-1, 93463, \"world\" /* comment here */},\n"
19161                "    { 7,     5,                       \"!!\"}\n"
19162                "};\n",
19163                Style);
19164 
19165   verifyFormat("test demo[] = {\n"
19166                "    {56, /* a comment */ 23, \"hello\"},\n"
19167                "    {-1,              93463, \"world\"},\n"
19168                "    { 7,                  5,    \"!!\"}\n"
19169                "};\n",
19170                Style);
19171 
19172   Style.ColumnLimit = 20;
19173   EXPECT_EQ(
19174       "demo = std::array<\n"
19175       "    struct test, 3>{\n"
19176       "    test{\n"
19177       "         56,    23,\n"
19178       "         \"hello \"\n"
19179       "         \"world i \"\n"
19180       "         \"am a very \"\n"
19181       "         \"long line \"\n"
19182       "         \"that \"\n"
19183       "         \"really, \"\n"
19184       "         \"in any \"\n"
19185       "         \"just \"\n"
19186       "         \"world, \"\n"
19187       "         \"ought to \"\n"
19188       "         \"be split \"\n"
19189       "         \"over \"\n"
19190       "         \"multiple \"\n"
19191       "         \"lines\"},\n"
19192       "    test{-1, 93463,\n"
19193       "         \"world\"},\n"
19194       "    test{ 7,     5,\n"
19195       "         \"!!\"   },\n"
19196       "};",
19197       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19198              "i am a very long line that really, in any just world, ought "
19199              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19200              "test{7, 5, \"!!\"},};",
19201              Style));
19202   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19203   Style = getLLVMStyleWithColumns(50);
19204   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19205   verifyFormat("static A x = {\n"
19206                "    {{init1, init2, init3, init4},\n"
19207                "     {init1, init2, init3, init4}}\n"
19208                "};",
19209                Style);
19210   // TODO: Fix the indentations below when this option is fully functional.
19211   verifyFormat("int a[][] = {\n"
19212                "    {\n"
19213                "     {0, 2}, //\n"
19214                " {1, 2}  //\n"
19215                "    }\n"
19216                "};",
19217                Style);
19218   Style.ColumnLimit = 100;
19219   EXPECT_EQ(
19220       "test demo[] = {\n"
19221       "    {56,    23,\n"
19222       "     \"hello world i am a very long line that really, in any just world"
19223       ", ought to be split over \"\n"
19224       "     \"multiple lines\"  },\n"
19225       "    {-1, 93463, \"world\"},\n"
19226       "    { 7,     5,    \"!!\"},\n"
19227       "};",
19228       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19229              "that really, in any just world, ought to be split over multiple "
19230              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19231              Style));
19232 
19233   Style = getLLVMStyleWithColumns(50);
19234   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19235   verifyFormat("struct test demo[] = {\n"
19236                "    {56,    23, \"hello\"},\n"
19237                "    {-1, 93463, \"world\"},\n"
19238                "    { 7,     5,    \"!!\"}\n"
19239                "};\n"
19240                "static A x = {\n"
19241                "    {{init1, init2, init3, init4},\n"
19242                "     {init1, init2, init3, init4}}\n"
19243                "};",
19244                Style);
19245   Style.ColumnLimit = 100;
19246   Style.AlignConsecutiveAssignments.AcrossComments = true;
19247   Style.AlignConsecutiveDeclarations.AcrossComments = true;
19248   verifyFormat("struct test demo[] = {\n"
19249                "    {56,    23, \"hello\"},\n"
19250                "    {-1, 93463, \"world\"},\n"
19251                "    { 7,     5,    \"!!\"}\n"
19252                "};\n"
19253                "struct test demo[4] = {\n"
19254                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19255                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19256                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19257                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19258                "};\n",
19259                Style);
19260   EXPECT_EQ(
19261       "test demo[] = {\n"
19262       "    {56,\n"
19263       "     \"hello world i am a very long line that really, in any just world"
19264       ", ought to be split over \"\n"
19265       "     \"multiple lines\",    23},\n"
19266       "    {-1,      \"world\", 93463},\n"
19267       "    { 7,         \"!!\",     5},\n"
19268       "};",
19269       format("test demo[] = {{56, \"hello world i am a very long line "
19270              "that really, in any just world, ought to be split over multiple "
19271              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
19272              Style));
19273 }
19274 
19275 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
19276   auto Style = getLLVMStyle();
19277   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19278   /* FIXME: This case gets misformatted.
19279   verifyFormat("auto foo = Items{\n"
19280                "    Section{0, bar(), },\n"
19281                "    Section{1, boo()  }\n"
19282                "};\n",
19283                Style);
19284   */
19285   verifyFormat("auto foo = Items{\n"
19286                "    Section{\n"
19287                "            0, bar(),\n"
19288                "            }\n"
19289                "};\n",
19290                Style);
19291   verifyFormat("struct test demo[] = {\n"
19292                "    {56, 23,    \"hello\"},\n"
19293                "    {-1, 93463, \"world\"},\n"
19294                "    {7,  5,     \"!!\"   }\n"
19295                "};\n",
19296                Style);
19297   verifyFormat("struct test demo[] = {\n"
19298                "    {56, 23,    \"hello\"}, // first line\n"
19299                "    {-1, 93463, \"world\"}, // second line\n"
19300                "    {7,  5,     \"!!\"   }  // third line\n"
19301                "};\n",
19302                Style);
19303   verifyFormat("struct test demo[4] = {\n"
19304                "    {56,  23,    21, \"oh\"      }, // first line\n"
19305                "    {-1,  93463, 22, \"my\"      }, // second line\n"
19306                "    {7,   5,     1,  \"goodness\"}  // third line\n"
19307                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
19308                "};\n",
19309                Style);
19310   verifyFormat("struct test demo[3] = {\n"
19311                "    {56, 23,    \"hello\"},\n"
19312                "    {-1, 93463, \"world\"},\n"
19313                "    {7,  5,     \"!!\"   }\n"
19314                "};\n",
19315                Style);
19316 
19317   verifyFormat("struct test demo[3] = {\n"
19318                "    {int{56}, 23,    \"hello\"},\n"
19319                "    {int{-1}, 93463, \"world\"},\n"
19320                "    {int{7},  5,     \"!!\"   }\n"
19321                "};\n",
19322                Style);
19323   verifyFormat("struct test demo[] = {\n"
19324                "    {56, 23,    \"hello\"},\n"
19325                "    {-1, 93463, \"world\"},\n"
19326                "    {7,  5,     \"!!\"   },\n"
19327                "};\n",
19328                Style);
19329   verifyFormat("test demo[] = {\n"
19330                "    {56, 23,    \"hello\"},\n"
19331                "    {-1, 93463, \"world\"},\n"
19332                "    {7,  5,     \"!!\"   },\n"
19333                "};\n",
19334                Style);
19335   verifyFormat("demo = std::array<struct test, 3>{\n"
19336                "    test{56, 23,    \"hello\"},\n"
19337                "    test{-1, 93463, \"world\"},\n"
19338                "    test{7,  5,     \"!!\"   },\n"
19339                "};\n",
19340                Style);
19341   verifyFormat("test demo[] = {\n"
19342                "    {56, 23,    \"hello\"},\n"
19343                "#if X\n"
19344                "    {-1, 93463, \"world\"},\n"
19345                "#endif\n"
19346                "    {7,  5,     \"!!\"   }\n"
19347                "};\n",
19348                Style);
19349   verifyFormat(
19350       "test demo[] = {\n"
19351       "    {7,  23,\n"
19352       "     \"hello world i am a very long line that really, in any\"\n"
19353       "     \"just world, ought to be split over multiple lines\"},\n"
19354       "    {-1, 93463, \"world\"                                 },\n"
19355       "    {56, 5,     \"!!\"                                    }\n"
19356       "};\n",
19357       Style);
19358 
19359   verifyFormat("return GradForUnaryCwise(g, {\n"
19360                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19361                "\"dy\"}   },\n"
19362                "                                {{\"dx\"},   \"Mul\",  "
19363                "{\"dy\", \"sign\"}},\n"
19364                "});\n",
19365                Style);
19366 
19367   Style.ColumnLimit = 0;
19368   EXPECT_EQ(
19369       "test demo[] = {\n"
19370       "    {56, 23,    \"hello world i am a very long line that really, in any "
19371       "just world, ought to be split over multiple lines\"},\n"
19372       "    {-1, 93463, \"world\"                                               "
19373       "                                                   },\n"
19374       "    {7,  5,     \"!!\"                                                  "
19375       "                                                   },\n"
19376       "};",
19377       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19378              "that really, in any just world, ought to be split over multiple "
19379              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19380              Style));
19381 
19382   Style.ColumnLimit = 80;
19383   verifyFormat("test demo[] = {\n"
19384                "    {56, 23,    /* a comment */ \"hello\"},\n"
19385                "    {-1, 93463, \"world\"                },\n"
19386                "    {7,  5,     \"!!\"                   }\n"
19387                "};\n",
19388                Style);
19389 
19390   verifyFormat("test demo[] = {\n"
19391                "    {56, 23,    \"hello\"                   },\n"
19392                "    {-1, 93463, \"world\" /* comment here */},\n"
19393                "    {7,  5,     \"!!\"                      }\n"
19394                "};\n",
19395                Style);
19396 
19397   verifyFormat("test demo[] = {\n"
19398                "    {56, /* a comment */ 23, \"hello\"},\n"
19399                "    {-1, 93463,              \"world\"},\n"
19400                "    {7,  5,                  \"!!\"   }\n"
19401                "};\n",
19402                Style);
19403 
19404   Style.ColumnLimit = 20;
19405   EXPECT_EQ(
19406       "demo = std::array<\n"
19407       "    struct test, 3>{\n"
19408       "    test{\n"
19409       "         56, 23,\n"
19410       "         \"hello \"\n"
19411       "         \"world i \"\n"
19412       "         \"am a very \"\n"
19413       "         \"long line \"\n"
19414       "         \"that \"\n"
19415       "         \"really, \"\n"
19416       "         \"in any \"\n"
19417       "         \"just \"\n"
19418       "         \"world, \"\n"
19419       "         \"ought to \"\n"
19420       "         \"be split \"\n"
19421       "         \"over \"\n"
19422       "         \"multiple \"\n"
19423       "         \"lines\"},\n"
19424       "    test{-1, 93463,\n"
19425       "         \"world\"},\n"
19426       "    test{7,  5,\n"
19427       "         \"!!\"   },\n"
19428       "};",
19429       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19430              "i am a very long line that really, in any just world, ought "
19431              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19432              "test{7, 5, \"!!\"},};",
19433              Style));
19434 
19435   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19436   Style = getLLVMStyleWithColumns(50);
19437   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19438   verifyFormat("static A x = {\n"
19439                "    {{init1, init2, init3, init4},\n"
19440                "     {init1, init2, init3, init4}}\n"
19441                "};",
19442                Style);
19443   Style.ColumnLimit = 100;
19444   EXPECT_EQ(
19445       "test demo[] = {\n"
19446       "    {56, 23,\n"
19447       "     \"hello world i am a very long line that really, in any just world"
19448       ", ought to be split over \"\n"
19449       "     \"multiple lines\"  },\n"
19450       "    {-1, 93463, \"world\"},\n"
19451       "    {7,  5,     \"!!\"   },\n"
19452       "};",
19453       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19454              "that really, in any just world, ought to be split over multiple "
19455              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19456              Style));
19457 }
19458 
19459 TEST_F(FormatTest, UnderstandsPragmas) {
19460   verifyFormat("#pragma omp reduction(| : var)");
19461   verifyFormat("#pragma omp reduction(+ : var)");
19462 
19463   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19464             "(including parentheses).",
19465             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19466                    "(including parentheses)."));
19467 }
19468 
19469 TEST_F(FormatTest, UnderstandPragmaOption) {
19470   verifyFormat("#pragma option -C -A");
19471 
19472   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19473 }
19474 
19475 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19476   FormatStyle Style = getLLVMStyleWithColumns(20);
19477 
19478   // See PR41213
19479   EXPECT_EQ("/*\n"
19480             " *\t9012345\n"
19481             " * /8901\n"
19482             " */",
19483             format("/*\n"
19484                    " *\t9012345 /8901\n"
19485                    " */",
19486                    Style));
19487   EXPECT_EQ("/*\n"
19488             " *345678\n"
19489             " *\t/8901\n"
19490             " */",
19491             format("/*\n"
19492                    " *345678\t/8901\n"
19493                    " */",
19494                    Style));
19495 
19496   verifyFormat("int a; // the\n"
19497                "       // comment",
19498                Style);
19499   EXPECT_EQ("int a; /* first line\n"
19500             "        * second\n"
19501             "        * line third\n"
19502             "        * line\n"
19503             "        */",
19504             format("int a; /* first line\n"
19505                    "        * second\n"
19506                    "        * line third\n"
19507                    "        * line\n"
19508                    "        */",
19509                    Style));
19510   EXPECT_EQ("int a; // first line\n"
19511             "       // second\n"
19512             "       // line third\n"
19513             "       // line",
19514             format("int a; // first line\n"
19515                    "       // second line\n"
19516                    "       // third line",
19517                    Style));
19518 
19519   Style.PenaltyExcessCharacter = 90;
19520   verifyFormat("int a; // the comment", Style);
19521   EXPECT_EQ("int a; // the comment\n"
19522             "       // aaa",
19523             format("int a; // the comment aaa", Style));
19524   EXPECT_EQ("int a; /* first line\n"
19525             "        * second line\n"
19526             "        * third line\n"
19527             "        */",
19528             format("int a; /* first line\n"
19529                    "        * second line\n"
19530                    "        * third line\n"
19531                    "        */",
19532                    Style));
19533   EXPECT_EQ("int a; // first line\n"
19534             "       // second line\n"
19535             "       // third line",
19536             format("int a; // first line\n"
19537                    "       // second line\n"
19538                    "       // third line",
19539                    Style));
19540   // FIXME: Investigate why this is not getting the same layout as the test
19541   // above.
19542   EXPECT_EQ("int a; /* first line\n"
19543             "        * second line\n"
19544             "        * third line\n"
19545             "        */",
19546             format("int a; /* first line second line third line"
19547                    "\n*/",
19548                    Style));
19549 
19550   EXPECT_EQ("// foo bar baz bazfoo\n"
19551             "// foo bar foo bar\n",
19552             format("// foo bar baz bazfoo\n"
19553                    "// foo bar foo           bar\n",
19554                    Style));
19555   EXPECT_EQ("// foo bar baz bazfoo\n"
19556             "// foo bar foo bar\n",
19557             format("// foo bar baz      bazfoo\n"
19558                    "// foo            bar foo bar\n",
19559                    Style));
19560 
19561   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19562   // next one.
19563   EXPECT_EQ("// foo bar baz bazfoo\n"
19564             "// bar foo bar\n",
19565             format("// foo bar baz      bazfoo bar\n"
19566                    "// foo            bar\n",
19567                    Style));
19568 
19569   EXPECT_EQ("// foo bar baz bazfoo\n"
19570             "// foo bar baz bazfoo\n"
19571             "// bar foo bar\n",
19572             format("// foo bar baz      bazfoo\n"
19573                    "// foo bar baz      bazfoo bar\n"
19574                    "// foo bar\n",
19575                    Style));
19576 
19577   EXPECT_EQ("// foo bar baz bazfoo\n"
19578             "// foo bar baz bazfoo\n"
19579             "// bar foo bar\n",
19580             format("// foo bar baz      bazfoo\n"
19581                    "// foo bar baz      bazfoo bar\n"
19582                    "// foo           bar\n",
19583                    Style));
19584 
19585   // Make sure we do not keep protruding characters if strict mode reflow is
19586   // cheaper than keeping protruding characters.
19587   Style.ColumnLimit = 21;
19588   EXPECT_EQ(
19589       "// foo foo foo foo\n"
19590       "// foo foo foo foo\n"
19591       "// foo foo foo foo\n",
19592       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19593 
19594   EXPECT_EQ("int a = /* long block\n"
19595             "           comment */\n"
19596             "    42;",
19597             format("int a = /* long block comment */ 42;", Style));
19598 }
19599 
19600 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19601   FormatStyle Style = getLLVMStyle();
19602   Style.ColumnLimit = 8;
19603   Style.PenaltyExcessCharacter = 15;
19604   verifyFormat("int foo(\n"
19605                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19606                Style);
19607   Style.PenaltyBreakOpenParenthesis = 200;
19608   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19609             format("int foo(\n"
19610                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19611                    Style));
19612 }
19613 
19614 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19615   FormatStyle Style = getLLVMStyle();
19616   Style.ColumnLimit = 5;
19617   Style.PenaltyExcessCharacter = 150;
19618   verifyFormat("foo((\n"
19619                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19620 
19621                Style);
19622   Style.PenaltyBreakOpenParenthesis = 100000;
19623   EXPECT_EQ("foo((int)\n"
19624             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19625             format("foo((\n"
19626                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19627                    Style));
19628 }
19629 
19630 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19631   FormatStyle Style = getLLVMStyle();
19632   Style.ColumnLimit = 4;
19633   Style.PenaltyExcessCharacter = 100;
19634   verifyFormat("for (\n"
19635                "    int iiiiiiiiiiiiiiiii =\n"
19636                "        0;\n"
19637                "    iiiiiiiiiiiiiiiii <\n"
19638                "    2;\n"
19639                "    iiiiiiiiiiiiiiiii++) {\n"
19640                "}",
19641 
19642                Style);
19643   Style.PenaltyBreakOpenParenthesis = 1250;
19644   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19645             "         0;\n"
19646             "     iiiiiiiiiiiiiiiii <\n"
19647             "     2;\n"
19648             "     iiiiiiiiiiiiiiiii++) {\n"
19649             "}",
19650             format("for (\n"
19651                    "    int iiiiiiiiiiiiiiiii =\n"
19652                    "        0;\n"
19653                    "    iiiiiiiiiiiiiiiii <\n"
19654                    "    2;\n"
19655                    "    iiiiiiiiiiiiiiiii++) {\n"
19656                    "}",
19657                    Style));
19658 }
19659 
19660 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19661   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19662   EXPECT_EQ(Styles[0], Styles[i])                                              \
19663       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19664 
19665 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19666   SmallVector<FormatStyle, 3> Styles;
19667   Styles.resize(3);
19668 
19669   Styles[0] = getLLVMStyle();
19670   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19671   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19672   EXPECT_ALL_STYLES_EQUAL(Styles);
19673 
19674   Styles[0] = getGoogleStyle();
19675   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19676   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19677   EXPECT_ALL_STYLES_EQUAL(Styles);
19678 
19679   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19680   EXPECT_TRUE(
19681       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19682   EXPECT_TRUE(
19683       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19684   EXPECT_ALL_STYLES_EQUAL(Styles);
19685 
19686   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19687   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19688   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19689   EXPECT_ALL_STYLES_EQUAL(Styles);
19690 
19691   Styles[0] = getMozillaStyle();
19692   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19693   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19694   EXPECT_ALL_STYLES_EQUAL(Styles);
19695 
19696   Styles[0] = getWebKitStyle();
19697   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19698   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19699   EXPECT_ALL_STYLES_EQUAL(Styles);
19700 
19701   Styles[0] = getGNUStyle();
19702   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19703   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19704   EXPECT_ALL_STYLES_EQUAL(Styles);
19705 
19706   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19707 }
19708 
19709 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19710   SmallVector<FormatStyle, 8> Styles;
19711   Styles.resize(2);
19712 
19713   Styles[0] = getGoogleStyle();
19714   Styles[1] = getLLVMStyle();
19715   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19716   EXPECT_ALL_STYLES_EQUAL(Styles);
19717 
19718   Styles.resize(5);
19719   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19720   Styles[1] = getLLVMStyle();
19721   Styles[1].Language = FormatStyle::LK_JavaScript;
19722   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19723 
19724   Styles[2] = getLLVMStyle();
19725   Styles[2].Language = FormatStyle::LK_JavaScript;
19726   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19727                                   "BasedOnStyle: Google",
19728                                   &Styles[2])
19729                    .value());
19730 
19731   Styles[3] = getLLVMStyle();
19732   Styles[3].Language = FormatStyle::LK_JavaScript;
19733   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19734                                   "Language: JavaScript",
19735                                   &Styles[3])
19736                    .value());
19737 
19738   Styles[4] = getLLVMStyle();
19739   Styles[4].Language = FormatStyle::LK_JavaScript;
19740   EXPECT_EQ(0, parseConfiguration("---\n"
19741                                   "BasedOnStyle: LLVM\n"
19742                                   "IndentWidth: 123\n"
19743                                   "---\n"
19744                                   "BasedOnStyle: Google\n"
19745                                   "Language: JavaScript",
19746                                   &Styles[4])
19747                    .value());
19748   EXPECT_ALL_STYLES_EQUAL(Styles);
19749 }
19750 
19751 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
19752   Style.FIELD = false;                                                         \
19753   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
19754   EXPECT_TRUE(Style.FIELD);                                                    \
19755   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
19756   EXPECT_FALSE(Style.FIELD);
19757 
19758 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
19759 
19760 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
19761   Style.STRUCT.FIELD = false;                                                  \
19762   EXPECT_EQ(0,                                                                 \
19763             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
19764                 .value());                                                     \
19765   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
19766   EXPECT_EQ(0,                                                                 \
19767             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
19768                 .value());                                                     \
19769   EXPECT_FALSE(Style.STRUCT.FIELD);
19770 
19771 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
19772   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
19773 
19774 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
19775   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
19776   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
19777   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
19778 
19779 TEST_F(FormatTest, ParsesConfigurationBools) {
19780   FormatStyle Style = {};
19781   Style.Language = FormatStyle::LK_Cpp;
19782   CHECK_PARSE_BOOL(AlignTrailingComments);
19783   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
19784   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
19785   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
19786   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
19787   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
19788   CHECK_PARSE_BOOL(BinPackArguments);
19789   CHECK_PARSE_BOOL(BinPackParameters);
19790   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
19791   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
19792   CHECK_PARSE_BOOL(BreakStringLiterals);
19793   CHECK_PARSE_BOOL(CompactNamespaces);
19794   CHECK_PARSE_BOOL(DeriveLineEnding);
19795   CHECK_PARSE_BOOL(DerivePointerAlignment);
19796   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
19797   CHECK_PARSE_BOOL(DisableFormat);
19798   CHECK_PARSE_BOOL(IndentAccessModifiers);
19799   CHECK_PARSE_BOOL(IndentCaseLabels);
19800   CHECK_PARSE_BOOL(IndentCaseBlocks);
19801   CHECK_PARSE_BOOL(IndentGotoLabels);
19802   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
19803   CHECK_PARSE_BOOL(IndentRequiresClause);
19804   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
19805   CHECK_PARSE_BOOL(InsertBraces);
19806   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
19807   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
19808   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
19809   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
19810   CHECK_PARSE_BOOL(ReflowComments);
19811   CHECK_PARSE_BOOL(RemoveBracesLLVM);
19812   CHECK_PARSE_BOOL(SortUsingDeclarations);
19813   CHECK_PARSE_BOOL(SpacesInParentheses);
19814   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
19815   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
19816   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
19817   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
19818   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
19819   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
19820   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
19821   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
19822   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
19823   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
19824   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
19825   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
19826   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
19827   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
19828   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
19829   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
19830   CHECK_PARSE_BOOL(UseCRLF);
19831 
19832   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
19833   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
19834   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
19835   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
19836   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
19837   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
19838   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
19839   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
19840   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
19841   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
19842   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
19843   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
19844   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
19845   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
19846   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
19847   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
19848   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
19849   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
19850   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
19851   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19852                           AfterFunctionDeclarationName);
19853   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19854                           AfterFunctionDefinitionName);
19855   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
19856   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
19857   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
19858 }
19859 
19860 #undef CHECK_PARSE_BOOL
19861 
19862 TEST_F(FormatTest, ParsesConfiguration) {
19863   FormatStyle Style = {};
19864   Style.Language = FormatStyle::LK_Cpp;
19865   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
19866   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
19867               ConstructorInitializerIndentWidth, 1234u);
19868   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
19869   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
19870   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
19871   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
19872   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
19873               PenaltyBreakBeforeFirstCallParameter, 1234u);
19874   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
19875               PenaltyBreakTemplateDeclaration, 1234u);
19876   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
19877               1234u);
19878   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
19879   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
19880               PenaltyReturnTypeOnItsOwnLine, 1234u);
19881   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
19882               SpacesBeforeTrailingComments, 1234u);
19883   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
19884   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
19885   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
19886 
19887   Style.QualifierAlignment = FormatStyle::QAS_Right;
19888   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
19889               FormatStyle::QAS_Leave);
19890   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
19891               FormatStyle::QAS_Right);
19892   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
19893               FormatStyle::QAS_Left);
19894   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
19895               FormatStyle::QAS_Custom);
19896 
19897   Style.QualifierOrder.clear();
19898   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
19899               std::vector<std::string>({"const", "volatile", "type"}));
19900   Style.QualifierOrder.clear();
19901   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
19902               std::vector<std::string>({"const", "type"}));
19903   Style.QualifierOrder.clear();
19904   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
19905               std::vector<std::string>({"volatile", "type"}));
19906 
19907 #define CHECK_ALIGN_CONSECUTIVE(FIELD)                                         \
19908   do {                                                                         \
19909     Style.FIELD.Enabled = true;                                                \
19910     CHECK_PARSE(#FIELD ": None", FIELD,                                        \
19911                 FormatStyle::AlignConsecutiveStyle(                            \
19912                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19913                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19914                      /*PadOperators=*/true}));                                 \
19915     CHECK_PARSE(#FIELD ": Consecutive", FIELD,                                 \
19916                 FormatStyle::AlignConsecutiveStyle(                            \
19917                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19918                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19919                      /*PadOperators=*/true}));                                 \
19920     CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD,                            \
19921                 FormatStyle::AlignConsecutiveStyle(                            \
19922                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19923                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19924                      /*PadOperators=*/true}));                                 \
19925     CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD,                 \
19926                 FormatStyle::AlignConsecutiveStyle(                            \
19927                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19928                      /*AcrossComments=*/true, /*AlignCompound=*/false,         \
19929                      /*PadOperators=*/true}));                                 \
19930     /* For backwards compability, false / true should still parse */           \
19931     CHECK_PARSE(#FIELD ": false", FIELD,                                       \
19932                 FormatStyle::AlignConsecutiveStyle(                            \
19933                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19934                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19935                      /*PadOperators=*/true}));                                 \
19936     CHECK_PARSE(#FIELD ": true", FIELD,                                        \
19937                 FormatStyle::AlignConsecutiveStyle(                            \
19938                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19939                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19940                      /*PadOperators=*/true}));                                 \
19941                                                                                \
19942     CHECK_PARSE_NESTED_BOOL(FIELD, Enabled);                                   \
19943     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines);                          \
19944     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments);                            \
19945     CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound);                             \
19946     CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators);                              \
19947   } while (false)
19948 
19949   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments);
19950   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields);
19951   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros);
19952   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations);
19953 
19954 #undef CHECK_ALIGN_CONSECUTIVE
19955 
19956   Style.PointerAlignment = FormatStyle::PAS_Middle;
19957   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
19958               FormatStyle::PAS_Left);
19959   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
19960               FormatStyle::PAS_Right);
19961   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
19962               FormatStyle::PAS_Middle);
19963   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
19964   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
19965               FormatStyle::RAS_Pointer);
19966   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
19967               FormatStyle::RAS_Left);
19968   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
19969               FormatStyle::RAS_Right);
19970   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
19971               FormatStyle::RAS_Middle);
19972   // For backward compatibility:
19973   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
19974               FormatStyle::PAS_Left);
19975   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
19976               FormatStyle::PAS_Right);
19977   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
19978               FormatStyle::PAS_Middle);
19979 
19980   Style.Standard = FormatStyle::LS_Auto;
19981   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
19982   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
19983   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
19984   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
19985   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
19986   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
19987   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
19988   // Legacy aliases:
19989   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
19990   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
19991   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
19992   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
19993 
19994   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
19995   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
19996               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
19997   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
19998               FormatStyle::BOS_None);
19999   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
20000               FormatStyle::BOS_All);
20001   // For backward compatibility:
20002   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
20003               FormatStyle::BOS_None);
20004   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
20005               FormatStyle::BOS_All);
20006 
20007   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
20008   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
20009               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20010   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
20011               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
20012   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
20013               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
20014   // For backward compatibility:
20015   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
20016               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20017 
20018   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
20019   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
20020               FormatStyle::BILS_AfterComma);
20021   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
20022               FormatStyle::BILS_BeforeComma);
20023   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
20024               FormatStyle::BILS_AfterColon);
20025   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
20026               FormatStyle::BILS_BeforeColon);
20027   // For backward compatibility:
20028   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
20029               FormatStyle::BILS_BeforeComma);
20030 
20031   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20032   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
20033               FormatStyle::PCIS_Never);
20034   CHECK_PARSE("PackConstructorInitializers: BinPack",
20035               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20036   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
20037               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20038   CHECK_PARSE("PackConstructorInitializers: NextLine",
20039               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20040   // For backward compatibility:
20041   CHECK_PARSE("BasedOnStyle: Google\n"
20042               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20043               "AllowAllConstructorInitializersOnNextLine: false",
20044               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20045   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20046   CHECK_PARSE("BasedOnStyle: Google\n"
20047               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
20048               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20049   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20050               "AllowAllConstructorInitializersOnNextLine: true",
20051               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20052   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20053   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20054               "AllowAllConstructorInitializersOnNextLine: false",
20055               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20056 
20057   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
20058   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
20059               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
20060   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
20061               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
20062   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
20063               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
20064   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
20065               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
20066 
20067   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20068   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
20069               FormatStyle::BAS_Align);
20070   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
20071               FormatStyle::BAS_DontAlign);
20072   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
20073               FormatStyle::BAS_AlwaysBreak);
20074   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
20075               FormatStyle::BAS_BlockIndent);
20076   // For backward compatibility:
20077   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
20078               FormatStyle::BAS_DontAlign);
20079   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
20080               FormatStyle::BAS_Align);
20081 
20082   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
20083   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
20084               FormatStyle::ENAS_DontAlign);
20085   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
20086               FormatStyle::ENAS_Left);
20087   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
20088               FormatStyle::ENAS_Right);
20089   // For backward compatibility:
20090   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
20091               FormatStyle::ENAS_Left);
20092   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
20093               FormatStyle::ENAS_Right);
20094 
20095   Style.AlignOperands = FormatStyle::OAS_Align;
20096   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
20097               FormatStyle::OAS_DontAlign);
20098   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
20099   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
20100               FormatStyle::OAS_AlignAfterOperator);
20101   // For backward compatibility:
20102   CHECK_PARSE("AlignOperands: false", AlignOperands,
20103               FormatStyle::OAS_DontAlign);
20104   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
20105 
20106   Style.UseTab = FormatStyle::UT_ForIndentation;
20107   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
20108   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
20109   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
20110   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
20111               FormatStyle::UT_ForContinuationAndIndentation);
20112   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
20113               FormatStyle::UT_AlignWithSpaces);
20114   // For backward compatibility:
20115   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
20116   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
20117 
20118   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
20119   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
20120               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20121   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
20122               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
20123   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
20124               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20125   // For backward compatibility:
20126   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
20127               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20128   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
20129               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20130 
20131   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
20132   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
20133               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20134   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
20135               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
20136   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
20137               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
20138   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
20139               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20140   // For backward compatibility:
20141   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
20142               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20143   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
20144               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20145 
20146   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
20147   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
20148               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
20149   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
20150               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
20151   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
20152               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
20153   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
20154               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
20155 
20156   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
20157   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
20158               FormatStyle::SBPO_Never);
20159   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
20160               FormatStyle::SBPO_Always);
20161   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
20162               FormatStyle::SBPO_ControlStatements);
20163   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
20164               SpaceBeforeParens,
20165               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20166   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
20167               FormatStyle::SBPO_NonEmptyParentheses);
20168   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
20169               FormatStyle::SBPO_Custom);
20170   // For backward compatibility:
20171   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
20172               FormatStyle::SBPO_Never);
20173   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
20174               FormatStyle::SBPO_ControlStatements);
20175   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
20176               SpaceBeforeParens,
20177               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20178 
20179   Style.ColumnLimit = 123;
20180   FormatStyle BaseStyle = getLLVMStyle();
20181   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
20182   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
20183 
20184   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
20185   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
20186               FormatStyle::BS_Attach);
20187   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
20188               FormatStyle::BS_Linux);
20189   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
20190               FormatStyle::BS_Mozilla);
20191   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
20192               FormatStyle::BS_Stroustrup);
20193   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
20194               FormatStyle::BS_Allman);
20195   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
20196               FormatStyle::BS_Whitesmiths);
20197   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
20198   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
20199               FormatStyle::BS_WebKit);
20200   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
20201               FormatStyle::BS_Custom);
20202 
20203   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
20204   CHECK_PARSE("BraceWrapping:\n"
20205               "  AfterControlStatement: MultiLine",
20206               BraceWrapping.AfterControlStatement,
20207               FormatStyle::BWACS_MultiLine);
20208   CHECK_PARSE("BraceWrapping:\n"
20209               "  AfterControlStatement: Always",
20210               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20211   CHECK_PARSE("BraceWrapping:\n"
20212               "  AfterControlStatement: Never",
20213               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20214   // For backward compatibility:
20215   CHECK_PARSE("BraceWrapping:\n"
20216               "  AfterControlStatement: true",
20217               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20218   CHECK_PARSE("BraceWrapping:\n"
20219               "  AfterControlStatement: false",
20220               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20221 
20222   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
20223   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
20224               FormatStyle::RTBS_None);
20225   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
20226               FormatStyle::RTBS_All);
20227   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
20228               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
20229   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
20230               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
20231   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
20232               AlwaysBreakAfterReturnType,
20233               FormatStyle::RTBS_TopLevelDefinitions);
20234 
20235   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
20236   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
20237               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
20238   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
20239               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20240   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
20241               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20242   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
20243               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20244   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
20245               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20246 
20247   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
20248   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
20249               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
20250   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
20251               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
20252   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
20253               AlwaysBreakAfterDefinitionReturnType,
20254               FormatStyle::DRTBS_TopLevel);
20255 
20256   Style.NamespaceIndentation = FormatStyle::NI_All;
20257   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
20258               FormatStyle::NI_None);
20259   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
20260               FormatStyle::NI_Inner);
20261   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
20262               FormatStyle::NI_All);
20263 
20264   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
20265   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
20266               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20267   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
20268               AllowShortIfStatementsOnASingleLine,
20269               FormatStyle::SIS_WithoutElse);
20270   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
20271               AllowShortIfStatementsOnASingleLine,
20272               FormatStyle::SIS_OnlyFirstIf);
20273   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
20274               AllowShortIfStatementsOnASingleLine,
20275               FormatStyle::SIS_AllIfsAndElse);
20276   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
20277               AllowShortIfStatementsOnASingleLine,
20278               FormatStyle::SIS_OnlyFirstIf);
20279   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
20280               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20281   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
20282               AllowShortIfStatementsOnASingleLine,
20283               FormatStyle::SIS_WithoutElse);
20284 
20285   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
20286   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
20287               FormatStyle::IEBS_AfterExternBlock);
20288   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
20289               FormatStyle::IEBS_Indent);
20290   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
20291               FormatStyle::IEBS_NoIndent);
20292   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
20293               FormatStyle::IEBS_Indent);
20294   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
20295               FormatStyle::IEBS_NoIndent);
20296 
20297   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
20298   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
20299               FormatStyle::BFCS_Both);
20300   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
20301               FormatStyle::BFCS_None);
20302   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
20303               FormatStyle::BFCS_Before);
20304   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
20305               FormatStyle::BFCS_After);
20306 
20307   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
20308   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
20309               FormatStyle::SJSIO_After);
20310   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
20311               FormatStyle::SJSIO_Before);
20312 
20313   // FIXME: This is required because parsing a configuration simply overwrites
20314   // the first N elements of the list instead of resetting it.
20315   Style.ForEachMacros.clear();
20316   std::vector<std::string> BoostForeach;
20317   BoostForeach.push_back("BOOST_FOREACH");
20318   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20319   std::vector<std::string> BoostAndQForeach;
20320   BoostAndQForeach.push_back("BOOST_FOREACH");
20321   BoostAndQForeach.push_back("Q_FOREACH");
20322   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20323               BoostAndQForeach);
20324 
20325   Style.IfMacros.clear();
20326   std::vector<std::string> CustomIfs;
20327   CustomIfs.push_back("MYIF");
20328   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20329 
20330   Style.AttributeMacros.clear();
20331   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20332               std::vector<std::string>{"__capability"});
20333   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20334               std::vector<std::string>({"attr1", "attr2"}));
20335 
20336   Style.StatementAttributeLikeMacros.clear();
20337   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20338               StatementAttributeLikeMacros,
20339               std::vector<std::string>({"emit", "Q_EMIT"}));
20340 
20341   Style.StatementMacros.clear();
20342   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20343               std::vector<std::string>{"QUNUSED"});
20344   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20345               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20346 
20347   Style.NamespaceMacros.clear();
20348   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20349               std::vector<std::string>{"TESTSUITE"});
20350   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20351               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20352 
20353   Style.WhitespaceSensitiveMacros.clear();
20354   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20355               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20356   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20357               WhitespaceSensitiveMacros,
20358               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20359   Style.WhitespaceSensitiveMacros.clear();
20360   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
20361               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20362   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
20363               WhitespaceSensitiveMacros,
20364               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20365 
20366   Style.IncludeStyle.IncludeCategories.clear();
20367   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20368       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20369   CHECK_PARSE("IncludeCategories:\n"
20370               "  - Regex: abc/.*\n"
20371               "    Priority: 2\n"
20372               "  - Regex: .*\n"
20373               "    Priority: 1\n"
20374               "    CaseSensitive: true\n",
20375               IncludeStyle.IncludeCategories, ExpectedCategories);
20376   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20377               "abc$");
20378   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20379               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20380 
20381   Style.SortIncludes = FormatStyle::SI_Never;
20382   CHECK_PARSE("SortIncludes: true", SortIncludes,
20383               FormatStyle::SI_CaseSensitive);
20384   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20385   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20386               FormatStyle::SI_CaseInsensitive);
20387   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20388               FormatStyle::SI_CaseSensitive);
20389   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20390 
20391   Style.RawStringFormats.clear();
20392   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20393       {
20394           FormatStyle::LK_TextProto,
20395           {"pb", "proto"},
20396           {"PARSE_TEXT_PROTO"},
20397           /*CanonicalDelimiter=*/"",
20398           "llvm",
20399       },
20400       {
20401           FormatStyle::LK_Cpp,
20402           {"cc", "cpp"},
20403           {"C_CODEBLOCK", "CPPEVAL"},
20404           /*CanonicalDelimiter=*/"cc",
20405           /*BasedOnStyle=*/"",
20406       },
20407   };
20408 
20409   CHECK_PARSE("RawStringFormats:\n"
20410               "  - Language: TextProto\n"
20411               "    Delimiters:\n"
20412               "      - 'pb'\n"
20413               "      - 'proto'\n"
20414               "    EnclosingFunctions:\n"
20415               "      - 'PARSE_TEXT_PROTO'\n"
20416               "    BasedOnStyle: llvm\n"
20417               "  - Language: Cpp\n"
20418               "    Delimiters:\n"
20419               "      - 'cc'\n"
20420               "      - 'cpp'\n"
20421               "    EnclosingFunctions:\n"
20422               "      - 'C_CODEBLOCK'\n"
20423               "      - 'CPPEVAL'\n"
20424               "    CanonicalDelimiter: 'cc'",
20425               RawStringFormats, ExpectedRawStringFormats);
20426 
20427   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20428               "  Minimum: 0\n"
20429               "  Maximum: 0",
20430               SpacesInLineCommentPrefix.Minimum, 0u);
20431   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20432   Style.SpacesInLineCommentPrefix.Minimum = 1;
20433   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20434               "  Minimum: 2",
20435               SpacesInLineCommentPrefix.Minimum, 0u);
20436   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20437               "  Maximum: -1",
20438               SpacesInLineCommentPrefix.Maximum, -1u);
20439   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20440               "  Minimum: 2",
20441               SpacesInLineCommentPrefix.Minimum, 2u);
20442   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20443               "  Maximum: 1",
20444               SpacesInLineCommentPrefix.Maximum, 1u);
20445   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20446 
20447   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20448   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20449   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20450               FormatStyle::SIAS_Always);
20451   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20452   // For backward compatibility:
20453   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20454   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20455 
20456   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20457               FormatStyle::RCPS_WithPreceding);
20458   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20459               FormatStyle::RCPS_WithFollowing);
20460   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20461               FormatStyle::RCPS_SingleLine);
20462   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20463               FormatStyle::RCPS_OwnLine);
20464 
20465   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20466               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20467   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20468               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20469   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20470               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20471   // For backward compatibility:
20472   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20473               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20474   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20475               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20476 }
20477 
20478 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20479   FormatStyle Style = {};
20480   Style.Language = FormatStyle::LK_Cpp;
20481   CHECK_PARSE("Language: Cpp\n"
20482               "IndentWidth: 12",
20483               IndentWidth, 12u);
20484   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20485                                "IndentWidth: 34",
20486                                &Style),
20487             ParseError::Unsuitable);
20488   FormatStyle BinPackedTCS = {};
20489   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20490   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20491                                "InsertTrailingCommas: Wrapped",
20492                                &BinPackedTCS),
20493             ParseError::BinPackTrailingCommaConflict);
20494   EXPECT_EQ(12u, Style.IndentWidth);
20495   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20496   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20497 
20498   Style.Language = FormatStyle::LK_JavaScript;
20499   CHECK_PARSE("Language: JavaScript\n"
20500               "IndentWidth: 12",
20501               IndentWidth, 12u);
20502   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20503   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20504                                "IndentWidth: 34",
20505                                &Style),
20506             ParseError::Unsuitable);
20507   EXPECT_EQ(23u, Style.IndentWidth);
20508   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20509   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20510 
20511   CHECK_PARSE("BasedOnStyle: LLVM\n"
20512               "IndentWidth: 67",
20513               IndentWidth, 67u);
20514 
20515   CHECK_PARSE("---\n"
20516               "Language: JavaScript\n"
20517               "IndentWidth: 12\n"
20518               "---\n"
20519               "Language: Cpp\n"
20520               "IndentWidth: 34\n"
20521               "...\n",
20522               IndentWidth, 12u);
20523 
20524   Style.Language = FormatStyle::LK_Cpp;
20525   CHECK_PARSE("---\n"
20526               "Language: JavaScript\n"
20527               "IndentWidth: 12\n"
20528               "---\n"
20529               "Language: Cpp\n"
20530               "IndentWidth: 34\n"
20531               "...\n",
20532               IndentWidth, 34u);
20533   CHECK_PARSE("---\n"
20534               "IndentWidth: 78\n"
20535               "---\n"
20536               "Language: JavaScript\n"
20537               "IndentWidth: 56\n"
20538               "...\n",
20539               IndentWidth, 78u);
20540 
20541   Style.ColumnLimit = 123;
20542   Style.IndentWidth = 234;
20543   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20544   Style.TabWidth = 345;
20545   EXPECT_FALSE(parseConfiguration("---\n"
20546                                   "IndentWidth: 456\n"
20547                                   "BreakBeforeBraces: Allman\n"
20548                                   "---\n"
20549                                   "Language: JavaScript\n"
20550                                   "IndentWidth: 111\n"
20551                                   "TabWidth: 111\n"
20552                                   "---\n"
20553                                   "Language: Cpp\n"
20554                                   "BreakBeforeBraces: Stroustrup\n"
20555                                   "TabWidth: 789\n"
20556                                   "...\n",
20557                                   &Style));
20558   EXPECT_EQ(123u, Style.ColumnLimit);
20559   EXPECT_EQ(456u, Style.IndentWidth);
20560   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20561   EXPECT_EQ(789u, Style.TabWidth);
20562 
20563   EXPECT_EQ(parseConfiguration("---\n"
20564                                "Language: JavaScript\n"
20565                                "IndentWidth: 56\n"
20566                                "---\n"
20567                                "IndentWidth: 78\n"
20568                                "...\n",
20569                                &Style),
20570             ParseError::Error);
20571   EXPECT_EQ(parseConfiguration("---\n"
20572                                "Language: JavaScript\n"
20573                                "IndentWidth: 56\n"
20574                                "---\n"
20575                                "Language: JavaScript\n"
20576                                "IndentWidth: 78\n"
20577                                "...\n",
20578                                &Style),
20579             ParseError::Error);
20580 
20581   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20582 }
20583 
20584 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20585   FormatStyle Style = {};
20586   Style.Language = FormatStyle::LK_JavaScript;
20587   Style.BreakBeforeTernaryOperators = true;
20588   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20589   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20590 
20591   Style.BreakBeforeTernaryOperators = true;
20592   EXPECT_EQ(0, parseConfiguration("---\n"
20593                                   "BasedOnStyle: Google\n"
20594                                   "---\n"
20595                                   "Language: JavaScript\n"
20596                                   "IndentWidth: 76\n"
20597                                   "...\n",
20598                                   &Style)
20599                    .value());
20600   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20601   EXPECT_EQ(76u, Style.IndentWidth);
20602   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20603 }
20604 
20605 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20606   FormatStyle Style = getLLVMStyle();
20607   std::string YAML = configurationAsText(Style);
20608   FormatStyle ParsedStyle = {};
20609   ParsedStyle.Language = FormatStyle::LK_Cpp;
20610   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20611   EXPECT_EQ(Style, ParsedStyle);
20612 }
20613 
20614 TEST_F(FormatTest, WorksFor8bitEncodings) {
20615   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20616             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20617             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20618             "\"\xef\xee\xf0\xf3...\"",
20619             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20620                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20621                    "\xef\xee\xf0\xf3...\"",
20622                    getLLVMStyleWithColumns(12)));
20623 }
20624 
20625 TEST_F(FormatTest, HandlesUTF8BOM) {
20626   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20627   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20628             format("\xef\xbb\xbf#include <iostream>"));
20629   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20630             format("\xef\xbb\xbf\n#include <iostream>"));
20631 }
20632 
20633 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20634 #if !defined(_MSC_VER)
20635 
20636 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20637   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20638                getLLVMStyleWithColumns(35));
20639   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20640                getLLVMStyleWithColumns(31));
20641   verifyFormat("// Однажды в студёную зимнюю пору...",
20642                getLLVMStyleWithColumns(36));
20643   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20644   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20645                getLLVMStyleWithColumns(39));
20646   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20647                getLLVMStyleWithColumns(35));
20648 }
20649 
20650 TEST_F(FormatTest, SplitsUTF8Strings) {
20651   // Non-printable characters' width is currently considered to be the length in
20652   // bytes in UTF8. The characters can be displayed in very different manner
20653   // (zero-width, single width with a substitution glyph, expanded to their code
20654   // (e.g. "<8d>"), so there's no single correct way to handle them.
20655   EXPECT_EQ("\"aaaaÄ\"\n"
20656             "\"\xc2\x8d\";",
20657             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20658   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20659             "\"\xc2\x8d\";",
20660             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20661   EXPECT_EQ("\"Однажды, в \"\n"
20662             "\"студёную \"\n"
20663             "\"зимнюю \"\n"
20664             "\"пору,\"",
20665             format("\"Однажды, в студёную зимнюю пору,\"",
20666                    getLLVMStyleWithColumns(13)));
20667   EXPECT_EQ(
20668       "\"一 二 三 \"\n"
20669       "\"四 五六 \"\n"
20670       "\"七 八 九 \"\n"
20671       "\"十\"",
20672       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20673   EXPECT_EQ("\"一\t\"\n"
20674             "\"二 \t\"\n"
20675             "\"三 四 \"\n"
20676             "\"五\t\"\n"
20677             "\"六 \t\"\n"
20678             "\"七 \"\n"
20679             "\"八九十\tqq\"",
20680             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20681                    getLLVMStyleWithColumns(11)));
20682 
20683   // UTF8 character in an escape sequence.
20684   EXPECT_EQ("\"aaaaaa\"\n"
20685             "\"\\\xC2\x8D\"",
20686             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20687 }
20688 
20689 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20690   EXPECT_EQ("const char *sssss =\n"
20691             "    \"一二三四五六七八\\\n"
20692             " 九 十\";",
20693             format("const char *sssss = \"一二三四五六七八\\\n"
20694                    " 九 十\";",
20695                    getLLVMStyleWithColumns(30)));
20696 }
20697 
20698 TEST_F(FormatTest, SplitsUTF8LineComments) {
20699   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20700             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20701   EXPECT_EQ("// Я из лесу\n"
20702             "// вышел; был\n"
20703             "// сильный\n"
20704             "// мороз.",
20705             format("// Я из лесу вышел; был сильный мороз.",
20706                    getLLVMStyleWithColumns(13)));
20707   EXPECT_EQ("// 一二三\n"
20708             "// 四五六七\n"
20709             "// 八  九\n"
20710             "// 十",
20711             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20712 }
20713 
20714 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20715   EXPECT_EQ("/* Гляжу,\n"
20716             " * поднимается\n"
20717             " * медленно в\n"
20718             " * гору\n"
20719             " * Лошадка,\n"
20720             " * везущая\n"
20721             " * хворосту\n"
20722             " * воз. */",
20723             format("/* Гляжу, поднимается медленно в гору\n"
20724                    " * Лошадка, везущая хворосту воз. */",
20725                    getLLVMStyleWithColumns(13)));
20726   EXPECT_EQ(
20727       "/* 一二三\n"
20728       " * 四五六七\n"
20729       " * 八  九\n"
20730       " * 十  */",
20731       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20732   EXPECT_EQ("/* �������� ��������\n"
20733             " * ��������\n"
20734             " * ������-�� */",
20735             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20736 }
20737 
20738 #endif // _MSC_VER
20739 
20740 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
20741   FormatStyle Style = getLLVMStyle();
20742 
20743   Style.ConstructorInitializerIndentWidth = 4;
20744   verifyFormat(
20745       "SomeClass::Constructor()\n"
20746       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20747       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20748       Style);
20749 
20750   Style.ConstructorInitializerIndentWidth = 2;
20751   verifyFormat(
20752       "SomeClass::Constructor()\n"
20753       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20754       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20755       Style);
20756 
20757   Style.ConstructorInitializerIndentWidth = 0;
20758   verifyFormat(
20759       "SomeClass::Constructor()\n"
20760       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20761       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20762       Style);
20763   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20764   verifyFormat(
20765       "SomeLongTemplateVariableName<\n"
20766       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
20767       Style);
20768   verifyFormat("bool smaller = 1 < "
20769                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
20770                "                       "
20771                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
20772                Style);
20773 
20774   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
20775   verifyFormat("SomeClass::Constructor() :\n"
20776                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
20777                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
20778                Style);
20779 }
20780 
20781 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
20782   FormatStyle Style = getLLVMStyle();
20783   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20784   Style.ConstructorInitializerIndentWidth = 4;
20785   verifyFormat("SomeClass::Constructor()\n"
20786                "    : a(a)\n"
20787                "    , b(b)\n"
20788                "    , c(c) {}",
20789                Style);
20790   verifyFormat("SomeClass::Constructor()\n"
20791                "    : a(a) {}",
20792                Style);
20793 
20794   Style.ColumnLimit = 0;
20795   verifyFormat("SomeClass::Constructor()\n"
20796                "    : a(a) {}",
20797                Style);
20798   verifyFormat("SomeClass::Constructor() noexcept\n"
20799                "    : a(a) {}",
20800                Style);
20801   verifyFormat("SomeClass::Constructor()\n"
20802                "    : a(a)\n"
20803                "    , b(b)\n"
20804                "    , c(c) {}",
20805                Style);
20806   verifyFormat("SomeClass::Constructor()\n"
20807                "    : a(a) {\n"
20808                "  foo();\n"
20809                "  bar();\n"
20810                "}",
20811                Style);
20812 
20813   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
20814   verifyFormat("SomeClass::Constructor()\n"
20815                "    : a(a)\n"
20816                "    , b(b)\n"
20817                "    , c(c) {\n}",
20818                Style);
20819   verifyFormat("SomeClass::Constructor()\n"
20820                "    : a(a) {\n}",
20821                Style);
20822 
20823   Style.ColumnLimit = 80;
20824   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
20825   Style.ConstructorInitializerIndentWidth = 2;
20826   verifyFormat("SomeClass::Constructor()\n"
20827                "  : a(a)\n"
20828                "  , b(b)\n"
20829                "  , c(c) {}",
20830                Style);
20831 
20832   Style.ConstructorInitializerIndentWidth = 0;
20833   verifyFormat("SomeClass::Constructor()\n"
20834                ": a(a)\n"
20835                ", b(b)\n"
20836                ", c(c) {}",
20837                Style);
20838 
20839   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20840   Style.ConstructorInitializerIndentWidth = 4;
20841   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
20842   verifyFormat(
20843       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
20844       Style);
20845   verifyFormat(
20846       "SomeClass::Constructor()\n"
20847       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
20848       Style);
20849   Style.ConstructorInitializerIndentWidth = 4;
20850   Style.ColumnLimit = 60;
20851   verifyFormat("SomeClass::Constructor()\n"
20852                "    : aaaaaaaa(aaaaaaaa)\n"
20853                "    , aaaaaaaa(aaaaaaaa)\n"
20854                "    , aaaaaaaa(aaaaaaaa) {}",
20855                Style);
20856 }
20857 
20858 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
20859   FormatStyle Style = getLLVMStyle();
20860   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20861   Style.ConstructorInitializerIndentWidth = 4;
20862   verifyFormat("SomeClass::Constructor()\n"
20863                "    : a{a}\n"
20864                "    , b{b} {}",
20865                Style);
20866   verifyFormat("SomeClass::Constructor()\n"
20867                "    : a{a}\n"
20868                "#if CONDITION\n"
20869                "    , b{b}\n"
20870                "#endif\n"
20871                "{\n}",
20872                Style);
20873   Style.ConstructorInitializerIndentWidth = 2;
20874   verifyFormat("SomeClass::Constructor()\n"
20875                "#if CONDITION\n"
20876                "  : a{a}\n"
20877                "#endif\n"
20878                "  , b{b}\n"
20879                "  , c{c} {\n}",
20880                Style);
20881   Style.ConstructorInitializerIndentWidth = 0;
20882   verifyFormat("SomeClass::Constructor()\n"
20883                ": a{a}\n"
20884                "#ifdef CONDITION\n"
20885                ", b{b}\n"
20886                "#else\n"
20887                ", c{c}\n"
20888                "#endif\n"
20889                ", d{d} {\n}",
20890                Style);
20891   Style.ConstructorInitializerIndentWidth = 4;
20892   verifyFormat("SomeClass::Constructor()\n"
20893                "    : a{a}\n"
20894                "#if WINDOWS\n"
20895                "#if DEBUG\n"
20896                "    , b{0}\n"
20897                "#else\n"
20898                "    , b{1}\n"
20899                "#endif\n"
20900                "#else\n"
20901                "#if DEBUG\n"
20902                "    , b{2}\n"
20903                "#else\n"
20904                "    , b{3}\n"
20905                "#endif\n"
20906                "#endif\n"
20907                "{\n}",
20908                Style);
20909   verifyFormat("SomeClass::Constructor()\n"
20910                "    : a{a}\n"
20911                "#if WINDOWS\n"
20912                "    , b{0}\n"
20913                "#if DEBUG\n"
20914                "    , c{0}\n"
20915                "#else\n"
20916                "    , c{1}\n"
20917                "#endif\n"
20918                "#else\n"
20919                "#if DEBUG\n"
20920                "    , c{2}\n"
20921                "#else\n"
20922                "    , c{3}\n"
20923                "#endif\n"
20924                "    , b{1}\n"
20925                "#endif\n"
20926                "{\n}",
20927                Style);
20928 }
20929 
20930 TEST_F(FormatTest, Destructors) {
20931   verifyFormat("void F(int &i) { i.~int(); }");
20932   verifyFormat("void F(int &i) { i->~int(); }");
20933 }
20934 
20935 TEST_F(FormatTest, FormatsWithWebKitStyle) {
20936   FormatStyle Style = getWebKitStyle();
20937 
20938   // Don't indent in outer namespaces.
20939   verifyFormat("namespace outer {\n"
20940                "int i;\n"
20941                "namespace inner {\n"
20942                "    int i;\n"
20943                "} // namespace inner\n"
20944                "} // namespace outer\n"
20945                "namespace other_outer {\n"
20946                "int i;\n"
20947                "}",
20948                Style);
20949 
20950   // Don't indent case labels.
20951   verifyFormat("switch (variable) {\n"
20952                "case 1:\n"
20953                "case 2:\n"
20954                "    doSomething();\n"
20955                "    break;\n"
20956                "default:\n"
20957                "    ++variable;\n"
20958                "}",
20959                Style);
20960 
20961   // Wrap before binary operators.
20962   EXPECT_EQ("void f()\n"
20963             "{\n"
20964             "    if (aaaaaaaaaaaaaaaa\n"
20965             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
20966             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20967             "        return;\n"
20968             "}",
20969             format("void f() {\n"
20970                    "if (aaaaaaaaaaaaaaaa\n"
20971                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
20972                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20973                    "return;\n"
20974                    "}",
20975                    Style));
20976 
20977   // Allow functions on a single line.
20978   verifyFormat("void f() { return; }", Style);
20979 
20980   // Allow empty blocks on a single line and insert a space in empty blocks.
20981   EXPECT_EQ("void f() { }", format("void f() {}", Style));
20982   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
20983   // However, don't merge non-empty short loops.
20984   EXPECT_EQ("while (true) {\n"
20985             "    continue;\n"
20986             "}",
20987             format("while (true) { continue; }", Style));
20988 
20989   // Constructor initializers are formatted one per line with the "," on the
20990   // new line.
20991   verifyFormat("Constructor()\n"
20992                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
20993                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
20994                "          aaaaaaaaaaaaaa)\n"
20995                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
20996                "{\n"
20997                "}",
20998                Style);
20999   verifyFormat("SomeClass::Constructor()\n"
21000                "    : a(a)\n"
21001                "{\n"
21002                "}",
21003                Style);
21004   EXPECT_EQ("SomeClass::Constructor()\n"
21005             "    : a(a)\n"
21006             "{\n"
21007             "}",
21008             format("SomeClass::Constructor():a(a){}", Style));
21009   verifyFormat("SomeClass::Constructor()\n"
21010                "    : a(a)\n"
21011                "    , b(b)\n"
21012                "    , c(c)\n"
21013                "{\n"
21014                "}",
21015                Style);
21016   verifyFormat("SomeClass::Constructor()\n"
21017                "    : a(a)\n"
21018                "{\n"
21019                "    foo();\n"
21020                "    bar();\n"
21021                "}",
21022                Style);
21023 
21024   // Access specifiers should be aligned left.
21025   verifyFormat("class C {\n"
21026                "public:\n"
21027                "    int i;\n"
21028                "};",
21029                Style);
21030 
21031   // Do not align comments.
21032   verifyFormat("int a; // Do not\n"
21033                "double b; // align comments.",
21034                Style);
21035 
21036   // Do not align operands.
21037   EXPECT_EQ("ASSERT(aaaa\n"
21038             "    || bbbb);",
21039             format("ASSERT ( aaaa\n||bbbb);", Style));
21040 
21041   // Accept input's line breaks.
21042   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
21043             "    || bbbbbbbbbbbbbbb) {\n"
21044             "    i++;\n"
21045             "}",
21046             format("if (aaaaaaaaaaaaaaa\n"
21047                    "|| bbbbbbbbbbbbbbb) { i++; }",
21048                    Style));
21049   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
21050             "    i++;\n"
21051             "}",
21052             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
21053 
21054   // Don't automatically break all macro definitions (llvm.org/PR17842).
21055   verifyFormat("#define aNumber 10", Style);
21056   // However, generally keep the line breaks that the user authored.
21057   EXPECT_EQ("#define aNumber \\\n"
21058             "    10",
21059             format("#define aNumber \\\n"
21060                    " 10",
21061                    Style));
21062 
21063   // Keep empty and one-element array literals on a single line.
21064   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
21065             "                                  copyItems:YES];",
21066             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
21067                    "copyItems:YES];",
21068                    Style));
21069   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
21070             "                                  copyItems:YES];",
21071             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
21072                    "             copyItems:YES];",
21073                    Style));
21074   // FIXME: This does not seem right, there should be more indentation before
21075   // the array literal's entries. Nested blocks have the same problem.
21076   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21077             "    @\"a\",\n"
21078             "    @\"a\"\n"
21079             "]\n"
21080             "                                  copyItems:YES];",
21081             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21082                    "     @\"a\",\n"
21083                    "     @\"a\"\n"
21084                    "     ]\n"
21085                    "       copyItems:YES];",
21086                    Style));
21087   EXPECT_EQ(
21088       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21089       "                                  copyItems:YES];",
21090       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21091              "   copyItems:YES];",
21092              Style));
21093 
21094   verifyFormat("[self.a b:c c:d];", Style);
21095   EXPECT_EQ("[self.a b:c\n"
21096             "        c:d];",
21097             format("[self.a b:c\n"
21098                    "c:d];",
21099                    Style));
21100 }
21101 
21102 TEST_F(FormatTest, FormatsLambdas) {
21103   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
21104   verifyFormat(
21105       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
21106   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
21107   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
21108   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
21109   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
21110   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
21111   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
21112   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
21113   verifyFormat("int x = f(*+[] {});");
21114   verifyFormat("void f() {\n"
21115                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
21116                "}\n");
21117   verifyFormat("void f() {\n"
21118                "  other(x.begin(), //\n"
21119                "        x.end(),   //\n"
21120                "        [&](int, int) { return 1; });\n"
21121                "}\n");
21122   verifyFormat("void f() {\n"
21123                "  other.other.other.other.other(\n"
21124                "      x.begin(), x.end(),\n"
21125                "      [something, rather](int, int, int, int, int, int, int) { "
21126                "return 1; });\n"
21127                "}\n");
21128   verifyFormat(
21129       "void f() {\n"
21130       "  other.other.other.other.other(\n"
21131       "      x.begin(), x.end(),\n"
21132       "      [something, rather](int, int, int, int, int, int, int) {\n"
21133       "        //\n"
21134       "      });\n"
21135       "}\n");
21136   verifyFormat("SomeFunction([]() { // A cool function...\n"
21137                "  return 43;\n"
21138                "});");
21139   EXPECT_EQ("SomeFunction([]() {\n"
21140             "#define A a\n"
21141             "  return 43;\n"
21142             "});",
21143             format("SomeFunction([](){\n"
21144                    "#define A a\n"
21145                    "return 43;\n"
21146                    "});"));
21147   verifyFormat("void f() {\n"
21148                "  SomeFunction([](decltype(x), A *a) {});\n"
21149                "  SomeFunction([](typeof(x), A *a) {});\n"
21150                "  SomeFunction([](_Atomic(x), A *a) {});\n"
21151                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
21152                "}");
21153   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21154                "    [](const aaaaaaaaaa &a) { return a; });");
21155   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
21156                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
21157                "});");
21158   verifyFormat("Constructor()\n"
21159                "    : Field([] { // comment\n"
21160                "        int i;\n"
21161                "      }) {}");
21162   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
21163                "  return some_parameter.size();\n"
21164                "};");
21165   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
21166                "    [](const string &s) { return s; };");
21167   verifyFormat("int i = aaaaaa ? 1 //\n"
21168                "               : [] {\n"
21169                "                   return 2; //\n"
21170                "                 }();");
21171   verifyFormat("llvm::errs() << \"number of twos is \"\n"
21172                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
21173                "                  return x == 2; // force break\n"
21174                "                });");
21175   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21176                "    [=](int iiiiiiiiiiii) {\n"
21177                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
21178                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
21179                "    });",
21180                getLLVMStyleWithColumns(60));
21181 
21182   verifyFormat("SomeFunction({[&] {\n"
21183                "                // comment\n"
21184                "              },\n"
21185                "              [&] {\n"
21186                "                // comment\n"
21187                "              }});");
21188   verifyFormat("SomeFunction({[&] {\n"
21189                "  // comment\n"
21190                "}});");
21191   verifyFormat(
21192       "virtual aaaaaaaaaaaaaaaa(\n"
21193       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
21194       "    aaaaa aaaaaaaaa);");
21195 
21196   // Lambdas with return types.
21197   verifyFormat("int c = []() -> int { return 2; }();\n");
21198   verifyFormat("int c = []() -> int * { return 2; }();\n");
21199   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
21200   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
21201   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
21202   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
21203   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
21204   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
21205   verifyFormat("[a, a]() -> a<1> {};");
21206   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
21207   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
21208   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
21209   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
21210   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
21211   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
21212   verifyFormat("[]() -> foo<!5> { return {}; };");
21213   verifyFormat("[]() -> foo<~5> { return {}; };");
21214   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
21215   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
21216   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
21217   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
21218   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
21219   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
21220   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
21221   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
21222   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
21223   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
21224   verifyFormat("namespace bar {\n"
21225                "// broken:\n"
21226                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
21227                "} // namespace bar");
21228   verifyFormat("namespace bar {\n"
21229                "// broken:\n"
21230                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
21231                "} // namespace bar");
21232   verifyFormat("namespace bar {\n"
21233                "// broken:\n"
21234                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
21235                "} // namespace bar");
21236   verifyFormat("namespace bar {\n"
21237                "// broken:\n"
21238                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
21239                "} // namespace bar");
21240   verifyFormat("namespace bar {\n"
21241                "// broken:\n"
21242                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
21243                "} // namespace bar");
21244   verifyFormat("namespace bar {\n"
21245                "// broken:\n"
21246                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
21247                "} // namespace bar");
21248   verifyFormat("namespace bar {\n"
21249                "// broken:\n"
21250                "auto foo{[]() -> foo<!5> { return {}; }};\n"
21251                "} // namespace bar");
21252   verifyFormat("namespace bar {\n"
21253                "// broken:\n"
21254                "auto foo{[]() -> foo<~5> { return {}; }};\n"
21255                "} // namespace bar");
21256   verifyFormat("namespace bar {\n"
21257                "// broken:\n"
21258                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
21259                "} // namespace bar");
21260   verifyFormat("namespace bar {\n"
21261                "// broken:\n"
21262                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
21263                "} // namespace bar");
21264   verifyFormat("namespace bar {\n"
21265                "// broken:\n"
21266                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
21267                "} // namespace bar");
21268   verifyFormat("namespace bar {\n"
21269                "// broken:\n"
21270                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
21271                "} // namespace bar");
21272   verifyFormat("namespace bar {\n"
21273                "// broken:\n"
21274                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
21275                "} // namespace bar");
21276   verifyFormat("namespace bar {\n"
21277                "// broken:\n"
21278                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
21279                "} // namespace bar");
21280   verifyFormat("namespace bar {\n"
21281                "// broken:\n"
21282                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
21283                "} // namespace bar");
21284   verifyFormat("namespace bar {\n"
21285                "// broken:\n"
21286                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
21287                "} // namespace bar");
21288   verifyFormat("namespace bar {\n"
21289                "// broken:\n"
21290                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
21291                "} // namespace bar");
21292   verifyFormat("namespace bar {\n"
21293                "// broken:\n"
21294                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
21295                "} // namespace bar");
21296   verifyFormat("[]() -> a<1> {};");
21297   verifyFormat("[]() -> a<1> { ; };");
21298   verifyFormat("[]() -> a<1> { ; }();");
21299   verifyFormat("[a, a]() -> a<true> {};");
21300   verifyFormat("[]() -> a<true> {};");
21301   verifyFormat("[]() -> a<true> { ; };");
21302   verifyFormat("[]() -> a<true> { ; }();");
21303   verifyFormat("[a, a]() -> a<false> {};");
21304   verifyFormat("[]() -> a<false> {};");
21305   verifyFormat("[]() -> a<false> { ; };");
21306   verifyFormat("[]() -> a<false> { ; }();");
21307   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
21308   verifyFormat("namespace bar {\n"
21309                "auto foo{[]() -> foo<false> { ; }};\n"
21310                "} // namespace bar");
21311   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
21312                "                   int j) -> int {\n"
21313                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21314                "};");
21315   verifyFormat(
21316       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21317       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21318       "      return aaaaaaaaaaaaaaaaa;\n"
21319       "    });",
21320       getLLVMStyleWithColumns(70));
21321   verifyFormat("[]() //\n"
21322                "    -> int {\n"
21323                "  return 1; //\n"
21324                "};");
21325   verifyFormat("[]() -> Void<T...> {};");
21326   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21327   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21328   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21329   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21330   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21331   verifyFormat("return int{[x = x]() { return x; }()};");
21332 
21333   // Lambdas with explicit template argument lists.
21334   verifyFormat(
21335       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21336   verifyFormat("auto L = []<class T>(T) {\n"
21337                "  {\n"
21338                "    f();\n"
21339                "    g();\n"
21340                "  }\n"
21341                "};\n");
21342   verifyFormat("auto L = []<class... T>(T...) {\n"
21343                "  {\n"
21344                "    f();\n"
21345                "    g();\n"
21346                "  }\n"
21347                "};\n");
21348   verifyFormat("auto L = []<typename... T>(T...) {\n"
21349                "  {\n"
21350                "    f();\n"
21351                "    g();\n"
21352                "  }\n"
21353                "};\n");
21354   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21355                "  {\n"
21356                "    f();\n"
21357                "    g();\n"
21358                "  }\n"
21359                "};\n");
21360   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21361                "  {\n"
21362                "    f();\n"
21363                "    g();\n"
21364                "  }\n"
21365                "};\n");
21366 
21367   // Multiple lambdas in the same parentheses change indentation rules. These
21368   // lambdas are forced to start on new lines.
21369   verifyFormat("SomeFunction(\n"
21370                "    []() {\n"
21371                "      //\n"
21372                "    },\n"
21373                "    []() {\n"
21374                "      //\n"
21375                "    });");
21376 
21377   // A lambda passed as arg0 is always pushed to the next line.
21378   verifyFormat("SomeFunction(\n"
21379                "    [this] {\n"
21380                "      //\n"
21381                "    },\n"
21382                "    1);\n");
21383 
21384   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21385   // the arg0 case above.
21386   auto Style = getGoogleStyle();
21387   Style.BinPackArguments = false;
21388   verifyFormat("SomeFunction(\n"
21389                "    a,\n"
21390                "    [this] {\n"
21391                "      //\n"
21392                "    },\n"
21393                "    b);\n",
21394                Style);
21395   verifyFormat("SomeFunction(\n"
21396                "    a,\n"
21397                "    [this] {\n"
21398                "      //\n"
21399                "    },\n"
21400                "    b);\n");
21401 
21402   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21403   // the BinPackArguments value (as long as the code is wide enough).
21404   verifyFormat(
21405       "something->SomeFunction(\n"
21406       "    a,\n"
21407       "    [this] {\n"
21408       "      "
21409       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21410       "    },\n"
21411       "    b);\n");
21412 
21413   // A multi-line lambda is pulled up as long as the introducer fits on the
21414   // previous line and there are no further args.
21415   verifyFormat("function(1, [this, that] {\n"
21416                "  //\n"
21417                "});\n");
21418   verifyFormat("function([this, that] {\n"
21419                "  //\n"
21420                "});\n");
21421   // FIXME: this format is not ideal and we should consider forcing the first
21422   // arg onto its own line.
21423   verifyFormat("function(a, b, c, //\n"
21424                "         d, [this, that] {\n"
21425                "           //\n"
21426                "         });\n");
21427 
21428   // Multiple lambdas are treated correctly even when there is a short arg0.
21429   verifyFormat("SomeFunction(\n"
21430                "    1,\n"
21431                "    [this] {\n"
21432                "      //\n"
21433                "    },\n"
21434                "    [this] {\n"
21435                "      //\n"
21436                "    },\n"
21437                "    1);\n");
21438 
21439   // More complex introducers.
21440   verifyFormat("return [i, args...] {};");
21441 
21442   // Not lambdas.
21443   verifyFormat("constexpr char hello[]{\"hello\"};");
21444   verifyFormat("double &operator[](int i) { return 0; }\n"
21445                "int i;");
21446   verifyFormat("std::unique_ptr<int[]> foo() {}");
21447   verifyFormat("int i = a[a][a]->f();");
21448   verifyFormat("int i = (*b)[a]->f();");
21449 
21450   // Other corner cases.
21451   verifyFormat("void f() {\n"
21452                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21453                "  );\n"
21454                "}");
21455 
21456   // Lambdas created through weird macros.
21457   verifyFormat("void f() {\n"
21458                "  MACRO((const AA &a) { return 1; });\n"
21459                "  MACRO((AA &a) { return 1; });\n"
21460                "}");
21461 
21462   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21463                "      doo_dah();\n"
21464                "      doo_dah();\n"
21465                "    })) {\n"
21466                "}");
21467   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21468                "                doo_dah();\n"
21469                "                doo_dah();\n"
21470                "              })) {\n"
21471                "}");
21472   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21473                "                doo_dah();\n"
21474                "                doo_dah();\n"
21475                "              })) {\n"
21476                "}");
21477   verifyFormat("auto lambda = []() {\n"
21478                "  int a = 2\n"
21479                "#if A\n"
21480                "          + 2\n"
21481                "#endif\n"
21482                "      ;\n"
21483                "};");
21484 
21485   // Lambdas with complex multiline introducers.
21486   verifyFormat(
21487       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21488       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21489       "        -> ::std::unordered_set<\n"
21490       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21491       "      //\n"
21492       "    });");
21493 
21494   FormatStyle DoNotMerge = getLLVMStyle();
21495   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21496   verifyFormat("auto c = []() {\n"
21497                "  return b;\n"
21498                "};",
21499                "auto c = []() { return b; };", DoNotMerge);
21500   verifyFormat("auto c = []() {\n"
21501                "};",
21502                " auto c = []() {};", DoNotMerge);
21503 
21504   FormatStyle MergeEmptyOnly = getLLVMStyle();
21505   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21506   verifyFormat("auto c = []() {\n"
21507                "  return b;\n"
21508                "};",
21509                "auto c = []() {\n"
21510                "  return b;\n"
21511                " };",
21512                MergeEmptyOnly);
21513   verifyFormat("auto c = []() {};",
21514                "auto c = []() {\n"
21515                "};",
21516                MergeEmptyOnly);
21517 
21518   FormatStyle MergeInline = getLLVMStyle();
21519   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21520   verifyFormat("auto c = []() {\n"
21521                "  return b;\n"
21522                "};",
21523                "auto c = []() { return b; };", MergeInline);
21524   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21525                MergeInline);
21526   verifyFormat("function([]() { return b; }, a)",
21527                "function([]() { return b; }, a)", MergeInline);
21528   verifyFormat("function(a, []() { return b; })",
21529                "function(a, []() { return b; })", MergeInline);
21530 
21531   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21532   // AllowShortLambdasOnASingleLine
21533   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21534   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21535   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21536   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21537       FormatStyle::ShortLambdaStyle::SLS_None;
21538   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21539                "    []()\n"
21540                "    {\n"
21541                "      return 17;\n"
21542                "    });",
21543                LLVMWithBeforeLambdaBody);
21544   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21545                "    []()\n"
21546                "    {\n"
21547                "    });",
21548                LLVMWithBeforeLambdaBody);
21549   verifyFormat("auto fct_SLS_None = []()\n"
21550                "{\n"
21551                "  return 17;\n"
21552                "};",
21553                LLVMWithBeforeLambdaBody);
21554   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21555                "    []()\n"
21556                "    {\n"
21557                "      return Call(\n"
21558                "          []()\n"
21559                "          {\n"
21560                "            return 17;\n"
21561                "          });\n"
21562                "    });",
21563                LLVMWithBeforeLambdaBody);
21564   verifyFormat("void Fct() {\n"
21565                "  return {[]()\n"
21566                "          {\n"
21567                "            return 17;\n"
21568                "          }};\n"
21569                "}",
21570                LLVMWithBeforeLambdaBody);
21571 
21572   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21573       FormatStyle::ShortLambdaStyle::SLS_Empty;
21574   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21575                "    []()\n"
21576                "    {\n"
21577                "      return 17;\n"
21578                "    });",
21579                LLVMWithBeforeLambdaBody);
21580   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21581                LLVMWithBeforeLambdaBody);
21582   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21583                "ongFunctionName_SLS_Empty(\n"
21584                "    []() {});",
21585                LLVMWithBeforeLambdaBody);
21586   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21587                "                                []()\n"
21588                "                                {\n"
21589                "                                  return 17;\n"
21590                "                                });",
21591                LLVMWithBeforeLambdaBody);
21592   verifyFormat("auto fct_SLS_Empty = []()\n"
21593                "{\n"
21594                "  return 17;\n"
21595                "};",
21596                LLVMWithBeforeLambdaBody);
21597   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21598                "    []()\n"
21599                "    {\n"
21600                "      return Call([]() {});\n"
21601                "    });",
21602                LLVMWithBeforeLambdaBody);
21603   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21604                "                           []()\n"
21605                "                           {\n"
21606                "                             return Call([]() {});\n"
21607                "                           });",
21608                LLVMWithBeforeLambdaBody);
21609   verifyFormat(
21610       "FctWithLongLineInLambda_SLS_Empty(\n"
21611       "    []()\n"
21612       "    {\n"
21613       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21614       "                               AndShouldNotBeConsiderAsInline,\n"
21615       "                               LambdaBodyMustBeBreak);\n"
21616       "    });",
21617       LLVMWithBeforeLambdaBody);
21618 
21619   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21620       FormatStyle::ShortLambdaStyle::SLS_Inline;
21621   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21622                LLVMWithBeforeLambdaBody);
21623   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21624                LLVMWithBeforeLambdaBody);
21625   verifyFormat("auto fct_SLS_Inline = []()\n"
21626                "{\n"
21627                "  return 17;\n"
21628                "};",
21629                LLVMWithBeforeLambdaBody);
21630   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21631                "17; }); });",
21632                LLVMWithBeforeLambdaBody);
21633   verifyFormat(
21634       "FctWithLongLineInLambda_SLS_Inline(\n"
21635       "    []()\n"
21636       "    {\n"
21637       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21638       "                               AndShouldNotBeConsiderAsInline,\n"
21639       "                               LambdaBodyMustBeBreak);\n"
21640       "    });",
21641       LLVMWithBeforeLambdaBody);
21642   verifyFormat("FctWithMultipleParams_SLS_Inline("
21643                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21644                "                                 []() { return 17; });",
21645                LLVMWithBeforeLambdaBody);
21646   verifyFormat(
21647       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21648       LLVMWithBeforeLambdaBody);
21649 
21650   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21651       FormatStyle::ShortLambdaStyle::SLS_All;
21652   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21653                LLVMWithBeforeLambdaBody);
21654   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21655                LLVMWithBeforeLambdaBody);
21656   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21657                LLVMWithBeforeLambdaBody);
21658   verifyFormat("FctWithOneParam_SLS_All(\n"
21659                "    []()\n"
21660                "    {\n"
21661                "      // A cool function...\n"
21662                "      return 43;\n"
21663                "    });",
21664                LLVMWithBeforeLambdaBody);
21665   verifyFormat("FctWithMultipleParams_SLS_All("
21666                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21667                "                              []() { return 17; });",
21668                LLVMWithBeforeLambdaBody);
21669   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21670                LLVMWithBeforeLambdaBody);
21671   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21672                LLVMWithBeforeLambdaBody);
21673   verifyFormat(
21674       "FctWithLongLineInLambda_SLS_All(\n"
21675       "    []()\n"
21676       "    {\n"
21677       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21678       "                               AndShouldNotBeConsiderAsInline,\n"
21679       "                               LambdaBodyMustBeBreak);\n"
21680       "    });",
21681       LLVMWithBeforeLambdaBody);
21682   verifyFormat(
21683       "auto fct_SLS_All = []()\n"
21684       "{\n"
21685       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21686       "                           AndShouldNotBeConsiderAsInline,\n"
21687       "                           LambdaBodyMustBeBreak);\n"
21688       "};",
21689       LLVMWithBeforeLambdaBody);
21690   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21691   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21692                LLVMWithBeforeLambdaBody);
21693   verifyFormat(
21694       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21695       "                                FirstParam,\n"
21696       "                                SecondParam,\n"
21697       "                                ThirdParam,\n"
21698       "                                FourthParam);",
21699       LLVMWithBeforeLambdaBody);
21700   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21701                "    []() { return "
21702                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21703                "    FirstParam,\n"
21704                "    SecondParam,\n"
21705                "    ThirdParam,\n"
21706                "    FourthParam);",
21707                LLVMWithBeforeLambdaBody);
21708   verifyFormat(
21709       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21710       "                                SecondParam,\n"
21711       "                                ThirdParam,\n"
21712       "                                FourthParam,\n"
21713       "                                []() { return SomeValueNotSoLong; });",
21714       LLVMWithBeforeLambdaBody);
21715   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21716                "    []()\n"
21717                "    {\n"
21718                "      return "
21719                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21720                "eConsiderAsInline;\n"
21721                "    });",
21722                LLVMWithBeforeLambdaBody);
21723   verifyFormat(
21724       "FctWithLongLineInLambda_SLS_All(\n"
21725       "    []()\n"
21726       "    {\n"
21727       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21728       "                               AndShouldNotBeConsiderAsInline,\n"
21729       "                               LambdaBodyMustBeBreak);\n"
21730       "    });",
21731       LLVMWithBeforeLambdaBody);
21732   verifyFormat("FctWithTwoParams_SLS_All(\n"
21733                "    []()\n"
21734                "    {\n"
21735                "      // A cool function...\n"
21736                "      return 43;\n"
21737                "    },\n"
21738                "    87);",
21739                LLVMWithBeforeLambdaBody);
21740   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
21741                LLVMWithBeforeLambdaBody);
21742   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
21743                LLVMWithBeforeLambdaBody);
21744   verifyFormat(
21745       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
21746       LLVMWithBeforeLambdaBody);
21747   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
21748                "}); }, x);",
21749                LLVMWithBeforeLambdaBody);
21750   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21751                "    []()\n"
21752                "    {\n"
21753                "      // A cool function...\n"
21754                "      return Call([]() { return 17; });\n"
21755                "    });",
21756                LLVMWithBeforeLambdaBody);
21757   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21758                "    []()\n"
21759                "    {\n"
21760                "      return Call(\n"
21761                "          []()\n"
21762                "          {\n"
21763                "            // A cool function...\n"
21764                "            return 17;\n"
21765                "          });\n"
21766                "    });",
21767                LLVMWithBeforeLambdaBody);
21768 
21769   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21770       FormatStyle::ShortLambdaStyle::SLS_None;
21771 
21772   verifyFormat("auto select = [this]() -> const Library::Object *\n"
21773                "{\n"
21774                "  return MyAssignment::SelectFromList(this);\n"
21775                "};\n",
21776                LLVMWithBeforeLambdaBody);
21777 
21778   verifyFormat("auto select = [this]() -> const Library::Object &\n"
21779                "{\n"
21780                "  return MyAssignment::SelectFromList(this);\n"
21781                "};\n",
21782                LLVMWithBeforeLambdaBody);
21783 
21784   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
21785                "{\n"
21786                "  return MyAssignment::SelectFromList(this);\n"
21787                "};\n",
21788                LLVMWithBeforeLambdaBody);
21789 
21790   verifyFormat("namespace test {\n"
21791                "class Test {\n"
21792                "public:\n"
21793                "  Test() = default;\n"
21794                "};\n"
21795                "} // namespace test",
21796                LLVMWithBeforeLambdaBody);
21797 
21798   // Lambdas with different indentation styles.
21799   Style = getLLVMStyleWithColumns(100);
21800   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21801             "  return promise.then(\n"
21802             "      [this, &someVariable, someObject = "
21803             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21804             "        return someObject.startAsyncAction().then(\n"
21805             "            [this, &someVariable](AsyncActionResult result) "
21806             "mutable { result.processMore(); });\n"
21807             "      });\n"
21808             "}\n",
21809             format("SomeResult doSomething(SomeObject promise) {\n"
21810                    "  return promise.then([this, &someVariable, someObject = "
21811                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21812                    "    return someObject.startAsyncAction().then([this, "
21813                    "&someVariable](AsyncActionResult result) mutable {\n"
21814                    "      result.processMore();\n"
21815                    "    });\n"
21816                    "  });\n"
21817                    "}\n",
21818                    Style));
21819   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21820   verifyFormat("test() {\n"
21821                "  ([]() -> {\n"
21822                "    int b = 32;\n"
21823                "    return 3;\n"
21824                "  }).foo();\n"
21825                "}",
21826                Style);
21827   verifyFormat("test() {\n"
21828                "  []() -> {\n"
21829                "    int b = 32;\n"
21830                "    return 3;\n"
21831                "  }\n"
21832                "}",
21833                Style);
21834   verifyFormat("std::sort(v.begin(), v.end(),\n"
21835                "          [](const auto &someLongArgumentName, const auto "
21836                "&someOtherLongArgumentName) {\n"
21837                "  return someLongArgumentName.someMemberVariable < "
21838                "someOtherLongArgumentName.someMemberVariable;\n"
21839                "});",
21840                Style);
21841   verifyFormat("test() {\n"
21842                "  (\n"
21843                "      []() -> {\n"
21844                "        int b = 32;\n"
21845                "        return 3;\n"
21846                "      },\n"
21847                "      foo, bar)\n"
21848                "      .foo();\n"
21849                "}",
21850                Style);
21851   verifyFormat("test() {\n"
21852                "  ([]() -> {\n"
21853                "    int b = 32;\n"
21854                "    return 3;\n"
21855                "  })\n"
21856                "      .foo()\n"
21857                "      .bar();\n"
21858                "}",
21859                Style);
21860   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21861             "  return promise.then(\n"
21862             "      [this, &someVariable, someObject = "
21863             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21864             "    return someObject.startAsyncAction().then(\n"
21865             "        [this, &someVariable](AsyncActionResult result) mutable { "
21866             "result.processMore(); });\n"
21867             "  });\n"
21868             "}\n",
21869             format("SomeResult doSomething(SomeObject promise) {\n"
21870                    "  return promise.then([this, &someVariable, someObject = "
21871                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21872                    "    return someObject.startAsyncAction().then([this, "
21873                    "&someVariable](AsyncActionResult result) mutable {\n"
21874                    "      result.processMore();\n"
21875                    "    });\n"
21876                    "  });\n"
21877                    "}\n",
21878                    Style));
21879   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21880             "  return promise.then([this, &someVariable] {\n"
21881             "    return someObject.startAsyncAction().then(\n"
21882             "        [this, &someVariable](AsyncActionResult result) mutable { "
21883             "result.processMore(); });\n"
21884             "  });\n"
21885             "}\n",
21886             format("SomeResult doSomething(SomeObject promise) {\n"
21887                    "  return promise.then([this, &someVariable] {\n"
21888                    "    return someObject.startAsyncAction().then([this, "
21889                    "&someVariable](AsyncActionResult result) mutable {\n"
21890                    "      result.processMore();\n"
21891                    "    });\n"
21892                    "  });\n"
21893                    "}\n",
21894                    Style));
21895   Style = getGoogleStyle();
21896   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21897   EXPECT_EQ("#define A                                       \\\n"
21898             "  [] {                                          \\\n"
21899             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
21900             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
21901             "      }",
21902             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
21903                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
21904                    Style));
21905   // TODO: The current formatting has a minor issue that's not worth fixing
21906   // right now whereby the closing brace is indented relative to the signature
21907   // instead of being aligned. This only happens with macros.
21908 }
21909 
21910 TEST_F(FormatTest, LambdaWithLineComments) {
21911   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21912   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21913   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21914   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21915       FormatStyle::ShortLambdaStyle::SLS_All;
21916 
21917   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
21918   verifyFormat("auto k = []() // comment\n"
21919                "{ return; }",
21920                LLVMWithBeforeLambdaBody);
21921   verifyFormat("auto k = []() /* comment */ { return; }",
21922                LLVMWithBeforeLambdaBody);
21923   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
21924                LLVMWithBeforeLambdaBody);
21925   verifyFormat("auto k = []() // X\n"
21926                "{ return; }",
21927                LLVMWithBeforeLambdaBody);
21928   verifyFormat(
21929       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
21930       "{ return; }",
21931       LLVMWithBeforeLambdaBody);
21932 }
21933 
21934 TEST_F(FormatTest, EmptyLinesInLambdas) {
21935   verifyFormat("auto lambda = []() {\n"
21936                "  x(); //\n"
21937                "};",
21938                "auto lambda = []() {\n"
21939                "\n"
21940                "  x(); //\n"
21941                "\n"
21942                "};");
21943 }
21944 
21945 TEST_F(FormatTest, FormatsBlocks) {
21946   FormatStyle ShortBlocks = getLLVMStyle();
21947   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21948   verifyFormat("int (^Block)(int, int);", ShortBlocks);
21949   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
21950   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
21951   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
21952   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
21953   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
21954 
21955   verifyFormat("foo(^{ bar(); });", ShortBlocks);
21956   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
21957   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
21958 
21959   verifyFormat("[operation setCompletionBlock:^{\n"
21960                "  [self onOperationDone];\n"
21961                "}];");
21962   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
21963                "  [self onOperationDone];\n"
21964                "}]};");
21965   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
21966                "  f();\n"
21967                "}];");
21968   verifyFormat("int a = [operation block:^int(int *i) {\n"
21969                "  return 1;\n"
21970                "}];");
21971   verifyFormat("[myObject doSomethingWith:arg1\n"
21972                "                      aaa:^int(int *a) {\n"
21973                "                        return 1;\n"
21974                "                      }\n"
21975                "                      bbb:f(a * bbbbbbbb)];");
21976 
21977   verifyFormat("[operation setCompletionBlock:^{\n"
21978                "  [self.delegate newDataAvailable];\n"
21979                "}];",
21980                getLLVMStyleWithColumns(60));
21981   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
21982                "  NSString *path = [self sessionFilePath];\n"
21983                "  if (path) {\n"
21984                "    // ...\n"
21985                "  }\n"
21986                "});");
21987   verifyFormat("[[SessionService sharedService]\n"
21988                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21989                "      if (window) {\n"
21990                "        [self windowDidLoad:window];\n"
21991                "      } else {\n"
21992                "        [self errorLoadingWindow];\n"
21993                "      }\n"
21994                "    }];");
21995   verifyFormat("void (^largeBlock)(void) = ^{\n"
21996                "  // ...\n"
21997                "};\n",
21998                getLLVMStyleWithColumns(40));
21999   verifyFormat("[[SessionService sharedService]\n"
22000                "    loadWindowWithCompletionBlock: //\n"
22001                "        ^(SessionWindow *window) {\n"
22002                "          if (window) {\n"
22003                "            [self windowDidLoad:window];\n"
22004                "          } else {\n"
22005                "            [self errorLoadingWindow];\n"
22006                "          }\n"
22007                "        }];",
22008                getLLVMStyleWithColumns(60));
22009   verifyFormat("[myObject doSomethingWith:arg1\n"
22010                "    firstBlock:^(Foo *a) {\n"
22011                "      // ...\n"
22012                "      int i;\n"
22013                "    }\n"
22014                "    secondBlock:^(Bar *b) {\n"
22015                "      // ...\n"
22016                "      int i;\n"
22017                "    }\n"
22018                "    thirdBlock:^Foo(Bar *b) {\n"
22019                "      // ...\n"
22020                "      int i;\n"
22021                "    }];");
22022   verifyFormat("[myObject doSomethingWith:arg1\n"
22023                "               firstBlock:-1\n"
22024                "              secondBlock:^(Bar *b) {\n"
22025                "                // ...\n"
22026                "                int i;\n"
22027                "              }];");
22028 
22029   verifyFormat("f(^{\n"
22030                "  @autoreleasepool {\n"
22031                "    if (a) {\n"
22032                "      g();\n"
22033                "    }\n"
22034                "  }\n"
22035                "});");
22036   verifyFormat("Block b = ^int *(A *a, B *b) {}");
22037   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
22038                "};");
22039 
22040   FormatStyle FourIndent = getLLVMStyle();
22041   FourIndent.ObjCBlockIndentWidth = 4;
22042   verifyFormat("[operation setCompletionBlock:^{\n"
22043                "    [self onOperationDone];\n"
22044                "}];",
22045                FourIndent);
22046 }
22047 
22048 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
22049   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
22050 
22051   verifyFormat("[[SessionService sharedService] "
22052                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22053                "  if (window) {\n"
22054                "    [self windowDidLoad:window];\n"
22055                "  } else {\n"
22056                "    [self errorLoadingWindow];\n"
22057                "  }\n"
22058                "}];",
22059                ZeroColumn);
22060   EXPECT_EQ("[[SessionService sharedService]\n"
22061             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22062             "      if (window) {\n"
22063             "        [self windowDidLoad:window];\n"
22064             "      } else {\n"
22065             "        [self errorLoadingWindow];\n"
22066             "      }\n"
22067             "    }];",
22068             format("[[SessionService sharedService]\n"
22069                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22070                    "                if (window) {\n"
22071                    "    [self windowDidLoad:window];\n"
22072                    "  } else {\n"
22073                    "    [self errorLoadingWindow];\n"
22074                    "  }\n"
22075                    "}];",
22076                    ZeroColumn));
22077   verifyFormat("[myObject doSomethingWith:arg1\n"
22078                "    firstBlock:^(Foo *a) {\n"
22079                "      // ...\n"
22080                "      int i;\n"
22081                "    }\n"
22082                "    secondBlock:^(Bar *b) {\n"
22083                "      // ...\n"
22084                "      int i;\n"
22085                "    }\n"
22086                "    thirdBlock:^Foo(Bar *b) {\n"
22087                "      // ...\n"
22088                "      int i;\n"
22089                "    }];",
22090                ZeroColumn);
22091   verifyFormat("f(^{\n"
22092                "  @autoreleasepool {\n"
22093                "    if (a) {\n"
22094                "      g();\n"
22095                "    }\n"
22096                "  }\n"
22097                "});",
22098                ZeroColumn);
22099   verifyFormat("void (^largeBlock)(void) = ^{\n"
22100                "  // ...\n"
22101                "};",
22102                ZeroColumn);
22103 
22104   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22105   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
22106             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22107   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
22108   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
22109             "  int i;\n"
22110             "};",
22111             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22112 }
22113 
22114 TEST_F(FormatTest, SupportsCRLF) {
22115   EXPECT_EQ("int a;\r\n"
22116             "int b;\r\n"
22117             "int c;\r\n",
22118             format("int a;\r\n"
22119                    "  int b;\r\n"
22120                    "    int c;\r\n",
22121                    getLLVMStyle()));
22122   EXPECT_EQ("int a;\r\n"
22123             "int b;\r\n"
22124             "int c;\r\n",
22125             format("int a;\r\n"
22126                    "  int b;\n"
22127                    "    int c;\r\n",
22128                    getLLVMStyle()));
22129   EXPECT_EQ("int a;\n"
22130             "int b;\n"
22131             "int c;\n",
22132             format("int a;\r\n"
22133                    "  int b;\n"
22134                    "    int c;\n",
22135                    getLLVMStyle()));
22136   EXPECT_EQ("\"aaaaaaa \"\r\n"
22137             "\"bbbbbbb\";\r\n",
22138             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
22139   EXPECT_EQ("#define A \\\r\n"
22140             "  b;      \\\r\n"
22141             "  c;      \\\r\n"
22142             "  d;\r\n",
22143             format("#define A \\\r\n"
22144                    "  b; \\\r\n"
22145                    "  c; d; \r\n",
22146                    getGoogleStyle()));
22147 
22148   EXPECT_EQ("/*\r\n"
22149             "multi line block comments\r\n"
22150             "should not introduce\r\n"
22151             "an extra carriage return\r\n"
22152             "*/\r\n",
22153             format("/*\r\n"
22154                    "multi line block comments\r\n"
22155                    "should not introduce\r\n"
22156                    "an extra carriage return\r\n"
22157                    "*/\r\n"));
22158   EXPECT_EQ("/*\r\n"
22159             "\r\n"
22160             "*/",
22161             format("/*\r\n"
22162                    "    \r\r\r\n"
22163                    "*/"));
22164 
22165   FormatStyle style = getLLVMStyle();
22166 
22167   style.DeriveLineEnding = true;
22168   style.UseCRLF = false;
22169   EXPECT_EQ("union FooBarBazQux {\n"
22170             "  int foo;\n"
22171             "  int bar;\n"
22172             "  int baz;\n"
22173             "};",
22174             format("union FooBarBazQux {\r\n"
22175                    "  int foo;\n"
22176                    "  int bar;\r\n"
22177                    "  int baz;\n"
22178                    "};",
22179                    style));
22180   style.UseCRLF = true;
22181   EXPECT_EQ("union FooBarBazQux {\r\n"
22182             "  int foo;\r\n"
22183             "  int bar;\r\n"
22184             "  int baz;\r\n"
22185             "};",
22186             format("union FooBarBazQux {\r\n"
22187                    "  int foo;\n"
22188                    "  int bar;\r\n"
22189                    "  int baz;\n"
22190                    "};",
22191                    style));
22192 
22193   style.DeriveLineEnding = false;
22194   style.UseCRLF = false;
22195   EXPECT_EQ("union FooBarBazQux {\n"
22196             "  int foo;\n"
22197             "  int bar;\n"
22198             "  int baz;\n"
22199             "  int qux;\n"
22200             "};",
22201             format("union FooBarBazQux {\r\n"
22202                    "  int foo;\n"
22203                    "  int bar;\r\n"
22204                    "  int baz;\n"
22205                    "  int qux;\r\n"
22206                    "};",
22207                    style));
22208   style.UseCRLF = true;
22209   EXPECT_EQ("union FooBarBazQux {\r\n"
22210             "  int foo;\r\n"
22211             "  int bar;\r\n"
22212             "  int baz;\r\n"
22213             "  int qux;\r\n"
22214             "};",
22215             format("union FooBarBazQux {\r\n"
22216                    "  int foo;\n"
22217                    "  int bar;\r\n"
22218                    "  int baz;\n"
22219                    "  int qux;\n"
22220                    "};",
22221                    style));
22222 
22223   style.DeriveLineEnding = true;
22224   style.UseCRLF = false;
22225   EXPECT_EQ("union FooBarBazQux {\r\n"
22226             "  int foo;\r\n"
22227             "  int bar;\r\n"
22228             "  int baz;\r\n"
22229             "  int qux;\r\n"
22230             "};",
22231             format("union FooBarBazQux {\r\n"
22232                    "  int foo;\n"
22233                    "  int bar;\r\n"
22234                    "  int baz;\n"
22235                    "  int qux;\r\n"
22236                    "};",
22237                    style));
22238   style.UseCRLF = true;
22239   EXPECT_EQ("union FooBarBazQux {\n"
22240             "  int foo;\n"
22241             "  int bar;\n"
22242             "  int baz;\n"
22243             "  int qux;\n"
22244             "};",
22245             format("union FooBarBazQux {\r\n"
22246                    "  int foo;\n"
22247                    "  int bar;\r\n"
22248                    "  int baz;\n"
22249                    "  int qux;\n"
22250                    "};",
22251                    style));
22252 }
22253 
22254 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
22255   verifyFormat("MY_CLASS(C) {\n"
22256                "  int i;\n"
22257                "  int j;\n"
22258                "};");
22259 }
22260 
22261 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
22262   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
22263   TwoIndent.ContinuationIndentWidth = 2;
22264 
22265   EXPECT_EQ("int i =\n"
22266             "  longFunction(\n"
22267             "    arg);",
22268             format("int i = longFunction(arg);", TwoIndent));
22269 
22270   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
22271   SixIndent.ContinuationIndentWidth = 6;
22272 
22273   EXPECT_EQ("int i =\n"
22274             "      longFunction(\n"
22275             "            arg);",
22276             format("int i = longFunction(arg);", SixIndent));
22277 }
22278 
22279 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
22280   FormatStyle Style = getLLVMStyle();
22281   verifyFormat("int Foo::getter(\n"
22282                "    //\n"
22283                ") const {\n"
22284                "  return foo;\n"
22285                "}",
22286                Style);
22287   verifyFormat("void Foo::setter(\n"
22288                "    //\n"
22289                ") {\n"
22290                "  foo = 1;\n"
22291                "}",
22292                Style);
22293 }
22294 
22295 TEST_F(FormatTest, SpacesInAngles) {
22296   FormatStyle Spaces = getLLVMStyle();
22297   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22298 
22299   verifyFormat("vector< ::std::string > x1;", Spaces);
22300   verifyFormat("Foo< int, Bar > x2;", Spaces);
22301   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
22302 
22303   verifyFormat("static_cast< int >(arg);", Spaces);
22304   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
22305   verifyFormat("f< int, float >();", Spaces);
22306   verifyFormat("template <> g() {}", Spaces);
22307   verifyFormat("template < std::vector< int > > f() {}", Spaces);
22308   verifyFormat("std::function< void(int, int) > fct;", Spaces);
22309   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
22310                Spaces);
22311 
22312   Spaces.Standard = FormatStyle::LS_Cpp03;
22313   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22314   verifyFormat("A< A< int > >();", Spaces);
22315 
22316   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22317   verifyFormat("A<A<int> >();", Spaces);
22318 
22319   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22320   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22321                Spaces);
22322   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22323                Spaces);
22324 
22325   verifyFormat("A<A<int> >();", Spaces);
22326   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22327   verifyFormat("A< A< int > >();", Spaces);
22328 
22329   Spaces.Standard = FormatStyle::LS_Cpp11;
22330   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22331   verifyFormat("A< A< int > >();", Spaces);
22332 
22333   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22334   verifyFormat("vector<::std::string> x4;", Spaces);
22335   verifyFormat("vector<int> x5;", Spaces);
22336   verifyFormat("Foo<int, Bar> x6;", Spaces);
22337   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22338 
22339   verifyFormat("A<A<int>>();", Spaces);
22340 
22341   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22342   verifyFormat("vector<::std::string> x4;", Spaces);
22343   verifyFormat("vector< ::std::string > x4;", Spaces);
22344   verifyFormat("vector<int> x5;", Spaces);
22345   verifyFormat("vector< int > x5;", Spaces);
22346   verifyFormat("Foo<int, Bar> x6;", Spaces);
22347   verifyFormat("Foo< int, Bar > x6;", Spaces);
22348   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22349   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22350 
22351   verifyFormat("A<A<int>>();", Spaces);
22352   verifyFormat("A< A< int > >();", Spaces);
22353   verifyFormat("A<A<int > >();", Spaces);
22354   verifyFormat("A< A< int>>();", Spaces);
22355 
22356   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22357   verifyFormat("// clang-format off\n"
22358                "foo<<<1, 1>>>();\n"
22359                "// clang-format on\n",
22360                Spaces);
22361   verifyFormat("// clang-format off\n"
22362                "foo< < <1, 1> > >();\n"
22363                "// clang-format on\n",
22364                Spaces);
22365 }
22366 
22367 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22368   FormatStyle Style = getLLVMStyle();
22369   Style.SpaceAfterTemplateKeyword = false;
22370   verifyFormat("template<int> void foo();", Style);
22371 }
22372 
22373 TEST_F(FormatTest, TripleAngleBrackets) {
22374   verifyFormat("f<<<1, 1>>>();");
22375   verifyFormat("f<<<1, 1, 1, s>>>();");
22376   verifyFormat("f<<<a, b, c, d>>>();");
22377   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22378   verifyFormat("f<param><<<1, 1>>>();");
22379   verifyFormat("f<1><<<1, 1>>>();");
22380   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22381   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22382                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22383   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22384                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22385 }
22386 
22387 TEST_F(FormatTest, MergeLessLessAtEnd) {
22388   verifyFormat("<<");
22389   EXPECT_EQ("< < <", format("\\\n<<<"));
22390   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22391                "aaallvm::outs() <<");
22392   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22393                "aaaallvm::outs()\n    <<");
22394 }
22395 
22396 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22397   std::string code = "#if A\n"
22398                      "#if B\n"
22399                      "a.\n"
22400                      "#endif\n"
22401                      "    a = 1;\n"
22402                      "#else\n"
22403                      "#endif\n"
22404                      "#if C\n"
22405                      "#else\n"
22406                      "#endif\n";
22407   EXPECT_EQ(code, format(code));
22408 }
22409 
22410 TEST_F(FormatTest, HandleConflictMarkers) {
22411   // Git/SVN conflict markers.
22412   EXPECT_EQ("int a;\n"
22413             "void f() {\n"
22414             "  callme(some(parameter1,\n"
22415             "<<<<<<< text by the vcs\n"
22416             "              parameter2),\n"
22417             "||||||| text by the vcs\n"
22418             "              parameter2),\n"
22419             "         parameter3,\n"
22420             "======= text by the vcs\n"
22421             "              parameter2, parameter3),\n"
22422             ">>>>>>> text by the vcs\n"
22423             "         otherparameter);\n",
22424             format("int a;\n"
22425                    "void f() {\n"
22426                    "  callme(some(parameter1,\n"
22427                    "<<<<<<< text by the vcs\n"
22428                    "  parameter2),\n"
22429                    "||||||| text by the vcs\n"
22430                    "  parameter2),\n"
22431                    "  parameter3,\n"
22432                    "======= text by the vcs\n"
22433                    "  parameter2,\n"
22434                    "  parameter3),\n"
22435                    ">>>>>>> text by the vcs\n"
22436                    "  otherparameter);\n"));
22437 
22438   // Perforce markers.
22439   EXPECT_EQ("void f() {\n"
22440             "  function(\n"
22441             ">>>> text by the vcs\n"
22442             "      parameter,\n"
22443             "==== text by the vcs\n"
22444             "      parameter,\n"
22445             "==== text by the vcs\n"
22446             "      parameter,\n"
22447             "<<<< text by the vcs\n"
22448             "      parameter);\n",
22449             format("void f() {\n"
22450                    "  function(\n"
22451                    ">>>> text by the vcs\n"
22452                    "  parameter,\n"
22453                    "==== text by the vcs\n"
22454                    "  parameter,\n"
22455                    "==== text by the vcs\n"
22456                    "  parameter,\n"
22457                    "<<<< text by the vcs\n"
22458                    "  parameter);\n"));
22459 
22460   EXPECT_EQ("<<<<<<<\n"
22461             "|||||||\n"
22462             "=======\n"
22463             ">>>>>>>",
22464             format("<<<<<<<\n"
22465                    "|||||||\n"
22466                    "=======\n"
22467                    ">>>>>>>"));
22468 
22469   EXPECT_EQ("<<<<<<<\n"
22470             "|||||||\n"
22471             "int i;\n"
22472             "=======\n"
22473             ">>>>>>>",
22474             format("<<<<<<<\n"
22475                    "|||||||\n"
22476                    "int i;\n"
22477                    "=======\n"
22478                    ">>>>>>>"));
22479 
22480   // FIXME: Handle parsing of macros around conflict markers correctly:
22481   EXPECT_EQ("#define Macro \\\n"
22482             "<<<<<<<\n"
22483             "Something \\\n"
22484             "|||||||\n"
22485             "Else \\\n"
22486             "=======\n"
22487             "Other \\\n"
22488             ">>>>>>>\n"
22489             "    End int i;\n",
22490             format("#define Macro \\\n"
22491                    "<<<<<<<\n"
22492                    "  Something \\\n"
22493                    "|||||||\n"
22494                    "  Else \\\n"
22495                    "=======\n"
22496                    "  Other \\\n"
22497                    ">>>>>>>\n"
22498                    "  End\n"
22499                    "int i;\n"));
22500 
22501   verifyFormat(R"(====
22502 #ifdef A
22503 a
22504 #else
22505 b
22506 #endif
22507 )");
22508 }
22509 
22510 TEST_F(FormatTest, DisableRegions) {
22511   EXPECT_EQ("int i;\n"
22512             "// clang-format off\n"
22513             "  int j;\n"
22514             "// clang-format on\n"
22515             "int k;",
22516             format(" int  i;\n"
22517                    "   // clang-format off\n"
22518                    "  int j;\n"
22519                    " // clang-format on\n"
22520                    "   int   k;"));
22521   EXPECT_EQ("int i;\n"
22522             "/* clang-format off */\n"
22523             "  int j;\n"
22524             "/* clang-format on */\n"
22525             "int k;",
22526             format(" int  i;\n"
22527                    "   /* clang-format off */\n"
22528                    "  int j;\n"
22529                    " /* clang-format on */\n"
22530                    "   int   k;"));
22531 
22532   // Don't reflow comments within disabled regions.
22533   EXPECT_EQ("// clang-format off\n"
22534             "// long long long long long long line\n"
22535             "/* clang-format on */\n"
22536             "/* long long long\n"
22537             " * long long long\n"
22538             " * line */\n"
22539             "int i;\n"
22540             "/* clang-format off */\n"
22541             "/* long long long long long long line */\n",
22542             format("// clang-format off\n"
22543                    "// long long long long long long line\n"
22544                    "/* clang-format on */\n"
22545                    "/* long long long long long long line */\n"
22546                    "int i;\n"
22547                    "/* clang-format off */\n"
22548                    "/* long long long long long long line */\n",
22549                    getLLVMStyleWithColumns(20)));
22550 }
22551 
22552 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22553   format("? ) =");
22554   verifyNoCrash("#define a\\\n /**/}");
22555 }
22556 
22557 TEST_F(FormatTest, FormatsTableGenCode) {
22558   FormatStyle Style = getLLVMStyle();
22559   Style.Language = FormatStyle::LK_TableGen;
22560   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22561 }
22562 
22563 TEST_F(FormatTest, ArrayOfTemplates) {
22564   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22565             format("auto a = new unique_ptr<int > [ 10];"));
22566 
22567   FormatStyle Spaces = getLLVMStyle();
22568   Spaces.SpacesInSquareBrackets = true;
22569   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22570             format("auto a = new unique_ptr<int > [10];", Spaces));
22571 }
22572 
22573 TEST_F(FormatTest, ArrayAsTemplateType) {
22574   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22575             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22576 
22577   FormatStyle Spaces = getLLVMStyle();
22578   Spaces.SpacesInSquareBrackets = true;
22579   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22580             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22581 }
22582 
22583 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22584 
22585 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22586   llvm::vfs::InMemoryFileSystem FS;
22587   auto Style1 = getStyle("file", "", "Google", "", &FS);
22588   ASSERT_TRUE((bool)Style1);
22589   ASSERT_EQ(*Style1, getGoogleStyle());
22590 }
22591 
22592 TEST(FormatStyle, GetStyleOfFile) {
22593   llvm::vfs::InMemoryFileSystem FS;
22594   // Test 1: format file in the same directory.
22595   ASSERT_TRUE(
22596       FS.addFile("/a/.clang-format", 0,
22597                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22598   ASSERT_TRUE(
22599       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22600   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22601   ASSERT_TRUE((bool)Style1);
22602   ASSERT_EQ(*Style1, getLLVMStyle());
22603 
22604   // Test 2.1: fallback to default.
22605   ASSERT_TRUE(
22606       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22607   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22608   ASSERT_TRUE((bool)Style2);
22609   ASSERT_EQ(*Style2, getMozillaStyle());
22610 
22611   // Test 2.2: no format on 'none' fallback style.
22612   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22613   ASSERT_TRUE((bool)Style2);
22614   ASSERT_EQ(*Style2, getNoStyle());
22615 
22616   // Test 2.3: format if config is found with no based style while fallback is
22617   // 'none'.
22618   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22619                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22620   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22621   ASSERT_TRUE((bool)Style2);
22622   ASSERT_EQ(*Style2, getLLVMStyle());
22623 
22624   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22625   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22626   ASSERT_TRUE((bool)Style2);
22627   ASSERT_EQ(*Style2, getLLVMStyle());
22628 
22629   // Test 3: format file in parent directory.
22630   ASSERT_TRUE(
22631       FS.addFile("/c/.clang-format", 0,
22632                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22633   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22634                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22635   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22636   ASSERT_TRUE((bool)Style3);
22637   ASSERT_EQ(*Style3, getGoogleStyle());
22638 
22639   // Test 4: error on invalid fallback style
22640   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22641   ASSERT_FALSE((bool)Style4);
22642   llvm::consumeError(Style4.takeError());
22643 
22644   // Test 5: error on invalid yaml on command line
22645   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22646   ASSERT_FALSE((bool)Style5);
22647   llvm::consumeError(Style5.takeError());
22648 
22649   // Test 6: error on invalid style
22650   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22651   ASSERT_FALSE((bool)Style6);
22652   llvm::consumeError(Style6.takeError());
22653 
22654   // Test 7: found config file, error on parsing it
22655   ASSERT_TRUE(
22656       FS.addFile("/d/.clang-format", 0,
22657                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22658                                                   "InvalidKey: InvalidValue")));
22659   ASSERT_TRUE(
22660       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22661   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22662   ASSERT_FALSE((bool)Style7a);
22663   llvm::consumeError(Style7a.takeError());
22664 
22665   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22666   ASSERT_TRUE((bool)Style7b);
22667 
22668   // Test 8: inferred per-language defaults apply.
22669   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22670   ASSERT_TRUE((bool)StyleTd);
22671   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22672 
22673   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22674   // fallback style.
22675   ASSERT_TRUE(FS.addFile(
22676       "/e/sub/.clang-format", 0,
22677       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22678                                        "ColumnLimit: 20")));
22679   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22680                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22681   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22682   ASSERT_TRUE(static_cast<bool>(Style9));
22683   ASSERT_EQ(*Style9, [] {
22684     auto Style = getNoStyle();
22685     Style.ColumnLimit = 20;
22686     return Style;
22687   }());
22688 
22689   // Test 9.1.2: propagate more than one level with no parent file.
22690   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22691                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22692   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22693                          llvm::MemoryBuffer::getMemBuffer(
22694                              "BasedOnStyle: InheritParentConfig\n"
22695                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22696   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22697 
22698   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22699   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22700   ASSERT_TRUE(static_cast<bool>(Style9));
22701   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22702     auto Style = getNoStyle();
22703     Style.ColumnLimit = 20;
22704     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22705     return Style;
22706   }());
22707 
22708   // Test 9.2: with LLVM fallback style
22709   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22710   ASSERT_TRUE(static_cast<bool>(Style9));
22711   ASSERT_EQ(*Style9, [] {
22712     auto Style = getLLVMStyle();
22713     Style.ColumnLimit = 20;
22714     return Style;
22715   }());
22716 
22717   // Test 9.3: with a parent file
22718   ASSERT_TRUE(
22719       FS.addFile("/e/.clang-format", 0,
22720                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
22721                                                   "UseTab: Always")));
22722   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22723   ASSERT_TRUE(static_cast<bool>(Style9));
22724   ASSERT_EQ(*Style9, [] {
22725     auto Style = getGoogleStyle();
22726     Style.ColumnLimit = 20;
22727     Style.UseTab = FormatStyle::UT_Always;
22728     return Style;
22729   }());
22730 
22731   // Test 9.4: propagate more than one level with a parent file.
22732   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
22733     auto Style = getGoogleStyle();
22734     Style.ColumnLimit = 20;
22735     Style.UseTab = FormatStyle::UT_Always;
22736     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22737     return Style;
22738   }();
22739 
22740   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22741   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22742   ASSERT_TRUE(static_cast<bool>(Style9));
22743   ASSERT_EQ(*Style9, SubSubStyle);
22744 
22745   // Test 9.5: use InheritParentConfig as style name
22746   Style9 =
22747       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
22748   ASSERT_TRUE(static_cast<bool>(Style9));
22749   ASSERT_EQ(*Style9, SubSubStyle);
22750 
22751   // Test 9.6: use command line style with inheritance
22752   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
22753                     "none", "", &FS);
22754   ASSERT_TRUE(static_cast<bool>(Style9));
22755   ASSERT_EQ(*Style9, SubSubStyle);
22756 
22757   // Test 9.7: use command line style with inheritance and own config
22758   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
22759                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
22760                     "/e/sub/code.cpp", "none", "", &FS);
22761   ASSERT_TRUE(static_cast<bool>(Style9));
22762   ASSERT_EQ(*Style9, SubSubStyle);
22763 
22764   // Test 9.8: use inheritance from a file without BasedOnStyle
22765   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
22766                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
22767   ASSERT_TRUE(
22768       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
22769                  llvm::MemoryBuffer::getMemBuffer(
22770                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
22771   // Make sure we do not use the fallback style
22772   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
22773   ASSERT_TRUE(static_cast<bool>(Style9));
22774   ASSERT_EQ(*Style9, [] {
22775     auto Style = getLLVMStyle();
22776     Style.ColumnLimit = 123;
22777     return Style;
22778   }());
22779 
22780   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
22781   ASSERT_TRUE(static_cast<bool>(Style9));
22782   ASSERT_EQ(*Style9, [] {
22783     auto Style = getLLVMStyle();
22784     Style.ColumnLimit = 123;
22785     Style.IndentWidth = 7;
22786     return Style;
22787   }());
22788 
22789   // Test 9.9: use inheritance from a specific config file.
22790   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
22791                     "none", "", &FS);
22792   ASSERT_TRUE(static_cast<bool>(Style9));
22793   ASSERT_EQ(*Style9, SubSubStyle);
22794 }
22795 
22796 TEST(FormatStyle, GetStyleOfSpecificFile) {
22797   llvm::vfs::InMemoryFileSystem FS;
22798   // Specify absolute path to a format file in a parent directory.
22799   ASSERT_TRUE(
22800       FS.addFile("/e/.clang-format", 0,
22801                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22802   ASSERT_TRUE(
22803       FS.addFile("/e/explicit.clang-format", 0,
22804                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22805   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
22806                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22807   auto Style = getStyle("file:/e/explicit.clang-format",
22808                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22809   ASSERT_TRUE(static_cast<bool>(Style));
22810   ASSERT_EQ(*Style, getGoogleStyle());
22811 
22812   // Specify relative path to a format file.
22813   ASSERT_TRUE(
22814       FS.addFile("../../e/explicit.clang-format", 0,
22815                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22816   Style = getStyle("file:../../e/explicit.clang-format",
22817                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22818   ASSERT_TRUE(static_cast<bool>(Style));
22819   ASSERT_EQ(*Style, getGoogleStyle());
22820 
22821   // Specify path to a format file that does not exist.
22822   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
22823                    "LLVM", "", &FS);
22824   ASSERT_FALSE(static_cast<bool>(Style));
22825   llvm::consumeError(Style.takeError());
22826 
22827   // Specify path to a file on the filesystem.
22828   SmallString<128> FormatFilePath;
22829   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
22830       "FormatFileTest", "tpl", FormatFilePath);
22831   EXPECT_FALSE((bool)ECF);
22832   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
22833   EXPECT_FALSE((bool)ECF);
22834   FormatFileTest << "BasedOnStyle: Google\n";
22835   FormatFileTest.close();
22836 
22837   SmallString<128> TestFilePath;
22838   std::error_code ECT =
22839       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
22840   EXPECT_FALSE((bool)ECT);
22841   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
22842   CodeFileTest << "int i;\n";
22843   CodeFileTest.close();
22844 
22845   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
22846   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
22847 
22848   llvm::sys::fs::remove(FormatFilePath.c_str());
22849   llvm::sys::fs::remove(TestFilePath.c_str());
22850   ASSERT_TRUE(static_cast<bool>(Style));
22851   ASSERT_EQ(*Style, getGoogleStyle());
22852 }
22853 
22854 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
22855   // Column limit is 20.
22856   std::string Code = "Type *a =\n"
22857                      "    new Type();\n"
22858                      "g(iiiii, 0, jjjjj,\n"
22859                      "  0, kkkkk, 0, mm);\n"
22860                      "int  bad     = format   ;";
22861   std::string Expected = "auto a = new Type();\n"
22862                          "g(iiiii, nullptr,\n"
22863                          "  jjjjj, nullptr,\n"
22864                          "  kkkkk, nullptr,\n"
22865                          "  mm);\n"
22866                          "int  bad     = format   ;";
22867   FileID ID = Context.createInMemoryFile("format.cpp", Code);
22868   tooling::Replacements Replaces = toReplacements(
22869       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
22870                             "auto "),
22871        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
22872                             "nullptr"),
22873        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
22874                             "nullptr"),
22875        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
22876                             "nullptr")});
22877 
22878   FormatStyle Style = getLLVMStyle();
22879   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
22880   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22881   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22882       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22883   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22884   EXPECT_TRUE(static_cast<bool>(Result));
22885   EXPECT_EQ(Expected, *Result);
22886 }
22887 
22888 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
22889   std::string Code = "#include \"a.h\"\n"
22890                      "#include \"c.h\"\n"
22891                      "\n"
22892                      "int main() {\n"
22893                      "  return 0;\n"
22894                      "}";
22895   std::string Expected = "#include \"a.h\"\n"
22896                          "#include \"b.h\"\n"
22897                          "#include \"c.h\"\n"
22898                          "\n"
22899                          "int main() {\n"
22900                          "  return 0;\n"
22901                          "}";
22902   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
22903   tooling::Replacements Replaces = toReplacements(
22904       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
22905                             "#include \"b.h\"\n")});
22906 
22907   FormatStyle Style = getLLVMStyle();
22908   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
22909   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22910   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22911       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22912   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22913   EXPECT_TRUE(static_cast<bool>(Result));
22914   EXPECT_EQ(Expected, *Result);
22915 }
22916 
22917 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
22918   EXPECT_EQ("using std::cin;\n"
22919             "using std::cout;",
22920             format("using std::cout;\n"
22921                    "using std::cin;",
22922                    getGoogleStyle()));
22923 }
22924 
22925 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
22926   FormatStyle Style = getLLVMStyle();
22927   Style.Standard = FormatStyle::LS_Cpp03;
22928   // cpp03 recognize this string as identifier u8 and literal character 'a'
22929   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
22930 }
22931 
22932 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
22933   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
22934   // all modes, including C++11, C++14 and C++17
22935   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
22936 }
22937 
22938 TEST_F(FormatTest, DoNotFormatLikelyXml) {
22939   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
22940   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
22941 }
22942 
22943 TEST_F(FormatTest, StructuredBindings) {
22944   // Structured bindings is a C++17 feature.
22945   // all modes, including C++11, C++14 and C++17
22946   verifyFormat("auto [a, b] = f();");
22947   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
22948   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
22949   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
22950   EXPECT_EQ("auto const volatile [a, b] = f();",
22951             format("auto  const   volatile[a, b] = f();"));
22952   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
22953   EXPECT_EQ("auto &[a, b, c] = f();",
22954             format("auto   &[  a  ,  b,c   ] = f();"));
22955   EXPECT_EQ("auto &&[a, b, c] = f();",
22956             format("auto   &&[  a  ,  b,c   ] = f();"));
22957   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
22958   EXPECT_EQ("auto const volatile &&[a, b] = f();",
22959             format("auto  const  volatile  &&[a, b] = f();"));
22960   EXPECT_EQ("auto const &&[a, b] = f();",
22961             format("auto  const   &&  [a, b] = f();"));
22962   EXPECT_EQ("const auto &[a, b] = f();",
22963             format("const  auto  &  [a, b] = f();"));
22964   EXPECT_EQ("const auto volatile &&[a, b] = f();",
22965             format("const  auto   volatile  &&[a, b] = f();"));
22966   EXPECT_EQ("volatile const auto &&[a, b] = f();",
22967             format("volatile  const  auto   &&[a, b] = f();"));
22968   EXPECT_EQ("const auto &&[a, b] = f();",
22969             format("const  auto  &&  [a, b] = f();"));
22970 
22971   // Make sure we don't mistake structured bindings for lambdas.
22972   FormatStyle PointerMiddle = getLLVMStyle();
22973   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
22974   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
22975   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
22976   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
22977   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
22978   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
22979   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
22980   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
22981   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
22982   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
22983   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
22984   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
22985   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
22986 
22987   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
22988             format("for (const auto   &&   [a, b] : some_range) {\n}"));
22989   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
22990             format("for (const auto   &   [a, b] : some_range) {\n}"));
22991   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
22992             format("for (const auto[a, b] : some_range) {\n}"));
22993   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
22994   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
22995   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
22996   EXPECT_EQ("auto const &[x, y](expr);",
22997             format("auto  const  &  [x,y]  (expr);"));
22998   EXPECT_EQ("auto const &&[x, y](expr);",
22999             format("auto  const  &&  [x,y]  (expr);"));
23000   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
23001   EXPECT_EQ("auto const &[x, y]{expr};",
23002             format("auto  const  &  [x,y]  {expr};"));
23003   EXPECT_EQ("auto const &&[x, y]{expr};",
23004             format("auto  const  &&  [x,y]  {expr};"));
23005 
23006   FormatStyle Spaces = getLLVMStyle();
23007   Spaces.SpacesInSquareBrackets = true;
23008   verifyFormat("auto [ a, b ] = f();", Spaces);
23009   verifyFormat("auto &&[ a, b ] = f();", Spaces);
23010   verifyFormat("auto &[ a, b ] = f();", Spaces);
23011   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
23012   verifyFormat("auto const &[ a, b ] = f();", Spaces);
23013 }
23014 
23015 TEST_F(FormatTest, FileAndCode) {
23016   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
23017   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
23018   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
23019   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
23020   EXPECT_EQ(FormatStyle::LK_ObjC,
23021             guessLanguage("foo.h", "@interface Foo\n@end\n"));
23022   EXPECT_EQ(
23023       FormatStyle::LK_ObjC,
23024       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
23025   EXPECT_EQ(FormatStyle::LK_ObjC,
23026             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
23027   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
23028   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
23029   EXPECT_EQ(FormatStyle::LK_ObjC,
23030             guessLanguage("foo", "@interface Foo\n@end\n"));
23031   EXPECT_EQ(FormatStyle::LK_ObjC,
23032             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
23033   EXPECT_EQ(
23034       FormatStyle::LK_ObjC,
23035       guessLanguage("foo.h",
23036                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
23037   EXPECT_EQ(
23038       FormatStyle::LK_Cpp,
23039       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
23040   // Only one of the two preprocessor regions has ObjC-like code.
23041   EXPECT_EQ(FormatStyle::LK_ObjC,
23042             guessLanguage("foo.h", "#if A\n"
23043                                    "#define B() C\n"
23044                                    "#else\n"
23045                                    "#define B() [NSString a:@\"\"]\n"
23046                                    "#endif\n"));
23047 }
23048 
23049 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
23050   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
23051   EXPECT_EQ(FormatStyle::LK_ObjC,
23052             guessLanguage("foo.h", "array[[calculator getIndex]];"));
23053   EXPECT_EQ(FormatStyle::LK_Cpp,
23054             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
23055   EXPECT_EQ(
23056       FormatStyle::LK_Cpp,
23057       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
23058   EXPECT_EQ(FormatStyle::LK_ObjC,
23059             guessLanguage("foo.h", "[[noreturn foo] bar];"));
23060   EXPECT_EQ(FormatStyle::LK_Cpp,
23061             guessLanguage("foo.h", "[[clang::fallthrough]];"));
23062   EXPECT_EQ(FormatStyle::LK_ObjC,
23063             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
23064   EXPECT_EQ(FormatStyle::LK_Cpp,
23065             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
23066   EXPECT_EQ(FormatStyle::LK_Cpp,
23067             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
23068   EXPECT_EQ(FormatStyle::LK_ObjC,
23069             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
23070   EXPECT_EQ(FormatStyle::LK_Cpp,
23071             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
23072   EXPECT_EQ(
23073       FormatStyle::LK_Cpp,
23074       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
23075   EXPECT_EQ(
23076       FormatStyle::LK_Cpp,
23077       guessLanguage("foo.h",
23078                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
23079   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
23080 }
23081 
23082 TEST_F(FormatTest, GuessLanguageWithCaret) {
23083   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
23084   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
23085   EXPECT_EQ(FormatStyle::LK_ObjC,
23086             guessLanguage("foo.h", "int(^)(char, float);"));
23087   EXPECT_EQ(FormatStyle::LK_ObjC,
23088             guessLanguage("foo.h", "int(^foo)(char, float);"));
23089   EXPECT_EQ(FormatStyle::LK_ObjC,
23090             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
23091   EXPECT_EQ(FormatStyle::LK_ObjC,
23092             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
23093   EXPECT_EQ(
23094       FormatStyle::LK_ObjC,
23095       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
23096 }
23097 
23098 TEST_F(FormatTest, GuessLanguageWithPragmas) {
23099   EXPECT_EQ(FormatStyle::LK_Cpp,
23100             guessLanguage("foo.h", "__pragma(warning(disable:))"));
23101   EXPECT_EQ(FormatStyle::LK_Cpp,
23102             guessLanguage("foo.h", "#pragma(warning(disable:))"));
23103   EXPECT_EQ(FormatStyle::LK_Cpp,
23104             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
23105 }
23106 
23107 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
23108   // ASM symbolic names are identifiers that must be surrounded by [] without
23109   // space in between:
23110   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
23111 
23112   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
23113   verifyFormat(R"(//
23114 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
23115 )");
23116 
23117   // A list of several ASM symbolic names.
23118   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
23119 
23120   // ASM symbolic names in inline ASM with inputs and outputs.
23121   verifyFormat(R"(//
23122 asm("cmoveq %1, %2, %[result]"
23123     : [result] "=r"(result)
23124     : "r"(test), "r"(new), "[result]"(old));
23125 )");
23126 
23127   // ASM symbolic names in inline ASM with no outputs.
23128   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
23129 }
23130 
23131 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
23132   EXPECT_EQ(FormatStyle::LK_Cpp,
23133             guessLanguage("foo.h", "void f() {\n"
23134                                    "  asm (\"mov %[e], %[d]\"\n"
23135                                    "     : [d] \"=rm\" (d)\n"
23136                                    "       [e] \"rm\" (*e));\n"
23137                                    "}"));
23138   EXPECT_EQ(FormatStyle::LK_Cpp,
23139             guessLanguage("foo.h", "void f() {\n"
23140                                    "  _asm (\"mov %[e], %[d]\"\n"
23141                                    "     : [d] \"=rm\" (d)\n"
23142                                    "       [e] \"rm\" (*e));\n"
23143                                    "}"));
23144   EXPECT_EQ(FormatStyle::LK_Cpp,
23145             guessLanguage("foo.h", "void f() {\n"
23146                                    "  __asm (\"mov %[e], %[d]\"\n"
23147                                    "     : [d] \"=rm\" (d)\n"
23148                                    "       [e] \"rm\" (*e));\n"
23149                                    "}"));
23150   EXPECT_EQ(FormatStyle::LK_Cpp,
23151             guessLanguage("foo.h", "void f() {\n"
23152                                    "  __asm__ (\"mov %[e], %[d]\"\n"
23153                                    "     : [d] \"=rm\" (d)\n"
23154                                    "       [e] \"rm\" (*e));\n"
23155                                    "}"));
23156   EXPECT_EQ(FormatStyle::LK_Cpp,
23157             guessLanguage("foo.h", "void f() {\n"
23158                                    "  asm (\"mov %[e], %[d]\"\n"
23159                                    "     : [d] \"=rm\" (d),\n"
23160                                    "       [e] \"rm\" (*e));\n"
23161                                    "}"));
23162   EXPECT_EQ(FormatStyle::LK_Cpp,
23163             guessLanguage("foo.h", "void f() {\n"
23164                                    "  asm volatile (\"mov %[e], %[d]\"\n"
23165                                    "     : [d] \"=rm\" (d)\n"
23166                                    "       [e] \"rm\" (*e));\n"
23167                                    "}"));
23168 }
23169 
23170 TEST_F(FormatTest, GuessLanguageWithChildLines) {
23171   EXPECT_EQ(FormatStyle::LK_Cpp,
23172             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
23173   EXPECT_EQ(FormatStyle::LK_ObjC,
23174             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
23175   EXPECT_EQ(
23176       FormatStyle::LK_Cpp,
23177       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
23178   EXPECT_EQ(
23179       FormatStyle::LK_ObjC,
23180       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
23181 }
23182 
23183 TEST_F(FormatTest, TypenameMacros) {
23184   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
23185 
23186   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
23187   FormatStyle Google = getGoogleStyleWithColumns(0);
23188   Google.TypenameMacros = TypenameMacros;
23189   verifyFormat("struct foo {\n"
23190                "  int bar;\n"
23191                "  TAILQ_ENTRY(a) bleh;\n"
23192                "};",
23193                Google);
23194 
23195   FormatStyle Macros = getLLVMStyle();
23196   Macros.TypenameMacros = TypenameMacros;
23197 
23198   verifyFormat("STACK_OF(int) a;", Macros);
23199   verifyFormat("STACK_OF(int) *a;", Macros);
23200   verifyFormat("STACK_OF(int const *) *a;", Macros);
23201   verifyFormat("STACK_OF(int *const) *a;", Macros);
23202   verifyFormat("STACK_OF(int, string) a;", Macros);
23203   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
23204   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
23205   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
23206   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
23207   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
23208   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
23209 
23210   Macros.PointerAlignment = FormatStyle::PAS_Left;
23211   verifyFormat("STACK_OF(int)* a;", Macros);
23212   verifyFormat("STACK_OF(int*)* a;", Macros);
23213   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
23214   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
23215   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
23216 }
23217 
23218 TEST_F(FormatTest, AtomicQualifier) {
23219   // Check that we treate _Atomic as a type and not a function call
23220   FormatStyle Google = getGoogleStyleWithColumns(0);
23221   verifyFormat("struct foo {\n"
23222                "  int a1;\n"
23223                "  _Atomic(a) a2;\n"
23224                "  _Atomic(_Atomic(int) *const) a3;\n"
23225                "};",
23226                Google);
23227   verifyFormat("_Atomic(uint64_t) a;");
23228   verifyFormat("_Atomic(uint64_t) *a;");
23229   verifyFormat("_Atomic(uint64_t const *) *a;");
23230   verifyFormat("_Atomic(uint64_t *const) *a;");
23231   verifyFormat("_Atomic(const uint64_t *) *a;");
23232   verifyFormat("_Atomic(uint64_t) a;");
23233   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
23234   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
23235   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
23236   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
23237 
23238   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
23239   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
23240   FormatStyle Style = getLLVMStyle();
23241   Style.PointerAlignment = FormatStyle::PAS_Left;
23242   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
23243   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
23244   verifyFormat("_Atomic(int)* a;", Style);
23245   verifyFormat("_Atomic(int*)* a;", Style);
23246   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
23247 
23248   Style.SpacesInCStyleCastParentheses = true;
23249   Style.SpacesInParentheses = false;
23250   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
23251   Style.SpacesInCStyleCastParentheses = false;
23252   Style.SpacesInParentheses = true;
23253   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
23254   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
23255 }
23256 
23257 TEST_F(FormatTest, AmbersandInLamda) {
23258   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
23259   FormatStyle AlignStyle = getLLVMStyle();
23260   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
23261   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23262   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
23263   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23264 }
23265 
23266 TEST_F(FormatTest, SpacesInConditionalStatement) {
23267   FormatStyle Spaces = getLLVMStyle();
23268   Spaces.IfMacros.clear();
23269   Spaces.IfMacros.push_back("MYIF");
23270   Spaces.SpacesInConditionalStatement = true;
23271   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
23272   verifyFormat("if ( !a )\n  return;", Spaces);
23273   verifyFormat("if ( a )\n  return;", Spaces);
23274   verifyFormat("if constexpr ( a )\n  return;", Spaces);
23275   verifyFormat("MYIF ( a )\n  return;", Spaces);
23276   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
23277   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
23278   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
23279   verifyFormat("while ( a )\n  return;", Spaces);
23280   verifyFormat("while ( (a && b) )\n  return;", Spaces);
23281   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
23282   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
23283   // Check that space on the left of "::" is inserted as expected at beginning
23284   // of condition.
23285   verifyFormat("while ( ::func() )\n  return;", Spaces);
23286 
23287   // Check impact of ControlStatementsExceptControlMacros is honored.
23288   Spaces.SpaceBeforeParens =
23289       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
23290   verifyFormat("MYIF( a )\n  return;", Spaces);
23291   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
23292   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
23293 }
23294 
23295 TEST_F(FormatTest, AlternativeOperators) {
23296   // Test case for ensuring alternate operators are not
23297   // combined with their right most neighbour.
23298   verifyFormat("int a and b;");
23299   verifyFormat("int a and_eq b;");
23300   verifyFormat("int a bitand b;");
23301   verifyFormat("int a bitor b;");
23302   verifyFormat("int a compl b;");
23303   verifyFormat("int a not b;");
23304   verifyFormat("int a not_eq b;");
23305   verifyFormat("int a or b;");
23306   verifyFormat("int a xor b;");
23307   verifyFormat("int a xor_eq b;");
23308   verifyFormat("return this not_eq bitand other;");
23309   verifyFormat("bool operator not_eq(const X bitand other)");
23310 
23311   verifyFormat("int a and 5;");
23312   verifyFormat("int a and_eq 5;");
23313   verifyFormat("int a bitand 5;");
23314   verifyFormat("int a bitor 5;");
23315   verifyFormat("int a compl 5;");
23316   verifyFormat("int a not 5;");
23317   verifyFormat("int a not_eq 5;");
23318   verifyFormat("int a or 5;");
23319   verifyFormat("int a xor 5;");
23320   verifyFormat("int a xor_eq 5;");
23321 
23322   verifyFormat("int a compl(5);");
23323   verifyFormat("int a not(5);");
23324 
23325   /* FIXME handle alternate tokens
23326    * https://en.cppreference.com/w/cpp/language/operator_alternative
23327   // alternative tokens
23328   verifyFormat("compl foo();");     //  ~foo();
23329   verifyFormat("foo() <%%>;");      // foo();
23330   verifyFormat("void foo() <%%>;"); // void foo(){}
23331   verifyFormat("int a <:1:>;");     // int a[1];[
23332   verifyFormat("%:define ABC abc"); // #define ABC abc
23333   verifyFormat("%:%:");             // ##
23334   */
23335 }
23336 
23337 TEST_F(FormatTest, STLWhileNotDefineChed) {
23338   verifyFormat("#if defined(while)\n"
23339                "#define while EMIT WARNING C4005\n"
23340                "#endif // while");
23341 }
23342 
23343 TEST_F(FormatTest, OperatorSpacing) {
23344   FormatStyle Style = getLLVMStyle();
23345   Style.PointerAlignment = FormatStyle::PAS_Right;
23346   verifyFormat("Foo::operator*();", Style);
23347   verifyFormat("Foo::operator void *();", Style);
23348   verifyFormat("Foo::operator void **();", Style);
23349   verifyFormat("Foo::operator void *&();", Style);
23350   verifyFormat("Foo::operator void *&&();", Style);
23351   verifyFormat("Foo::operator void const *();", Style);
23352   verifyFormat("Foo::operator void const **();", Style);
23353   verifyFormat("Foo::operator void const *&();", Style);
23354   verifyFormat("Foo::operator void const *&&();", Style);
23355   verifyFormat("Foo::operator()(void *);", Style);
23356   verifyFormat("Foo::operator*(void *);", Style);
23357   verifyFormat("Foo::operator*();", Style);
23358   verifyFormat("Foo::operator**();", Style);
23359   verifyFormat("Foo::operator&();", Style);
23360   verifyFormat("Foo::operator<int> *();", Style);
23361   verifyFormat("Foo::operator<Foo> *();", Style);
23362   verifyFormat("Foo::operator<int> **();", Style);
23363   verifyFormat("Foo::operator<Foo> **();", Style);
23364   verifyFormat("Foo::operator<int> &();", Style);
23365   verifyFormat("Foo::operator<Foo> &();", Style);
23366   verifyFormat("Foo::operator<int> &&();", Style);
23367   verifyFormat("Foo::operator<Foo> &&();", Style);
23368   verifyFormat("Foo::operator<int> *&();", Style);
23369   verifyFormat("Foo::operator<Foo> *&();", Style);
23370   verifyFormat("Foo::operator<int> *&&();", Style);
23371   verifyFormat("Foo::operator<Foo> *&&();", Style);
23372   verifyFormat("operator*(int (*)(), class Foo);", Style);
23373 
23374   verifyFormat("Foo::operator&();", Style);
23375   verifyFormat("Foo::operator void &();", Style);
23376   verifyFormat("Foo::operator void const &();", Style);
23377   verifyFormat("Foo::operator()(void &);", Style);
23378   verifyFormat("Foo::operator&(void &);", Style);
23379   verifyFormat("Foo::operator&();", Style);
23380   verifyFormat("operator&(int (&)(), class Foo);", Style);
23381   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23382 
23383   verifyFormat("Foo::operator&&();", Style);
23384   verifyFormat("Foo::operator**();", Style);
23385   verifyFormat("Foo::operator void &&();", Style);
23386   verifyFormat("Foo::operator void const &&();", Style);
23387   verifyFormat("Foo::operator()(void &&);", Style);
23388   verifyFormat("Foo::operator&&(void &&);", Style);
23389   verifyFormat("Foo::operator&&();", Style);
23390   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23391   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23392   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23393                Style);
23394   verifyFormat("operator void **()", Style);
23395   verifyFormat("operator const FooRight<Object> &()", Style);
23396   verifyFormat("operator const FooRight<Object> *()", Style);
23397   verifyFormat("operator const FooRight<Object> **()", Style);
23398   verifyFormat("operator const FooRight<Object> *&()", Style);
23399   verifyFormat("operator const FooRight<Object> *&&()", Style);
23400 
23401   Style.PointerAlignment = FormatStyle::PAS_Left;
23402   verifyFormat("Foo::operator*();", Style);
23403   verifyFormat("Foo::operator**();", Style);
23404   verifyFormat("Foo::operator void*();", Style);
23405   verifyFormat("Foo::operator void**();", Style);
23406   verifyFormat("Foo::operator void*&();", Style);
23407   verifyFormat("Foo::operator void*&&();", Style);
23408   verifyFormat("Foo::operator void const*();", Style);
23409   verifyFormat("Foo::operator void const**();", Style);
23410   verifyFormat("Foo::operator void const*&();", Style);
23411   verifyFormat("Foo::operator void const*&&();", Style);
23412   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23413   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23414   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23415   verifyFormat("Foo::operator()(void*);", Style);
23416   verifyFormat("Foo::operator*(void*);", Style);
23417   verifyFormat("Foo::operator*();", Style);
23418   verifyFormat("Foo::operator<int>*();", Style);
23419   verifyFormat("Foo::operator<Foo>*();", Style);
23420   verifyFormat("Foo::operator<int>**();", Style);
23421   verifyFormat("Foo::operator<Foo>**();", Style);
23422   verifyFormat("Foo::operator<Foo>*&();", Style);
23423   verifyFormat("Foo::operator<int>&();", Style);
23424   verifyFormat("Foo::operator<Foo>&();", Style);
23425   verifyFormat("Foo::operator<int>&&();", Style);
23426   verifyFormat("Foo::operator<Foo>&&();", Style);
23427   verifyFormat("Foo::operator<int>*&();", Style);
23428   verifyFormat("Foo::operator<Foo>*&();", Style);
23429   verifyFormat("operator*(int (*)(), class Foo);", Style);
23430 
23431   verifyFormat("Foo::operator&();", Style);
23432   verifyFormat("Foo::operator void&();", Style);
23433   verifyFormat("Foo::operator void const&();", Style);
23434   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23435   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23436   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
23437   verifyFormat("Foo::operator()(void&);", Style);
23438   verifyFormat("Foo::operator&(void&);", Style);
23439   verifyFormat("Foo::operator&();", Style);
23440   verifyFormat("operator&(int (&)(), class Foo);", Style);
23441   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23442   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23443 
23444   verifyFormat("Foo::operator&&();", Style);
23445   verifyFormat("Foo::operator void&&();", Style);
23446   verifyFormat("Foo::operator void const&&();", Style);
23447   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23448   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23449   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23450   verifyFormat("Foo::operator()(void&&);", Style);
23451   verifyFormat("Foo::operator&&(void&&);", Style);
23452   verifyFormat("Foo::operator&&();", Style);
23453   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23454   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23455   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23456                Style);
23457   verifyFormat("operator void**()", Style);
23458   verifyFormat("operator const FooLeft<Object>&()", Style);
23459   verifyFormat("operator const FooLeft<Object>*()", Style);
23460   verifyFormat("operator const FooLeft<Object>**()", Style);
23461   verifyFormat("operator const FooLeft<Object>*&()", Style);
23462   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23463 
23464   // PR45107
23465   verifyFormat("operator Vector<String>&();", Style);
23466   verifyFormat("operator const Vector<String>&();", Style);
23467   verifyFormat("operator foo::Bar*();", Style);
23468   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23469   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23470                Style);
23471 
23472   Style.PointerAlignment = FormatStyle::PAS_Middle;
23473   verifyFormat("Foo::operator*();", Style);
23474   verifyFormat("Foo::operator void *();", Style);
23475   verifyFormat("Foo::operator()(void *);", Style);
23476   verifyFormat("Foo::operator*(void *);", Style);
23477   verifyFormat("Foo::operator*();", Style);
23478   verifyFormat("operator*(int (*)(), class Foo);", Style);
23479 
23480   verifyFormat("Foo::operator&();", Style);
23481   verifyFormat("Foo::operator void &();", Style);
23482   verifyFormat("Foo::operator void const &();", Style);
23483   verifyFormat("Foo::operator()(void &);", Style);
23484   verifyFormat("Foo::operator&(void &);", Style);
23485   verifyFormat("Foo::operator&();", Style);
23486   verifyFormat("operator&(int (&)(), class Foo);", Style);
23487 
23488   verifyFormat("Foo::operator&&();", Style);
23489   verifyFormat("Foo::operator void &&();", Style);
23490   verifyFormat("Foo::operator void const &&();", Style);
23491   verifyFormat("Foo::operator()(void &&);", Style);
23492   verifyFormat("Foo::operator&&(void &&);", Style);
23493   verifyFormat("Foo::operator&&();", Style);
23494   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23495 }
23496 
23497 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23498   FormatStyle Style = getLLVMStyle();
23499   // PR46157
23500   verifyFormat("foo(operator+, -42);", Style);
23501   verifyFormat("foo(operator++, -42);", Style);
23502   verifyFormat("foo(operator--, -42);", Style);
23503   verifyFormat("foo(-42, operator--);", Style);
23504   verifyFormat("foo(-42, operator, );", Style);
23505   verifyFormat("foo(operator, , -42);", Style);
23506 }
23507 
23508 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23509   FormatStyle Style = getLLVMStyle();
23510   Style.WhitespaceSensitiveMacros.push_back("FOO");
23511 
23512   // Don't use the helpers here, since 'mess up' will change the whitespace
23513   // and these are all whitespace sensitive by definition
23514   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23515             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23516   EXPECT_EQ(
23517       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23518       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23519   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23520             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23521   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23522             "       Still=Intentional);",
23523             format("FOO(String-ized&Messy+But,: :\n"
23524                    "       Still=Intentional);",
23525                    Style));
23526   Style.AlignConsecutiveAssignments.Enabled = true;
23527   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
23528             "       Still=Intentional);",
23529             format("FOO(String-ized=&Messy+But,: :\n"
23530                    "       Still=Intentional);",
23531                    Style));
23532 
23533   Style.ColumnLimit = 21;
23534   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23535             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23536 }
23537 
23538 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23539   // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
23540   // test its interaction with line wrapping
23541   FormatStyle Style = getLLVMStyleWithColumns(80);
23542   verifyFormat("namespace {\n"
23543                "int i;\n"
23544                "int j;\n"
23545                "} // namespace",
23546                Style);
23547 
23548   verifyFormat("namespace AAA {\n"
23549                "int i;\n"
23550                "int j;\n"
23551                "} // namespace AAA",
23552                Style);
23553 
23554   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23555             "int i;\n"
23556             "int j;\n"
23557             "} // namespace Averyveryveryverylongnamespace",
23558             format("namespace Averyveryveryverylongnamespace {\n"
23559                    "int i;\n"
23560                    "int j;\n"
23561                    "}",
23562                    Style));
23563 
23564   EXPECT_EQ(
23565       "namespace "
23566       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23567       "    went::mad::now {\n"
23568       "int i;\n"
23569       "int j;\n"
23570       "} // namespace\n"
23571       "  // "
23572       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23573       "went::mad::now",
23574       format("namespace "
23575              "would::it::save::you::a::lot::of::time::if_::i::"
23576              "just::gave::up::and_::went::mad::now {\n"
23577              "int i;\n"
23578              "int j;\n"
23579              "}",
23580              Style));
23581 
23582   // This used to duplicate the comment again and again on subsequent runs
23583   EXPECT_EQ(
23584       "namespace "
23585       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23586       "    went::mad::now {\n"
23587       "int i;\n"
23588       "int j;\n"
23589       "} // namespace\n"
23590       "  // "
23591       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23592       "went::mad::now",
23593       format("namespace "
23594              "would::it::save::you::a::lot::of::time::if_::i::"
23595              "just::gave::up::and_::went::mad::now {\n"
23596              "int i;\n"
23597              "int j;\n"
23598              "} // namespace\n"
23599              "  // "
23600              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23601              "and_::went::mad::now",
23602              Style));
23603 }
23604 
23605 TEST_F(FormatTest, LikelyUnlikely) {
23606   FormatStyle Style = getLLVMStyle();
23607 
23608   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23609                "  return 29;\n"
23610                "}",
23611                Style);
23612 
23613   verifyFormat("if (argc > 5) [[likely]] {\n"
23614                "  return 29;\n"
23615                "}",
23616                Style);
23617 
23618   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23619                "  return 29;\n"
23620                "} else [[likely]] {\n"
23621                "  return 42;\n"
23622                "}\n",
23623                Style);
23624 
23625   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23626                "  return 29;\n"
23627                "} else if (argc > 10) [[likely]] {\n"
23628                "  return 99;\n"
23629                "} else {\n"
23630                "  return 42;\n"
23631                "}\n",
23632                Style);
23633 
23634   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23635                "  return 29;\n"
23636                "}",
23637                Style);
23638 
23639   verifyFormat("if (argc > 5) [[unlikely]]\n"
23640                "  return 29;\n",
23641                Style);
23642   verifyFormat("if (argc > 5) [[likely]]\n"
23643                "  return 29;\n",
23644                Style);
23645 
23646   Style.AttributeMacros.push_back("UNLIKELY");
23647   Style.AttributeMacros.push_back("LIKELY");
23648   verifyFormat("if (argc > 5) UNLIKELY\n"
23649                "  return 29;\n",
23650                Style);
23651 
23652   verifyFormat("if (argc > 5) UNLIKELY {\n"
23653                "  return 29;\n"
23654                "}",
23655                Style);
23656   verifyFormat("if (argc > 5) UNLIKELY {\n"
23657                "  return 29;\n"
23658                "} else [[likely]] {\n"
23659                "  return 42;\n"
23660                "}\n",
23661                Style);
23662   verifyFormat("if (argc > 5) UNLIKELY {\n"
23663                "  return 29;\n"
23664                "} else LIKELY {\n"
23665                "  return 42;\n"
23666                "}\n",
23667                Style);
23668   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23669                "  return 29;\n"
23670                "} else LIKELY {\n"
23671                "  return 42;\n"
23672                "}\n",
23673                Style);
23674 }
23675 
23676 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23677   verifyFormat("Constructor()\n"
23678                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23679                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
23680                "aaaaaaaaaaaaaaaaaat))");
23681   verifyFormat("Constructor()\n"
23682                "    : aaaaaaaaaaaaa(aaaaaa), "
23683                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
23684 
23685   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
23686   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
23687   verifyFormat("Constructor()\n"
23688                "    : aaaaaa(aaaaaa),\n"
23689                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23690                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
23691                StyleWithWhitespacePenalty);
23692   verifyFormat("Constructor()\n"
23693                "    : aaaaaaaaaaaaa(aaaaaa), "
23694                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
23695                StyleWithWhitespacePenalty);
23696 }
23697 
23698 TEST_F(FormatTest, LLVMDefaultStyle) {
23699   FormatStyle Style = getLLVMStyle();
23700   verifyFormat("extern \"C\" {\n"
23701                "int foo();\n"
23702                "}",
23703                Style);
23704 }
23705 TEST_F(FormatTest, GNUDefaultStyle) {
23706   FormatStyle Style = getGNUStyle();
23707   verifyFormat("extern \"C\"\n"
23708                "{\n"
23709                "  int foo ();\n"
23710                "}",
23711                Style);
23712 }
23713 TEST_F(FormatTest, MozillaDefaultStyle) {
23714   FormatStyle Style = getMozillaStyle();
23715   verifyFormat("extern \"C\"\n"
23716                "{\n"
23717                "  int foo();\n"
23718                "}",
23719                Style);
23720 }
23721 TEST_F(FormatTest, GoogleDefaultStyle) {
23722   FormatStyle Style = getGoogleStyle();
23723   verifyFormat("extern \"C\" {\n"
23724                "int foo();\n"
23725                "}",
23726                Style);
23727 }
23728 TEST_F(FormatTest, ChromiumDefaultStyle) {
23729   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
23730   verifyFormat("extern \"C\" {\n"
23731                "int foo();\n"
23732                "}",
23733                Style);
23734 }
23735 TEST_F(FormatTest, MicrosoftDefaultStyle) {
23736   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
23737   verifyFormat("extern \"C\"\n"
23738                "{\n"
23739                "    int foo();\n"
23740                "}",
23741                Style);
23742 }
23743 TEST_F(FormatTest, WebKitDefaultStyle) {
23744   FormatStyle Style = getWebKitStyle();
23745   verifyFormat("extern \"C\" {\n"
23746                "int foo();\n"
23747                "}",
23748                Style);
23749 }
23750 
23751 TEST_F(FormatTest, Concepts) {
23752   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
23753             FormatStyle::BBCDS_Always);
23754   verifyFormat("template <typename T>\n"
23755                "concept True = true;");
23756 
23757   verifyFormat("template <typename T>\n"
23758                "concept C = ((false || foo()) && C2<T>) ||\n"
23759                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
23760                getLLVMStyleWithColumns(60));
23761 
23762   verifyFormat("template <typename T>\n"
23763                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
23764                "sizeof(T) <= 8;");
23765 
23766   verifyFormat("template <typename T>\n"
23767                "concept DelayedCheck = true && requires(T t) {\n"
23768                "                                 t.bar();\n"
23769                "                                 t.baz();\n"
23770                "                               } && sizeof(T) <= 8;");
23771 
23772   verifyFormat("template <typename T>\n"
23773                "concept DelayedCheck = true && requires(T t) { // Comment\n"
23774                "                                 t.bar();\n"
23775                "                                 t.baz();\n"
23776                "                               } && sizeof(T) <= 8;");
23777 
23778   verifyFormat("template <typename T>\n"
23779                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
23780                "sizeof(T) <= 8;");
23781 
23782   verifyFormat("template <typename T>\n"
23783                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
23784                "&& sizeof(T) <= 8;");
23785 
23786   verifyFormat(
23787       "template <typename T>\n"
23788       "concept DelayedCheck = static_cast<bool>(0) ||\n"
23789       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23790 
23791   verifyFormat("template <typename T>\n"
23792                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
23793                "&& sizeof(T) <= 8;");
23794 
23795   verifyFormat(
23796       "template <typename T>\n"
23797       "concept DelayedCheck = (bool)(0) ||\n"
23798       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23799 
23800   verifyFormat("template <typename T>\n"
23801                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
23802                "&& sizeof(T) <= 8;");
23803 
23804   verifyFormat("template <typename T>\n"
23805                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
23806                "sizeof(T) <= 8;");
23807 
23808   verifyFormat("template <typename T>\n"
23809                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
23810                "               requires(T t) {\n"
23811                "                 t.bar();\n"
23812                "                 t.baz();\n"
23813                "               } && sizeof(T) <= 8 && !(4 < 3);",
23814                getLLVMStyleWithColumns(60));
23815 
23816   verifyFormat("template <typename T>\n"
23817                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
23818 
23819   verifyFormat("template <typename T>\n"
23820                "concept C = foo();");
23821 
23822   verifyFormat("template <typename T>\n"
23823                "concept C = foo(T());");
23824 
23825   verifyFormat("template <typename T>\n"
23826                "concept C = foo(T{});");
23827 
23828   verifyFormat("template <typename T>\n"
23829                "concept Size = V<sizeof(T)>::Value > 5;");
23830 
23831   verifyFormat("template <typename T>\n"
23832                "concept True = S<T>::Value;");
23833 
23834   verifyFormat(
23835       "template <typename T>\n"
23836       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
23837       "            sizeof(T) <= 8;");
23838 
23839   // FIXME: This is misformatted because the fake l paren starts at bool, not at
23840   // the lambda l square.
23841   verifyFormat("template <typename T>\n"
23842                "concept C = [] -> bool { return true; }() && requires(T t) { "
23843                "t.bar(); } &&\n"
23844                "                      sizeof(T) <= 8;");
23845 
23846   verifyFormat(
23847       "template <typename T>\n"
23848       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
23849       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23850 
23851   verifyFormat("template <typename T>\n"
23852                "concept C = decltype([]() { return std::true_type{}; "
23853                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
23854                getLLVMStyleWithColumns(120));
23855 
23856   verifyFormat("template <typename T>\n"
23857                "concept C = decltype([]() -> std::true_type { return {}; "
23858                "}())::value &&\n"
23859                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23860 
23861   verifyFormat("template <typename T>\n"
23862                "concept C = true;\n"
23863                "Foo Bar;");
23864 
23865   verifyFormat("template <typename T>\n"
23866                "concept Hashable = requires(T a) {\n"
23867                "                     { std::hash<T>{}(a) } -> "
23868                "std::convertible_to<std::size_t>;\n"
23869                "                   };");
23870 
23871   verifyFormat(
23872       "template <typename T>\n"
23873       "concept EqualityComparable = requires(T a, T b) {\n"
23874       "                               { a == b } -> std::same_as<bool>;\n"
23875       "                             };");
23876 
23877   verifyFormat(
23878       "template <typename T>\n"
23879       "concept EqualityComparable = requires(T a, T b) {\n"
23880       "                               { a == b } -> std::same_as<bool>;\n"
23881       "                               { a != b } -> std::same_as<bool>;\n"
23882       "                             };");
23883 
23884   verifyFormat("template <typename T>\n"
23885                "concept WeakEqualityComparable = requires(T a, T b) {\n"
23886                "                                   { a == b };\n"
23887                "                                   { a != b };\n"
23888                "                                 };");
23889 
23890   verifyFormat("template <typename T>\n"
23891                "concept HasSizeT = requires { typename T::size_t; };");
23892 
23893   verifyFormat("template <typename T>\n"
23894                "concept Semiregular =\n"
23895                "    DefaultConstructible<T> && CopyConstructible<T> && "
23896                "CopyAssignable<T> &&\n"
23897                "    requires(T a, std::size_t n) {\n"
23898                "      requires Same<T *, decltype(&a)>;\n"
23899                "      { a.~T() } noexcept;\n"
23900                "      requires Same<T *, decltype(new T)>;\n"
23901                "      requires Same<T *, decltype(new T[n])>;\n"
23902                "      { delete new T; };\n"
23903                "      { delete new T[n]; };\n"
23904                "    };");
23905 
23906   verifyFormat("template <typename T>\n"
23907                "concept Semiregular =\n"
23908                "    requires(T a, std::size_t n) {\n"
23909                "      requires Same<T *, decltype(&a)>;\n"
23910                "      { a.~T() } noexcept;\n"
23911                "      requires Same<T *, decltype(new T)>;\n"
23912                "      requires Same<T *, decltype(new T[n])>;\n"
23913                "      { delete new T; };\n"
23914                "      { delete new T[n]; };\n"
23915                "      { new T } -> std::same_as<T *>;\n"
23916                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
23917                "CopyAssignable<T>;");
23918 
23919   verifyFormat(
23920       "template <typename T>\n"
23921       "concept Semiregular =\n"
23922       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
23923       "                                 requires Same<T *, decltype(&a)>;\n"
23924       "                                 { a.~T() } noexcept;\n"
23925       "                                 requires Same<T *, decltype(new T)>;\n"
23926       "                                 requires Same<T *, decltype(new "
23927       "T[n])>;\n"
23928       "                                 { delete new T; };\n"
23929       "                                 { delete new T[n]; };\n"
23930       "                               } && CopyConstructible<T> && "
23931       "CopyAssignable<T>;");
23932 
23933   verifyFormat("template <typename T>\n"
23934                "concept Two = requires(T t) {\n"
23935                "                { t.foo() } -> std::same_as<Bar>;\n"
23936                "              } && requires(T &&t) {\n"
23937                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
23938                "                   };");
23939 
23940   verifyFormat(
23941       "template <typename T>\n"
23942       "concept C = requires(T x) {\n"
23943       "              { *x } -> std::convertible_to<typename T::inner>;\n"
23944       "              { x + 1 } noexcept -> std::same_as<int>;\n"
23945       "              { x * 1 } -> std::convertible_to<T>;\n"
23946       "            };");
23947 
23948   verifyFormat(
23949       "template <typename T, typename U = T>\n"
23950       "concept Swappable = requires(T &&t, U &&u) {\n"
23951       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
23952       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
23953       "                    };");
23954 
23955   verifyFormat("template <typename T, typename U>\n"
23956                "concept Common = requires(T &&t, U &&u) {\n"
23957                "                   typename CommonType<T, U>;\n"
23958                "                   { CommonType<T, U>(std::forward<T>(t)) };\n"
23959                "                 };");
23960 
23961   verifyFormat("template <typename T, typename U>\n"
23962                "concept Common = requires(T &&t, U &&u) {\n"
23963                "                   typename CommonType<T, U>;\n"
23964                "                   { CommonType<T, U>{std::forward<T>(t)} };\n"
23965                "                 };");
23966 
23967   verifyFormat(
23968       "template <typename T>\n"
23969       "concept C = requires(T t) {\n"
23970       "              requires Bar<T> && Foo<T>;\n"
23971       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
23972       "            };");
23973 
23974   verifyFormat("template <typename T>\n"
23975                "concept HasFoo = requires(T t) {\n"
23976                "                   { t.foo() };\n"
23977                "                   t.foo();\n"
23978                "                 };\n"
23979                "template <typename T>\n"
23980                "concept HasBar = requires(T t) {\n"
23981                "                   { t.bar() };\n"
23982                "                   t.bar();\n"
23983                "                 };");
23984 
23985   verifyFormat("template <typename T>\n"
23986                "concept Large = sizeof(T) > 10;");
23987 
23988   verifyFormat("template <typename T, typename U>\n"
23989                "concept FooableWith = requires(T t, U u) {\n"
23990                "                        typename T::foo_type;\n"
23991                "                        { t.foo(u) } -> typename T::foo_type;\n"
23992                "                        t++;\n"
23993                "                      };\n"
23994                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
23995 
23996   verifyFormat("template <typename T>\n"
23997                "concept Context = is_specialization_of_v<context, T>;");
23998 
23999   verifyFormat("template <typename T>\n"
24000                "concept Node = std::is_object_v<T>;");
24001 
24002   verifyFormat("template <class T>\n"
24003                "concept integral = __is_integral(T);");
24004 
24005   verifyFormat("template <class T>\n"
24006                "concept is2D = __array_extent(T, 1) == 2;");
24007 
24008   verifyFormat("template <class T>\n"
24009                "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
24010 
24011   verifyFormat("template <class T, class T2>\n"
24012                "concept Same = __is_same_as<T, T2>;");
24013 
24014   auto Style = getLLVMStyle();
24015   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
24016 
24017   verifyFormat(
24018       "template <typename T>\n"
24019       "concept C = requires(T t) {\n"
24020       "              requires Bar<T> && Foo<T>;\n"
24021       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24022       "            };",
24023       Style);
24024 
24025   verifyFormat("template <typename T>\n"
24026                "concept HasFoo = requires(T t) {\n"
24027                "                   { t.foo() };\n"
24028                "                   t.foo();\n"
24029                "                 };\n"
24030                "template <typename T>\n"
24031                "concept HasBar = requires(T t) {\n"
24032                "                   { t.bar() };\n"
24033                "                   t.bar();\n"
24034                "                 };",
24035                Style);
24036 
24037   verifyFormat("template <typename T> concept True = true;", Style);
24038 
24039   verifyFormat("template <typename T>\n"
24040                "concept C = decltype([]() -> std::true_type { return {}; "
24041                "}())::value &&\n"
24042                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24043                Style);
24044 
24045   verifyFormat("template <typename T>\n"
24046                "concept Semiregular =\n"
24047                "    DefaultConstructible<T> && CopyConstructible<T> && "
24048                "CopyAssignable<T> &&\n"
24049                "    requires(T a, std::size_t n) {\n"
24050                "      requires Same<T *, decltype(&a)>;\n"
24051                "      { a.~T() } noexcept;\n"
24052                "      requires Same<T *, decltype(new T)>;\n"
24053                "      requires Same<T *, decltype(new T[n])>;\n"
24054                "      { delete new T; };\n"
24055                "      { delete new T[n]; };\n"
24056                "    };",
24057                Style);
24058 
24059   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
24060 
24061   verifyFormat("template <typename T> concept C =\n"
24062                "    requires(T t) {\n"
24063                "      requires Bar<T> && Foo<T>;\n"
24064                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24065                "    };",
24066                Style);
24067 
24068   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
24069                "                                         { t.foo() };\n"
24070                "                                         t.foo();\n"
24071                "                                       };\n"
24072                "template <typename T> concept HasBar = requires(T t) {\n"
24073                "                                         { t.bar() };\n"
24074                "                                         t.bar();\n"
24075                "                                       };",
24076                Style);
24077 
24078   verifyFormat("template <typename T> concept True = true;", Style);
24079 
24080   verifyFormat(
24081       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
24082       "                                    return {};\n"
24083       "                                  }())::value &&\n"
24084       "                                  requires(T t) { t.bar(); } && "
24085       "sizeof(T) <= 8;",
24086       Style);
24087 
24088   verifyFormat("template <typename T> concept Semiregular =\n"
24089                "    DefaultConstructible<T> && CopyConstructible<T> && "
24090                "CopyAssignable<T> &&\n"
24091                "    requires(T a, std::size_t n) {\n"
24092                "      requires Same<T *, decltype(&a)>;\n"
24093                "      { a.~T() } noexcept;\n"
24094                "      requires Same<T *, decltype(new T)>;\n"
24095                "      requires Same<T *, decltype(new T[n])>;\n"
24096                "      { delete new T; };\n"
24097                "      { delete new T[n]; };\n"
24098                "    };",
24099                Style);
24100 
24101   // The following tests are invalid C++, we just want to make sure we don't
24102   // assert.
24103   verifyFormat("template <typename T>\n"
24104                "concept C = requires C2<T>;");
24105 
24106   verifyFormat("template <typename T>\n"
24107                "concept C = 5 + 4;");
24108 
24109   verifyFormat("template <typename T>\n"
24110                "concept C =\n"
24111                "class X;");
24112 
24113   verifyFormat("template <typename T>\n"
24114                "concept C = [] && true;");
24115 
24116   verifyFormat("template <typename T>\n"
24117                "concept C = [] && requires(T t) { typename T::size_type; };");
24118 }
24119 
24120 TEST_F(FormatTest, RequiresClausesPositions) {
24121   auto Style = getLLVMStyle();
24122   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
24123   EXPECT_EQ(Style.IndentRequiresClause, true);
24124 
24125   verifyFormat("template <typename T>\n"
24126                "  requires(Foo<T> && std::trait<T>)\n"
24127                "struct Bar;",
24128                Style);
24129 
24130   verifyFormat("template <typename T>\n"
24131                "  requires(Foo<T> && std::trait<T>)\n"
24132                "class Bar {\n"
24133                "public:\n"
24134                "  Bar(T t);\n"
24135                "  bool baz();\n"
24136                "};",
24137                Style);
24138 
24139   verifyFormat(
24140       "template <typename T>\n"
24141       "  requires requires(T &&t) {\n"
24142       "             typename T::I;\n"
24143       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
24144       "           }\n"
24145       "Bar(T) -> Bar<typename T::I>;",
24146       Style);
24147 
24148   verifyFormat("template <typename T>\n"
24149                "  requires(Foo<T> && std::trait<T>)\n"
24150                "constexpr T MyGlobal;",
24151                Style);
24152 
24153   verifyFormat("template <typename T>\n"
24154                "  requires Foo<T> && requires(T t) {\n"
24155                "                       { t.baz() } -> std::same_as<bool>;\n"
24156                "                       requires std::same_as<T::Factor, int>;\n"
24157                "                     }\n"
24158                "inline int bar(T t) {\n"
24159                "  return t.baz() ? T::Factor : 5;\n"
24160                "}",
24161                Style);
24162 
24163   verifyFormat("template <typename T>\n"
24164                "inline int bar(T t)\n"
24165                "  requires Foo<T> && requires(T t) {\n"
24166                "                       { t.baz() } -> std::same_as<bool>;\n"
24167                "                       requires std::same_as<T::Factor, int>;\n"
24168                "                     }\n"
24169                "{\n"
24170                "  return t.baz() ? T::Factor : 5;\n"
24171                "}",
24172                Style);
24173 
24174   verifyFormat("template <typename T>\n"
24175                "  requires F<T>\n"
24176                "int bar(T t) {\n"
24177                "  return 5;\n"
24178                "}",
24179                Style);
24180 
24181   verifyFormat("template <typename T>\n"
24182                "int bar(T t)\n"
24183                "  requires F<T>\n"
24184                "{\n"
24185                "  return 5;\n"
24186                "}",
24187                Style);
24188 
24189   verifyFormat("template <typename T>\n"
24190                "int bar(T t)\n"
24191                "  requires F<T>;",
24192                Style);
24193 
24194   Style.IndentRequiresClause = false;
24195   verifyFormat("template <typename T>\n"
24196                "requires F<T>\n"
24197                "int bar(T t) {\n"
24198                "  return 5;\n"
24199                "}",
24200                Style);
24201 
24202   verifyFormat("template <typename T>\n"
24203                "int bar(T t)\n"
24204                "requires F<T>\n"
24205                "{\n"
24206                "  return 5;\n"
24207                "}",
24208                Style);
24209 
24210   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
24211   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
24212                "template <typename T> requires Foo<T> void bar() {}\n"
24213                "template <typename T> void bar() requires Foo<T> {}\n"
24214                "template <typename T> void bar() requires Foo<T>;\n"
24215                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
24216                Style);
24217 
24218   auto ColumnStyle = Style;
24219   ColumnStyle.ColumnLimit = 40;
24220   verifyFormat("template <typename AAAAAAA>\n"
24221                "requires Foo<T> struct Bar {};\n"
24222                "template <typename AAAAAAA>\n"
24223                "requires Foo<T> void bar() {}\n"
24224                "template <typename AAAAAAA>\n"
24225                "void bar() requires Foo<T> {}\n"
24226                "template <typename AAAAAAA>\n"
24227                "requires Foo<T> Baz(T) -> Baz<T>;",
24228                ColumnStyle);
24229 
24230   verifyFormat("template <typename T>\n"
24231                "requires Foo<AAAAAAA> struct Bar {};\n"
24232                "template <typename T>\n"
24233                "requires Foo<AAAAAAA> void bar() {}\n"
24234                "template <typename T>\n"
24235                "void bar() requires Foo<AAAAAAA> {}\n"
24236                "template <typename T>\n"
24237                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
24238                ColumnStyle);
24239 
24240   verifyFormat("template <typename AAAAAAA>\n"
24241                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24242                "struct Bar {};\n"
24243                "template <typename AAAAAAA>\n"
24244                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24245                "void bar() {}\n"
24246                "template <typename AAAAAAA>\n"
24247                "void bar()\n"
24248                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24249                "template <typename AAAAAAA>\n"
24250                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24251                "template <typename AAAAAAA>\n"
24252                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24253                "Bar(T) -> Bar<T>;",
24254                ColumnStyle);
24255 
24256   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24257   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24258 
24259   verifyFormat("template <typename T>\n"
24260                "requires Foo<T> struct Bar {};\n"
24261                "template <typename T>\n"
24262                "requires Foo<T> void bar() {}\n"
24263                "template <typename T>\n"
24264                "void bar()\n"
24265                "requires Foo<T> {}\n"
24266                "template <typename T>\n"
24267                "void bar()\n"
24268                "requires Foo<T>;\n"
24269                "template <typename T>\n"
24270                "requires Foo<T> Bar(T) -> Bar<T>;",
24271                Style);
24272 
24273   verifyFormat("template <typename AAAAAAA>\n"
24274                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24275                "struct Bar {};\n"
24276                "template <typename AAAAAAA>\n"
24277                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24278                "void bar() {}\n"
24279                "template <typename AAAAAAA>\n"
24280                "void bar()\n"
24281                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24282                "template <typename AAAAAAA>\n"
24283                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24284                "template <typename AAAAAAA>\n"
24285                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24286                "Bar(T) -> Bar<T>;",
24287                ColumnStyle);
24288 
24289   Style.IndentRequiresClause = true;
24290   ColumnStyle.IndentRequiresClause = true;
24291 
24292   verifyFormat("template <typename T>\n"
24293                "  requires Foo<T> struct Bar {};\n"
24294                "template <typename T>\n"
24295                "  requires Foo<T> void bar() {}\n"
24296                "template <typename T>\n"
24297                "void bar()\n"
24298                "  requires Foo<T> {}\n"
24299                "template <typename T>\n"
24300                "  requires Foo<T> Bar(T) -> Bar<T>;",
24301                Style);
24302 
24303   verifyFormat("template <typename AAAAAAA>\n"
24304                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24305                "struct Bar {};\n"
24306                "template <typename AAAAAAA>\n"
24307                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24308                "void bar() {}\n"
24309                "template <typename AAAAAAA>\n"
24310                "void bar()\n"
24311                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24312                "template <typename AAAAAAA>\n"
24313                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
24314                "template <typename AAAAAAA>\n"
24315                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24316                "Bar(T) -> Bar<T>;",
24317                ColumnStyle);
24318 
24319   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24320   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24321 
24322   verifyFormat("template <typename T> requires Foo<T>\n"
24323                "struct Bar {};\n"
24324                "template <typename T> requires Foo<T>\n"
24325                "void bar() {}\n"
24326                "template <typename T>\n"
24327                "void bar() requires Foo<T>\n"
24328                "{}\n"
24329                "template <typename T> void bar() requires Foo<T>;\n"
24330                "template <typename T> requires Foo<T>\n"
24331                "Bar(T) -> Bar<T>;",
24332                Style);
24333 
24334   verifyFormat("template <typename AAAAAAA>\n"
24335                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24336                "struct Bar {};\n"
24337                "template <typename AAAAAAA>\n"
24338                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24339                "void bar() {}\n"
24340                "template <typename AAAAAAA>\n"
24341                "void bar()\n"
24342                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24343                "{}\n"
24344                "template <typename AAAAAAA>\n"
24345                "requires Foo<AAAAAAAA>\n"
24346                "Bar(T) -> Bar<T>;\n"
24347                "template <typename AAAAAAA>\n"
24348                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24349                "Bar(T) -> Bar<T>;",
24350                ColumnStyle);
24351 }
24352 
24353 TEST_F(FormatTest, RequiresClauses) {
24354   verifyFormat("struct [[nodiscard]] zero_t {\n"
24355                "  template <class T>\n"
24356                "    requires requires { number_zero_v<T>; }\n"
24357                "  [[nodiscard]] constexpr operator T() const {\n"
24358                "    return number_zero_v<T>;\n"
24359                "  }\n"
24360                "};");
24361 
24362   auto Style = getLLVMStyle();
24363 
24364   verifyFormat(
24365       "template <typename T>\n"
24366       "  requires is_default_constructible_v<hash<T>> and\n"
24367       "           is_copy_constructible_v<hash<T>> and\n"
24368       "           is_move_constructible_v<hash<T>> and\n"
24369       "           is_copy_assignable_v<hash<T>> and "
24370       "is_move_assignable_v<hash<T>> and\n"
24371       "           is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
24372       "           is_callable_v<hash<T>(T)> and\n"
24373       "           is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n"
24374       "           is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n"
24375       "           is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
24376       "struct S {};",
24377       Style);
24378 
24379   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
24380   verifyFormat(
24381       "template <typename T>\n"
24382       "  requires is_default_constructible_v<hash<T>>\n"
24383       "           and is_copy_constructible_v<hash<T>>\n"
24384       "           and is_move_constructible_v<hash<T>>\n"
24385       "           and is_copy_assignable_v<hash<T>> and "
24386       "is_move_assignable_v<hash<T>>\n"
24387       "           and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
24388       "           and is_callable_v<hash<T>(T)>\n"
24389       "           and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n"
24390       "           and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n"
24391       "           and is_same_v<size_t, decltype(hash<T>(declval<const T "
24392       "&>()))>\n"
24393       "struct S {};",
24394       Style);
24395 
24396   // Not a clause, but we once hit an assert.
24397   verifyFormat("#if 0\n"
24398                "#else\n"
24399                "foo();\n"
24400                "#endif\n"
24401                "bar(requires);");
24402 }
24403 
24404 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24405   FormatStyle Style = getLLVMStyle();
24406   StringRef Source = "void Foo::slot() {\n"
24407                      "  unsigned char MyChar = 'x';\n"
24408                      "  emit signal(MyChar);\n"
24409                      "  Q_EMIT signal(MyChar);\n"
24410                      "}";
24411 
24412   EXPECT_EQ(Source, format(Source, Style));
24413 
24414   Style.AlignConsecutiveDeclarations.Enabled = true;
24415   EXPECT_EQ("void Foo::slot() {\n"
24416             "  unsigned char MyChar = 'x';\n"
24417             "  emit          signal(MyChar);\n"
24418             "  Q_EMIT signal(MyChar);\n"
24419             "}",
24420             format(Source, Style));
24421 
24422   Style.StatementAttributeLikeMacros.push_back("emit");
24423   EXPECT_EQ(Source, format(Source, Style));
24424 
24425   Style.StatementAttributeLikeMacros = {};
24426   EXPECT_EQ("void Foo::slot() {\n"
24427             "  unsigned char MyChar = 'x';\n"
24428             "  emit          signal(MyChar);\n"
24429             "  Q_EMIT        signal(MyChar);\n"
24430             "}",
24431             format(Source, Style));
24432 }
24433 
24434 TEST_F(FormatTest, IndentAccessModifiers) {
24435   FormatStyle Style = getLLVMStyle();
24436   Style.IndentAccessModifiers = true;
24437   // Members are *two* levels below the record;
24438   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24439   verifyFormat("class C {\n"
24440                "    int i;\n"
24441                "};\n",
24442                Style);
24443   verifyFormat("union C {\n"
24444                "    int i;\n"
24445                "    unsigned u;\n"
24446                "};\n",
24447                Style);
24448   // Access modifiers should be indented one level below the record.
24449   verifyFormat("class C {\n"
24450                "  public:\n"
24451                "    int i;\n"
24452                "};\n",
24453                Style);
24454   verifyFormat("struct S {\n"
24455                "  private:\n"
24456                "    class C {\n"
24457                "        int j;\n"
24458                "\n"
24459                "      public:\n"
24460                "        C();\n"
24461                "    };\n"
24462                "\n"
24463                "  public:\n"
24464                "    int i;\n"
24465                "};\n",
24466                Style);
24467   // Enumerations are not records and should be unaffected.
24468   Style.AllowShortEnumsOnASingleLine = false;
24469   verifyFormat("enum class E {\n"
24470                "  A,\n"
24471                "  B\n"
24472                "};\n",
24473                Style);
24474   // Test with a different indentation width;
24475   // also proves that the result is Style.AccessModifierOffset agnostic.
24476   Style.IndentWidth = 3;
24477   verifyFormat("class C {\n"
24478                "   public:\n"
24479                "      int i;\n"
24480                "};\n",
24481                Style);
24482 }
24483 
24484 TEST_F(FormatTest, LimitlessStringsAndComments) {
24485   auto Style = getLLVMStyleWithColumns(0);
24486   constexpr StringRef Code =
24487       "/**\n"
24488       " * This is a multiline comment with quite some long lines, at least for "
24489       "the LLVM Style.\n"
24490       " * We will redo this with strings and line comments. Just to  check if "
24491       "everything is working.\n"
24492       " */\n"
24493       "bool foo() {\n"
24494       "  /* Single line multi line comment. */\n"
24495       "  const std::string String = \"This is a multiline string with quite "
24496       "some long lines, at least for the LLVM Style.\"\n"
24497       "                             \"We already did it with multi line "
24498       "comments, and we will do it with line comments. Just to check if "
24499       "everything is working.\";\n"
24500       "  // This is a line comment (block) with quite some long lines, at "
24501       "least for the LLVM Style.\n"
24502       "  // We already did this with multi line comments and strings. Just to "
24503       "check if everything is working.\n"
24504       "  const std::string SmallString = \"Hello World\";\n"
24505       "  // Small line comment\n"
24506       "  return String.size() > SmallString.size();\n"
24507       "}";
24508   EXPECT_EQ(Code, format(Code, Style));
24509 }
24510 
24511 TEST_F(FormatTest, FormatDecayCopy) {
24512   // error cases from unit tests
24513   verifyFormat("foo(auto())");
24514   verifyFormat("foo(auto{})");
24515   verifyFormat("foo(auto({}))");
24516   verifyFormat("foo(auto{{}})");
24517 
24518   verifyFormat("foo(auto(1))");
24519   verifyFormat("foo(auto{1})");
24520   verifyFormat("foo(new auto(1))");
24521   verifyFormat("foo(new auto{1})");
24522   verifyFormat("decltype(auto(1)) x;");
24523   verifyFormat("decltype(auto{1}) x;");
24524   verifyFormat("auto(x);");
24525   verifyFormat("auto{x};");
24526   verifyFormat("new auto{x};");
24527   verifyFormat("auto{x} = y;");
24528   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24529                                 // the user's own fault
24530   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24531                                          // clearly the user's own fault
24532   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24533 }
24534 
24535 TEST_F(FormatTest, Cpp20ModulesSupport) {
24536   FormatStyle Style = getLLVMStyle();
24537   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24538   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24539 
24540   verifyFormat("export import foo;", Style);
24541   verifyFormat("export import foo:bar;", Style);
24542   verifyFormat("export import foo.bar;", Style);
24543   verifyFormat("export import foo.bar:baz;", Style);
24544   verifyFormat("export import :bar;", Style);
24545   verifyFormat("export module foo:bar;", Style);
24546   verifyFormat("export module foo;", Style);
24547   verifyFormat("export module foo.bar;", Style);
24548   verifyFormat("export module foo.bar:baz;", Style);
24549   verifyFormat("export import <string_view>;", Style);
24550 
24551   verifyFormat("export type_name var;", Style);
24552   verifyFormat("template <class T> export using A = B<T>;", Style);
24553   verifyFormat("export using A = B;", Style);
24554   verifyFormat("export int func() {\n"
24555                "  foo();\n"
24556                "}",
24557                Style);
24558   verifyFormat("export struct {\n"
24559                "  int foo;\n"
24560                "};",
24561                Style);
24562   verifyFormat("export {\n"
24563                "  int foo;\n"
24564                "};",
24565                Style);
24566   verifyFormat("export export char const *hello() { return \"hello\"; }");
24567 
24568   verifyFormat("import bar;", Style);
24569   verifyFormat("import foo.bar;", Style);
24570   verifyFormat("import foo:bar;", Style);
24571   verifyFormat("import :bar;", Style);
24572   verifyFormat("import <ctime>;", Style);
24573   verifyFormat("import \"header\";", Style);
24574 
24575   verifyFormat("module foo;", Style);
24576   verifyFormat("module foo:bar;", Style);
24577   verifyFormat("module foo.bar;", Style);
24578   verifyFormat("module;", Style);
24579 
24580   verifyFormat("export namespace hi {\n"
24581                "const char *sayhi();\n"
24582                "}",
24583                Style);
24584 
24585   verifyFormat("module :private;", Style);
24586   verifyFormat("import <foo/bar.h>;", Style);
24587   verifyFormat("import foo...bar;", Style);
24588   verifyFormat("import ..........;", Style);
24589   verifyFormat("module foo:private;", Style);
24590   verifyFormat("import a", Style);
24591   verifyFormat("module a", Style);
24592   verifyFormat("export import a", Style);
24593   verifyFormat("export module a", Style);
24594 
24595   verifyFormat("import", Style);
24596   verifyFormat("module", Style);
24597   verifyFormat("export", Style);
24598 }
24599 
24600 TEST_F(FormatTest, CoroutineForCoawait) {
24601   FormatStyle Style = getLLVMStyle();
24602   verifyFormat("for co_await (auto x : range())\n  ;");
24603   verifyFormat("for (auto i : arr) {\n"
24604                "}",
24605                Style);
24606   verifyFormat("for co_await (auto i : arr) {\n"
24607                "}",
24608                Style);
24609   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24610                "}",
24611                Style);
24612 }
24613 
24614 TEST_F(FormatTest, CoroutineCoAwait) {
24615   verifyFormat("int x = co_await foo();");
24616   verifyFormat("int x = (co_await foo());");
24617   verifyFormat("co_await (42);");
24618   verifyFormat("void operator co_await(int);");
24619   verifyFormat("void operator co_await(a);");
24620   verifyFormat("co_await a;");
24621   verifyFormat("co_await missing_await_resume{};");
24622   verifyFormat("co_await a; // comment");
24623   verifyFormat("void test0() { co_await a; }");
24624   verifyFormat("co_await co_await co_await foo();");
24625   verifyFormat("co_await foo().bar();");
24626   verifyFormat("co_await [this]() -> Task { co_return x; }");
24627   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24628                "foo(); }(x, y);");
24629 
24630   FormatStyle Style = getLLVMStyleWithColumns(40);
24631   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24632                "  co_return co_await foo();\n"
24633                "}(x, y);",
24634                Style);
24635   verifyFormat("co_await;");
24636 }
24637 
24638 TEST_F(FormatTest, CoroutineCoYield) {
24639   verifyFormat("int x = co_yield foo();");
24640   verifyFormat("int x = (co_yield foo());");
24641   verifyFormat("co_yield (42);");
24642   verifyFormat("co_yield {42};");
24643   verifyFormat("co_yield 42;");
24644   verifyFormat("co_yield n++;");
24645   verifyFormat("co_yield ++n;");
24646   verifyFormat("co_yield;");
24647 }
24648 
24649 TEST_F(FormatTest, CoroutineCoReturn) {
24650   verifyFormat("co_return (42);");
24651   verifyFormat("co_return;");
24652   verifyFormat("co_return {};");
24653   verifyFormat("co_return x;");
24654   verifyFormat("co_return co_await foo();");
24655   verifyFormat("co_return co_yield foo();");
24656 }
24657 
24658 TEST_F(FormatTest, EmptyShortBlock) {
24659   auto Style = getLLVMStyle();
24660   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24661 
24662   verifyFormat("try {\n"
24663                "  doA();\n"
24664                "} catch (Exception &e) {\n"
24665                "  e.printStackTrace();\n"
24666                "}\n",
24667                Style);
24668 
24669   verifyFormat("try {\n"
24670                "  doA();\n"
24671                "} catch (Exception &e) {}\n",
24672                Style);
24673 }
24674 
24675 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
24676   auto Style = getLLVMStyle();
24677 
24678   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
24679   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
24680   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
24681   verifyFormat("struct Y<[] { return 0; }> {};", Style);
24682 
24683   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
24684   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
24685 }
24686 
24687 TEST_F(FormatTest, InsertBraces) {
24688   FormatStyle Style = getLLVMStyle();
24689   Style.InsertBraces = true;
24690 
24691   verifyFormat("// clang-format off\n"
24692                "// comment\n"
24693                "if (a) f();\n"
24694                "// clang-format on\n"
24695                "if (b) {\n"
24696                "  g();\n"
24697                "}",
24698                "// clang-format off\n"
24699                "// comment\n"
24700                "if (a) f();\n"
24701                "// clang-format on\n"
24702                "if (b) g();",
24703                Style);
24704 
24705   verifyFormat("if (a) {\n"
24706                "  switch (b) {\n"
24707                "  case 1:\n"
24708                "    c = 0;\n"
24709                "    break;\n"
24710                "  default:\n"
24711                "    c = 1;\n"
24712                "  }\n"
24713                "}",
24714                "if (a)\n"
24715                "  switch (b) {\n"
24716                "  case 1:\n"
24717                "    c = 0;\n"
24718                "    break;\n"
24719                "  default:\n"
24720                "    c = 1;\n"
24721                "  }",
24722                Style);
24723 
24724   verifyFormat("for (auto node : nodes) {\n"
24725                "  if (node) {\n"
24726                "    break;\n"
24727                "  }\n"
24728                "}",
24729                "for (auto node : nodes)\n"
24730                "  if (node)\n"
24731                "    break;",
24732                Style);
24733 
24734   verifyFormat("for (auto node : nodes) {\n"
24735                "  if (node)\n"
24736                "}",
24737                "for (auto node : nodes)\n"
24738                "  if (node)",
24739                Style);
24740 
24741   verifyFormat("do {\n"
24742                "  --a;\n"
24743                "} while (a);",
24744                "do\n"
24745                "  --a;\n"
24746                "while (a);",
24747                Style);
24748 
24749   verifyFormat("if (i) {\n"
24750                "  ++i;\n"
24751                "} else {\n"
24752                "  --i;\n"
24753                "}",
24754                "if (i)\n"
24755                "  ++i;\n"
24756                "else {\n"
24757                "  --i;\n"
24758                "}",
24759                Style);
24760 
24761   verifyFormat("void f() {\n"
24762                "  while (j--) {\n"
24763                "    while (i) {\n"
24764                "      --i;\n"
24765                "    }\n"
24766                "  }\n"
24767                "}",
24768                "void f() {\n"
24769                "  while (j--)\n"
24770                "    while (i)\n"
24771                "      --i;\n"
24772                "}",
24773                Style);
24774 
24775   verifyFormat("f({\n"
24776                "  if (a) {\n"
24777                "    g();\n"
24778                "  }\n"
24779                "});",
24780                "f({\n"
24781                "  if (a)\n"
24782                "    g();\n"
24783                "});",
24784                Style);
24785 
24786   verifyFormat("if (a) {\n"
24787                "  f();\n"
24788                "} else if (b) {\n"
24789                "  g();\n"
24790                "} else {\n"
24791                "  h();\n"
24792                "}",
24793                "if (a)\n"
24794                "  f();\n"
24795                "else if (b)\n"
24796                "  g();\n"
24797                "else\n"
24798                "  h();",
24799                Style);
24800 
24801   verifyFormat("if (a) {\n"
24802                "  f();\n"
24803                "}\n"
24804                "// comment\n"
24805                "/* comment */",
24806                "if (a)\n"
24807                "  f();\n"
24808                "// comment\n"
24809                "/* comment */",
24810                Style);
24811 
24812   verifyFormat("if (a) {\n"
24813                "  // foo\n"
24814                "  // bar\n"
24815                "  f();\n"
24816                "}",
24817                "if (a)\n"
24818                "  // foo\n"
24819                "  // bar\n"
24820                "  f();",
24821                Style);
24822 
24823   verifyFormat("if (a) { // comment\n"
24824                "  // comment\n"
24825                "  f();\n"
24826                "}",
24827                "if (a) // comment\n"
24828                "  // comment\n"
24829                "  f();",
24830                Style);
24831 
24832   verifyFormat("if (a) {\n"
24833                "  f(); // comment\n"
24834                "}",
24835                "if (a)\n"
24836                "  f(); // comment",
24837                Style);
24838 
24839   verifyFormat("if (a) {\n"
24840                "  f();\n"
24841                "}\n"
24842                "#undef A\n"
24843                "#undef B",
24844                "if (a)\n"
24845                "  f();\n"
24846                "#undef A\n"
24847                "#undef B",
24848                Style);
24849 
24850   verifyFormat("if (a)\n"
24851                "#ifdef A\n"
24852                "  f();\n"
24853                "#else\n"
24854                "  g();\n"
24855                "#endif",
24856                Style);
24857 
24858   verifyFormat("#if 0\n"
24859                "#elif 1\n"
24860                "#endif\n"
24861                "void f() {\n"
24862                "  if (a) {\n"
24863                "    g();\n"
24864                "  }\n"
24865                "}",
24866                "#if 0\n"
24867                "#elif 1\n"
24868                "#endif\n"
24869                "void f() {\n"
24870                "  if (a) g();\n"
24871                "}",
24872                Style);
24873 
24874   Style.ColumnLimit = 15;
24875 
24876   verifyFormat("#define A     \\\n"
24877                "  if (a)      \\\n"
24878                "    f();",
24879                Style);
24880 
24881   verifyFormat("if (a + b >\n"
24882                "    c) {\n"
24883                "  f();\n"
24884                "}",
24885                "if (a + b > c)\n"
24886                "  f();",
24887                Style);
24888 }
24889 
24890 TEST_F(FormatTest, RemoveBraces) {
24891   FormatStyle Style = getLLVMStyle();
24892   Style.RemoveBracesLLVM = true;
24893 
24894   // The following eight test cases are fully-braced versions of the examples at
24895   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
24896   // statement-bodies-of-if-else-loop-statements".
24897 
24898   // 1. Omit the braces, since the body is simple and clearly associated with
24899   // the if.
24900   verifyFormat("if (isa<FunctionDecl>(D))\n"
24901                "  handleFunctionDecl(D);\n"
24902                "else if (isa<VarDecl>(D))\n"
24903                "  handleVarDecl(D);",
24904                "if (isa<FunctionDecl>(D)) {\n"
24905                "  handleFunctionDecl(D);\n"
24906                "} else if (isa<VarDecl>(D)) {\n"
24907                "  handleVarDecl(D);\n"
24908                "}",
24909                Style);
24910 
24911   // 2. Here we document the condition itself and not the body.
24912   verifyFormat("if (isa<VarDecl>(D)) {\n"
24913                "  // It is necessary that we explain the situation with this\n"
24914                "  // surprisingly long comment, so it would be unclear\n"
24915                "  // without the braces whether the following statement is in\n"
24916                "  // the scope of the `if`.\n"
24917                "  // Because the condition is documented, we can't really\n"
24918                "  // hoist this comment that applies to the body above the\n"
24919                "  // if.\n"
24920                "  handleOtherDecl(D);\n"
24921                "}",
24922                Style);
24923 
24924   // 3. Use braces on the outer `if` to avoid a potential dangling else
24925   // situation.
24926   verifyFormat("if (isa<VarDecl>(D)) {\n"
24927                "  for (auto *A : D.attrs())\n"
24928                "    if (shouldProcessAttr(A))\n"
24929                "      handleAttr(A);\n"
24930                "}",
24931                "if (isa<VarDecl>(D)) {\n"
24932                "  for (auto *A : D.attrs()) {\n"
24933                "    if (shouldProcessAttr(A)) {\n"
24934                "      handleAttr(A);\n"
24935                "    }\n"
24936                "  }\n"
24937                "}",
24938                Style);
24939 
24940   // 4. Use braces for the `if` block to keep it uniform with the else block.
24941   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24942                "  handleFunctionDecl(D);\n"
24943                "} else {\n"
24944                "  // In this else case, it is necessary that we explain the\n"
24945                "  // situation with this surprisingly long comment, so it\n"
24946                "  // would be unclear without the braces whether the\n"
24947                "  // following statement is in the scope of the `if`.\n"
24948                "  handleOtherDecl(D);\n"
24949                "}",
24950                Style);
24951 
24952   // 5. This should also omit braces.  The `for` loop contains only a single
24953   // statement, so it shouldn't have braces.  The `if` also only contains a
24954   // single simple statement (the for loop), so it also should omit braces.
24955   verifyFormat("if (isa<FunctionDecl>(D))\n"
24956                "  for (auto *A : D.attrs())\n"
24957                "    handleAttr(A);",
24958                "if (isa<FunctionDecl>(D)) {\n"
24959                "  for (auto *A : D.attrs()) {\n"
24960                "    handleAttr(A);\n"
24961                "  }\n"
24962                "}",
24963                Style);
24964 
24965   // 6. Use braces for the outer `if` since the nested `for` is braced.
24966   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24967                "  for (auto *A : D.attrs()) {\n"
24968                "    // In this for loop body, it is necessary that we explain\n"
24969                "    // the situation with this surprisingly long comment,\n"
24970                "    // forcing braces on the `for` block.\n"
24971                "    handleAttr(A);\n"
24972                "  }\n"
24973                "}",
24974                Style);
24975 
24976   // 7. Use braces on the outer block because there are more than two levels of
24977   // nesting.
24978   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24979                "  for (auto *A : D.attrs())\n"
24980                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
24981                "      handleAttrOnDecl(D, A, i);\n"
24982                "}",
24983                "if (isa<FunctionDecl>(D)) {\n"
24984                "  for (auto *A : D.attrs()) {\n"
24985                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
24986                "      handleAttrOnDecl(D, A, i);\n"
24987                "    }\n"
24988                "  }\n"
24989                "}",
24990                Style);
24991 
24992   // 8. Use braces on the outer block because of a nested `if`, otherwise the
24993   // compiler would warn: `add explicit braces to avoid dangling else`
24994   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
24995                "  if (shouldProcess(D))\n"
24996                "    handleVarDecl(D);\n"
24997                "  else\n"
24998                "    markAsIgnored(D);\n"
24999                "}",
25000                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25001                "  if (shouldProcess(D)) {\n"
25002                "    handleVarDecl(D);\n"
25003                "  } else {\n"
25004                "    markAsIgnored(D);\n"
25005                "  }\n"
25006                "}",
25007                Style);
25008 
25009   verifyFormat("// clang-format off\n"
25010                "// comment\n"
25011                "while (i > 0) { --i; }\n"
25012                "// clang-format on\n"
25013                "while (j < 0)\n"
25014                "  ++j;",
25015                "// clang-format off\n"
25016                "// comment\n"
25017                "while (i > 0) { --i; }\n"
25018                "// clang-format on\n"
25019                "while (j < 0) { ++j; }",
25020                Style);
25021 
25022   verifyFormat("if (a)\n"
25023                "  b; // comment\n"
25024                "else if (c)\n"
25025                "  d; /* comment */\n"
25026                "else\n"
25027                "  e;",
25028                "if (a) {\n"
25029                "  b; // comment\n"
25030                "} else if (c) {\n"
25031                "  d; /* comment */\n"
25032                "} else {\n"
25033                "  e;\n"
25034                "}",
25035                Style);
25036 
25037   verifyFormat("if (a) {\n"
25038                "  b;\n"
25039                "  c;\n"
25040                "} else if (d) {\n"
25041                "  e;\n"
25042                "}",
25043                Style);
25044 
25045   verifyFormat("if (a) {\n"
25046                "#undef NDEBUG\n"
25047                "  b;\n"
25048                "} else {\n"
25049                "  c;\n"
25050                "}",
25051                Style);
25052 
25053   verifyFormat("if (a) {\n"
25054                "  // comment\n"
25055                "} else if (b) {\n"
25056                "  c;\n"
25057                "}",
25058                Style);
25059 
25060   verifyFormat("if (a) {\n"
25061                "  b;\n"
25062                "} else {\n"
25063                "  { c; }\n"
25064                "}",
25065                Style);
25066 
25067   verifyFormat("if (a) {\n"
25068                "  if (b) // comment\n"
25069                "    c;\n"
25070                "} else if (d) {\n"
25071                "  e;\n"
25072                "}",
25073                "if (a) {\n"
25074                "  if (b) { // comment\n"
25075                "    c;\n"
25076                "  }\n"
25077                "} else if (d) {\n"
25078                "  e;\n"
25079                "}",
25080                Style);
25081 
25082   verifyFormat("if (a) {\n"
25083                "  if (b) {\n"
25084                "    c;\n"
25085                "    // comment\n"
25086                "  } else if (d) {\n"
25087                "    e;\n"
25088                "  }\n"
25089                "}",
25090                Style);
25091 
25092   verifyFormat("if (a) {\n"
25093                "  if (b)\n"
25094                "    c;\n"
25095                "}",
25096                "if (a) {\n"
25097                "  if (b) {\n"
25098                "    c;\n"
25099                "  }\n"
25100                "}",
25101                Style);
25102 
25103   verifyFormat("if (a)\n"
25104                "  if (b)\n"
25105                "    c;\n"
25106                "  else\n"
25107                "    d;\n"
25108                "else\n"
25109                "  e;",
25110                "if (a) {\n"
25111                "  if (b) {\n"
25112                "    c;\n"
25113                "  } else {\n"
25114                "    d;\n"
25115                "  }\n"
25116                "} else {\n"
25117                "  e;\n"
25118                "}",
25119                Style);
25120 
25121   verifyFormat("if (a) {\n"
25122                "  // comment\n"
25123                "  if (b)\n"
25124                "    c;\n"
25125                "  else if (d)\n"
25126                "    e;\n"
25127                "} else {\n"
25128                "  g;\n"
25129                "}",
25130                "if (a) {\n"
25131                "  // comment\n"
25132                "  if (b) {\n"
25133                "    c;\n"
25134                "  } else if (d) {\n"
25135                "    e;\n"
25136                "  }\n"
25137                "} else {\n"
25138                "  g;\n"
25139                "}",
25140                Style);
25141 
25142   verifyFormat("if (a)\n"
25143                "  b;\n"
25144                "else if (c)\n"
25145                "  d;\n"
25146                "else\n"
25147                "  e;",
25148                "if (a) {\n"
25149                "  b;\n"
25150                "} else {\n"
25151                "  if (c) {\n"
25152                "    d;\n"
25153                "  } else {\n"
25154                "    e;\n"
25155                "  }\n"
25156                "}",
25157                Style);
25158 
25159   verifyFormat("if (a) {\n"
25160                "  if (b)\n"
25161                "    c;\n"
25162                "  else if (d)\n"
25163                "    e;\n"
25164                "} else {\n"
25165                "  g;\n"
25166                "}",
25167                "if (a) {\n"
25168                "  if (b)\n"
25169                "    c;\n"
25170                "  else {\n"
25171                "    if (d)\n"
25172                "      e;\n"
25173                "  }\n"
25174                "} else {\n"
25175                "  g;\n"
25176                "}",
25177                Style);
25178 
25179   verifyFormat("if (a)\n"
25180                "  b;\n"
25181                "else if (c)\n"
25182                "  while (d)\n"
25183                "    e;\n"
25184                "// comment",
25185                "if (a)\n"
25186                "{\n"
25187                "  b;\n"
25188                "} else if (c) {\n"
25189                "  while (d) {\n"
25190                "    e;\n"
25191                "  }\n"
25192                "}\n"
25193                "// comment",
25194                Style);
25195 
25196   verifyFormat("if (a) {\n"
25197                "  b;\n"
25198                "} else if (c) {\n"
25199                "  d;\n"
25200                "} else {\n"
25201                "  e;\n"
25202                "  g;\n"
25203                "}",
25204                Style);
25205 
25206   verifyFormat("if (a) {\n"
25207                "  b;\n"
25208                "} else if (c) {\n"
25209                "  d;\n"
25210                "} else {\n"
25211                "  e;\n"
25212                "} // comment",
25213                Style);
25214 
25215   verifyFormat("int abs = [](int i) {\n"
25216                "  if (i >= 0)\n"
25217                "    return i;\n"
25218                "  return -i;\n"
25219                "};",
25220                "int abs = [](int i) {\n"
25221                "  if (i >= 0) {\n"
25222                "    return i;\n"
25223                "  }\n"
25224                "  return -i;\n"
25225                "};",
25226                Style);
25227 
25228   verifyFormat("if (a)\n"
25229                "  foo();\n"
25230                "else\n"
25231                "  bar();",
25232                "if (a)\n"
25233                "{\n"
25234                "  foo();\n"
25235                "}\n"
25236                "else\n"
25237                "{\n"
25238                "  bar();\n"
25239                "}",
25240                Style);
25241 
25242   verifyFormat("if (a) {\n"
25243                "Label:\n"
25244                "}",
25245                Style);
25246 
25247   verifyFormat("if (a) {\n"
25248                "Label:\n"
25249                "  f();\n"
25250                "}",
25251                Style);
25252 
25253   verifyFormat("if (a) {\n"
25254                "  f();\n"
25255                "Label:\n"
25256                "}",
25257                Style);
25258 
25259   // FIXME: See https://github.com/llvm/llvm-project/issues/53543.
25260 #if 0
25261   Style.ColumnLimit = 65;
25262 
25263   verifyFormat("if (condition) {\n"
25264                "  ff(Indices,\n"
25265                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25266                "} else {\n"
25267                "  ff(Indices,\n"
25268                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25269                "}",
25270                Style);
25271 
25272   Style.ColumnLimit = 20;
25273 
25274   verifyFormat("if (a) {\n"
25275                "  b = c + // 1 -\n"
25276                "      d;\n"
25277                "}",
25278                Style);
25279 
25280   verifyFormat("if (a) {\n"
25281                "  b = c >= 0 ? d\n"
25282                "             : e;\n"
25283                "}",
25284                "if (a) {\n"
25285                "  b = c >= 0 ? d : e;\n"
25286                "}",
25287                Style);
25288 #endif
25289 
25290   Style.ColumnLimit = 20;
25291 
25292   verifyFormat("if (a)\n"
25293                "  b = c > 0 ? d : e;",
25294                "if (a) {\n"
25295                "  b = c > 0 ? d : e;\n"
25296                "}",
25297                Style);
25298 
25299   Style.ColumnLimit = 0;
25300 
25301   verifyFormat("if (a)\n"
25302                "  b234567890223456789032345678904234567890 = "
25303                "c234567890223456789032345678904234567890;",
25304                "if (a) {\n"
25305                "  b234567890223456789032345678904234567890 = "
25306                "c234567890223456789032345678904234567890;\n"
25307                "}",
25308                Style);
25309 }
25310 
25311 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
25312   auto Style = getLLVMStyle();
25313 
25314   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
25315                     "void functionDecl(int a, int b, int c);";
25316 
25317   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25318                      "paramF, paramG, paramH, paramI);\n"
25319                      "void functionDecl(int argumentA, int argumentB, int "
25320                      "argumentC, int argumentD, int argumentE);";
25321 
25322   verifyFormat(Short, Style);
25323 
25324   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25325                       "paramF, paramG, paramH,\n"
25326                       "             paramI);\n"
25327                       "void functionDecl(int argumentA, int argumentB, int "
25328                       "argumentC, int argumentD,\n"
25329                       "                  int argumentE);";
25330 
25331   verifyFormat(NoBreak, Medium, Style);
25332   verifyFormat(NoBreak,
25333                "functionCall(\n"
25334                "    paramA,\n"
25335                "    paramB,\n"
25336                "    paramC,\n"
25337                "    paramD,\n"
25338                "    paramE,\n"
25339                "    paramF,\n"
25340                "    paramG,\n"
25341                "    paramH,\n"
25342                "    paramI\n"
25343                ");\n"
25344                "void functionDecl(\n"
25345                "    int argumentA,\n"
25346                "    int argumentB,\n"
25347                "    int argumentC,\n"
25348                "    int argumentD,\n"
25349                "    int argumentE\n"
25350                ");",
25351                Style);
25352 
25353   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
25354                "                  nestedLongFunctionCall(argument1, "
25355                "argument2, argument3,\n"
25356                "                                         argument4, "
25357                "argument5));",
25358                Style);
25359 
25360   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25361 
25362   verifyFormat(Short, Style);
25363   verifyFormat(
25364       "functionCall(\n"
25365       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25366       "paramI\n"
25367       ");\n"
25368       "void functionDecl(\n"
25369       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25370       "argumentE\n"
25371       ");",
25372       Medium, Style);
25373 
25374   Style.AllowAllArgumentsOnNextLine = false;
25375   Style.AllowAllParametersOfDeclarationOnNextLine = false;
25376 
25377   verifyFormat(Short, Style);
25378   verifyFormat(
25379       "functionCall(\n"
25380       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25381       "paramI\n"
25382       ");\n"
25383       "void functionDecl(\n"
25384       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25385       "argumentE\n"
25386       ");",
25387       Medium, Style);
25388 
25389   Style.BinPackArguments = false;
25390   Style.BinPackParameters = false;
25391 
25392   verifyFormat(Short, Style);
25393 
25394   verifyFormat("functionCall(\n"
25395                "    paramA,\n"
25396                "    paramB,\n"
25397                "    paramC,\n"
25398                "    paramD,\n"
25399                "    paramE,\n"
25400                "    paramF,\n"
25401                "    paramG,\n"
25402                "    paramH,\n"
25403                "    paramI\n"
25404                ");\n"
25405                "void functionDecl(\n"
25406                "    int argumentA,\n"
25407                "    int argumentB,\n"
25408                "    int argumentC,\n"
25409                "    int argumentD,\n"
25410                "    int argumentE\n"
25411                ");",
25412                Medium, Style);
25413 
25414   verifyFormat("outerFunctionCall(\n"
25415                "    nestedFunctionCall(argument1),\n"
25416                "    nestedLongFunctionCall(\n"
25417                "        argument1,\n"
25418                "        argument2,\n"
25419                "        argument3,\n"
25420                "        argument4,\n"
25421                "        argument5\n"
25422                "    )\n"
25423                ");",
25424                Style);
25425 
25426   verifyFormat("int a = (int)b;", Style);
25427   verifyFormat("int a = (int)b;",
25428                "int a = (\n"
25429                "    int\n"
25430                ") b;",
25431                Style);
25432 
25433   verifyFormat("return (true);", Style);
25434   verifyFormat("return (true);",
25435                "return (\n"
25436                "    true\n"
25437                ");",
25438                Style);
25439 
25440   verifyFormat("void foo();", Style);
25441   verifyFormat("void foo();",
25442                "void foo(\n"
25443                ");",
25444                Style);
25445 
25446   verifyFormat("void foo() {}", Style);
25447   verifyFormat("void foo() {}",
25448                "void foo(\n"
25449                ") {\n"
25450                "}",
25451                Style);
25452 
25453   verifyFormat("auto string = std::string();", Style);
25454   verifyFormat("auto string = std::string();",
25455                "auto string = std::string(\n"
25456                ");",
25457                Style);
25458 
25459   verifyFormat("void (*functionPointer)() = nullptr;", Style);
25460   verifyFormat("void (*functionPointer)() = nullptr;",
25461                "void (\n"
25462                "    *functionPointer\n"
25463                ")\n"
25464                "(\n"
25465                ") = nullptr;",
25466                Style);
25467 }
25468 
25469 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
25470   auto Style = getLLVMStyle();
25471 
25472   verifyFormat("if (foo()) {\n"
25473                "  return;\n"
25474                "}",
25475                Style);
25476 
25477   verifyFormat("if (quitelongarg !=\n"
25478                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25479                "comment\n"
25480                "  return;\n"
25481                "}",
25482                Style);
25483 
25484   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25485 
25486   verifyFormat("if (foo()) {\n"
25487                "  return;\n"
25488                "}",
25489                Style);
25490 
25491   verifyFormat("if (quitelongarg !=\n"
25492                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25493                "comment\n"
25494                "  return;\n"
25495                "}",
25496                Style);
25497 }
25498 
25499 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
25500   auto Style = getLLVMStyle();
25501 
25502   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25503                "  doSomething();\n"
25504                "}",
25505                Style);
25506 
25507   verifyFormat("for (int myReallyLongCountVariable = 0; "
25508                "myReallyLongCountVariable < count;\n"
25509                "     myReallyLongCountVariable++) {\n"
25510                "  doSomething();\n"
25511                "}",
25512                Style);
25513 
25514   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25515 
25516   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25517                "  doSomething();\n"
25518                "}",
25519                Style);
25520 
25521   verifyFormat("for (int myReallyLongCountVariable = 0; "
25522                "myReallyLongCountVariable < count;\n"
25523                "     myReallyLongCountVariable++) {\n"
25524                "  doSomething();\n"
25525                "}",
25526                Style);
25527 }
25528 
25529 TEST_F(FormatTest, UnderstandsDigraphs) {
25530   verifyFormat("int arr<:5:> = {};");
25531   verifyFormat("int arr[5] = <%%>;");
25532   verifyFormat("int arr<:::qualified_variable:> = {};");
25533   verifyFormat("int arr[::qualified_variable] = <%%>;");
25534   verifyFormat("%:include <header>");
25535   verifyFormat("%:define A x##y");
25536   verifyFormat("#define A x%:%:y");
25537 }
25538 
25539 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
25540   auto Style = getLLVMStyle();
25541   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
25542   Style.AlignConsecutiveAssignments.Enabled = true;
25543   Style.AlignConsecutiveDeclarations.Enabled = true;
25544 
25545   // The AlignArray code is incorrect for non square Arrays and can cause
25546   // crashes, these tests assert that the array is not changed but will
25547   // also act as regression tests for when it is properly fixed
25548   verifyFormat("struct test demo[] = {\n"
25549                "    {1, 2},\n"
25550                "    {3, 4, 5},\n"
25551                "    {6, 7, 8}\n"
25552                "};",
25553                Style);
25554   verifyFormat("struct test demo[] = {\n"
25555                "    {1, 2, 3, 4, 5},\n"
25556                "    {3, 4, 5},\n"
25557                "    {6, 7, 8}\n"
25558                "};",
25559                Style);
25560   verifyFormat("struct test demo[] = {\n"
25561                "    {1, 2, 3, 4, 5},\n"
25562                "    {3, 4, 5},\n"
25563                "    {6, 7, 8, 9, 10, 11, 12}\n"
25564                "};",
25565                Style);
25566   verifyFormat("struct test demo[] = {\n"
25567                "    {1, 2, 3},\n"
25568                "    {3, 4, 5},\n"
25569                "    {6, 7, 8, 9, 10, 11, 12}\n"
25570                "};",
25571                Style);
25572 
25573   verifyFormat("S{\n"
25574                "    {},\n"
25575                "    {},\n"
25576                "    {a, b}\n"
25577                "};",
25578                Style);
25579   verifyFormat("S{\n"
25580                "    {},\n"
25581                "    {},\n"
25582                "    {a, b},\n"
25583                "};",
25584                Style);
25585   verifyFormat("void foo() {\n"
25586                "  auto thing = test{\n"
25587                "      {\n"
25588                "       {13}, {something}, // A\n"
25589                "      }\n"
25590                "  };\n"
25591                "}",
25592                "void foo() {\n"
25593                "  auto thing = test{\n"
25594                "      {\n"
25595                "       {13},\n"
25596                "       {something}, // A\n"
25597                "      }\n"
25598                "  };\n"
25599                "}",
25600                Style);
25601 }
25602 
25603 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
25604   auto Style = getLLVMStyle();
25605   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
25606   Style.AlignConsecutiveAssignments.Enabled = true;
25607   Style.AlignConsecutiveDeclarations.Enabled = true;
25608 
25609   // The AlignArray code is incorrect for non square Arrays and can cause
25610   // crashes, these tests assert that the array is not changed but will
25611   // also act as regression tests for when it is properly fixed
25612   verifyFormat("struct test demo[] = {\n"
25613                "    {1, 2},\n"
25614                "    {3, 4, 5},\n"
25615                "    {6, 7, 8}\n"
25616                "};",
25617                Style);
25618   verifyFormat("struct test demo[] = {\n"
25619                "    {1, 2, 3, 4, 5},\n"
25620                "    {3, 4, 5},\n"
25621                "    {6, 7, 8}\n"
25622                "};",
25623                Style);
25624   verifyFormat("struct test demo[] = {\n"
25625                "    {1, 2, 3, 4, 5},\n"
25626                "    {3, 4, 5},\n"
25627                "    {6, 7, 8, 9, 10, 11, 12}\n"
25628                "};",
25629                Style);
25630   verifyFormat("struct test demo[] = {\n"
25631                "    {1, 2, 3},\n"
25632                "    {3, 4, 5},\n"
25633                "    {6, 7, 8, 9, 10, 11, 12}\n"
25634                "};",
25635                Style);
25636 
25637   verifyFormat("S{\n"
25638                "    {},\n"
25639                "    {},\n"
25640                "    {a, b}\n"
25641                "};",
25642                Style);
25643   verifyFormat("S{\n"
25644                "    {},\n"
25645                "    {},\n"
25646                "    {a, b},\n"
25647                "};",
25648                Style);
25649   verifyFormat("void foo() {\n"
25650                "  auto thing = test{\n"
25651                "      {\n"
25652                "       {13}, {something}, // A\n"
25653                "      }\n"
25654                "  };\n"
25655                "}",
25656                "void foo() {\n"
25657                "  auto thing = test{\n"
25658                "      {\n"
25659                "       {13},\n"
25660                "       {something}, // A\n"
25661                "      }\n"
25662                "  };\n"
25663                "}",
25664                Style);
25665 }
25666 
25667 TEST_F(FormatTest, FormatsVariableTemplates) {
25668   verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
25669   verifyFormat("template <typename T> "
25670                "inline bool var = is_integral_v<T> && is_signed_v<T>;");
25671 }
25672 
25673 } // namespace
25674 } // namespace format
25675 } // namespace clang
25676