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   EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine);
2771   EXPECT_FALSE(Style.BraceWrapping.AfterEnum);
2772   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2773   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2774   Style.AllowShortEnumsOnASingleLine = false;
2775   verifyFormat("enum {\n"
2776                "  A,\n"
2777                "  B,\n"
2778                "  C\n"
2779                "} ShortEnum1, ShortEnum2;",
2780                Style);
2781   verifyFormat("typedef enum {\n"
2782                "  A,\n"
2783                "  B,\n"
2784                "  C\n"
2785                "} ShortEnum1, ShortEnum2;",
2786                Style);
2787   verifyFormat("enum {\n"
2788                "  A,\n"
2789                "} ShortEnum1, ShortEnum2;",
2790                Style);
2791   verifyFormat("typedef enum {\n"
2792                "  A,\n"
2793                "} ShortEnum1, ShortEnum2;",
2794                Style);
2795   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2796   Style.BraceWrapping.AfterEnum = true;
2797   verifyFormat("enum\n"
2798                "{\n"
2799                "  A,\n"
2800                "  B,\n"
2801                "  C\n"
2802                "} ShortEnum1, ShortEnum2;",
2803                Style);
2804   verifyFormat("typedef enum\n"
2805                "{\n"
2806                "  A,\n"
2807                "  B,\n"
2808                "  C\n"
2809                "} ShortEnum1, ShortEnum2;",
2810                Style);
2811 }
2812 
2813 TEST_F(FormatTest, ShortCaseLabels) {
2814   FormatStyle Style = getLLVMStyle();
2815   Style.AllowShortCaseLabelsOnASingleLine = true;
2816   verifyFormat("switch (a) {\n"
2817                "case 1: x = 1; break;\n"
2818                "case 2: return;\n"
2819                "case 3:\n"
2820                "case 4:\n"
2821                "case 5: return;\n"
2822                "case 6: // comment\n"
2823                "  return;\n"
2824                "case 7:\n"
2825                "  // comment\n"
2826                "  return;\n"
2827                "case 8:\n"
2828                "  x = 8; // comment\n"
2829                "  break;\n"
2830                "default: y = 1; break;\n"
2831                "}",
2832                Style);
2833   verifyFormat("switch (a) {\n"
2834                "case 0: return; // comment\n"
2835                "case 1: break;  // comment\n"
2836                "case 2: return;\n"
2837                "// comment\n"
2838                "case 3: return;\n"
2839                "// comment 1\n"
2840                "// comment 2\n"
2841                "// comment 3\n"
2842                "case 4: break; /* comment */\n"
2843                "case 5:\n"
2844                "  // comment\n"
2845                "  break;\n"
2846                "case 6: /* comment */ x = 1; break;\n"
2847                "case 7: x = /* comment */ 1; break;\n"
2848                "case 8:\n"
2849                "  x = 1; /* comment */\n"
2850                "  break;\n"
2851                "case 9:\n"
2852                "  break; // comment line 1\n"
2853                "         // comment line 2\n"
2854                "}",
2855                Style);
2856   EXPECT_EQ("switch (a) {\n"
2857             "case 1:\n"
2858             "  x = 8;\n"
2859             "  // fall through\n"
2860             "case 2: x = 8;\n"
2861             "// comment\n"
2862             "case 3:\n"
2863             "  return; /* comment line 1\n"
2864             "           * comment line 2 */\n"
2865             "case 4: i = 8;\n"
2866             "// something else\n"
2867             "#if FOO\n"
2868             "case 5: break;\n"
2869             "#endif\n"
2870             "}",
2871             format("switch (a) {\n"
2872                    "case 1: x = 8;\n"
2873                    "  // fall through\n"
2874                    "case 2:\n"
2875                    "  x = 8;\n"
2876                    "// comment\n"
2877                    "case 3:\n"
2878                    "  return; /* comment line 1\n"
2879                    "           * comment line 2 */\n"
2880                    "case 4:\n"
2881                    "  i = 8;\n"
2882                    "// something else\n"
2883                    "#if FOO\n"
2884                    "case 5: break;\n"
2885                    "#endif\n"
2886                    "}",
2887                    Style));
2888   EXPECT_EQ("switch (a) {\n"
2889             "case 0:\n"
2890             "  return; // long long long long long long long long long long "
2891             "long long comment\n"
2892             "          // line\n"
2893             "}",
2894             format("switch (a) {\n"
2895                    "case 0: return; // long long long long long long long long "
2896                    "long long long long comment line\n"
2897                    "}",
2898                    Style));
2899   EXPECT_EQ("switch (a) {\n"
2900             "case 0:\n"
2901             "  return; /* long long long long long long long long long long "
2902             "long long comment\n"
2903             "             line */\n"
2904             "}",
2905             format("switch (a) {\n"
2906                    "case 0: return; /* long long long long long long long long "
2907                    "long long long long comment line */\n"
2908                    "}",
2909                    Style));
2910   verifyFormat("switch (a) {\n"
2911                "#if FOO\n"
2912                "case 0: return 0;\n"
2913                "#endif\n"
2914                "}",
2915                Style);
2916   verifyFormat("switch (a) {\n"
2917                "case 1: {\n"
2918                "}\n"
2919                "case 2: {\n"
2920                "  return;\n"
2921                "}\n"
2922                "case 3: {\n"
2923                "  x = 1;\n"
2924                "  return;\n"
2925                "}\n"
2926                "case 4:\n"
2927                "  if (x)\n"
2928                "    return;\n"
2929                "}",
2930                Style);
2931   Style.ColumnLimit = 21;
2932   verifyFormat("switch (a) {\n"
2933                "case 1: x = 1; break;\n"
2934                "case 2: return;\n"
2935                "case 3:\n"
2936                "case 4:\n"
2937                "case 5: return;\n"
2938                "default:\n"
2939                "  y = 1;\n"
2940                "  break;\n"
2941                "}",
2942                Style);
2943   Style.ColumnLimit = 80;
2944   Style.AllowShortCaseLabelsOnASingleLine = false;
2945   Style.IndentCaseLabels = true;
2946   EXPECT_EQ("switch (n) {\n"
2947             "  default /*comments*/:\n"
2948             "    return true;\n"
2949             "  case 0:\n"
2950             "    return false;\n"
2951             "}",
2952             format("switch (n) {\n"
2953                    "default/*comments*/:\n"
2954                    "  return true;\n"
2955                    "case 0:\n"
2956                    "  return false;\n"
2957                    "}",
2958                    Style));
2959   Style.AllowShortCaseLabelsOnASingleLine = true;
2960   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2961   Style.BraceWrapping.AfterCaseLabel = true;
2962   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2963   EXPECT_EQ("switch (n)\n"
2964             "{\n"
2965             "  case 0:\n"
2966             "  {\n"
2967             "    return false;\n"
2968             "  }\n"
2969             "  default:\n"
2970             "  {\n"
2971             "    return true;\n"
2972             "  }\n"
2973             "}",
2974             format("switch (n) {\n"
2975                    "  case 0: {\n"
2976                    "    return false;\n"
2977                    "  }\n"
2978                    "  default:\n"
2979                    "  {\n"
2980                    "    return true;\n"
2981                    "  }\n"
2982                    "}",
2983                    Style));
2984 }
2985 
2986 TEST_F(FormatTest, FormatsLabels) {
2987   verifyFormat("void f() {\n"
2988                "  some_code();\n"
2989                "test_label:\n"
2990                "  some_other_code();\n"
2991                "  {\n"
2992                "    some_more_code();\n"
2993                "  another_label:\n"
2994                "    some_more_code();\n"
2995                "  }\n"
2996                "}");
2997   verifyFormat("{\n"
2998                "  some_code();\n"
2999                "test_label:\n"
3000                "  some_other_code();\n"
3001                "}");
3002   verifyFormat("{\n"
3003                "  some_code();\n"
3004                "test_label:;\n"
3005                "  int i = 0;\n"
3006                "}");
3007   FormatStyle Style = getLLVMStyle();
3008   Style.IndentGotoLabels = false;
3009   verifyFormat("void f() {\n"
3010                "  some_code();\n"
3011                "test_label:\n"
3012                "  some_other_code();\n"
3013                "  {\n"
3014                "    some_more_code();\n"
3015                "another_label:\n"
3016                "    some_more_code();\n"
3017                "  }\n"
3018                "}",
3019                Style);
3020   verifyFormat("{\n"
3021                "  some_code();\n"
3022                "test_label:\n"
3023                "  some_other_code();\n"
3024                "}",
3025                Style);
3026   verifyFormat("{\n"
3027                "  some_code();\n"
3028                "test_label:;\n"
3029                "  int i = 0;\n"
3030                "}");
3031 }
3032 
3033 TEST_F(FormatTest, MultiLineControlStatements) {
3034   FormatStyle Style = getLLVMStyleWithColumns(20);
3035   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3036   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3037   // Short lines should keep opening brace on same line.
3038   EXPECT_EQ("if (foo) {\n"
3039             "  bar();\n"
3040             "}",
3041             format("if(foo){bar();}", Style));
3042   EXPECT_EQ("if (foo) {\n"
3043             "  bar();\n"
3044             "} else {\n"
3045             "  baz();\n"
3046             "}",
3047             format("if(foo){bar();}else{baz();}", Style));
3048   EXPECT_EQ("if (foo && bar) {\n"
3049             "  baz();\n"
3050             "}",
3051             format("if(foo&&bar){baz();}", Style));
3052   EXPECT_EQ("if (foo) {\n"
3053             "  bar();\n"
3054             "} else if (baz) {\n"
3055             "  quux();\n"
3056             "}",
3057             format("if(foo){bar();}else if(baz){quux();}", Style));
3058   EXPECT_EQ(
3059       "if (foo) {\n"
3060       "  bar();\n"
3061       "} else if (baz) {\n"
3062       "  quux();\n"
3063       "} else {\n"
3064       "  foobar();\n"
3065       "}",
3066       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
3067   EXPECT_EQ("for (;;) {\n"
3068             "  foo();\n"
3069             "}",
3070             format("for(;;){foo();}"));
3071   EXPECT_EQ("while (1) {\n"
3072             "  foo();\n"
3073             "}",
3074             format("while(1){foo();}", Style));
3075   EXPECT_EQ("switch (foo) {\n"
3076             "case bar:\n"
3077             "  return;\n"
3078             "}",
3079             format("switch(foo){case bar:return;}", Style));
3080   EXPECT_EQ("try {\n"
3081             "  foo();\n"
3082             "} catch (...) {\n"
3083             "  bar();\n"
3084             "}",
3085             format("try{foo();}catch(...){bar();}", Style));
3086   EXPECT_EQ("do {\n"
3087             "  foo();\n"
3088             "} while (bar &&\n"
3089             "         baz);",
3090             format("do{foo();}while(bar&&baz);", Style));
3091   // Long lines should put opening brace on new line.
3092   EXPECT_EQ("if (foo && bar &&\n"
3093             "    baz)\n"
3094             "{\n"
3095             "  quux();\n"
3096             "}",
3097             format("if(foo&&bar&&baz){quux();}", Style));
3098   EXPECT_EQ("if (foo && bar &&\n"
3099             "    baz)\n"
3100             "{\n"
3101             "  quux();\n"
3102             "}",
3103             format("if (foo && bar &&\n"
3104                    "    baz) {\n"
3105                    "  quux();\n"
3106                    "}",
3107                    Style));
3108   EXPECT_EQ("if (foo) {\n"
3109             "  bar();\n"
3110             "} else if (baz ||\n"
3111             "           quux)\n"
3112             "{\n"
3113             "  foobar();\n"
3114             "}",
3115             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
3116   EXPECT_EQ(
3117       "if (foo) {\n"
3118       "  bar();\n"
3119       "} else if (baz ||\n"
3120       "           quux)\n"
3121       "{\n"
3122       "  foobar();\n"
3123       "} else {\n"
3124       "  barbaz();\n"
3125       "}",
3126       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3127              Style));
3128   EXPECT_EQ("for (int i = 0;\n"
3129             "     i < 10; ++i)\n"
3130             "{\n"
3131             "  foo();\n"
3132             "}",
3133             format("for(int i=0;i<10;++i){foo();}", Style));
3134   EXPECT_EQ("foreach (int i,\n"
3135             "         list)\n"
3136             "{\n"
3137             "  foo();\n"
3138             "}",
3139             format("foreach(int i, list){foo();}", Style));
3140   Style.ColumnLimit =
3141       40; // to concentrate at brace wrapping, not line wrap due to column limit
3142   EXPECT_EQ("foreach (int i, list) {\n"
3143             "  foo();\n"
3144             "}",
3145             format("foreach(int i, list){foo();}", Style));
3146   Style.ColumnLimit =
3147       20; // to concentrate at brace wrapping, not line wrap due to column limit
3148   EXPECT_EQ("while (foo || bar ||\n"
3149             "       baz)\n"
3150             "{\n"
3151             "  quux();\n"
3152             "}",
3153             format("while(foo||bar||baz){quux();}", Style));
3154   EXPECT_EQ("switch (\n"
3155             "    foo = barbaz)\n"
3156             "{\n"
3157             "case quux:\n"
3158             "  return;\n"
3159             "}",
3160             format("switch(foo=barbaz){case quux:return;}", Style));
3161   EXPECT_EQ("try {\n"
3162             "  foo();\n"
3163             "} catch (\n"
3164             "    Exception &bar)\n"
3165             "{\n"
3166             "  baz();\n"
3167             "}",
3168             format("try{foo();}catch(Exception&bar){baz();}", Style));
3169   Style.ColumnLimit =
3170       40; // to concentrate at brace wrapping, not line wrap due to column limit
3171   EXPECT_EQ("try {\n"
3172             "  foo();\n"
3173             "} catch (Exception &bar) {\n"
3174             "  baz();\n"
3175             "}",
3176             format("try{foo();}catch(Exception&bar){baz();}", Style));
3177   Style.ColumnLimit =
3178       20; // to concentrate at brace wrapping, not line wrap due to column limit
3179 
3180   Style.BraceWrapping.BeforeElse = true;
3181   EXPECT_EQ(
3182       "if (foo) {\n"
3183       "  bar();\n"
3184       "}\n"
3185       "else if (baz ||\n"
3186       "         quux)\n"
3187       "{\n"
3188       "  foobar();\n"
3189       "}\n"
3190       "else {\n"
3191       "  barbaz();\n"
3192       "}",
3193       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3194              Style));
3195 
3196   Style.BraceWrapping.BeforeCatch = true;
3197   EXPECT_EQ("try {\n"
3198             "  foo();\n"
3199             "}\n"
3200             "catch (...) {\n"
3201             "  baz();\n"
3202             "}",
3203             format("try{foo();}catch(...){baz();}", Style));
3204 
3205   Style.BraceWrapping.AfterFunction = true;
3206   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3207   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
3208   Style.ColumnLimit = 80;
3209   verifyFormat("void shortfunction() { bar(); }", Style);
3210 
3211   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
3212   verifyFormat("void shortfunction()\n"
3213                "{\n"
3214                "  bar();\n"
3215                "}",
3216                Style);
3217 }
3218 
3219 TEST_F(FormatTest, BeforeWhile) {
3220   FormatStyle Style = getLLVMStyle();
3221   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3222 
3223   verifyFormat("do {\n"
3224                "  foo();\n"
3225                "} while (1);",
3226                Style);
3227   Style.BraceWrapping.BeforeWhile = true;
3228   verifyFormat("do {\n"
3229                "  foo();\n"
3230                "}\n"
3231                "while (1);",
3232                Style);
3233 }
3234 
3235 //===----------------------------------------------------------------------===//
3236 // Tests for classes, namespaces, etc.
3237 //===----------------------------------------------------------------------===//
3238 
3239 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
3240   verifyFormat("class A {};");
3241 }
3242 
3243 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
3244   verifyFormat("class A {\n"
3245                "public:\n"
3246                "public: // comment\n"
3247                "protected:\n"
3248                "private:\n"
3249                "  void f() {}\n"
3250                "};");
3251   verifyFormat("export class A {\n"
3252                "public:\n"
3253                "public: // comment\n"
3254                "protected:\n"
3255                "private:\n"
3256                "  void f() {}\n"
3257                "};");
3258   verifyGoogleFormat("class A {\n"
3259                      " public:\n"
3260                      " protected:\n"
3261                      " private:\n"
3262                      "  void f() {}\n"
3263                      "};");
3264   verifyGoogleFormat("export class A {\n"
3265                      " public:\n"
3266                      " protected:\n"
3267                      " private:\n"
3268                      "  void f() {}\n"
3269                      "};");
3270   verifyFormat("class A {\n"
3271                "public slots:\n"
3272                "  void f1() {}\n"
3273                "public Q_SLOTS:\n"
3274                "  void f2() {}\n"
3275                "protected slots:\n"
3276                "  void f3() {}\n"
3277                "protected Q_SLOTS:\n"
3278                "  void f4() {}\n"
3279                "private slots:\n"
3280                "  void f5() {}\n"
3281                "private Q_SLOTS:\n"
3282                "  void f6() {}\n"
3283                "signals:\n"
3284                "  void g1();\n"
3285                "Q_SIGNALS:\n"
3286                "  void g2();\n"
3287                "};");
3288 
3289   // Don't interpret 'signals' the wrong way.
3290   verifyFormat("signals.set();");
3291   verifyFormat("for (Signals signals : f()) {\n}");
3292   verifyFormat("{\n"
3293                "  signals.set(); // This needs indentation.\n"
3294                "}");
3295   verifyFormat("void f() {\n"
3296                "label:\n"
3297                "  signals.baz();\n"
3298                "}");
3299   verifyFormat("private[1];");
3300   verifyFormat("testArray[public] = 1;");
3301   verifyFormat("public();");
3302   verifyFormat("myFunc(public);");
3303   verifyFormat("std::vector<int> testVec = {private};");
3304   verifyFormat("private.p = 1;");
3305   verifyFormat("void function(private...){};");
3306   verifyFormat("if (private && public)\n");
3307   verifyFormat("private &= true;");
3308   verifyFormat("int x = private * public;");
3309   verifyFormat("public *= private;");
3310   verifyFormat("int x = public + private;");
3311   verifyFormat("private++;");
3312   verifyFormat("++private;");
3313   verifyFormat("public += private;");
3314   verifyFormat("public = public - private;");
3315   verifyFormat("public->foo();");
3316   verifyFormat("private--;");
3317   verifyFormat("--private;");
3318   verifyFormat("public -= 1;");
3319   verifyFormat("if (!private && !public)\n");
3320   verifyFormat("public != private;");
3321   verifyFormat("int x = public / private;");
3322   verifyFormat("public /= 2;");
3323   verifyFormat("public = public % 2;");
3324   verifyFormat("public %= 2;");
3325   verifyFormat("if (public < private)\n");
3326   verifyFormat("public << private;");
3327   verifyFormat("public <<= private;");
3328   verifyFormat("if (public > private)\n");
3329   verifyFormat("public >> private;");
3330   verifyFormat("public >>= private;");
3331   verifyFormat("public ^ private;");
3332   verifyFormat("public ^= private;");
3333   verifyFormat("public | private;");
3334   verifyFormat("public |= private;");
3335   verifyFormat("auto x = private ? 1 : 2;");
3336   verifyFormat("if (public == private)\n");
3337   verifyFormat("void foo(public, private)");
3338   verifyFormat("public::foo();");
3339 }
3340 
3341 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3342   EXPECT_EQ("class A {\n"
3343             "public:\n"
3344             "  void f();\n"
3345             "\n"
3346             "private:\n"
3347             "  void g() {}\n"
3348             "  // test\n"
3349             "protected:\n"
3350             "  int h;\n"
3351             "};",
3352             format("class A {\n"
3353                    "public:\n"
3354                    "void f();\n"
3355                    "private:\n"
3356                    "void g() {}\n"
3357                    "// test\n"
3358                    "protected:\n"
3359                    "int h;\n"
3360                    "};"));
3361   EXPECT_EQ("class A {\n"
3362             "protected:\n"
3363             "public:\n"
3364             "  void f();\n"
3365             "};",
3366             format("class A {\n"
3367                    "protected:\n"
3368                    "\n"
3369                    "public:\n"
3370                    "\n"
3371                    "  void f();\n"
3372                    "};"));
3373 
3374   // Even ensure proper spacing inside macros.
3375   EXPECT_EQ("#define B     \\\n"
3376             "  class A {   \\\n"
3377             "   protected: \\\n"
3378             "   public:    \\\n"
3379             "    void f(); \\\n"
3380             "  };",
3381             format("#define B     \\\n"
3382                    "  class A {   \\\n"
3383                    "   protected: \\\n"
3384                    "              \\\n"
3385                    "   public:    \\\n"
3386                    "              \\\n"
3387                    "    void f(); \\\n"
3388                    "  };",
3389                    getGoogleStyle()));
3390   // But don't remove empty lines after macros ending in access specifiers.
3391   EXPECT_EQ("#define A private:\n"
3392             "\n"
3393             "int i;",
3394             format("#define A         private:\n"
3395                    "\n"
3396                    "int              i;"));
3397 }
3398 
3399 TEST_F(FormatTest, FormatsClasses) {
3400   verifyFormat("class A : public B {};");
3401   verifyFormat("class A : public ::B {};");
3402 
3403   verifyFormat(
3404       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3405       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3406   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3407                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3408                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3409   verifyFormat(
3410       "class A : public B, public C, public D, public E, public F {};");
3411   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3412                "                     public C,\n"
3413                "                     public D,\n"
3414                "                     public E,\n"
3415                "                     public F,\n"
3416                "                     public G {};");
3417 
3418   verifyFormat("class\n"
3419                "    ReallyReallyLongClassName {\n"
3420                "  int i;\n"
3421                "};",
3422                getLLVMStyleWithColumns(32));
3423   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3424                "                           aaaaaaaaaaaaaaaa> {};");
3425   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3426                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3427                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3428   verifyFormat("template <class R, class C>\n"
3429                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3430                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3431   verifyFormat("class ::A::B {};");
3432 }
3433 
3434 TEST_F(FormatTest, BreakInheritanceStyle) {
3435   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3436   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3437       FormatStyle::BILS_BeforeComma;
3438   verifyFormat("class MyClass : public X {};",
3439                StyleWithInheritanceBreakBeforeComma);
3440   verifyFormat("class MyClass\n"
3441                "    : public X\n"
3442                "    , public Y {};",
3443                StyleWithInheritanceBreakBeforeComma);
3444   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3445                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3446                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3447                StyleWithInheritanceBreakBeforeComma);
3448   verifyFormat("struct aaaaaaaaaaaaa\n"
3449                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3450                "          aaaaaaaaaaaaaaaa> {};",
3451                StyleWithInheritanceBreakBeforeComma);
3452 
3453   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3454   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3455       FormatStyle::BILS_AfterColon;
3456   verifyFormat("class MyClass : public X {};",
3457                StyleWithInheritanceBreakAfterColon);
3458   verifyFormat("class MyClass : public X, public Y {};",
3459                StyleWithInheritanceBreakAfterColon);
3460   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3461                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3462                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3463                StyleWithInheritanceBreakAfterColon);
3464   verifyFormat("struct aaaaaaaaaaaaa :\n"
3465                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3466                "        aaaaaaaaaaaaaaaa> {};",
3467                StyleWithInheritanceBreakAfterColon);
3468 
3469   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3470   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3471       FormatStyle::BILS_AfterComma;
3472   verifyFormat("class MyClass : public X {};",
3473                StyleWithInheritanceBreakAfterComma);
3474   verifyFormat("class MyClass : public X,\n"
3475                "                public Y {};",
3476                StyleWithInheritanceBreakAfterComma);
3477   verifyFormat(
3478       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3479       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3480       "{};",
3481       StyleWithInheritanceBreakAfterComma);
3482   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3483                "                           aaaaaaaaaaaaaaaa> {};",
3484                StyleWithInheritanceBreakAfterComma);
3485   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3486                "    : public OnceBreak,\n"
3487                "      public AlwaysBreak,\n"
3488                "      EvenBasesFitInOneLine {};",
3489                StyleWithInheritanceBreakAfterComma);
3490 }
3491 
3492 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) {
3493   verifyFormat("class A {\n} a, b;");
3494   verifyFormat("struct A {\n} a, b;");
3495   verifyFormat("union A {\n} a, b;");
3496 
3497   verifyFormat("constexpr class A {\n} a, b;");
3498   verifyFormat("constexpr struct A {\n} a, b;");
3499   verifyFormat("constexpr union A {\n} a, b;");
3500 
3501   verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace");
3502   verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace");
3503   verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace");
3504 
3505   verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace");
3506   verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace");
3507   verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace");
3508 
3509   verifyFormat("namespace ns {\n"
3510                "class {\n"
3511                "} a, b;\n"
3512                "} // namespace ns");
3513   verifyFormat("namespace ns {\n"
3514                "const class {\n"
3515                "} a, b;\n"
3516                "} // namespace ns");
3517   verifyFormat("namespace ns {\n"
3518                "constexpr class C {\n"
3519                "} a, b;\n"
3520                "} // namespace ns");
3521   verifyFormat("namespace ns {\n"
3522                "class { /* comment */\n"
3523                "} a, b;\n"
3524                "} // namespace ns");
3525   verifyFormat("namespace ns {\n"
3526                "const class { /* comment */\n"
3527                "} a, b;\n"
3528                "} // namespace ns");
3529 }
3530 
3531 TEST_F(FormatTest, FormatsEnum) {
3532   verifyFormat("enum {\n"
3533                "  Zero,\n"
3534                "  One = 1,\n"
3535                "  Two = One + 1,\n"
3536                "  Three = (One + Two),\n"
3537                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3538                "  Five = (One, Two, Three, Four, 5)\n"
3539                "};");
3540   verifyGoogleFormat("enum {\n"
3541                      "  Zero,\n"
3542                      "  One = 1,\n"
3543                      "  Two = One + 1,\n"
3544                      "  Three = (One + Two),\n"
3545                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3546                      "  Five = (One, Two, Three, Four, 5)\n"
3547                      "};");
3548   verifyFormat("enum Enum {};");
3549   verifyFormat("enum {};");
3550   verifyFormat("enum X E {} d;");
3551   verifyFormat("enum __attribute__((...)) E {} d;");
3552   verifyFormat("enum __declspec__((...)) E {} d;");
3553   verifyFormat("enum {\n"
3554                "  Bar = Foo<int, int>::value\n"
3555                "};",
3556                getLLVMStyleWithColumns(30));
3557 
3558   verifyFormat("enum ShortEnum { A, B, C };");
3559   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3560 
3561   EXPECT_EQ("enum KeepEmptyLines {\n"
3562             "  ONE,\n"
3563             "\n"
3564             "  TWO,\n"
3565             "\n"
3566             "  THREE\n"
3567             "}",
3568             format("enum KeepEmptyLines {\n"
3569                    "  ONE,\n"
3570                    "\n"
3571                    "  TWO,\n"
3572                    "\n"
3573                    "\n"
3574                    "  THREE\n"
3575                    "}"));
3576   verifyFormat("enum E { // comment\n"
3577                "  ONE,\n"
3578                "  TWO\n"
3579                "};\n"
3580                "int i;");
3581 
3582   FormatStyle EightIndent = getLLVMStyle();
3583   EightIndent.IndentWidth = 8;
3584   verifyFormat("enum {\n"
3585                "        VOID,\n"
3586                "        CHAR,\n"
3587                "        SHORT,\n"
3588                "        INT,\n"
3589                "        LONG,\n"
3590                "        SIGNED,\n"
3591                "        UNSIGNED,\n"
3592                "        BOOL,\n"
3593                "        FLOAT,\n"
3594                "        DOUBLE,\n"
3595                "        COMPLEX\n"
3596                "};",
3597                EightIndent);
3598 
3599   // Not enums.
3600   verifyFormat("enum X f() {\n"
3601                "  a();\n"
3602                "  return 42;\n"
3603                "}");
3604   verifyFormat("enum X Type::f() {\n"
3605                "  a();\n"
3606                "  return 42;\n"
3607                "}");
3608   verifyFormat("enum ::X f() {\n"
3609                "  a();\n"
3610                "  return 42;\n"
3611                "}");
3612   verifyFormat("enum ns::X f() {\n"
3613                "  a();\n"
3614                "  return 42;\n"
3615                "}");
3616 }
3617 
3618 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3619   verifyFormat("enum Type {\n"
3620                "  One = 0; // These semicolons should be commas.\n"
3621                "  Two = 1;\n"
3622                "};");
3623   verifyFormat("namespace n {\n"
3624                "enum Type {\n"
3625                "  One,\n"
3626                "  Two, // missing };\n"
3627                "  int i;\n"
3628                "}\n"
3629                "void g() {}");
3630 }
3631 
3632 TEST_F(FormatTest, FormatsEnumStruct) {
3633   verifyFormat("enum struct {\n"
3634                "  Zero,\n"
3635                "  One = 1,\n"
3636                "  Two = One + 1,\n"
3637                "  Three = (One + Two),\n"
3638                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3639                "  Five = (One, Two, Three, Four, 5)\n"
3640                "};");
3641   verifyFormat("enum struct Enum {};");
3642   verifyFormat("enum struct {};");
3643   verifyFormat("enum struct X E {} d;");
3644   verifyFormat("enum struct __attribute__((...)) E {} d;");
3645   verifyFormat("enum struct __declspec__((...)) E {} d;");
3646   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3647 }
3648 
3649 TEST_F(FormatTest, FormatsEnumClass) {
3650   verifyFormat("enum class {\n"
3651                "  Zero,\n"
3652                "  One = 1,\n"
3653                "  Two = One + 1,\n"
3654                "  Three = (One + Two),\n"
3655                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3656                "  Five = (One, Two, Three, Four, 5)\n"
3657                "};");
3658   verifyFormat("enum class Enum {};");
3659   verifyFormat("enum class {};");
3660   verifyFormat("enum class X E {} d;");
3661   verifyFormat("enum class __attribute__((...)) E {} d;");
3662   verifyFormat("enum class __declspec__((...)) E {} d;");
3663   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3664 }
3665 
3666 TEST_F(FormatTest, FormatsEnumTypes) {
3667   verifyFormat("enum X : int {\n"
3668                "  A, // Force multiple lines.\n"
3669                "  B\n"
3670                "};");
3671   verifyFormat("enum X : int { A, B };");
3672   verifyFormat("enum X : std::uint32_t { A, B };");
3673 }
3674 
3675 TEST_F(FormatTest, FormatsTypedefEnum) {
3676   FormatStyle Style = getLLVMStyleWithColumns(40);
3677   verifyFormat("typedef enum {} EmptyEnum;");
3678   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3679   verifyFormat("typedef enum {\n"
3680                "  ZERO = 0,\n"
3681                "  ONE = 1,\n"
3682                "  TWO = 2,\n"
3683                "  THREE = 3\n"
3684                "} LongEnum;",
3685                Style);
3686   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3687   Style.BraceWrapping.AfterEnum = true;
3688   verifyFormat("typedef enum {} EmptyEnum;");
3689   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3690   verifyFormat("typedef enum\n"
3691                "{\n"
3692                "  ZERO = 0,\n"
3693                "  ONE = 1,\n"
3694                "  TWO = 2,\n"
3695                "  THREE = 3\n"
3696                "} LongEnum;",
3697                Style);
3698 }
3699 
3700 TEST_F(FormatTest, FormatsNSEnums) {
3701   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3702   verifyGoogleFormat(
3703       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3704   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3705                      "  // Information about someDecentlyLongValue.\n"
3706                      "  someDecentlyLongValue,\n"
3707                      "  // Information about anotherDecentlyLongValue.\n"
3708                      "  anotherDecentlyLongValue,\n"
3709                      "  // Information about aThirdDecentlyLongValue.\n"
3710                      "  aThirdDecentlyLongValue\n"
3711                      "};");
3712   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3713                      "  // Information about someDecentlyLongValue.\n"
3714                      "  someDecentlyLongValue,\n"
3715                      "  // Information about anotherDecentlyLongValue.\n"
3716                      "  anotherDecentlyLongValue,\n"
3717                      "  // Information about aThirdDecentlyLongValue.\n"
3718                      "  aThirdDecentlyLongValue\n"
3719                      "};");
3720   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3721                      "  a = 1,\n"
3722                      "  b = 2,\n"
3723                      "  c = 3,\n"
3724                      "};");
3725   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3726                      "  a = 1,\n"
3727                      "  b = 2,\n"
3728                      "  c = 3,\n"
3729                      "};");
3730   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3731                      "  a = 1,\n"
3732                      "  b = 2,\n"
3733                      "  c = 3,\n"
3734                      "};");
3735   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3736                      "  a = 1,\n"
3737                      "  b = 2,\n"
3738                      "  c = 3,\n"
3739                      "};");
3740 }
3741 
3742 TEST_F(FormatTest, FormatsBitfields) {
3743   verifyFormat("struct Bitfields {\n"
3744                "  unsigned sClass : 8;\n"
3745                "  unsigned ValueKind : 2;\n"
3746                "};");
3747   verifyFormat("struct A {\n"
3748                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3749                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3750                "};");
3751   verifyFormat("struct MyStruct {\n"
3752                "  uchar data;\n"
3753                "  uchar : 8;\n"
3754                "  uchar : 8;\n"
3755                "  uchar other;\n"
3756                "};");
3757   FormatStyle Style = getLLVMStyle();
3758   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3759   verifyFormat("struct Bitfields {\n"
3760                "  unsigned sClass:8;\n"
3761                "  unsigned ValueKind:2;\n"
3762                "  uchar other;\n"
3763                "};",
3764                Style);
3765   verifyFormat("struct A {\n"
3766                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3767                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3768                "};",
3769                Style);
3770   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3771   verifyFormat("struct Bitfields {\n"
3772                "  unsigned sClass :8;\n"
3773                "  unsigned ValueKind :2;\n"
3774                "  uchar other;\n"
3775                "};",
3776                Style);
3777   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3778   verifyFormat("struct Bitfields {\n"
3779                "  unsigned sClass: 8;\n"
3780                "  unsigned ValueKind: 2;\n"
3781                "  uchar other;\n"
3782                "};",
3783                Style);
3784 }
3785 
3786 TEST_F(FormatTest, FormatsNamespaces) {
3787   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3788   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3789 
3790   verifyFormat("namespace some_namespace {\n"
3791                "class A {};\n"
3792                "void f() { f(); }\n"
3793                "}",
3794                LLVMWithNoNamespaceFix);
3795   verifyFormat("#define M(x) x##x\n"
3796                "namespace M(x) {\n"
3797                "class A {};\n"
3798                "void f() { f(); }\n"
3799                "}",
3800                LLVMWithNoNamespaceFix);
3801   verifyFormat("#define M(x) x##x\n"
3802                "namespace N::inline M(x) {\n"
3803                "class A {};\n"
3804                "void f() { f(); }\n"
3805                "}",
3806                LLVMWithNoNamespaceFix);
3807   verifyFormat("#define M(x) x##x\n"
3808                "namespace M(x)::inline N {\n"
3809                "class A {};\n"
3810                "void f() { f(); }\n"
3811                "}",
3812                LLVMWithNoNamespaceFix);
3813   verifyFormat("#define M(x) x##x\n"
3814                "namespace N::M(x) {\n"
3815                "class A {};\n"
3816                "void f() { f(); }\n"
3817                "}",
3818                LLVMWithNoNamespaceFix);
3819   verifyFormat("#define M(x) x##x\n"
3820                "namespace M::N(x) {\n"
3821                "class A {};\n"
3822                "void f() { f(); }\n"
3823                "}",
3824                LLVMWithNoNamespaceFix);
3825   verifyFormat("namespace N::inline D {\n"
3826                "class A {};\n"
3827                "void f() { f(); }\n"
3828                "}",
3829                LLVMWithNoNamespaceFix);
3830   verifyFormat("namespace N::inline D::E {\n"
3831                "class A {};\n"
3832                "void f() { f(); }\n"
3833                "}",
3834                LLVMWithNoNamespaceFix);
3835   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3836                "class A {};\n"
3837                "void f() { f(); }\n"
3838                "}",
3839                LLVMWithNoNamespaceFix);
3840   verifyFormat("/* something */ namespace some_namespace {\n"
3841                "class A {};\n"
3842                "void f() { f(); }\n"
3843                "}",
3844                LLVMWithNoNamespaceFix);
3845   verifyFormat("namespace {\n"
3846                "class A {};\n"
3847                "void f() { f(); }\n"
3848                "}",
3849                LLVMWithNoNamespaceFix);
3850   verifyFormat("/* something */ namespace {\n"
3851                "class A {};\n"
3852                "void f() { f(); }\n"
3853                "}",
3854                LLVMWithNoNamespaceFix);
3855   verifyFormat("inline namespace X {\n"
3856                "class A {};\n"
3857                "void f() { f(); }\n"
3858                "}",
3859                LLVMWithNoNamespaceFix);
3860   verifyFormat("/* something */ inline namespace X {\n"
3861                "class A {};\n"
3862                "void f() { f(); }\n"
3863                "}",
3864                LLVMWithNoNamespaceFix);
3865   verifyFormat("export namespace X {\n"
3866                "class A {};\n"
3867                "void f() { f(); }\n"
3868                "}",
3869                LLVMWithNoNamespaceFix);
3870   verifyFormat("using namespace some_namespace;\n"
3871                "class A {};\n"
3872                "void f() { f(); }",
3873                LLVMWithNoNamespaceFix);
3874 
3875   // This code is more common than we thought; if we
3876   // layout this correctly the semicolon will go into
3877   // its own line, which is undesirable.
3878   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3879   verifyFormat("namespace {\n"
3880                "class A {};\n"
3881                "};",
3882                LLVMWithNoNamespaceFix);
3883 
3884   verifyFormat("namespace {\n"
3885                "int SomeVariable = 0; // comment\n"
3886                "} // namespace",
3887                LLVMWithNoNamespaceFix);
3888   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3889             "#define HEADER_GUARD\n"
3890             "namespace my_namespace {\n"
3891             "int i;\n"
3892             "} // my_namespace\n"
3893             "#endif // HEADER_GUARD",
3894             format("#ifndef HEADER_GUARD\n"
3895                    " #define HEADER_GUARD\n"
3896                    "   namespace my_namespace {\n"
3897                    "int i;\n"
3898                    "}    // my_namespace\n"
3899                    "#endif    // HEADER_GUARD",
3900                    LLVMWithNoNamespaceFix));
3901 
3902   EXPECT_EQ("namespace A::B {\n"
3903             "class C {};\n"
3904             "}",
3905             format("namespace A::B {\n"
3906                    "class C {};\n"
3907                    "}",
3908                    LLVMWithNoNamespaceFix));
3909 
3910   FormatStyle Style = getLLVMStyle();
3911   Style.NamespaceIndentation = FormatStyle::NI_All;
3912   EXPECT_EQ("namespace out {\n"
3913             "  int i;\n"
3914             "  namespace in {\n"
3915             "    int i;\n"
3916             "  } // namespace in\n"
3917             "} // namespace out",
3918             format("namespace out {\n"
3919                    "int i;\n"
3920                    "namespace in {\n"
3921                    "int i;\n"
3922                    "} // namespace in\n"
3923                    "} // namespace out",
3924                    Style));
3925 
3926   FormatStyle ShortInlineFunctions = getLLVMStyle();
3927   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3928   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3929       FormatStyle::SFS_Inline;
3930   verifyFormat("namespace {\n"
3931                "  void f() {\n"
3932                "    return;\n"
3933                "  }\n"
3934                "} // namespace\n",
3935                ShortInlineFunctions);
3936   verifyFormat("namespace { /* comment */\n"
3937                "  void f() {\n"
3938                "    return;\n"
3939                "  }\n"
3940                "} // namespace\n",
3941                ShortInlineFunctions);
3942   verifyFormat("namespace { // comment\n"
3943                "  void f() {\n"
3944                "    return;\n"
3945                "  }\n"
3946                "} // namespace\n",
3947                ShortInlineFunctions);
3948   verifyFormat("namespace {\n"
3949                "  int some_int;\n"
3950                "  void f() {\n"
3951                "    return;\n"
3952                "  }\n"
3953                "} // namespace\n",
3954                ShortInlineFunctions);
3955   verifyFormat("namespace interface {\n"
3956                "  void f() {\n"
3957                "    return;\n"
3958                "  }\n"
3959                "} // namespace interface\n",
3960                ShortInlineFunctions);
3961   verifyFormat("namespace {\n"
3962                "  class X {\n"
3963                "    void f() { return; }\n"
3964                "  };\n"
3965                "} // namespace\n",
3966                ShortInlineFunctions);
3967   verifyFormat("namespace {\n"
3968                "  class X { /* comment */\n"
3969                "    void f() { return; }\n"
3970                "  };\n"
3971                "} // namespace\n",
3972                ShortInlineFunctions);
3973   verifyFormat("namespace {\n"
3974                "  class X { // comment\n"
3975                "    void f() { return; }\n"
3976                "  };\n"
3977                "} // namespace\n",
3978                ShortInlineFunctions);
3979   verifyFormat("namespace {\n"
3980                "  struct X {\n"
3981                "    void f() { return; }\n"
3982                "  };\n"
3983                "} // namespace\n",
3984                ShortInlineFunctions);
3985   verifyFormat("namespace {\n"
3986                "  union X {\n"
3987                "    void f() { return; }\n"
3988                "  };\n"
3989                "} // namespace\n",
3990                ShortInlineFunctions);
3991   verifyFormat("extern \"C\" {\n"
3992                "void f() {\n"
3993                "  return;\n"
3994                "}\n"
3995                "} // namespace\n",
3996                ShortInlineFunctions);
3997   verifyFormat("namespace {\n"
3998                "  class X {\n"
3999                "    void f() { return; }\n"
4000                "  } x;\n"
4001                "} // namespace\n",
4002                ShortInlineFunctions);
4003   verifyFormat("namespace {\n"
4004                "  [[nodiscard]] class X {\n"
4005                "    void f() { return; }\n"
4006                "  };\n"
4007                "} // namespace\n",
4008                ShortInlineFunctions);
4009   verifyFormat("namespace {\n"
4010                "  static class X {\n"
4011                "    void f() { return; }\n"
4012                "  } x;\n"
4013                "} // namespace\n",
4014                ShortInlineFunctions);
4015   verifyFormat("namespace {\n"
4016                "  constexpr class X {\n"
4017                "    void f() { return; }\n"
4018                "  } x;\n"
4019                "} // namespace\n",
4020                ShortInlineFunctions);
4021 
4022   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
4023   verifyFormat("extern \"C\" {\n"
4024                "  void f() {\n"
4025                "    return;\n"
4026                "  }\n"
4027                "} // namespace\n",
4028                ShortInlineFunctions);
4029 
4030   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4031   EXPECT_EQ("namespace out {\n"
4032             "int i;\n"
4033             "namespace in {\n"
4034             "  int i;\n"
4035             "} // namespace in\n"
4036             "} // namespace out",
4037             format("namespace out {\n"
4038                    "int i;\n"
4039                    "namespace in {\n"
4040                    "int i;\n"
4041                    "} // namespace in\n"
4042                    "} // namespace out",
4043                    Style));
4044 
4045   Style.NamespaceIndentation = FormatStyle::NI_None;
4046   verifyFormat("template <class T>\n"
4047                "concept a_concept = X<>;\n"
4048                "namespace B {\n"
4049                "struct b_struct {};\n"
4050                "} // namespace B\n",
4051                Style);
4052   verifyFormat("template <int I>\n"
4053                "constexpr void foo()\n"
4054                "  requires(I == 42)\n"
4055                "{}\n"
4056                "namespace ns {\n"
4057                "void foo() {}\n"
4058                "} // namespace ns\n",
4059                Style);
4060 }
4061 
4062 TEST_F(FormatTest, NamespaceMacros) {
4063   FormatStyle Style = getLLVMStyle();
4064   Style.NamespaceMacros.push_back("TESTSUITE");
4065 
4066   verifyFormat("TESTSUITE(A) {\n"
4067                "int foo();\n"
4068                "} // TESTSUITE(A)",
4069                Style);
4070 
4071   verifyFormat("TESTSUITE(A, B) {\n"
4072                "int foo();\n"
4073                "} // TESTSUITE(A)",
4074                Style);
4075 
4076   // Properly indent according to NamespaceIndentation style
4077   Style.NamespaceIndentation = FormatStyle::NI_All;
4078   verifyFormat("TESTSUITE(A) {\n"
4079                "  int foo();\n"
4080                "} // TESTSUITE(A)",
4081                Style);
4082   verifyFormat("TESTSUITE(A) {\n"
4083                "  namespace B {\n"
4084                "    int foo();\n"
4085                "  } // namespace B\n"
4086                "} // TESTSUITE(A)",
4087                Style);
4088   verifyFormat("namespace A {\n"
4089                "  TESTSUITE(B) {\n"
4090                "    int foo();\n"
4091                "  } // TESTSUITE(B)\n"
4092                "} // namespace A",
4093                Style);
4094 
4095   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4096   verifyFormat("TESTSUITE(A) {\n"
4097                "TESTSUITE(B) {\n"
4098                "  int foo();\n"
4099                "} // TESTSUITE(B)\n"
4100                "} // TESTSUITE(A)",
4101                Style);
4102   verifyFormat("TESTSUITE(A) {\n"
4103                "namespace B {\n"
4104                "  int foo();\n"
4105                "} // namespace B\n"
4106                "} // TESTSUITE(A)",
4107                Style);
4108   verifyFormat("namespace A {\n"
4109                "TESTSUITE(B) {\n"
4110                "  int foo();\n"
4111                "} // TESTSUITE(B)\n"
4112                "} // namespace A",
4113                Style);
4114 
4115   // Properly merge namespace-macros blocks in CompactNamespaces mode
4116   Style.NamespaceIndentation = FormatStyle::NI_None;
4117   Style.CompactNamespaces = true;
4118   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
4119                "}} // TESTSUITE(A::B)",
4120                Style);
4121 
4122   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4123             "}} // TESTSUITE(out::in)",
4124             format("TESTSUITE(out) {\n"
4125                    "TESTSUITE(in) {\n"
4126                    "} // TESTSUITE(in)\n"
4127                    "} // TESTSUITE(out)",
4128                    Style));
4129 
4130   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4131             "}} // TESTSUITE(out::in)",
4132             format("TESTSUITE(out) {\n"
4133                    "TESTSUITE(in) {\n"
4134                    "} // TESTSUITE(in)\n"
4135                    "} // TESTSUITE(out)",
4136                    Style));
4137 
4138   // Do not merge different namespaces/macros
4139   EXPECT_EQ("namespace out {\n"
4140             "TESTSUITE(in) {\n"
4141             "} // TESTSUITE(in)\n"
4142             "} // namespace out",
4143             format("namespace out {\n"
4144                    "TESTSUITE(in) {\n"
4145                    "} // TESTSUITE(in)\n"
4146                    "} // namespace out",
4147                    Style));
4148   EXPECT_EQ("TESTSUITE(out) {\n"
4149             "namespace in {\n"
4150             "} // namespace in\n"
4151             "} // TESTSUITE(out)",
4152             format("TESTSUITE(out) {\n"
4153                    "namespace in {\n"
4154                    "} // namespace in\n"
4155                    "} // TESTSUITE(out)",
4156                    Style));
4157   Style.NamespaceMacros.push_back("FOOBAR");
4158   EXPECT_EQ("TESTSUITE(out) {\n"
4159             "FOOBAR(in) {\n"
4160             "} // FOOBAR(in)\n"
4161             "} // TESTSUITE(out)",
4162             format("TESTSUITE(out) {\n"
4163                    "FOOBAR(in) {\n"
4164                    "} // FOOBAR(in)\n"
4165                    "} // TESTSUITE(out)",
4166                    Style));
4167 }
4168 
4169 TEST_F(FormatTest, FormatsCompactNamespaces) {
4170   FormatStyle Style = getLLVMStyle();
4171   Style.CompactNamespaces = true;
4172   Style.NamespaceMacros.push_back("TESTSUITE");
4173 
4174   verifyFormat("namespace A { namespace B {\n"
4175                "}} // namespace A::B",
4176                Style);
4177 
4178   EXPECT_EQ("namespace out { namespace in {\n"
4179             "}} // namespace out::in",
4180             format("namespace out {\n"
4181                    "namespace in {\n"
4182                    "} // namespace in\n"
4183                    "} // namespace out",
4184                    Style));
4185 
4186   // Only namespaces which have both consecutive opening and end get compacted
4187   EXPECT_EQ("namespace out {\n"
4188             "namespace in1 {\n"
4189             "} // namespace in1\n"
4190             "namespace in2 {\n"
4191             "} // namespace in2\n"
4192             "} // namespace out",
4193             format("namespace out {\n"
4194                    "namespace in1 {\n"
4195                    "} // namespace in1\n"
4196                    "namespace in2 {\n"
4197                    "} // namespace in2\n"
4198                    "} // namespace out",
4199                    Style));
4200 
4201   EXPECT_EQ("namespace out {\n"
4202             "int i;\n"
4203             "namespace in {\n"
4204             "int j;\n"
4205             "} // namespace in\n"
4206             "int k;\n"
4207             "} // namespace out",
4208             format("namespace out { int i;\n"
4209                    "namespace in { int j; } // namespace in\n"
4210                    "int k; } // namespace out",
4211                    Style));
4212 
4213   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
4214             "}}} // namespace A::B::C\n",
4215             format("namespace A { namespace B {\n"
4216                    "namespace C {\n"
4217                    "}} // namespace B::C\n"
4218                    "} // namespace A\n",
4219                    Style));
4220 
4221   Style.ColumnLimit = 40;
4222   EXPECT_EQ("namespace aaaaaaaaaa {\n"
4223             "namespace bbbbbbbbbb {\n"
4224             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
4225             format("namespace aaaaaaaaaa {\n"
4226                    "namespace bbbbbbbbbb {\n"
4227                    "} // namespace bbbbbbbbbb\n"
4228                    "} // namespace aaaaaaaaaa",
4229                    Style));
4230 
4231   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
4232             "namespace cccccc {\n"
4233             "}}} // namespace aaaaaa::bbbbbb::cccccc",
4234             format("namespace aaaaaa {\n"
4235                    "namespace bbbbbb {\n"
4236                    "namespace cccccc {\n"
4237                    "} // namespace cccccc\n"
4238                    "} // namespace bbbbbb\n"
4239                    "} // namespace aaaaaa",
4240                    Style));
4241   Style.ColumnLimit = 80;
4242 
4243   // Extra semicolon after 'inner' closing brace prevents merging
4244   EXPECT_EQ("namespace out { namespace in {\n"
4245             "}; } // namespace out::in",
4246             format("namespace out {\n"
4247                    "namespace in {\n"
4248                    "}; // namespace in\n"
4249                    "} // namespace out",
4250                    Style));
4251 
4252   // Extra semicolon after 'outer' closing brace is conserved
4253   EXPECT_EQ("namespace out { namespace in {\n"
4254             "}}; // namespace out::in",
4255             format("namespace out {\n"
4256                    "namespace in {\n"
4257                    "} // namespace in\n"
4258                    "}; // namespace out",
4259                    Style));
4260 
4261   Style.NamespaceIndentation = FormatStyle::NI_All;
4262   EXPECT_EQ("namespace out { namespace in {\n"
4263             "  int i;\n"
4264             "}} // namespace out::in",
4265             format("namespace out {\n"
4266                    "namespace in {\n"
4267                    "int i;\n"
4268                    "} // namespace in\n"
4269                    "} // namespace out",
4270                    Style));
4271   EXPECT_EQ("namespace out { namespace mid {\n"
4272             "  namespace in {\n"
4273             "    int j;\n"
4274             "  } // namespace in\n"
4275             "  int k;\n"
4276             "}} // namespace out::mid",
4277             format("namespace out { namespace mid {\n"
4278                    "namespace in { int j; } // namespace in\n"
4279                    "int k; }} // namespace out::mid",
4280                    Style));
4281 
4282   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4283   EXPECT_EQ("namespace out { namespace in {\n"
4284             "  int i;\n"
4285             "}} // namespace out::in",
4286             format("namespace out {\n"
4287                    "namespace in {\n"
4288                    "int i;\n"
4289                    "} // namespace in\n"
4290                    "} // namespace out",
4291                    Style));
4292   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
4293             "  int i;\n"
4294             "}}} // namespace out::mid::in",
4295             format("namespace out {\n"
4296                    "namespace mid {\n"
4297                    "namespace in {\n"
4298                    "int i;\n"
4299                    "} // namespace in\n"
4300                    "} // namespace mid\n"
4301                    "} // namespace out",
4302                    Style));
4303 
4304   Style.CompactNamespaces = true;
4305   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
4306   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4307   Style.BraceWrapping.BeforeLambdaBody = true;
4308   verifyFormat("namespace out { namespace in {\n"
4309                "}} // namespace out::in",
4310                Style);
4311   EXPECT_EQ("namespace out { namespace in {\n"
4312             "}} // namespace out::in",
4313             format("namespace out {\n"
4314                    "namespace in {\n"
4315                    "} // namespace in\n"
4316                    "} // namespace out",
4317                    Style));
4318 }
4319 
4320 TEST_F(FormatTest, FormatsExternC) {
4321   verifyFormat("extern \"C\" {\nint a;");
4322   verifyFormat("extern \"C\" {}");
4323   verifyFormat("extern \"C\" {\n"
4324                "int foo();\n"
4325                "}");
4326   verifyFormat("extern \"C\" int foo() {}");
4327   verifyFormat("extern \"C\" int foo();");
4328   verifyFormat("extern \"C\" int foo() {\n"
4329                "  int i = 42;\n"
4330                "  return i;\n"
4331                "}");
4332 
4333   FormatStyle Style = getLLVMStyle();
4334   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4335   Style.BraceWrapping.AfterFunction = true;
4336   verifyFormat("extern \"C\" int foo() {}", Style);
4337   verifyFormat("extern \"C\" int foo();", Style);
4338   verifyFormat("extern \"C\" int foo()\n"
4339                "{\n"
4340                "  int i = 42;\n"
4341                "  return i;\n"
4342                "}",
4343                Style);
4344 
4345   Style.BraceWrapping.AfterExternBlock = true;
4346   Style.BraceWrapping.SplitEmptyRecord = false;
4347   verifyFormat("extern \"C\"\n"
4348                "{}",
4349                Style);
4350   verifyFormat("extern \"C\"\n"
4351                "{\n"
4352                "  int foo();\n"
4353                "}",
4354                Style);
4355 }
4356 
4357 TEST_F(FormatTest, IndentExternBlockStyle) {
4358   FormatStyle Style = getLLVMStyle();
4359   Style.IndentWidth = 2;
4360 
4361   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4362   verifyFormat("extern \"C\" { /*9*/\n"
4363                "}",
4364                Style);
4365   verifyFormat("extern \"C\" {\n"
4366                "  int foo10();\n"
4367                "}",
4368                Style);
4369 
4370   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4371   verifyFormat("extern \"C\" { /*11*/\n"
4372                "}",
4373                Style);
4374   verifyFormat("extern \"C\" {\n"
4375                "int foo12();\n"
4376                "}",
4377                Style);
4378 
4379   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4380   Style.BraceWrapping.AfterExternBlock = true;
4381   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4382   verifyFormat("extern \"C\"\n"
4383                "{ /*13*/\n"
4384                "}",
4385                Style);
4386   verifyFormat("extern \"C\"\n{\n"
4387                "  int foo14();\n"
4388                "}",
4389                Style);
4390 
4391   Style.BraceWrapping.AfterExternBlock = false;
4392   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4393   verifyFormat("extern \"C\" { /*15*/\n"
4394                "}",
4395                Style);
4396   verifyFormat("extern \"C\" {\n"
4397                "int foo16();\n"
4398                "}",
4399                Style);
4400 
4401   Style.BraceWrapping.AfterExternBlock = true;
4402   verifyFormat("extern \"C\"\n"
4403                "{ /*13*/\n"
4404                "}",
4405                Style);
4406   verifyFormat("extern \"C\"\n"
4407                "{\n"
4408                "int foo14();\n"
4409                "}",
4410                Style);
4411 
4412   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4413   verifyFormat("extern \"C\"\n"
4414                "{ /*13*/\n"
4415                "}",
4416                Style);
4417   verifyFormat("extern \"C\"\n"
4418                "{\n"
4419                "  int foo14();\n"
4420                "}",
4421                Style);
4422 }
4423 
4424 TEST_F(FormatTest, FormatsInlineASM) {
4425   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4426   verifyFormat("asm(\"nop\" ::: \"memory\");");
4427   verifyFormat(
4428       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4429       "    \"cpuid\\n\\t\"\n"
4430       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4431       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4432       "    : \"a\"(value));");
4433   EXPECT_EQ(
4434       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4435       "  __asm {\n"
4436       "        mov     edx,[that] // vtable in edx\n"
4437       "        mov     eax,methodIndex\n"
4438       "        call    [edx][eax*4] // stdcall\n"
4439       "  }\n"
4440       "}",
4441       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4442              "    __asm {\n"
4443              "        mov     edx,[that] // vtable in edx\n"
4444              "        mov     eax,methodIndex\n"
4445              "        call    [edx][eax*4] // stdcall\n"
4446              "    }\n"
4447              "}"));
4448   EXPECT_EQ("_asm {\n"
4449             "  xor eax, eax;\n"
4450             "  cpuid;\n"
4451             "}",
4452             format("_asm {\n"
4453                    "  xor eax, eax;\n"
4454                    "  cpuid;\n"
4455                    "}"));
4456   verifyFormat("void function() {\n"
4457                "  // comment\n"
4458                "  asm(\"\");\n"
4459                "}");
4460   EXPECT_EQ("__asm {\n"
4461             "}\n"
4462             "int i;",
4463             format("__asm   {\n"
4464                    "}\n"
4465                    "int   i;"));
4466 }
4467 
4468 TEST_F(FormatTest, FormatTryCatch) {
4469   verifyFormat("try {\n"
4470                "  throw a * b;\n"
4471                "} catch (int a) {\n"
4472                "  // Do nothing.\n"
4473                "} catch (...) {\n"
4474                "  exit(42);\n"
4475                "}");
4476 
4477   // Function-level try statements.
4478   verifyFormat("int f() try { return 4; } catch (...) {\n"
4479                "  return 5;\n"
4480                "}");
4481   verifyFormat("class A {\n"
4482                "  int a;\n"
4483                "  A() try : a(0) {\n"
4484                "  } catch (...) {\n"
4485                "    throw;\n"
4486                "  }\n"
4487                "};\n");
4488   verifyFormat("class A {\n"
4489                "  int a;\n"
4490                "  A() try : a(0), b{1} {\n"
4491                "  } catch (...) {\n"
4492                "    throw;\n"
4493                "  }\n"
4494                "};\n");
4495   verifyFormat("class A {\n"
4496                "  int a;\n"
4497                "  A() try : a(0), b{1}, c{2} {\n"
4498                "  } catch (...) {\n"
4499                "    throw;\n"
4500                "  }\n"
4501                "};\n");
4502   verifyFormat("class A {\n"
4503                "  int a;\n"
4504                "  A() try : a(0), b{1}, c{2} {\n"
4505                "    { // New scope.\n"
4506                "    }\n"
4507                "  } catch (...) {\n"
4508                "    throw;\n"
4509                "  }\n"
4510                "};\n");
4511 
4512   // Incomplete try-catch blocks.
4513   verifyIncompleteFormat("try {} catch (");
4514 }
4515 
4516 TEST_F(FormatTest, FormatTryAsAVariable) {
4517   verifyFormat("int try;");
4518   verifyFormat("int try, size;");
4519   verifyFormat("try = foo();");
4520   verifyFormat("if (try < size) {\n  return true;\n}");
4521 
4522   verifyFormat("int catch;");
4523   verifyFormat("int catch, size;");
4524   verifyFormat("catch = foo();");
4525   verifyFormat("if (catch < size) {\n  return true;\n}");
4526 
4527   FormatStyle Style = getLLVMStyle();
4528   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4529   Style.BraceWrapping.AfterFunction = true;
4530   Style.BraceWrapping.BeforeCatch = true;
4531   verifyFormat("try {\n"
4532                "  int bar = 1;\n"
4533                "}\n"
4534                "catch (...) {\n"
4535                "  int bar = 1;\n"
4536                "}",
4537                Style);
4538   verifyFormat("#if NO_EX\n"
4539                "try\n"
4540                "#endif\n"
4541                "{\n"
4542                "}\n"
4543                "#if NO_EX\n"
4544                "catch (...) {\n"
4545                "}",
4546                Style);
4547   verifyFormat("try /* abc */ {\n"
4548                "  int bar = 1;\n"
4549                "}\n"
4550                "catch (...) {\n"
4551                "  int bar = 1;\n"
4552                "}",
4553                Style);
4554   verifyFormat("try\n"
4555                "// abc\n"
4556                "{\n"
4557                "  int bar = 1;\n"
4558                "}\n"
4559                "catch (...) {\n"
4560                "  int bar = 1;\n"
4561                "}",
4562                Style);
4563 }
4564 
4565 TEST_F(FormatTest, FormatSEHTryCatch) {
4566   verifyFormat("__try {\n"
4567                "  int a = b * c;\n"
4568                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4569                "  // Do nothing.\n"
4570                "}");
4571 
4572   verifyFormat("__try {\n"
4573                "  int a = b * c;\n"
4574                "} __finally {\n"
4575                "  // Do nothing.\n"
4576                "}");
4577 
4578   verifyFormat("DEBUG({\n"
4579                "  __try {\n"
4580                "  } __finally {\n"
4581                "  }\n"
4582                "});\n");
4583 }
4584 
4585 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4586   verifyFormat("try {\n"
4587                "  f();\n"
4588                "} catch {\n"
4589                "  g();\n"
4590                "}");
4591   verifyFormat("try {\n"
4592                "  f();\n"
4593                "} catch (A a) MACRO(x) {\n"
4594                "  g();\n"
4595                "} catch (B b) MACRO(x) {\n"
4596                "  g();\n"
4597                "}");
4598 }
4599 
4600 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4601   FormatStyle Style = getLLVMStyle();
4602   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4603                           FormatStyle::BS_WebKit}) {
4604     Style.BreakBeforeBraces = BraceStyle;
4605     verifyFormat("try {\n"
4606                  "  // something\n"
4607                  "} catch (...) {\n"
4608                  "  // something\n"
4609                  "}",
4610                  Style);
4611   }
4612   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4613   verifyFormat("try {\n"
4614                "  // something\n"
4615                "}\n"
4616                "catch (...) {\n"
4617                "  // something\n"
4618                "}",
4619                Style);
4620   verifyFormat("__try {\n"
4621                "  // something\n"
4622                "}\n"
4623                "__finally {\n"
4624                "  // something\n"
4625                "}",
4626                Style);
4627   verifyFormat("@try {\n"
4628                "  // something\n"
4629                "}\n"
4630                "@finally {\n"
4631                "  // something\n"
4632                "}",
4633                Style);
4634   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4635   verifyFormat("try\n"
4636                "{\n"
4637                "  // something\n"
4638                "}\n"
4639                "catch (...)\n"
4640                "{\n"
4641                "  // something\n"
4642                "}",
4643                Style);
4644   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4645   verifyFormat("try\n"
4646                "  {\n"
4647                "  // something white\n"
4648                "  }\n"
4649                "catch (...)\n"
4650                "  {\n"
4651                "  // something white\n"
4652                "  }",
4653                Style);
4654   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4655   verifyFormat("try\n"
4656                "  {\n"
4657                "    // something\n"
4658                "  }\n"
4659                "catch (...)\n"
4660                "  {\n"
4661                "    // something\n"
4662                "  }",
4663                Style);
4664   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4665   Style.BraceWrapping.BeforeCatch = true;
4666   verifyFormat("try {\n"
4667                "  // something\n"
4668                "}\n"
4669                "catch (...) {\n"
4670                "  // something\n"
4671                "}",
4672                Style);
4673 }
4674 
4675 TEST_F(FormatTest, StaticInitializers) {
4676   verifyFormat("static SomeClass SC = {1, 'a'};");
4677 
4678   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4679                "    100000000, "
4680                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4681 
4682   // Here, everything other than the "}" would fit on a line.
4683   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4684                "    10000000000000000000000000};");
4685   EXPECT_EQ("S s = {a,\n"
4686             "\n"
4687             "       b};",
4688             format("S s = {\n"
4689                    "  a,\n"
4690                    "\n"
4691                    "  b\n"
4692                    "};"));
4693 
4694   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4695   // line. However, the formatting looks a bit off and this probably doesn't
4696   // happen often in practice.
4697   verifyFormat("static int Variable[1] = {\n"
4698                "    {1000000000000000000000000000000000000}};",
4699                getLLVMStyleWithColumns(40));
4700 }
4701 
4702 TEST_F(FormatTest, DesignatedInitializers) {
4703   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4704   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4705                "                    .bbbbbbbbbb = 2,\n"
4706                "                    .cccccccccc = 3,\n"
4707                "                    .dddddddddd = 4,\n"
4708                "                    .eeeeeeeeee = 5};");
4709   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4710                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4711                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4712                "    .ccccccccccccccccccccccccccc = 3,\n"
4713                "    .ddddddddddddddddddddddddddd = 4,\n"
4714                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4715 
4716   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4717 
4718   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4719   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4720                "                    [2] = bbbbbbbbbb,\n"
4721                "                    [3] = cccccccccc,\n"
4722                "                    [4] = dddddddddd,\n"
4723                "                    [5] = eeeeeeeeee};");
4724   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4725                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4726                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4727                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4728                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4729                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4730 }
4731 
4732 TEST_F(FormatTest, NestedStaticInitializers) {
4733   verifyFormat("static A x = {{{}}};\n");
4734   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4735                "               {init1, init2, init3, init4}}};",
4736                getLLVMStyleWithColumns(50));
4737 
4738   verifyFormat("somes Status::global_reps[3] = {\n"
4739                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4740                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4741                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4742                getLLVMStyleWithColumns(60));
4743   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4744                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4745                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4746                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4747   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4748                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4749                "rect.fTop}};");
4750 
4751   verifyFormat(
4752       "SomeArrayOfSomeType a = {\n"
4753       "    {{1, 2, 3},\n"
4754       "     {1, 2, 3},\n"
4755       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4756       "      333333333333333333333333333333},\n"
4757       "     {1, 2, 3},\n"
4758       "     {1, 2, 3}}};");
4759   verifyFormat(
4760       "SomeArrayOfSomeType a = {\n"
4761       "    {{1, 2, 3}},\n"
4762       "    {{1, 2, 3}},\n"
4763       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4764       "      333333333333333333333333333333}},\n"
4765       "    {{1, 2, 3}},\n"
4766       "    {{1, 2, 3}}};");
4767 
4768   verifyFormat("struct {\n"
4769                "  unsigned bit;\n"
4770                "  const char *const name;\n"
4771                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4772                "                 {kOsWin, \"Windows\"},\n"
4773                "                 {kOsLinux, \"Linux\"},\n"
4774                "                 {kOsCrOS, \"Chrome OS\"}};");
4775   verifyFormat("struct {\n"
4776                "  unsigned bit;\n"
4777                "  const char *const name;\n"
4778                "} kBitsToOs[] = {\n"
4779                "    {kOsMac, \"Mac\"},\n"
4780                "    {kOsWin, \"Windows\"},\n"
4781                "    {kOsLinux, \"Linux\"},\n"
4782                "    {kOsCrOS, \"Chrome OS\"},\n"
4783                "};");
4784 }
4785 
4786 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4787   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4788                "                      \\\n"
4789                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4790 }
4791 
4792 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4793   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4794                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4795 
4796   // Do break defaulted and deleted functions.
4797   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4798                "    default;",
4799                getLLVMStyleWithColumns(40));
4800   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4801                "    delete;",
4802                getLLVMStyleWithColumns(40));
4803 }
4804 
4805 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4806   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4807                getLLVMStyleWithColumns(40));
4808   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4809                getLLVMStyleWithColumns(40));
4810   EXPECT_EQ("#define Q                              \\\n"
4811             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4812             "  \"aaaaaaaa.cpp\"",
4813             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4814                    getLLVMStyleWithColumns(40)));
4815 }
4816 
4817 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4818   EXPECT_EQ("# 123 \"A string literal\"",
4819             format("   #     123    \"A string literal\""));
4820 }
4821 
4822 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4823   EXPECT_EQ("#;", format("#;"));
4824   verifyFormat("#\n;\n;\n;");
4825 }
4826 
4827 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4828   EXPECT_EQ("#line 42 \"test\"\n",
4829             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4830   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4831                                     getLLVMStyleWithColumns(12)));
4832 }
4833 
4834 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4835   EXPECT_EQ("#line 42 \"test\"",
4836             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4837   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4838 }
4839 
4840 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4841   verifyFormat("#define A \\x20");
4842   verifyFormat("#define A \\ x20");
4843   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4844   verifyFormat("#define A ''");
4845   verifyFormat("#define A ''qqq");
4846   verifyFormat("#define A `qqq");
4847   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4848   EXPECT_EQ("const char *c = STRINGIFY(\n"
4849             "\\na : b);",
4850             format("const char * c = STRINGIFY(\n"
4851                    "\\na : b);"));
4852 
4853   verifyFormat("a\r\\");
4854   verifyFormat("a\v\\");
4855   verifyFormat("a\f\\");
4856 }
4857 
4858 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4859   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4860   style.IndentWidth = 4;
4861   style.PPIndentWidth = 1;
4862 
4863   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4864   verifyFormat("#ifdef __linux__\n"
4865                "void foo() {\n"
4866                "    int x = 0;\n"
4867                "}\n"
4868                "#define FOO\n"
4869                "#endif\n"
4870                "void bar() {\n"
4871                "    int y = 0;\n"
4872                "}\n",
4873                style);
4874 
4875   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4876   verifyFormat("#ifdef __linux__\n"
4877                "void foo() {\n"
4878                "    int x = 0;\n"
4879                "}\n"
4880                "# define FOO foo\n"
4881                "#endif\n"
4882                "void bar() {\n"
4883                "    int y = 0;\n"
4884                "}\n",
4885                style);
4886 
4887   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4888   verifyFormat("#ifdef __linux__\n"
4889                "void foo() {\n"
4890                "    int x = 0;\n"
4891                "}\n"
4892                " #define FOO foo\n"
4893                "#endif\n"
4894                "void bar() {\n"
4895                "    int y = 0;\n"
4896                "}\n",
4897                style);
4898 }
4899 
4900 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4901   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4902   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4903   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4904   // FIXME: We never break before the macro name.
4905   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4906 
4907   verifyFormat("#define A A\n#define A A");
4908   verifyFormat("#define A(X) A\n#define A A");
4909 
4910   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4911   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4912 }
4913 
4914 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4915   EXPECT_EQ("// somecomment\n"
4916             "#include \"a.h\"\n"
4917             "#define A(  \\\n"
4918             "    A, B)\n"
4919             "#include \"b.h\"\n"
4920             "// somecomment\n",
4921             format("  // somecomment\n"
4922                    "  #include \"a.h\"\n"
4923                    "#define A(A,\\\n"
4924                    "    B)\n"
4925                    "    #include \"b.h\"\n"
4926                    " // somecomment\n",
4927                    getLLVMStyleWithColumns(13)));
4928 }
4929 
4930 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4931 
4932 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4933   EXPECT_EQ("#define A    \\\n"
4934             "  c;         \\\n"
4935             "  e;\n"
4936             "f;",
4937             format("#define A c; e;\n"
4938                    "f;",
4939                    getLLVMStyleWithColumns(14)));
4940 }
4941 
4942 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4943 
4944 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4945   EXPECT_EQ("int x,\n"
4946             "#define A\n"
4947             "    y;",
4948             format("int x,\n#define A\ny;"));
4949 }
4950 
4951 TEST_F(FormatTest, HashInMacroDefinition) {
4952   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4953   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4954   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4955   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4956   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4957   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4958   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4959   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4960   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4961   verifyFormat("#define A  \\\n"
4962                "  {        \\\n"
4963                "    f(#c); \\\n"
4964                "  }",
4965                getLLVMStyleWithColumns(11));
4966 
4967   verifyFormat("#define A(X)         \\\n"
4968                "  void function##X()",
4969                getLLVMStyleWithColumns(22));
4970 
4971   verifyFormat("#define A(a, b, c)   \\\n"
4972                "  void a##b##c()",
4973                getLLVMStyleWithColumns(22));
4974 
4975   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4976 }
4977 
4978 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4979   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4980   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4981 
4982   FormatStyle Style = getLLVMStyle();
4983   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4984   verifyFormat("#define true ((foo)1)", Style);
4985   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4986   verifyFormat("#define false((foo)0)", Style);
4987 }
4988 
4989 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4990   EXPECT_EQ("#define A b;", format("#define A \\\n"
4991                                    "          \\\n"
4992                                    "  b;",
4993                                    getLLVMStyleWithColumns(25)));
4994   EXPECT_EQ("#define A \\\n"
4995             "          \\\n"
4996             "  a;      \\\n"
4997             "  b;",
4998             format("#define A \\\n"
4999                    "          \\\n"
5000                    "  a;      \\\n"
5001                    "  b;",
5002                    getLLVMStyleWithColumns(11)));
5003   EXPECT_EQ("#define A \\\n"
5004             "  a;      \\\n"
5005             "          \\\n"
5006             "  b;",
5007             format("#define A \\\n"
5008                    "  a;      \\\n"
5009                    "          \\\n"
5010                    "  b;",
5011                    getLLVMStyleWithColumns(11)));
5012 }
5013 
5014 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
5015   verifyIncompleteFormat("#define A :");
5016   verifyFormat("#define SOMECASES  \\\n"
5017                "  case 1:          \\\n"
5018                "  case 2\n",
5019                getLLVMStyleWithColumns(20));
5020   verifyFormat("#define MACRO(a) \\\n"
5021                "  if (a)         \\\n"
5022                "    f();         \\\n"
5023                "  else           \\\n"
5024                "    g()",
5025                getLLVMStyleWithColumns(18));
5026   verifyFormat("#define A template <typename T>");
5027   verifyIncompleteFormat("#define STR(x) #x\n"
5028                          "f(STR(this_is_a_string_literal{));");
5029   verifyFormat("#pragma omp threadprivate( \\\n"
5030                "    y)), // expected-warning",
5031                getLLVMStyleWithColumns(28));
5032   verifyFormat("#d, = };");
5033   verifyFormat("#if \"a");
5034   verifyIncompleteFormat("({\n"
5035                          "#define b     \\\n"
5036                          "  }           \\\n"
5037                          "  a\n"
5038                          "a",
5039                          getLLVMStyleWithColumns(15));
5040   verifyFormat("#define A     \\\n"
5041                "  {           \\\n"
5042                "    {\n"
5043                "#define B     \\\n"
5044                "  }           \\\n"
5045                "  }",
5046                getLLVMStyleWithColumns(15));
5047   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
5048   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
5049   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
5050   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
5051 }
5052 
5053 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
5054   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
5055   EXPECT_EQ("class A : public QObject {\n"
5056             "  Q_OBJECT\n"
5057             "\n"
5058             "  A() {}\n"
5059             "};",
5060             format("class A  :  public QObject {\n"
5061                    "     Q_OBJECT\n"
5062                    "\n"
5063                    "  A() {\n}\n"
5064                    "}  ;"));
5065   EXPECT_EQ("MACRO\n"
5066             "/*static*/ int i;",
5067             format("MACRO\n"
5068                    " /*static*/ int   i;"));
5069   EXPECT_EQ("SOME_MACRO\n"
5070             "namespace {\n"
5071             "void f();\n"
5072             "} // namespace",
5073             format("SOME_MACRO\n"
5074                    "  namespace    {\n"
5075                    "void   f(  );\n"
5076                    "} // namespace"));
5077   // Only if the identifier contains at least 5 characters.
5078   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
5079   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
5080   // Only if everything is upper case.
5081   EXPECT_EQ("class A : public QObject {\n"
5082             "  Q_Object A() {}\n"
5083             "};",
5084             format("class A  :  public QObject {\n"
5085                    "     Q_Object\n"
5086                    "  A() {\n}\n"
5087                    "}  ;"));
5088 
5089   // Only if the next line can actually start an unwrapped line.
5090   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
5091             format("SOME_WEIRD_LOG_MACRO\n"
5092                    "<< SomeThing;"));
5093 
5094   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
5095                "(n, buffers))\n",
5096                getChromiumStyle(FormatStyle::LK_Cpp));
5097 
5098   // See PR41483
5099   EXPECT_EQ("/**/ FOO(a)\n"
5100             "FOO(b)",
5101             format("/**/ FOO(a)\n"
5102                    "FOO(b)"));
5103 }
5104 
5105 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
5106   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5107             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5108             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5109             "class X {};\n"
5110             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5111             "int *createScopDetectionPass() { return 0; }",
5112             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5113                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5114                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5115                    "  class X {};\n"
5116                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5117                    "  int *createScopDetectionPass() { return 0; }"));
5118   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
5119   // braces, so that inner block is indented one level more.
5120   EXPECT_EQ("int q() {\n"
5121             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5122             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5123             "  IPC_END_MESSAGE_MAP()\n"
5124             "}",
5125             format("int q() {\n"
5126                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5127                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5128                    "  IPC_END_MESSAGE_MAP()\n"
5129                    "}"));
5130 
5131   // Same inside macros.
5132   EXPECT_EQ("#define LIST(L) \\\n"
5133             "  L(A)          \\\n"
5134             "  L(B)          \\\n"
5135             "  L(C)",
5136             format("#define LIST(L) \\\n"
5137                    "  L(A) \\\n"
5138                    "  L(B) \\\n"
5139                    "  L(C)",
5140                    getGoogleStyle()));
5141 
5142   // These must not be recognized as macros.
5143   EXPECT_EQ("int q() {\n"
5144             "  f(x);\n"
5145             "  f(x) {}\n"
5146             "  f(x)->g();\n"
5147             "  f(x)->*g();\n"
5148             "  f(x).g();\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) <<= x;\n"
5160             "  f(x)[y].z();\n"
5161             "  LOG(INFO) << x;\n"
5162             "  ifstream(x) >> x;\n"
5163             "}\n",
5164             format("int q() {\n"
5165                    "  f(x)\n;\n"
5166                    "  f(x)\n {}\n"
5167                    "  f(x)\n->g();\n"
5168                    "  f(x)\n->*g();\n"
5169                    "  f(x)\n.g();\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 <<= x;\n"
5181                    "  f(x)\n[y].z();\n"
5182                    "  LOG(INFO)\n << x;\n"
5183                    "  ifstream(x)\n >> x;\n"
5184                    "}\n"));
5185   EXPECT_EQ("int q() {\n"
5186             "  F(x)\n"
5187             "  if (1) {\n"
5188             "  }\n"
5189             "  F(x)\n"
5190             "  while (1) {\n"
5191             "  }\n"
5192             "  F(x)\n"
5193             "  G(x);\n"
5194             "  F(x)\n"
5195             "  try {\n"
5196             "    Q();\n"
5197             "  } catch (...) {\n"
5198             "  }\n"
5199             "}\n",
5200             format("int q() {\n"
5201                    "F(x)\n"
5202                    "if (1) {}\n"
5203                    "F(x)\n"
5204                    "while (1) {}\n"
5205                    "F(x)\n"
5206                    "G(x);\n"
5207                    "F(x)\n"
5208                    "try { Q(); } catch (...) {}\n"
5209                    "}\n"));
5210   EXPECT_EQ("class A {\n"
5211             "  A() : t(0) {}\n"
5212             "  A(int i) noexcept() : {}\n"
5213             "  A(X x)\n" // FIXME: function-level try blocks are broken.
5214             "  try : t(0) {\n"
5215             "  } catch (...) {\n"
5216             "  }\n"
5217             "};",
5218             format("class A {\n"
5219                    "  A()\n : t(0) {}\n"
5220                    "  A(int i)\n noexcept() : {}\n"
5221                    "  A(X x)\n"
5222                    "  try : t(0) {} catch (...) {}\n"
5223                    "};"));
5224   FormatStyle Style = getLLVMStyle();
5225   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5226   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5227   Style.BraceWrapping.AfterFunction = true;
5228   EXPECT_EQ("void f()\n"
5229             "try\n"
5230             "{\n"
5231             "}",
5232             format("void f() try {\n"
5233                    "}",
5234                    Style));
5235   EXPECT_EQ("class SomeClass {\n"
5236             "public:\n"
5237             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5238             "};",
5239             format("class SomeClass {\n"
5240                    "public:\n"
5241                    "  SomeClass()\n"
5242                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5243                    "};"));
5244   EXPECT_EQ("class SomeClass {\n"
5245             "public:\n"
5246             "  SomeClass()\n"
5247             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5248             "};",
5249             format("class SomeClass {\n"
5250                    "public:\n"
5251                    "  SomeClass()\n"
5252                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5253                    "};",
5254                    getLLVMStyleWithColumns(40)));
5255 
5256   verifyFormat("MACRO(>)");
5257 
5258   // Some macros contain an implicit semicolon.
5259   Style = getLLVMStyle();
5260   Style.StatementMacros.push_back("FOO");
5261   verifyFormat("FOO(a) int b = 0;");
5262   verifyFormat("FOO(a)\n"
5263                "int b = 0;",
5264                Style);
5265   verifyFormat("FOO(a);\n"
5266                "int b = 0;",
5267                Style);
5268   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
5269                "int b = 0;",
5270                Style);
5271   verifyFormat("FOO()\n"
5272                "int b = 0;",
5273                Style);
5274   verifyFormat("FOO\n"
5275                "int b = 0;",
5276                Style);
5277   verifyFormat("void f() {\n"
5278                "  FOO(a)\n"
5279                "  return a;\n"
5280                "}",
5281                Style);
5282   verifyFormat("FOO(a)\n"
5283                "FOO(b)",
5284                Style);
5285   verifyFormat("int a = 0;\n"
5286                "FOO(b)\n"
5287                "int c = 0;",
5288                Style);
5289   verifyFormat("int a = 0;\n"
5290                "int x = FOO(a)\n"
5291                "int b = 0;",
5292                Style);
5293   verifyFormat("void foo(int a) { FOO(a) }\n"
5294                "uint32_t bar() {}",
5295                Style);
5296 }
5297 
5298 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
5299   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
5300 
5301   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
5302                ZeroColumn);
5303 }
5304 
5305 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5306   verifyFormat("#define A \\\n"
5307                "  f({     \\\n"
5308                "    g();  \\\n"
5309                "  });",
5310                getLLVMStyleWithColumns(11));
5311 }
5312 
5313 TEST_F(FormatTest, IndentPreprocessorDirectives) {
5314   FormatStyle Style = getLLVMStyleWithColumns(40);
5315   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
5316   verifyFormat("#ifdef _WIN32\n"
5317                "#define A 0\n"
5318                "#ifdef VAR2\n"
5319                "#define B 1\n"
5320                "#include <someheader.h>\n"
5321                "#define MACRO                          \\\n"
5322                "  some_very_long_func_aaaaaaaaaa();\n"
5323                "#endif\n"
5324                "#else\n"
5325                "#define A 1\n"
5326                "#endif",
5327                Style);
5328   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
5329   verifyFormat("#ifdef _WIN32\n"
5330                "#  define A 0\n"
5331                "#  ifdef VAR2\n"
5332                "#    define B 1\n"
5333                "#    include <someheader.h>\n"
5334                "#    define MACRO                      \\\n"
5335                "      some_very_long_func_aaaaaaaaaa();\n"
5336                "#  endif\n"
5337                "#else\n"
5338                "#  define A 1\n"
5339                "#endif",
5340                Style);
5341   verifyFormat("#if A\n"
5342                "#  define MACRO                        \\\n"
5343                "    void a(int x) {                    \\\n"
5344                "      b();                             \\\n"
5345                "      c();                             \\\n"
5346                "      d();                             \\\n"
5347                "      e();                             \\\n"
5348                "      f();                             \\\n"
5349                "    }\n"
5350                "#endif",
5351                Style);
5352   // Comments before include guard.
5353   verifyFormat("// file comment\n"
5354                "// file comment\n"
5355                "#ifndef HEADER_H\n"
5356                "#define HEADER_H\n"
5357                "code();\n"
5358                "#endif",
5359                Style);
5360   // Test with include guards.
5361   verifyFormat("#ifndef HEADER_H\n"
5362                "#define HEADER_H\n"
5363                "code();\n"
5364                "#endif",
5365                Style);
5366   // Include guards must have a #define with the same variable immediately
5367   // after #ifndef.
5368   verifyFormat("#ifndef NOT_GUARD\n"
5369                "#  define FOO\n"
5370                "code();\n"
5371                "#endif",
5372                Style);
5373 
5374   // Include guards must cover the entire file.
5375   verifyFormat("code();\n"
5376                "code();\n"
5377                "#ifndef NOT_GUARD\n"
5378                "#  define NOT_GUARD\n"
5379                "code();\n"
5380                "#endif",
5381                Style);
5382   verifyFormat("#ifndef NOT_GUARD\n"
5383                "#  define NOT_GUARD\n"
5384                "code();\n"
5385                "#endif\n"
5386                "code();",
5387                Style);
5388   // Test with trailing blank lines.
5389   verifyFormat("#ifndef HEADER_H\n"
5390                "#define HEADER_H\n"
5391                "code();\n"
5392                "#endif\n",
5393                Style);
5394   // Include guards don't have #else.
5395   verifyFormat("#ifndef NOT_GUARD\n"
5396                "#  define NOT_GUARD\n"
5397                "code();\n"
5398                "#else\n"
5399                "#endif",
5400                Style);
5401   verifyFormat("#ifndef NOT_GUARD\n"
5402                "#  define NOT_GUARD\n"
5403                "code();\n"
5404                "#elif FOO\n"
5405                "#endif",
5406                Style);
5407   // Non-identifier #define after potential include guard.
5408   verifyFormat("#ifndef FOO\n"
5409                "#  define 1\n"
5410                "#endif\n",
5411                Style);
5412   // #if closes past last non-preprocessor line.
5413   verifyFormat("#ifndef FOO\n"
5414                "#define FOO\n"
5415                "#if 1\n"
5416                "int i;\n"
5417                "#  define A 0\n"
5418                "#endif\n"
5419                "#endif\n",
5420                Style);
5421   // Don't crash if there is an #elif directive without a condition.
5422   verifyFormat("#if 1\n"
5423                "int x;\n"
5424                "#elif\n"
5425                "int y;\n"
5426                "#else\n"
5427                "int z;\n"
5428                "#endif",
5429                Style);
5430   // FIXME: This doesn't handle the case where there's code between the
5431   // #ifndef and #define but all other conditions hold. This is because when
5432   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5433   // previous code line yet, so we can't detect it.
5434   EXPECT_EQ("#ifndef NOT_GUARD\n"
5435             "code();\n"
5436             "#define NOT_GUARD\n"
5437             "code();\n"
5438             "#endif",
5439             format("#ifndef NOT_GUARD\n"
5440                    "code();\n"
5441                    "#  define NOT_GUARD\n"
5442                    "code();\n"
5443                    "#endif",
5444                    Style));
5445   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5446   // be outside an include guard. Examples are #pragma once and
5447   // #pragma GCC diagnostic, or anything else that does not change the meaning
5448   // of the file if it's included multiple times.
5449   EXPECT_EQ("#ifdef WIN32\n"
5450             "#  pragma once\n"
5451             "#endif\n"
5452             "#ifndef HEADER_H\n"
5453             "#  define HEADER_H\n"
5454             "code();\n"
5455             "#endif",
5456             format("#ifdef WIN32\n"
5457                    "#  pragma once\n"
5458                    "#endif\n"
5459                    "#ifndef HEADER_H\n"
5460                    "#define HEADER_H\n"
5461                    "code();\n"
5462                    "#endif",
5463                    Style));
5464   // FIXME: This does not detect when there is a single non-preprocessor line
5465   // in front of an include-guard-like structure where other conditions hold
5466   // because ScopedLineState hides the line.
5467   EXPECT_EQ("code();\n"
5468             "#ifndef HEADER_H\n"
5469             "#define HEADER_H\n"
5470             "code();\n"
5471             "#endif",
5472             format("code();\n"
5473                    "#ifndef HEADER_H\n"
5474                    "#  define HEADER_H\n"
5475                    "code();\n"
5476                    "#endif",
5477                    Style));
5478   // Keep comments aligned with #, otherwise indent comments normally. These
5479   // tests cannot use verifyFormat because messUp manipulates leading
5480   // whitespace.
5481   {
5482     const char *Expected = ""
5483                            "void f() {\n"
5484                            "#if 1\n"
5485                            "// Preprocessor aligned.\n"
5486                            "#  define A 0\n"
5487                            "  // Code. Separated by blank line.\n"
5488                            "\n"
5489                            "#  define B 0\n"
5490                            "  // Code. Not aligned with #\n"
5491                            "#  define C 0\n"
5492                            "#endif";
5493     const char *ToFormat = ""
5494                            "void f() {\n"
5495                            "#if 1\n"
5496                            "// Preprocessor aligned.\n"
5497                            "#  define A 0\n"
5498                            "// Code. Separated by blank line.\n"
5499                            "\n"
5500                            "#  define B 0\n"
5501                            "   // Code. Not aligned with #\n"
5502                            "#  define C 0\n"
5503                            "#endif";
5504     EXPECT_EQ(Expected, format(ToFormat, Style));
5505     EXPECT_EQ(Expected, format(Expected, Style));
5506   }
5507   // Keep block quotes aligned.
5508   {
5509     const char *Expected = ""
5510                            "void f() {\n"
5511                            "#if 1\n"
5512                            "/* Preprocessor aligned. */\n"
5513                            "#  define A 0\n"
5514                            "  /* Code. Separated by blank line. */\n"
5515                            "\n"
5516                            "#  define B 0\n"
5517                            "  /* Code. Not aligned with # */\n"
5518                            "#  define C 0\n"
5519                            "#endif";
5520     const char *ToFormat = ""
5521                            "void f() {\n"
5522                            "#if 1\n"
5523                            "/* Preprocessor aligned. */\n"
5524                            "#  define A 0\n"
5525                            "/* Code. Separated by blank line. */\n"
5526                            "\n"
5527                            "#  define B 0\n"
5528                            "   /* Code. Not aligned with # */\n"
5529                            "#  define C 0\n"
5530                            "#endif";
5531     EXPECT_EQ(Expected, format(ToFormat, Style));
5532     EXPECT_EQ(Expected, format(Expected, Style));
5533   }
5534   // Keep comments aligned with un-indented directives.
5535   {
5536     const char *Expected = ""
5537                            "void f() {\n"
5538                            "// Preprocessor aligned.\n"
5539                            "#define A 0\n"
5540                            "  // Code. Separated by blank line.\n"
5541                            "\n"
5542                            "#define B 0\n"
5543                            "  // Code. Not aligned with #\n"
5544                            "#define C 0\n";
5545     const char *ToFormat = ""
5546                            "void f() {\n"
5547                            "// Preprocessor aligned.\n"
5548                            "#define A 0\n"
5549                            "// Code. Separated by blank line.\n"
5550                            "\n"
5551                            "#define B 0\n"
5552                            "   // Code. Not aligned with #\n"
5553                            "#define C 0\n";
5554     EXPECT_EQ(Expected, format(ToFormat, Style));
5555     EXPECT_EQ(Expected, format(Expected, Style));
5556   }
5557   // Test AfterHash with tabs.
5558   {
5559     FormatStyle Tabbed = Style;
5560     Tabbed.UseTab = FormatStyle::UT_Always;
5561     Tabbed.IndentWidth = 8;
5562     Tabbed.TabWidth = 8;
5563     verifyFormat("#ifdef _WIN32\n"
5564                  "#\tdefine A 0\n"
5565                  "#\tifdef VAR2\n"
5566                  "#\t\tdefine B 1\n"
5567                  "#\t\tinclude <someheader.h>\n"
5568                  "#\t\tdefine MACRO          \\\n"
5569                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5570                  "#\tendif\n"
5571                  "#else\n"
5572                  "#\tdefine A 1\n"
5573                  "#endif",
5574                  Tabbed);
5575   }
5576 
5577   // Regression test: Multiline-macro inside include guards.
5578   verifyFormat("#ifndef HEADER_H\n"
5579                "#define HEADER_H\n"
5580                "#define A()        \\\n"
5581                "  int i;           \\\n"
5582                "  int j;\n"
5583                "#endif // HEADER_H",
5584                getLLVMStyleWithColumns(20));
5585 
5586   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5587   // Basic before hash indent tests
5588   verifyFormat("#ifdef _WIN32\n"
5589                "  #define A 0\n"
5590                "  #ifdef VAR2\n"
5591                "    #define B 1\n"
5592                "    #include <someheader.h>\n"
5593                "    #define MACRO                      \\\n"
5594                "      some_very_long_func_aaaaaaaaaa();\n"
5595                "  #endif\n"
5596                "#else\n"
5597                "  #define A 1\n"
5598                "#endif",
5599                Style);
5600   verifyFormat("#if A\n"
5601                "  #define MACRO                        \\\n"
5602                "    void a(int x) {                    \\\n"
5603                "      b();                             \\\n"
5604                "      c();                             \\\n"
5605                "      d();                             \\\n"
5606                "      e();                             \\\n"
5607                "      f();                             \\\n"
5608                "    }\n"
5609                "#endif",
5610                Style);
5611   // Keep comments aligned with indented directives. These
5612   // tests cannot use verifyFormat because messUp manipulates leading
5613   // whitespace.
5614   {
5615     const char *Expected = "void f() {\n"
5616                            "// Aligned to preprocessor.\n"
5617                            "#if 1\n"
5618                            "  // Aligned to code.\n"
5619                            "  int a;\n"
5620                            "  #if 1\n"
5621                            "    // Aligned to preprocessor.\n"
5622                            "    #define A 0\n"
5623                            "  // Aligned to code.\n"
5624                            "  int b;\n"
5625                            "  #endif\n"
5626                            "#endif\n"
5627                            "}";
5628     const char *ToFormat = "void f() {\n"
5629                            "// Aligned to preprocessor.\n"
5630                            "#if 1\n"
5631                            "// Aligned to code.\n"
5632                            "int a;\n"
5633                            "#if 1\n"
5634                            "// Aligned to preprocessor.\n"
5635                            "#define A 0\n"
5636                            "// Aligned to code.\n"
5637                            "int b;\n"
5638                            "#endif\n"
5639                            "#endif\n"
5640                            "}";
5641     EXPECT_EQ(Expected, format(ToFormat, Style));
5642     EXPECT_EQ(Expected, format(Expected, Style));
5643   }
5644   {
5645     const char *Expected = "void f() {\n"
5646                            "/* Aligned to preprocessor. */\n"
5647                            "#if 1\n"
5648                            "  /* Aligned to code. */\n"
5649                            "  int a;\n"
5650                            "  #if 1\n"
5651                            "    /* Aligned to preprocessor. */\n"
5652                            "    #define A 0\n"
5653                            "  /* Aligned to code. */\n"
5654                            "  int b;\n"
5655                            "  #endif\n"
5656                            "#endif\n"
5657                            "}";
5658     const char *ToFormat = "void f() {\n"
5659                            "/* Aligned to preprocessor. */\n"
5660                            "#if 1\n"
5661                            "/* Aligned to code. */\n"
5662                            "int a;\n"
5663                            "#if 1\n"
5664                            "/* Aligned to preprocessor. */\n"
5665                            "#define A 0\n"
5666                            "/* Aligned to code. */\n"
5667                            "int b;\n"
5668                            "#endif\n"
5669                            "#endif\n"
5670                            "}";
5671     EXPECT_EQ(Expected, format(ToFormat, Style));
5672     EXPECT_EQ(Expected, format(Expected, Style));
5673   }
5674 
5675   // Test single comment before preprocessor
5676   verifyFormat("// Comment\n"
5677                "\n"
5678                "#if 1\n"
5679                "#endif",
5680                Style);
5681 }
5682 
5683 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5684   verifyFormat("{\n  { a #c; }\n}");
5685 }
5686 
5687 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5688   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5689             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5690   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5691             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5692 }
5693 
5694 TEST_F(FormatTest, EscapedNewlines) {
5695   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5696   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5697             format("#define A \\\nint i;\\\n  int j;", Narrow));
5698   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5699   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5700   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5701   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5702 
5703   FormatStyle AlignLeft = getLLVMStyle();
5704   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5705   EXPECT_EQ("#define MACRO(x) \\\n"
5706             "private:         \\\n"
5707             "  int x(int a);\n",
5708             format("#define MACRO(x) \\\n"
5709                    "private:         \\\n"
5710                    "  int x(int a);\n",
5711                    AlignLeft));
5712 
5713   // CRLF line endings
5714   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5715             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5716   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5717   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5718   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5719   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5720   EXPECT_EQ("#define MACRO(x) \\\r\n"
5721             "private:         \\\r\n"
5722             "  int x(int a);\r\n",
5723             format("#define MACRO(x) \\\r\n"
5724                    "private:         \\\r\n"
5725                    "  int x(int a);\r\n",
5726                    AlignLeft));
5727 
5728   FormatStyle DontAlign = getLLVMStyle();
5729   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5730   DontAlign.MaxEmptyLinesToKeep = 3;
5731   // FIXME: can't use verifyFormat here because the newline before
5732   // "public:" is not inserted the first time it's reformatted
5733   EXPECT_EQ("#define A \\\n"
5734             "  class Foo { \\\n"
5735             "    void bar(); \\\n"
5736             "\\\n"
5737             "\\\n"
5738             "\\\n"
5739             "  public: \\\n"
5740             "    void baz(); \\\n"
5741             "  };",
5742             format("#define A \\\n"
5743                    "  class Foo { \\\n"
5744                    "    void bar(); \\\n"
5745                    "\\\n"
5746                    "\\\n"
5747                    "\\\n"
5748                    "  public: \\\n"
5749                    "    void baz(); \\\n"
5750                    "  };",
5751                    DontAlign));
5752 }
5753 
5754 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5755   verifyFormat("#define A \\\n"
5756                "  int v(  \\\n"
5757                "      a); \\\n"
5758                "  int i;",
5759                getLLVMStyleWithColumns(11));
5760 }
5761 
5762 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5763   EXPECT_EQ(
5764       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5765       "                      \\\n"
5766       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5767       "\n"
5768       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5769       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5770       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5771              "\\\n"
5772              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5773              "  \n"
5774              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5775              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5776 }
5777 
5778 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5779   EXPECT_EQ("int\n"
5780             "#define A\n"
5781             "    a;",
5782             format("int\n#define A\na;"));
5783   verifyFormat("functionCallTo(\n"
5784                "    someOtherFunction(\n"
5785                "        withSomeParameters, whichInSequence,\n"
5786                "        areLongerThanALine(andAnotherCall,\n"
5787                "#define A B\n"
5788                "                           withMoreParamters,\n"
5789                "                           whichStronglyInfluenceTheLayout),\n"
5790                "        andMoreParameters),\n"
5791                "    trailing);",
5792                getLLVMStyleWithColumns(69));
5793   verifyFormat("Foo::Foo()\n"
5794                "#ifdef BAR\n"
5795                "    : baz(0)\n"
5796                "#endif\n"
5797                "{\n"
5798                "}");
5799   verifyFormat("void f() {\n"
5800                "  if (true)\n"
5801                "#ifdef A\n"
5802                "    f(42);\n"
5803                "  x();\n"
5804                "#else\n"
5805                "    g();\n"
5806                "  x();\n"
5807                "#endif\n"
5808                "}");
5809   verifyFormat("void f(param1, param2,\n"
5810                "       param3,\n"
5811                "#ifdef A\n"
5812                "       param4(param5,\n"
5813                "#ifdef A1\n"
5814                "              param6,\n"
5815                "#ifdef A2\n"
5816                "              param7),\n"
5817                "#else\n"
5818                "              param8),\n"
5819                "       param9,\n"
5820                "#endif\n"
5821                "       param10,\n"
5822                "#endif\n"
5823                "       param11)\n"
5824                "#else\n"
5825                "       param12)\n"
5826                "#endif\n"
5827                "{\n"
5828                "  x();\n"
5829                "}",
5830                getLLVMStyleWithColumns(28));
5831   verifyFormat("#if 1\n"
5832                "int i;");
5833   verifyFormat("#if 1\n"
5834                "#endif\n"
5835                "#if 1\n"
5836                "#else\n"
5837                "#endif\n");
5838   verifyFormat("DEBUG({\n"
5839                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5840                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5841                "});\n"
5842                "#if a\n"
5843                "#else\n"
5844                "#endif");
5845 
5846   verifyIncompleteFormat("void f(\n"
5847                          "#if A\n"
5848                          ");\n"
5849                          "#else\n"
5850                          "#endif");
5851 }
5852 
5853 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5854   verifyFormat("#endif\n"
5855                "#if B");
5856 }
5857 
5858 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5859   FormatStyle SingleLine = getLLVMStyle();
5860   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5861   verifyFormat("#if 0\n"
5862                "#elif 1\n"
5863                "#endif\n"
5864                "void foo() {\n"
5865                "  if (test) foo2();\n"
5866                "}",
5867                SingleLine);
5868 }
5869 
5870 TEST_F(FormatTest, LayoutBlockInsideParens) {
5871   verifyFormat("functionCall({ int i; });");
5872   verifyFormat("functionCall({\n"
5873                "  int i;\n"
5874                "  int j;\n"
5875                "});");
5876   verifyFormat("functionCall(\n"
5877                "    {\n"
5878                "      int i;\n"
5879                "      int j;\n"
5880                "    },\n"
5881                "    aaaa, bbbb, cccc);");
5882   verifyFormat("functionA(functionB({\n"
5883                "            int i;\n"
5884                "            int j;\n"
5885                "          }),\n"
5886                "          aaaa, bbbb, cccc);");
5887   verifyFormat("functionCall(\n"
5888                "    {\n"
5889                "      int i;\n"
5890                "      int j;\n"
5891                "    },\n"
5892                "    aaaa, bbbb, // comment\n"
5893                "    cccc);");
5894   verifyFormat("functionA(functionB({\n"
5895                "            int i;\n"
5896                "            int j;\n"
5897                "          }),\n"
5898                "          aaaa, bbbb, // comment\n"
5899                "          cccc);");
5900   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5901   verifyFormat("functionCall(aaaa, bbbb, {\n"
5902                "  int i;\n"
5903                "  int j;\n"
5904                "});");
5905   verifyFormat(
5906       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5907       "    {\n"
5908       "      int i; // break\n"
5909       "    },\n"
5910       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5911       "                                     ccccccccccccccccc));");
5912   verifyFormat("DEBUG({\n"
5913                "  if (a)\n"
5914                "    f();\n"
5915                "});");
5916 }
5917 
5918 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5919   EXPECT_EQ("SOME_MACRO { int i; }\n"
5920             "int i;",
5921             format("  SOME_MACRO  {int i;}  int i;"));
5922 }
5923 
5924 TEST_F(FormatTest, LayoutNestedBlocks) {
5925   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5926                "  struct s {\n"
5927                "    int i;\n"
5928                "  };\n"
5929                "  s kBitsToOs[] = {{10}};\n"
5930                "  for (int i = 0; i < 10; ++i)\n"
5931                "    return;\n"
5932                "}");
5933   verifyFormat("call(parameter, {\n"
5934                "  something();\n"
5935                "  // Comment using all columns.\n"
5936                "  somethingelse();\n"
5937                "});",
5938                getLLVMStyleWithColumns(40));
5939   verifyFormat("DEBUG( //\n"
5940                "    { f(); }, a);");
5941   verifyFormat("DEBUG( //\n"
5942                "    {\n"
5943                "      f(); //\n"
5944                "    },\n"
5945                "    a);");
5946 
5947   EXPECT_EQ("call(parameter, {\n"
5948             "  something();\n"
5949             "  // Comment too\n"
5950             "  // looooooooooong.\n"
5951             "  somethingElse();\n"
5952             "});",
5953             format("call(parameter, {\n"
5954                    "  something();\n"
5955                    "  // Comment too looooooooooong.\n"
5956                    "  somethingElse();\n"
5957                    "});",
5958                    getLLVMStyleWithColumns(29)));
5959   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5960   EXPECT_EQ("DEBUG({ // comment\n"
5961             "  int i;\n"
5962             "});",
5963             format("DEBUG({ // comment\n"
5964                    "int  i;\n"
5965                    "});"));
5966   EXPECT_EQ("DEBUG({\n"
5967             "  int i;\n"
5968             "\n"
5969             "  // comment\n"
5970             "  int j;\n"
5971             "});",
5972             format("DEBUG({\n"
5973                    "  int  i;\n"
5974                    "\n"
5975                    "  // comment\n"
5976                    "  int  j;\n"
5977                    "});"));
5978 
5979   verifyFormat("DEBUG({\n"
5980                "  if (a)\n"
5981                "    return;\n"
5982                "});");
5983   verifyGoogleFormat("DEBUG({\n"
5984                      "  if (a) return;\n"
5985                      "});");
5986   FormatStyle Style = getGoogleStyle();
5987   Style.ColumnLimit = 45;
5988   verifyFormat("Debug(\n"
5989                "    aaaaa,\n"
5990                "    {\n"
5991                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5992                "    },\n"
5993                "    a);",
5994                Style);
5995 
5996   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5997 
5998   verifyNoCrash("^{v^{a}}");
5999 }
6000 
6001 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
6002   EXPECT_EQ("#define MACRO()                     \\\n"
6003             "  Debug(aaa, /* force line break */ \\\n"
6004             "        {                           \\\n"
6005             "          int i;                    \\\n"
6006             "          int j;                    \\\n"
6007             "        })",
6008             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
6009                    "          {  int   i;  int  j;   })",
6010                    getGoogleStyle()));
6011 
6012   EXPECT_EQ("#define A                                       \\\n"
6013             "  [] {                                          \\\n"
6014             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
6015             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
6016             "  }",
6017             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
6018                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
6019                    getGoogleStyle()));
6020 }
6021 
6022 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
6023   EXPECT_EQ("{}", format("{}"));
6024   verifyFormat("enum E {};");
6025   verifyFormat("enum E {}");
6026   FormatStyle Style = getLLVMStyle();
6027   Style.SpaceInEmptyBlock = true;
6028   EXPECT_EQ("void f() { }", format("void f() {}", Style));
6029   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
6030   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
6031   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
6032   Style.BraceWrapping.BeforeElse = false;
6033   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
6034   verifyFormat("if (a)\n"
6035                "{\n"
6036                "} else if (b)\n"
6037                "{\n"
6038                "} else\n"
6039                "{ }",
6040                Style);
6041   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
6042   verifyFormat("if (a) {\n"
6043                "} else if (b) {\n"
6044                "} else {\n"
6045                "}",
6046                Style);
6047   Style.BraceWrapping.BeforeElse = true;
6048   verifyFormat("if (a) { }\n"
6049                "else if (b) { }\n"
6050                "else { }",
6051                Style);
6052 }
6053 
6054 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
6055   FormatStyle Style = getLLVMStyle();
6056   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
6057   Style.MacroBlockEnd = "^[A-Z_]+_END$";
6058   verifyFormat("FOO_BEGIN\n"
6059                "  FOO_ENTRY\n"
6060                "FOO_END",
6061                Style);
6062   verifyFormat("FOO_BEGIN\n"
6063                "  NESTED_FOO_BEGIN\n"
6064                "    NESTED_FOO_ENTRY\n"
6065                "  NESTED_FOO_END\n"
6066                "FOO_END",
6067                Style);
6068   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
6069                "  int x;\n"
6070                "  x = 1;\n"
6071                "FOO_END(Baz)",
6072                Style);
6073 }
6074 
6075 //===----------------------------------------------------------------------===//
6076 // Line break tests.
6077 //===----------------------------------------------------------------------===//
6078 
6079 TEST_F(FormatTest, PreventConfusingIndents) {
6080   verifyFormat(
6081       "void f() {\n"
6082       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
6083       "                         parameter, parameter, parameter)),\n"
6084       "                     SecondLongCall(parameter));\n"
6085       "}");
6086   verifyFormat(
6087       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6088       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6089       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6090       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
6091   verifyFormat(
6092       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6093       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
6094       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6095       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
6096   verifyFormat(
6097       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
6098       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
6099       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
6100       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
6101   verifyFormat("int a = bbbb && ccc &&\n"
6102                "        fffff(\n"
6103                "#define A Just forcing a new line\n"
6104                "            ddd);");
6105 }
6106 
6107 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
6108   verifyFormat(
6109       "bool aaaaaaa =\n"
6110       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
6111       "    bbbbbbbb();");
6112   verifyFormat(
6113       "bool aaaaaaa =\n"
6114       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
6115       "    bbbbbbbb();");
6116 
6117   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6118                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
6119                "    ccccccccc == ddddddddddd;");
6120   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6121                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
6122                "    ccccccccc == ddddddddddd;");
6123   verifyFormat(
6124       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6125       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
6126       "    ccccccccc == ddddddddddd;");
6127 
6128   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6129                "                 aaaaaa) &&\n"
6130                "         bbbbbb && cccccc;");
6131   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6132                "                 aaaaaa) >>\n"
6133                "         bbbbbb;");
6134   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
6135                "    SourceMgr.getSpellingColumnNumber(\n"
6136                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
6137                "    1);");
6138 
6139   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6140                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
6141                "    cccccc) {\n}");
6142   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6143                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6144                "              cccccc) {\n}");
6145   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6146                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6147                "              cccccc) {\n}");
6148   verifyFormat("b = a &&\n"
6149                "    // Comment\n"
6150                "    b.c && d;");
6151 
6152   // If the LHS of a comparison is not a binary expression itself, the
6153   // additional linebreak confuses many people.
6154   verifyFormat(
6155       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6156       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
6157       "}");
6158   verifyFormat(
6159       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6160       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6161       "}");
6162   verifyFormat(
6163       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
6164       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6165       "}");
6166   verifyFormat(
6167       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6168       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
6169       "}");
6170   // Even explicit parentheses stress the precedence enough to make the
6171   // additional break unnecessary.
6172   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6173                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6174                "}");
6175   // This cases is borderline, but with the indentation it is still readable.
6176   verifyFormat(
6177       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6178       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6179       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
6180       "}",
6181       getLLVMStyleWithColumns(75));
6182 
6183   // If the LHS is a binary expression, we should still use the additional break
6184   // as otherwise the formatting hides the operator precedence.
6185   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6186                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6187                "    5) {\n"
6188                "}");
6189   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6190                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
6191                "    5) {\n"
6192                "}");
6193 
6194   FormatStyle OnePerLine = getLLVMStyle();
6195   OnePerLine.BinPackParameters = false;
6196   verifyFormat(
6197       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6198       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6199       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
6200       OnePerLine);
6201 
6202   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
6203                "                .aaa(aaaaaaaaaaaaa) *\n"
6204                "            aaaaaaa +\n"
6205                "        aaaaaaa;",
6206                getLLVMStyleWithColumns(40));
6207 }
6208 
6209 TEST_F(FormatTest, ExpressionIndentation) {
6210   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6211                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6212                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6213                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6214                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6215                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
6216                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6217                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
6218                "                 ccccccccccccccccccccccccccccccccccccccccc;");
6219   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6220                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6221                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6222                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6223   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6224                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6225                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6226                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6227   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6228                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6229                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6230                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6231   verifyFormat("if () {\n"
6232                "} else if (aaaaa && bbbbb > // break\n"
6233                "                        ccccc) {\n"
6234                "}");
6235   verifyFormat("if () {\n"
6236                "} else if constexpr (aaaaa && bbbbb > // break\n"
6237                "                                  ccccc) {\n"
6238                "}");
6239   verifyFormat("if () {\n"
6240                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
6241                "                                  ccccc) {\n"
6242                "}");
6243   verifyFormat("if () {\n"
6244                "} else if (aaaaa &&\n"
6245                "           bbbbb > // break\n"
6246                "               ccccc &&\n"
6247                "           ddddd) {\n"
6248                "}");
6249 
6250   // Presence of a trailing comment used to change indentation of b.
6251   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
6252                "       b;\n"
6253                "return aaaaaaaaaaaaaaaaaaa +\n"
6254                "       b; //",
6255                getLLVMStyleWithColumns(30));
6256 }
6257 
6258 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
6259   // Not sure what the best system is here. Like this, the LHS can be found
6260   // immediately above an operator (everything with the same or a higher
6261   // indent). The RHS is aligned right of the operator and so compasses
6262   // everything until something with the same indent as the operator is found.
6263   // FIXME: Is this a good system?
6264   FormatStyle Style = getLLVMStyle();
6265   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6266   verifyFormat(
6267       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6268       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6269       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6270       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6271       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6272       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6273       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6274       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6275       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
6276       Style);
6277   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6278                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6279                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6280                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6281                Style);
6282   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6283                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6284                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6285                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6286                Style);
6287   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6288                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6289                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6290                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6291                Style);
6292   verifyFormat("if () {\n"
6293                "} else if (aaaaa\n"
6294                "           && bbbbb // break\n"
6295                "                  > ccccc) {\n"
6296                "}",
6297                Style);
6298   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6299                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6300                Style);
6301   verifyFormat("return (a)\n"
6302                "       // comment\n"
6303                "       + b;",
6304                Style);
6305   verifyFormat(
6306       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6307       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6308       "             + cc;",
6309       Style);
6310 
6311   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6312                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6313                Style);
6314 
6315   // Forced by comments.
6316   verifyFormat(
6317       "unsigned ContentSize =\n"
6318       "    sizeof(int16_t)   // DWARF ARange version number\n"
6319       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6320       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6321       "    + sizeof(int8_t); // Segment Size (in bytes)");
6322 
6323   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6324                "       == boost::fusion::at_c<1>(iiii).second;",
6325                Style);
6326 
6327   Style.ColumnLimit = 60;
6328   verifyFormat("zzzzzzzzzz\n"
6329                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6330                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6331                Style);
6332 
6333   Style.ColumnLimit = 80;
6334   Style.IndentWidth = 4;
6335   Style.TabWidth = 4;
6336   Style.UseTab = FormatStyle::UT_Always;
6337   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6338   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6339   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
6340             "\t&& (someOtherLongishConditionPart1\n"
6341             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
6342             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
6343                    "(someOtherLongishConditionPart1 || "
6344                    "someOtherEvenLongerNestedConditionPart2);",
6345                    Style));
6346 }
6347 
6348 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
6349   FormatStyle Style = getLLVMStyle();
6350   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6351   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
6352 
6353   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6354                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6355                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6356                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6357                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6358                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6359                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6360                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6361                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
6362                Style);
6363   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6364                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6365                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6366                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6367                Style);
6368   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6369                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6370                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6371                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6372                Style);
6373   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6374                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6375                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6376                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6377                Style);
6378   verifyFormat("if () {\n"
6379                "} else if (aaaaa\n"
6380                "           && bbbbb // break\n"
6381                "                  > ccccc) {\n"
6382                "}",
6383                Style);
6384   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6385                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6386                Style);
6387   verifyFormat("return (a)\n"
6388                "     // comment\n"
6389                "     + b;",
6390                Style);
6391   verifyFormat(
6392       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6393       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6394       "           + cc;",
6395       Style);
6396   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6397                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6398                "                        : 3333333333333333;",
6399                Style);
6400   verifyFormat(
6401       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6402       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6403       "                                             : eeeeeeeeeeeeeeeeee)\n"
6404       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6405       "                        : 3333333333333333;",
6406       Style);
6407   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6408                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6409                Style);
6410 
6411   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6412                "    == boost::fusion::at_c<1>(iiii).second;",
6413                Style);
6414 
6415   Style.ColumnLimit = 60;
6416   verifyFormat("zzzzzzzzzzzzz\n"
6417                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6418                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6419                Style);
6420 
6421   // Forced by comments.
6422   Style.ColumnLimit = 80;
6423   verifyFormat(
6424       "unsigned ContentSize\n"
6425       "    = sizeof(int16_t) // DWARF ARange version number\n"
6426       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6427       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6428       "    + sizeof(int8_t); // Segment Size (in bytes)",
6429       Style);
6430 
6431   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6432   verifyFormat(
6433       "unsigned ContentSize =\n"
6434       "    sizeof(int16_t)   // DWARF ARange version number\n"
6435       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6436       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6437       "    + sizeof(int8_t); // Segment Size (in bytes)",
6438       Style);
6439 
6440   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6441   verifyFormat(
6442       "unsigned ContentSize =\n"
6443       "    sizeof(int16_t)   // DWARF ARange version number\n"
6444       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6445       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6446       "    + sizeof(int8_t); // Segment Size (in bytes)",
6447       Style);
6448 }
6449 
6450 TEST_F(FormatTest, EnforcedOperatorWraps) {
6451   // Here we'd like to wrap after the || operators, but a comment is forcing an
6452   // earlier wrap.
6453   verifyFormat("bool x = aaaaa //\n"
6454                "         || bbbbb\n"
6455                "         //\n"
6456                "         || cccc;");
6457 }
6458 
6459 TEST_F(FormatTest, NoOperandAlignment) {
6460   FormatStyle Style = getLLVMStyle();
6461   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6462   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6463                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6464                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6465                Style);
6466   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6467   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6468                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6469                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6470                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6471                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6472                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6473                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6474                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6475                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6476                Style);
6477 
6478   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6479                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6480                "    + cc;",
6481                Style);
6482   verifyFormat("int a = aa\n"
6483                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6484                "        * cccccccccccccccccccccccccccccccccccc;\n",
6485                Style);
6486 
6487   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6488   verifyFormat("return (a > b\n"
6489                "    // comment1\n"
6490                "    // comment2\n"
6491                "    || c);",
6492                Style);
6493 }
6494 
6495 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6496   FormatStyle Style = getLLVMStyle();
6497   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6498   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6499                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6500                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6501                Style);
6502 }
6503 
6504 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6505   FormatStyle Style = getLLVMStyleWithColumns(40);
6506   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6507   Style.BinPackArguments = false;
6508   verifyFormat("void test() {\n"
6509                "  someFunction(\n"
6510                "      this + argument + is + quite\n"
6511                "      + long + so + it + gets + wrapped\n"
6512                "      + but + remains + bin - packed);\n"
6513                "}",
6514                Style);
6515   verifyFormat("void test() {\n"
6516                "  someFunction(arg1,\n"
6517                "               this + argument + is\n"
6518                "                   + quite + long + so\n"
6519                "                   + it + gets + wrapped\n"
6520                "                   + but + remains + bin\n"
6521                "                   - packed,\n"
6522                "               arg3);\n"
6523                "}",
6524                Style);
6525   verifyFormat("void test() {\n"
6526                "  someFunction(\n"
6527                "      arg1,\n"
6528                "      this + argument + has\n"
6529                "          + anotherFunc(nested,\n"
6530                "                        calls + whose\n"
6531                "                            + arguments\n"
6532                "                            + are + also\n"
6533                "                            + wrapped,\n"
6534                "                        in + addition)\n"
6535                "          + to + being + bin - packed,\n"
6536                "      arg3);\n"
6537                "}",
6538                Style);
6539 
6540   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6541   verifyFormat("void test() {\n"
6542                "  someFunction(\n"
6543                "      arg1,\n"
6544                "      this + argument + has +\n"
6545                "          anotherFunc(nested,\n"
6546                "                      calls + whose +\n"
6547                "                          arguments +\n"
6548                "                          are + also +\n"
6549                "                          wrapped,\n"
6550                "                      in + addition) +\n"
6551                "          to + being + bin - packed,\n"
6552                "      arg3);\n"
6553                "}",
6554                Style);
6555 }
6556 
6557 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) {
6558   auto Style = getLLVMStyleWithColumns(45);
6559   EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None);
6560   verifyFormat("bool b =\n"
6561                "    is_default_constructible_v<hash<T>> and\n"
6562                "    is_copy_constructible_v<hash<T>> and\n"
6563                "    is_move_constructible_v<hash<T>> and\n"
6564                "    is_copy_assignable_v<hash<T>> and\n"
6565                "    is_move_assignable_v<hash<T>> and\n"
6566                "    is_destructible_v<hash<T>> and\n"
6567                "    is_swappable_v<hash<T>> and\n"
6568                "    is_callable_v<hash<T>(T)>;",
6569                Style);
6570 
6571   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6572   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6573                "         and is_copy_constructible_v<hash<T>>\n"
6574                "         and is_move_constructible_v<hash<T>>\n"
6575                "         and is_copy_assignable_v<hash<T>>\n"
6576                "         and is_move_assignable_v<hash<T>>\n"
6577                "         and is_destructible_v<hash<T>>\n"
6578                "         and is_swappable_v<hash<T>>\n"
6579                "         and is_callable_v<hash<T>(T)>;",
6580                Style);
6581 
6582   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6583   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6584                "         and is_copy_constructible_v<hash<T>>\n"
6585                "         and is_move_constructible_v<hash<T>>\n"
6586                "         and is_copy_assignable_v<hash<T>>\n"
6587                "         and is_move_assignable_v<hash<T>>\n"
6588                "         and is_destructible_v<hash<T>>\n"
6589                "         and is_swappable_v<hash<T>>\n"
6590                "         and is_callable_v<hash<T>(T)>;",
6591                Style);
6592 }
6593 
6594 TEST_F(FormatTest, ConstructorInitializers) {
6595   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6596   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6597                getLLVMStyleWithColumns(45));
6598   verifyFormat("Constructor()\n"
6599                "    : Inttializer(FitsOnTheLine) {}",
6600                getLLVMStyleWithColumns(44));
6601   verifyFormat("Constructor()\n"
6602                "    : Inttializer(FitsOnTheLine) {}",
6603                getLLVMStyleWithColumns(43));
6604 
6605   verifyFormat("template <typename T>\n"
6606                "Constructor() : Initializer(FitsOnTheLine) {}",
6607                getLLVMStyleWithColumns(45));
6608 
6609   verifyFormat(
6610       "SomeClass::Constructor()\n"
6611       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6612 
6613   verifyFormat(
6614       "SomeClass::Constructor()\n"
6615       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6616       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6617   verifyFormat(
6618       "SomeClass::Constructor()\n"
6619       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6620       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6621   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6622                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6623                "    : aaaaaaaaaa(aaaaaa) {}");
6624 
6625   verifyFormat("Constructor()\n"
6626                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6627                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6628                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6629                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6630 
6631   verifyFormat("Constructor()\n"
6632                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6633                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6634 
6635   verifyFormat("Constructor(int Parameter = 0)\n"
6636                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6637                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6638   verifyFormat("Constructor()\n"
6639                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6640                "}",
6641                getLLVMStyleWithColumns(60));
6642   verifyFormat("Constructor()\n"
6643                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6644                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6645 
6646   // Here a line could be saved by splitting the second initializer onto two
6647   // lines, but that is not desirable.
6648   verifyFormat("Constructor()\n"
6649                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6650                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6651                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6652 
6653   FormatStyle OnePerLine = getLLVMStyle();
6654   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6655   verifyFormat("MyClass::MyClass()\n"
6656                "    : a(a),\n"
6657                "      b(b),\n"
6658                "      c(c) {}",
6659                OnePerLine);
6660   verifyFormat("MyClass::MyClass()\n"
6661                "    : a(a), // comment\n"
6662                "      b(b),\n"
6663                "      c(c) {}",
6664                OnePerLine);
6665   verifyFormat("MyClass::MyClass(int a)\n"
6666                "    : b(a),      // comment\n"
6667                "      c(a + 1) { // lined up\n"
6668                "}",
6669                OnePerLine);
6670   verifyFormat("Constructor()\n"
6671                "    : a(b, b, b) {}",
6672                OnePerLine);
6673   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6674   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6675   verifyFormat("SomeClass::Constructor()\n"
6676                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6677                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6678                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6679                OnePerLine);
6680   verifyFormat("SomeClass::Constructor()\n"
6681                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6682                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6683                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6684                OnePerLine);
6685   verifyFormat("MyClass::MyClass(int var)\n"
6686                "    : some_var_(var),            // 4 space indent\n"
6687                "      some_other_var_(var + 1) { // lined up\n"
6688                "}",
6689                OnePerLine);
6690   verifyFormat("Constructor()\n"
6691                "    : aaaaa(aaaaaa),\n"
6692                "      aaaaa(aaaaaa),\n"
6693                "      aaaaa(aaaaaa),\n"
6694                "      aaaaa(aaaaaa),\n"
6695                "      aaaaa(aaaaaa) {}",
6696                OnePerLine);
6697   verifyFormat("Constructor()\n"
6698                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6699                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6700                OnePerLine);
6701   OnePerLine.BinPackParameters = false;
6702   verifyFormat(
6703       "Constructor()\n"
6704       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6705       "          aaaaaaaaaaa().aaa(),\n"
6706       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6707       OnePerLine);
6708   OnePerLine.ColumnLimit = 60;
6709   verifyFormat("Constructor()\n"
6710                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6711                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6712                OnePerLine);
6713 
6714   EXPECT_EQ("Constructor()\n"
6715             "    : // Comment forcing unwanted break.\n"
6716             "      aaaa(aaaa) {}",
6717             format("Constructor() :\n"
6718                    "    // Comment forcing unwanted break.\n"
6719                    "    aaaa(aaaa) {}"));
6720 }
6721 
6722 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6723   FormatStyle Style = getLLVMStyleWithColumns(60);
6724   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6725   Style.BinPackParameters = false;
6726 
6727   for (int i = 0; i < 4; ++i) {
6728     // Test all combinations of parameters that should not have an effect.
6729     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6730     Style.AllowAllArgumentsOnNextLine = i & 2;
6731 
6732     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6733     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6734     verifyFormat("Constructor()\n"
6735                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6736                  Style);
6737     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6738 
6739     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6740     verifyFormat("Constructor()\n"
6741                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6742                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6743                  Style);
6744     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6745 
6746     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6747     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6748     verifyFormat("Constructor()\n"
6749                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6750                  Style);
6751 
6752     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6753     verifyFormat("Constructor()\n"
6754                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6755                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6756                  Style);
6757 
6758     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6759     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6760     verifyFormat("Constructor() :\n"
6761                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6762                  Style);
6763 
6764     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6765     verifyFormat("Constructor() :\n"
6766                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6767                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6768                  Style);
6769   }
6770 
6771   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6772   // AllowAllConstructorInitializersOnNextLine in all
6773   // BreakConstructorInitializers modes
6774   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6775   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6776   verifyFormat("SomeClassWithALongName::Constructor(\n"
6777                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6778                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6779                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6780                Style);
6781 
6782   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6783   verifyFormat("SomeClassWithALongName::Constructor(\n"
6784                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6785                "    int bbbbbbbbbbbbb,\n"
6786                "    int cccccccccccccccc)\n"
6787                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6788                Style);
6789 
6790   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6791   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6792   verifyFormat("SomeClassWithALongName::Constructor(\n"
6793                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6794                "    int bbbbbbbbbbbbb)\n"
6795                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6796                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6797                Style);
6798 
6799   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6800 
6801   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6802   verifyFormat("SomeClassWithALongName::Constructor(\n"
6803                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6804                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6805                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6806                Style);
6807 
6808   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6809   verifyFormat("SomeClassWithALongName::Constructor(\n"
6810                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6811                "    int bbbbbbbbbbbbb,\n"
6812                "    int cccccccccccccccc)\n"
6813                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6814                Style);
6815 
6816   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6817   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6818   verifyFormat("SomeClassWithALongName::Constructor(\n"
6819                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6820                "    int bbbbbbbbbbbbb)\n"
6821                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6822                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6823                Style);
6824 
6825   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6826   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6827   verifyFormat("SomeClassWithALongName::Constructor(\n"
6828                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6829                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6830                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6831                Style);
6832 
6833   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6834   verifyFormat("SomeClassWithALongName::Constructor(\n"
6835                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6836                "    int bbbbbbbbbbbbb,\n"
6837                "    int cccccccccccccccc) :\n"
6838                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6839                Style);
6840 
6841   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6842   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6843   verifyFormat("SomeClassWithALongName::Constructor(\n"
6844                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6845                "    int bbbbbbbbbbbbb) :\n"
6846                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6847                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6848                Style);
6849 }
6850 
6851 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6852   FormatStyle Style = getLLVMStyleWithColumns(60);
6853   Style.BinPackArguments = false;
6854   for (int i = 0; i < 4; ++i) {
6855     // Test all combinations of parameters that should not have an effect.
6856     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6857     Style.PackConstructorInitializers =
6858         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6859 
6860     Style.AllowAllArgumentsOnNextLine = true;
6861     verifyFormat("void foo() {\n"
6862                  "  FunctionCallWithReallyLongName(\n"
6863                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6864                  "}",
6865                  Style);
6866     Style.AllowAllArgumentsOnNextLine = false;
6867     verifyFormat("void foo() {\n"
6868                  "  FunctionCallWithReallyLongName(\n"
6869                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6870                  "      bbbbbbbbbbbb);\n"
6871                  "}",
6872                  Style);
6873 
6874     Style.AllowAllArgumentsOnNextLine = true;
6875     verifyFormat("void foo() {\n"
6876                  "  auto VariableWithReallyLongName = {\n"
6877                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6878                  "}",
6879                  Style);
6880     Style.AllowAllArgumentsOnNextLine = false;
6881     verifyFormat("void foo() {\n"
6882                  "  auto VariableWithReallyLongName = {\n"
6883                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6884                  "      bbbbbbbbbbbb};\n"
6885                  "}",
6886                  Style);
6887   }
6888 
6889   // This parameter should not affect declarations.
6890   Style.BinPackParameters = false;
6891   Style.AllowAllArgumentsOnNextLine = false;
6892   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6893   verifyFormat("void FunctionCallWithReallyLongName(\n"
6894                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6895                Style);
6896   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6897   verifyFormat("void FunctionCallWithReallyLongName(\n"
6898                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6899                "    int bbbbbbbbbbbb);",
6900                Style);
6901 }
6902 
6903 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6904   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6905   // and BAS_Align.
6906   FormatStyle Style = getLLVMStyleWithColumns(35);
6907   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6908                     "void functionDecl(int A, int B, int C);";
6909   Style.AllowAllArgumentsOnNextLine = false;
6910   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6911   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6912                       "    paramC);\n"
6913                       "void functionDecl(int A, int B,\n"
6914                       "    int C);"),
6915             format(Input, Style));
6916   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6917   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6918                       "             paramC);\n"
6919                       "void functionDecl(int A, int B,\n"
6920                       "                  int C);"),
6921             format(Input, Style));
6922   // However, BAS_AlwaysBreak should take precedence over
6923   // AllowAllArgumentsOnNextLine.
6924   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6925   EXPECT_EQ(StringRef("functionCall(\n"
6926                       "    paramA, paramB, paramC);\n"
6927                       "void functionDecl(\n"
6928                       "    int A, int B, int C);"),
6929             format(Input, Style));
6930 
6931   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6932   // first argument.
6933   Style.AllowAllArgumentsOnNextLine = true;
6934   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6935   EXPECT_EQ(StringRef("functionCall(\n"
6936                       "    paramA, paramB, paramC);\n"
6937                       "void functionDecl(\n"
6938                       "    int A, int B, int C);"),
6939             format(Input, Style));
6940   // It wouldn't fit on one line with aligned parameters so this setting
6941   // doesn't change anything for BAS_Align.
6942   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6943   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6944                       "             paramC);\n"
6945                       "void functionDecl(int A, int B,\n"
6946                       "                  int C);"),
6947             format(Input, Style));
6948   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6949   EXPECT_EQ(StringRef("functionCall(\n"
6950                       "    paramA, paramB, paramC);\n"
6951                       "void functionDecl(\n"
6952                       "    int A, int B, int C);"),
6953             format(Input, Style));
6954 }
6955 
6956 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6957   FormatStyle Style = getLLVMStyle();
6958   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6959 
6960   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6961   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6962                getStyleWithColumns(Style, 45));
6963   verifyFormat("Constructor() :\n"
6964                "    Initializer(FitsOnTheLine) {}",
6965                getStyleWithColumns(Style, 44));
6966   verifyFormat("Constructor() :\n"
6967                "    Initializer(FitsOnTheLine) {}",
6968                getStyleWithColumns(Style, 43));
6969 
6970   verifyFormat("template <typename T>\n"
6971                "Constructor() : Initializer(FitsOnTheLine) {}",
6972                getStyleWithColumns(Style, 50));
6973   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6974   verifyFormat(
6975       "SomeClass::Constructor() :\n"
6976       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6977       Style);
6978 
6979   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6980   verifyFormat(
6981       "SomeClass::Constructor() :\n"
6982       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6983       Style);
6984 
6985   verifyFormat(
6986       "SomeClass::Constructor() :\n"
6987       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6988       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6989       Style);
6990   verifyFormat(
6991       "SomeClass::Constructor() :\n"
6992       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6993       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6994       Style);
6995   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6996                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6997                "    aaaaaaaaaa(aaaaaa) {}",
6998                Style);
6999 
7000   verifyFormat("Constructor() :\n"
7001                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7002                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7003                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7004                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
7005                Style);
7006 
7007   verifyFormat("Constructor() :\n"
7008                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7009                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7010                Style);
7011 
7012   verifyFormat("Constructor(int Parameter = 0) :\n"
7013                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
7014                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
7015                Style);
7016   verifyFormat("Constructor() :\n"
7017                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
7018                "}",
7019                getStyleWithColumns(Style, 60));
7020   verifyFormat("Constructor() :\n"
7021                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7022                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
7023                Style);
7024 
7025   // Here a line could be saved by splitting the second initializer onto two
7026   // lines, but that is not desirable.
7027   verifyFormat("Constructor() :\n"
7028                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
7029                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
7030                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7031                Style);
7032 
7033   FormatStyle OnePerLine = Style;
7034   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
7035   verifyFormat("SomeClass::Constructor() :\n"
7036                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7037                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7038                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7039                OnePerLine);
7040   verifyFormat("SomeClass::Constructor() :\n"
7041                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
7042                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7043                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7044                OnePerLine);
7045   verifyFormat("MyClass::MyClass(int var) :\n"
7046                "    some_var_(var),            // 4 space indent\n"
7047                "    some_other_var_(var + 1) { // lined up\n"
7048                "}",
7049                OnePerLine);
7050   verifyFormat("Constructor() :\n"
7051                "    aaaaa(aaaaaa),\n"
7052                "    aaaaa(aaaaaa),\n"
7053                "    aaaaa(aaaaaa),\n"
7054                "    aaaaa(aaaaaa),\n"
7055                "    aaaaa(aaaaaa) {}",
7056                OnePerLine);
7057   verifyFormat("Constructor() :\n"
7058                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
7059                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
7060                OnePerLine);
7061   OnePerLine.BinPackParameters = false;
7062   verifyFormat("Constructor() :\n"
7063                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7064                "        aaaaaaaaaaa().aaa(),\n"
7065                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7066                OnePerLine);
7067   OnePerLine.ColumnLimit = 60;
7068   verifyFormat("Constructor() :\n"
7069                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
7070                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
7071                OnePerLine);
7072 
7073   EXPECT_EQ("Constructor() :\n"
7074             "    // Comment forcing unwanted break.\n"
7075             "    aaaa(aaaa) {}",
7076             format("Constructor() :\n"
7077                    "    // Comment forcing unwanted break.\n"
7078                    "    aaaa(aaaa) {}",
7079                    Style));
7080 
7081   Style.ColumnLimit = 0;
7082   verifyFormat("SomeClass::Constructor() :\n"
7083                "    a(a) {}",
7084                Style);
7085   verifyFormat("SomeClass::Constructor() noexcept :\n"
7086                "    a(a) {}",
7087                Style);
7088   verifyFormat("SomeClass::Constructor() :\n"
7089                "    a(a), b(b), c(c) {}",
7090                Style);
7091   verifyFormat("SomeClass::Constructor() :\n"
7092                "    a(a) {\n"
7093                "  foo();\n"
7094                "  bar();\n"
7095                "}",
7096                Style);
7097 
7098   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
7099   verifyFormat("SomeClass::Constructor() :\n"
7100                "    a(a), b(b), c(c) {\n"
7101                "}",
7102                Style);
7103   verifyFormat("SomeClass::Constructor() :\n"
7104                "    a(a) {\n"
7105                "}",
7106                Style);
7107 
7108   Style.ColumnLimit = 80;
7109   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
7110   Style.ConstructorInitializerIndentWidth = 2;
7111   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
7112   verifyFormat("SomeClass::Constructor() :\n"
7113                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7114                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
7115                Style);
7116 
7117   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
7118   // well
7119   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
7120   verifyFormat(
7121       "class SomeClass\n"
7122       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7123       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7124       Style);
7125   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
7126   verifyFormat(
7127       "class SomeClass\n"
7128       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7129       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7130       Style);
7131   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
7132   verifyFormat(
7133       "class SomeClass :\n"
7134       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7135       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7136       Style);
7137   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
7138   verifyFormat(
7139       "class SomeClass\n"
7140       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7141       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7142       Style);
7143 }
7144 
7145 #ifndef EXPENSIVE_CHECKS
7146 // Expensive checks enables libstdc++ checking which includes validating the
7147 // state of ranges used in std::priority_queue - this blows out the
7148 // runtime/scalability of the function and makes this test unacceptably slow.
7149 TEST_F(FormatTest, MemoizationTests) {
7150   // This breaks if the memoization lookup does not take \c Indent and
7151   // \c LastSpace into account.
7152   verifyFormat(
7153       "extern CFRunLoopTimerRef\n"
7154       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
7155       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
7156       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
7157       "                     CFRunLoopTimerContext *context) {}");
7158 
7159   // Deep nesting somewhat works around our memoization.
7160   verifyFormat(
7161       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7162       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7163       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7164       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7165       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
7166       getLLVMStyleWithColumns(65));
7167   verifyFormat(
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,\n"
7192       "                                                aaaaa))))))))))));",
7193       getLLVMStyleWithColumns(65));
7194   verifyFormat(
7195       "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"
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),\n"
7212       "  a)",
7213       getLLVMStyleWithColumns(65));
7214 
7215   // This test takes VERY long when memoization is broken.
7216   FormatStyle OnePerLine = getLLVMStyle();
7217   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
7218   OnePerLine.BinPackParameters = false;
7219   std::string input = "Constructor()\n"
7220                       "    : aaaa(a,\n";
7221   for (unsigned i = 0, e = 80; i != e; ++i)
7222     input += "           a,\n";
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   verifyFormat("for (x = 0; -10 < x; --x) {\n}");
9758   verifyFormat("sizeof -x");
9759   verifyFormat("sizeof +x");
9760   verifyFormat("sizeof *x");
9761   verifyFormat("sizeof &x");
9762   verifyFormat("delete +x;");
9763   verifyFormat("co_await +x;");
9764   verifyFormat("case *x:");
9765   verifyFormat("case &x:");
9766 
9767   verifyFormat("a-- > b;");
9768   verifyFormat("b ? -a : c;");
9769   verifyFormat("n * sizeof char16;");
9770   verifyFormat("n * alignof char16;", getGoogleStyle());
9771   verifyFormat("sizeof(char);");
9772   verifyFormat("alignof(char);", getGoogleStyle());
9773 
9774   verifyFormat("return -1;");
9775   verifyFormat("throw -1;");
9776   verifyFormat("switch (a) {\n"
9777                "case -1:\n"
9778                "  break;\n"
9779                "}");
9780   verifyFormat("#define X -1");
9781   verifyFormat("#define X -kConstant");
9782 
9783   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9784   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9785 
9786   verifyFormat("int a = /* confusing comment */ -1;");
9787   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9788   verifyFormat("int a = i /* confusing comment */++;");
9789 
9790   verifyFormat("co_yield -1;");
9791   verifyFormat("co_return -1;");
9792 
9793   // Check that * is not treated as a binary operator when we set
9794   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9795   FormatStyle PASLeftStyle = getLLVMStyle();
9796   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9797   verifyFormat("co_return *a;", PASLeftStyle);
9798   verifyFormat("co_await *a;", PASLeftStyle);
9799   verifyFormat("co_yield *a", PASLeftStyle);
9800   verifyFormat("return *a;", PASLeftStyle);
9801 }
9802 
9803 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9804   verifyFormat("if (!aaaaaaaaaa( // break\n"
9805                "        aaaaa)) {\n"
9806                "}");
9807   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9808                "    aaaaa));");
9809   verifyFormat("*aaa = aaaaaaa( // break\n"
9810                "    bbbbbb);");
9811 }
9812 
9813 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9814   verifyFormat("bool operator<();");
9815   verifyFormat("bool operator>();");
9816   verifyFormat("bool operator=();");
9817   verifyFormat("bool operator==();");
9818   verifyFormat("bool operator!=();");
9819   verifyFormat("int operator+();");
9820   verifyFormat("int operator++();");
9821   verifyFormat("int operator++(int) volatile noexcept;");
9822   verifyFormat("bool operator,();");
9823   verifyFormat("bool operator();");
9824   verifyFormat("bool operator()();");
9825   verifyFormat("bool operator[]();");
9826   verifyFormat("operator bool();");
9827   verifyFormat("operator int();");
9828   verifyFormat("operator void *();");
9829   verifyFormat("operator SomeType<int>();");
9830   verifyFormat("operator SomeType<int, int>();");
9831   verifyFormat("operator SomeType<SomeType<int>>();");
9832   verifyFormat("operator< <>();");
9833   verifyFormat("operator<< <>();");
9834   verifyFormat("< <>");
9835 
9836   verifyFormat("void *operator new(std::size_t size);");
9837   verifyFormat("void *operator new[](std::size_t size);");
9838   verifyFormat("void operator delete(void *ptr);");
9839   verifyFormat("void operator delete[](void *ptr);");
9840   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9841                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9842   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9843                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9844 
9845   verifyFormat(
9846       "ostream &operator<<(ostream &OutputStream,\n"
9847       "                    SomeReallyLongType WithSomeReallyLongValue);");
9848   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9849                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9850                "  return left.group < right.group;\n"
9851                "}");
9852   verifyFormat("SomeType &operator=(const SomeType &S);");
9853   verifyFormat("f.template operator()<int>();");
9854 
9855   verifyGoogleFormat("operator void*();");
9856   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9857   verifyGoogleFormat("operator ::A();");
9858 
9859   verifyFormat("using A::operator+;");
9860   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9861                "int i;");
9862 
9863   // Calling an operator as a member function.
9864   verifyFormat("void f() { a.operator*(); }");
9865   verifyFormat("void f() { a.operator*(b & b); }");
9866   verifyFormat("void f() { a->operator&(a * b); }");
9867   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9868   // TODO: Calling an operator as a non-member function is hard to distinguish.
9869   // https://llvm.org/PR50629
9870   // verifyFormat("void f() { operator*(a & a); }");
9871   // verifyFormat("void f() { operator&(a, b * b); }");
9872 
9873   verifyFormat("::operator delete(foo);");
9874   verifyFormat("::operator new(n * sizeof(foo));");
9875   verifyFormat("foo() { ::operator delete(foo); }");
9876   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9877 }
9878 
9879 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9880   verifyFormat("void A::b() && {}");
9881   verifyFormat("void A::b() &&noexcept {}");
9882   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9883   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9884   verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
9885   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9886   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9887   verifyFormat("Deleted &operator=(const Deleted &) &;");
9888   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9889   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9890   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9891   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9892   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9893   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9894   verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
9895   verifyFormat("void Fn(T const &) const &;");
9896   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9897   verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
9898   verifyFormat("template <typename T>\n"
9899                "void F(T) && = delete;",
9900                getGoogleStyle());
9901   verifyFormat("template <typename T> void operator=(T) &;");
9902   verifyFormat("template <typename T> void operator=(T) const &;");
9903   verifyFormat("template <typename T> void operator=(T) &noexcept;");
9904   verifyFormat("template <typename T> void operator=(T) & = default;");
9905   verifyFormat("template <typename T> void operator=(T) &&;");
9906   verifyFormat("template <typename T> void operator=(T) && = delete;");
9907   verifyFormat("template <typename T> void operator=(T) & {}");
9908   verifyFormat("template <typename T> void operator=(T) && {}");
9909 
9910   FormatStyle AlignLeft = getLLVMStyle();
9911   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9912   verifyFormat("void A::b() && {}", AlignLeft);
9913   verifyFormat("void A::b() && noexcept {}", AlignLeft);
9914   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9915   verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
9916                AlignLeft);
9917   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9918                AlignLeft);
9919   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9920   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9921   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9922   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9923   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9924   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9925   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9926   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9927   verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
9928                AlignLeft);
9929   verifyFormat("template <typename T> void operator=(T) &;", AlignLeft);
9930   verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft);
9931   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9932                AlignLeft);
9933   verifyFormat("template <typename T> void operator=(T) & = default;",
9934                AlignLeft);
9935   verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft);
9936   verifyFormat("template <typename T> void operator=(T) && = delete;",
9937                AlignLeft);
9938   verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft);
9939   verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft);
9940 
9941   FormatStyle AlignMiddle = getLLVMStyle();
9942   AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9943   verifyFormat("void A::b() && {}", AlignMiddle);
9944   verifyFormat("void A::b() && noexcept {}", AlignMiddle);
9945   verifyFormat("Deleted & operator=(const Deleted &) & = default;",
9946                AlignMiddle);
9947   verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
9948                AlignMiddle);
9949   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
9950                AlignMiddle);
9951   verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
9952   verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
9953   verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
9954   verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
9955   verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
9956   verifyFormat("auto Function(T) & -> void;", AlignMiddle);
9957   verifyFormat("void Fn(T const &) const &;", AlignMiddle);
9958   verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
9959   verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
9960                AlignMiddle);
9961   verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle);
9962   verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle);
9963   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9964                AlignMiddle);
9965   verifyFormat("template <typename T> void operator=(T) & = default;",
9966                AlignMiddle);
9967   verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle);
9968   verifyFormat("template <typename T> void operator=(T) && = delete;",
9969                AlignMiddle);
9970   verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle);
9971   verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle);
9972 
9973   FormatStyle Spaces = getLLVMStyle();
9974   Spaces.SpacesInCStyleCastParentheses = true;
9975   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9976   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9977   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9978   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9979 
9980   Spaces.SpacesInCStyleCastParentheses = false;
9981   Spaces.SpacesInParentheses = true;
9982   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9983   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9984                Spaces);
9985   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9986   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9987 
9988   FormatStyle BreakTemplate = getLLVMStyle();
9989   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9990 
9991   verifyFormat("struct f {\n"
9992                "  template <class T>\n"
9993                "  int &foo(const std::string &str) &noexcept {}\n"
9994                "};",
9995                BreakTemplate);
9996 
9997   verifyFormat("struct f {\n"
9998                "  template <class T>\n"
9999                "  int &foo(const std::string &str) &&noexcept {}\n"
10000                "};",
10001                BreakTemplate);
10002 
10003   verifyFormat("struct f {\n"
10004                "  template <class T>\n"
10005                "  int &foo(const std::string &str) const &noexcept {}\n"
10006                "};",
10007                BreakTemplate);
10008 
10009   verifyFormat("struct f {\n"
10010                "  template <class T>\n"
10011                "  int &foo(const std::string &str) const &noexcept {}\n"
10012                "};",
10013                BreakTemplate);
10014 
10015   verifyFormat("struct f {\n"
10016                "  template <class T>\n"
10017                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
10018                "};",
10019                BreakTemplate);
10020 
10021   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
10022   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
10023       FormatStyle::BTDS_Yes;
10024   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
10025 
10026   verifyFormat("struct f {\n"
10027                "  template <class T>\n"
10028                "  int& foo(const std::string& str) & noexcept {}\n"
10029                "};",
10030                AlignLeftBreakTemplate);
10031 
10032   verifyFormat("struct f {\n"
10033                "  template <class T>\n"
10034                "  int& foo(const std::string& str) && noexcept {}\n"
10035                "};",
10036                AlignLeftBreakTemplate);
10037 
10038   verifyFormat("struct f {\n"
10039                "  template <class T>\n"
10040                "  int& foo(const std::string& str) const& noexcept {}\n"
10041                "};",
10042                AlignLeftBreakTemplate);
10043 
10044   verifyFormat("struct f {\n"
10045                "  template <class T>\n"
10046                "  int& foo(const std::string& str) const&& noexcept {}\n"
10047                "};",
10048                AlignLeftBreakTemplate);
10049 
10050   verifyFormat("struct f {\n"
10051                "  template <class T>\n"
10052                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
10053                "};",
10054                AlignLeftBreakTemplate);
10055 
10056   // The `&` in `Type&` should not be confused with a trailing `&` of
10057   // DEPRECATED(reason) member function.
10058   verifyFormat("struct f {\n"
10059                "  template <class T>\n"
10060                "  DEPRECATED(reason)\n"
10061                "  Type &foo(arguments) {}\n"
10062                "};",
10063                BreakTemplate);
10064 
10065   verifyFormat("struct f {\n"
10066                "  template <class T>\n"
10067                "  DEPRECATED(reason)\n"
10068                "  Type& foo(arguments) {}\n"
10069                "};",
10070                AlignLeftBreakTemplate);
10071 
10072   verifyFormat("void (*foopt)(int) = &func;");
10073 
10074   FormatStyle DerivePointerAlignment = getLLVMStyle();
10075   DerivePointerAlignment.DerivePointerAlignment = true;
10076   // There's always a space between the function and its trailing qualifiers.
10077   // This isn't evidence for PAS_Right (or for PAS_Left).
10078   std::string Prefix = "void a() &;\n"
10079                        "void b() &;\n";
10080   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10081   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10082   // Same if the function is an overloaded operator, and with &&.
10083   Prefix = "void operator()() &&;\n"
10084            "void operator()() &&;\n";
10085   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10086   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10087   // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
10088   Prefix = "void a() const &;\n"
10089            "void b() const &;\n";
10090   EXPECT_EQ(Prefix + "int *x;",
10091             format(Prefix + "int* x;", DerivePointerAlignment));
10092 }
10093 
10094 TEST_F(FormatTest, UnderstandsNewAndDelete) {
10095   verifyFormat("void f() {\n"
10096                "  A *a = new A;\n"
10097                "  A *a = new (placement) A;\n"
10098                "  delete a;\n"
10099                "  delete (A *)a;\n"
10100                "}");
10101   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10102                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10103   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10104                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10105                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10106   verifyFormat("delete[] h->p;");
10107   verifyFormat("delete[] (void *)p;");
10108 
10109   verifyFormat("void operator delete(void *foo) ATTRIB;");
10110   verifyFormat("void operator new(void *foo) ATTRIB;");
10111   verifyFormat("void operator delete[](void *foo) ATTRIB;");
10112   verifyFormat("void operator delete(void *ptr) noexcept;");
10113 
10114   EXPECT_EQ("void new(link p);\n"
10115             "void delete(link p);\n",
10116             format("void new (link p);\n"
10117                    "void delete (link p);\n"));
10118 }
10119 
10120 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
10121   verifyFormat("int *f(int *a) {}");
10122   verifyFormat("int main(int argc, char **argv) {}");
10123   verifyFormat("Test::Test(int b) : a(b * b) {}");
10124   verifyIndependentOfContext("f(a, *a);");
10125   verifyFormat("void g() { f(*a); }");
10126   verifyIndependentOfContext("int a = b * 10;");
10127   verifyIndependentOfContext("int a = 10 * b;");
10128   verifyIndependentOfContext("int a = b * c;");
10129   verifyIndependentOfContext("int a += b * c;");
10130   verifyIndependentOfContext("int a -= b * c;");
10131   verifyIndependentOfContext("int a *= b * c;");
10132   verifyIndependentOfContext("int a /= b * c;");
10133   verifyIndependentOfContext("int a = *b;");
10134   verifyIndependentOfContext("int a = *b * c;");
10135   verifyIndependentOfContext("int a = b * *c;");
10136   verifyIndependentOfContext("int a = b * (10);");
10137   verifyIndependentOfContext("S << b * (10);");
10138   verifyIndependentOfContext("return 10 * b;");
10139   verifyIndependentOfContext("return *b * *c;");
10140   verifyIndependentOfContext("return a & ~b;");
10141   verifyIndependentOfContext("f(b ? *c : *d);");
10142   verifyIndependentOfContext("int a = b ? *c : *d;");
10143   verifyIndependentOfContext("*b = a;");
10144   verifyIndependentOfContext("a * ~b;");
10145   verifyIndependentOfContext("a * !b;");
10146   verifyIndependentOfContext("a * +b;");
10147   verifyIndependentOfContext("a * -b;");
10148   verifyIndependentOfContext("a * ++b;");
10149   verifyIndependentOfContext("a * --b;");
10150   verifyIndependentOfContext("a[4] * b;");
10151   verifyIndependentOfContext("a[a * a] = 1;");
10152   verifyIndependentOfContext("f() * b;");
10153   verifyIndependentOfContext("a * [self dostuff];");
10154   verifyIndependentOfContext("int x = a * (a + b);");
10155   verifyIndependentOfContext("(a *)(a + b);");
10156   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
10157   verifyIndependentOfContext("int *pa = (int *)&a;");
10158   verifyIndependentOfContext("return sizeof(int **);");
10159   verifyIndependentOfContext("return sizeof(int ******);");
10160   verifyIndependentOfContext("return (int **&)a;");
10161   verifyIndependentOfContext("f((*PointerToArray)[10]);");
10162   verifyFormat("void f(Type (*parameter)[10]) {}");
10163   verifyFormat("void f(Type (&parameter)[10]) {}");
10164   verifyGoogleFormat("return sizeof(int**);");
10165   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
10166   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
10167   verifyFormat("auto a = [](int **&, int ***) {};");
10168   verifyFormat("auto PointerBinding = [](const char *S) {};");
10169   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
10170   verifyFormat("[](const decltype(*a) &value) {}");
10171   verifyFormat("[](const typeof(*a) &value) {}");
10172   verifyFormat("[](const _Atomic(a *) &value) {}");
10173   verifyFormat("[](const __underlying_type(a) &value) {}");
10174   verifyFormat("decltype(a * b) F();");
10175   verifyFormat("typeof(a * b) F();");
10176   verifyFormat("#define MACRO() [](A *a) { return 1; }");
10177   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
10178   verifyIndependentOfContext("typedef void (*f)(int *a);");
10179   verifyIndependentOfContext("int i{a * b};");
10180   verifyIndependentOfContext("aaa && aaa->f();");
10181   verifyIndependentOfContext("int x = ~*p;");
10182   verifyFormat("Constructor() : a(a), area(width * height) {}");
10183   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
10184   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
10185   verifyFormat("void f() { f(a, c * d); }");
10186   verifyFormat("void f() { f(new a(), c * d); }");
10187   verifyFormat("void f(const MyOverride &override);");
10188   verifyFormat("void f(const MyFinal &final);");
10189   verifyIndependentOfContext("bool a = f() && override.f();");
10190   verifyIndependentOfContext("bool a = f() && final.f();");
10191 
10192   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
10193 
10194   verifyIndependentOfContext("A<int *> a;");
10195   verifyIndependentOfContext("A<int **> a;");
10196   verifyIndependentOfContext("A<int *, int *> a;");
10197   verifyIndependentOfContext("A<int *[]> a;");
10198   verifyIndependentOfContext(
10199       "const char *const p = reinterpret_cast<const char *const>(q);");
10200   verifyIndependentOfContext("A<int **, int **> a;");
10201   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
10202   verifyFormat("for (char **a = b; *a; ++a) {\n}");
10203   verifyFormat("for (; a && b;) {\n}");
10204   verifyFormat("bool foo = true && [] { return false; }();");
10205 
10206   verifyFormat(
10207       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10208       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10209 
10210   verifyGoogleFormat("int const* a = &b;");
10211   verifyGoogleFormat("**outparam = 1;");
10212   verifyGoogleFormat("*outparam = a * b;");
10213   verifyGoogleFormat("int main(int argc, char** argv) {}");
10214   verifyGoogleFormat("A<int*> a;");
10215   verifyGoogleFormat("A<int**> a;");
10216   verifyGoogleFormat("A<int*, int*> a;");
10217   verifyGoogleFormat("A<int**, int**> a;");
10218   verifyGoogleFormat("f(b ? *c : *d);");
10219   verifyGoogleFormat("int a = b ? *c : *d;");
10220   verifyGoogleFormat("Type* t = **x;");
10221   verifyGoogleFormat("Type* t = *++*x;");
10222   verifyGoogleFormat("*++*x;");
10223   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
10224   verifyGoogleFormat("Type* t = x++ * y;");
10225   verifyGoogleFormat(
10226       "const char* const p = reinterpret_cast<const char* const>(q);");
10227   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
10228   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
10229   verifyGoogleFormat("template <typename T>\n"
10230                      "void f(int i = 0, SomeType** temps = NULL);");
10231 
10232   FormatStyle Left = getLLVMStyle();
10233   Left.PointerAlignment = FormatStyle::PAS_Left;
10234   verifyFormat("x = *a(x) = *a(y);", Left);
10235   verifyFormat("for (;; *a = b) {\n}", Left);
10236   verifyFormat("return *this += 1;", Left);
10237   verifyFormat("throw *x;", Left);
10238   verifyFormat("delete *x;", Left);
10239   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
10240   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
10241   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
10242   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
10243   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
10244   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
10245   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
10246   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
10247   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
10248 
10249   verifyIndependentOfContext("a = *(x + y);");
10250   verifyIndependentOfContext("a = &(x + y);");
10251   verifyIndependentOfContext("*(x + y).call();");
10252   verifyIndependentOfContext("&(x + y)->call();");
10253   verifyFormat("void f() { &(*I).first; }");
10254 
10255   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
10256   verifyFormat("f(* /* confusing comment */ foo);");
10257   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
10258   verifyFormat("void foo(int * // this is the first paramters\n"
10259                "         ,\n"
10260                "         int second);");
10261   verifyFormat("double term = a * // first\n"
10262                "              b;");
10263   verifyFormat(
10264       "int *MyValues = {\n"
10265       "    *A, // Operator detection might be confused by the '{'\n"
10266       "    *BB // Operator detection might be confused by previous comment\n"
10267       "};");
10268 
10269   verifyIndependentOfContext("if (int *a = &b)");
10270   verifyIndependentOfContext("if (int &a = *b)");
10271   verifyIndependentOfContext("if (a & b[i])");
10272   verifyIndependentOfContext("if constexpr (a & b[i])");
10273   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
10274   verifyIndependentOfContext("if (a * (b * c))");
10275   verifyIndependentOfContext("if constexpr (a * (b * c))");
10276   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
10277   verifyIndependentOfContext("if (a::b::c::d & b[i])");
10278   verifyIndependentOfContext("if (*b[i])");
10279   verifyIndependentOfContext("if (int *a = (&b))");
10280   verifyIndependentOfContext("while (int *a = &b)");
10281   verifyIndependentOfContext("while (a * (b * c))");
10282   verifyIndependentOfContext("size = sizeof *a;");
10283   verifyIndependentOfContext("if (a && (b = c))");
10284   verifyFormat("void f() {\n"
10285                "  for (const int &v : Values) {\n"
10286                "  }\n"
10287                "}");
10288   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
10289   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
10290   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
10291 
10292   verifyFormat("#define A (!a * b)");
10293   verifyFormat("#define MACRO     \\\n"
10294                "  int *i = a * b; \\\n"
10295                "  void f(a *b);",
10296                getLLVMStyleWithColumns(19));
10297 
10298   verifyIndependentOfContext("A = new SomeType *[Length];");
10299   verifyIndependentOfContext("A = new SomeType *[Length]();");
10300   verifyIndependentOfContext("T **t = new T *;");
10301   verifyIndependentOfContext("T **t = new T *();");
10302   verifyGoogleFormat("A = new SomeType*[Length]();");
10303   verifyGoogleFormat("A = new SomeType*[Length];");
10304   verifyGoogleFormat("T** t = new T*;");
10305   verifyGoogleFormat("T** t = new T*();");
10306 
10307   verifyFormat("STATIC_ASSERT((a & b) == 0);");
10308   verifyFormat("STATIC_ASSERT(0 == (a & b));");
10309   verifyFormat("template <bool a, bool b> "
10310                "typename t::if<x && y>::type f() {}");
10311   verifyFormat("template <int *y> f() {}");
10312   verifyFormat("vector<int *> v;");
10313   verifyFormat("vector<int *const> v;");
10314   verifyFormat("vector<int *const **const *> v;");
10315   verifyFormat("vector<int *volatile> v;");
10316   verifyFormat("vector<a *_Nonnull> v;");
10317   verifyFormat("vector<a *_Nullable> v;");
10318   verifyFormat("vector<a *_Null_unspecified> v;");
10319   verifyFormat("vector<a *__ptr32> v;");
10320   verifyFormat("vector<a *__ptr64> v;");
10321   verifyFormat("vector<a *__capability> v;");
10322   FormatStyle TypeMacros = getLLVMStyle();
10323   TypeMacros.TypenameMacros = {"LIST"};
10324   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
10325   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
10326   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
10327   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
10328   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
10329 
10330   FormatStyle CustomQualifier = getLLVMStyle();
10331   // Add identifiers that should not be parsed as a qualifier by default.
10332   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10333   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
10334   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
10335   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
10336   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
10337   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
10338   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
10339   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
10340   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
10341   verifyFormat("vector<a * _NotAQualifier> v;");
10342   verifyFormat("vector<a * __not_a_qualifier> v;");
10343   verifyFormat("vector<a * b> v;");
10344   verifyFormat("foo<b && false>();");
10345   verifyFormat("foo<b & 1>();");
10346   verifyFormat("foo<b & (1)>();");
10347   verifyFormat("foo<b & (~0)>();");
10348   verifyFormat("foo<b & (true)>();");
10349   verifyFormat("foo<b & ((1))>();");
10350   verifyFormat("foo<b & (/*comment*/ 1)>();");
10351   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
10352   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
10353   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
10354   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
10355   verifyFormat(
10356       "template <class T, class = typename std::enable_if<\n"
10357       "                       std::is_integral<T>::value &&\n"
10358       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
10359       "void F();",
10360       getLLVMStyleWithColumns(70));
10361   verifyFormat("template <class T,\n"
10362                "          class = typename std::enable_if<\n"
10363                "              std::is_integral<T>::value &&\n"
10364                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
10365                "          class U>\n"
10366                "void F();",
10367                getLLVMStyleWithColumns(70));
10368   verifyFormat(
10369       "template <class T,\n"
10370       "          class = typename ::std::enable_if<\n"
10371       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
10372       "void F();",
10373       getGoogleStyleWithColumns(68));
10374 
10375   verifyIndependentOfContext("MACRO(int *i);");
10376   verifyIndependentOfContext("MACRO(auto *a);");
10377   verifyIndependentOfContext("MACRO(const A *a);");
10378   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
10379   verifyIndependentOfContext("MACRO(decltype(A) *a);");
10380   verifyIndependentOfContext("MACRO(typeof(A) *a);");
10381   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
10382   verifyIndependentOfContext("MACRO(A *const a);");
10383   verifyIndependentOfContext("MACRO(A *restrict a);");
10384   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
10385   verifyIndependentOfContext("MACRO(A *__restrict a);");
10386   verifyIndependentOfContext("MACRO(A *volatile a);");
10387   verifyIndependentOfContext("MACRO(A *__volatile a);");
10388   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
10389   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
10390   verifyIndependentOfContext("MACRO(A *_Nullable a);");
10391   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
10392   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
10393   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
10394   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
10395   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
10396   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
10397   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
10398   verifyIndependentOfContext("MACRO(A *__capability);");
10399   verifyIndependentOfContext("MACRO(A &__capability);");
10400   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
10401   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
10402   // If we add __my_qualifier to AttributeMacros it should always be parsed as
10403   // a type declaration:
10404   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
10405   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
10406   // Also check that TypenameMacros prevents parsing it as multiplication:
10407   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
10408   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
10409 
10410   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
10411   verifyFormat("void f() { f(float{1}, a * a); }");
10412   verifyFormat("void f() { f(float(1), a * a); }");
10413 
10414   verifyFormat("f((void (*)(int))g);");
10415   verifyFormat("f((void (&)(int))g);");
10416   verifyFormat("f((void (^)(int))g);");
10417 
10418   // FIXME: Is there a way to make this work?
10419   // verifyIndependentOfContext("MACRO(A *a);");
10420   verifyFormat("MACRO(A &B);");
10421   verifyFormat("MACRO(A *B);");
10422   verifyFormat("void f() { MACRO(A * B); }");
10423   verifyFormat("void f() { MACRO(A & B); }");
10424 
10425   // This lambda was mis-formatted after D88956 (treating it as a binop):
10426   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
10427   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
10428   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
10429   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
10430 
10431   verifyFormat("DatumHandle const *operator->() const { return input_; }");
10432   verifyFormat("return options != nullptr && operator==(*options);");
10433 
10434   EXPECT_EQ("#define OP(x)                                    \\\n"
10435             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
10436             "    return s << a.DebugString();                 \\\n"
10437             "  }",
10438             format("#define OP(x) \\\n"
10439                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
10440                    "    return s << a.DebugString(); \\\n"
10441                    "  }",
10442                    getLLVMStyleWithColumns(50)));
10443 
10444   // FIXME: We cannot handle this case yet; we might be able to figure out that
10445   // foo<x> d > v; doesn't make sense.
10446   verifyFormat("foo<a<b && c> d> v;");
10447 
10448   FormatStyle PointerMiddle = getLLVMStyle();
10449   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10450   verifyFormat("delete *x;", PointerMiddle);
10451   verifyFormat("int * x;", PointerMiddle);
10452   verifyFormat("int *[] x;", PointerMiddle);
10453   verifyFormat("template <int * y> f() {}", PointerMiddle);
10454   verifyFormat("int * f(int * a) {}", PointerMiddle);
10455   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
10456   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10457   verifyFormat("A<int *> a;", PointerMiddle);
10458   verifyFormat("A<int **> a;", PointerMiddle);
10459   verifyFormat("A<int *, int *> a;", PointerMiddle);
10460   verifyFormat("A<int *[]> a;", PointerMiddle);
10461   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10462   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10463   verifyFormat("T ** t = new T *;", PointerMiddle);
10464 
10465   // Member function reference qualifiers aren't binary operators.
10466   verifyFormat("string // break\n"
10467                "operator()() & {}");
10468   verifyFormat("string // break\n"
10469                "operator()() && {}");
10470   verifyGoogleFormat("template <typename T>\n"
10471                      "auto x() & -> int {}");
10472 
10473   // Should be binary operators when used as an argument expression (overloaded
10474   // operator invoked as a member function).
10475   verifyFormat("void f() { a.operator()(a * a); }");
10476   verifyFormat("void f() { a->operator()(a & a); }");
10477   verifyFormat("void f() { a.operator()(*a & *a); }");
10478   verifyFormat("void f() { a->operator()(*a * *a); }");
10479 
10480   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10481   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10482 }
10483 
10484 TEST_F(FormatTest, UnderstandsAttributes) {
10485   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10486   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10487                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10488   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10489   FormatStyle AfterType = getLLVMStyle();
10490   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10491   verifyFormat("__attribute__((nodebug)) void\n"
10492                "foo() {}\n",
10493                AfterType);
10494   verifyFormat("__unused void\n"
10495                "foo() {}",
10496                AfterType);
10497 
10498   FormatStyle CustomAttrs = getLLVMStyle();
10499   CustomAttrs.AttributeMacros.push_back("__unused");
10500   CustomAttrs.AttributeMacros.push_back("__attr1");
10501   CustomAttrs.AttributeMacros.push_back("__attr2");
10502   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10503   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10504   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10505   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10506   // Check that it is parsed as a multiplication without AttributeMacros and
10507   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10508   verifyFormat("vector<SomeType * __attr1> v;");
10509   verifyFormat("vector<SomeType __attr1 *> v;");
10510   verifyFormat("vector<SomeType __attr1 *const> v;");
10511   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10512   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10513   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10514   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10515   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10516   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10517   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10518   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10519 
10520   // Check that these are not parsed as function declarations:
10521   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10522   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10523   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10524   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10525   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10526   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10527   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10528   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10529   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10530   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10531 }
10532 
10533 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10534   // Check that qualifiers on pointers don't break parsing of casts.
10535   verifyFormat("x = (foo *const)*v;");
10536   verifyFormat("x = (foo *volatile)*v;");
10537   verifyFormat("x = (foo *restrict)*v;");
10538   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10539   verifyFormat("x = (foo *_Nonnull)*v;");
10540   verifyFormat("x = (foo *_Nullable)*v;");
10541   verifyFormat("x = (foo *_Null_unspecified)*v;");
10542   verifyFormat("x = (foo *_Nonnull)*v;");
10543   verifyFormat("x = (foo *[[clang::attr]])*v;");
10544   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10545   verifyFormat("x = (foo *__ptr32)*v;");
10546   verifyFormat("x = (foo *__ptr64)*v;");
10547   verifyFormat("x = (foo *__capability)*v;");
10548 
10549   // Check that we handle multiple trailing qualifiers and skip them all to
10550   // determine that the expression is a cast to a pointer type.
10551   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10552   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10553   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10554   StringRef AllQualifiers =
10555       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10556       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10557   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10558   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10559 
10560   // Also check that address-of is not parsed as a binary bitwise-and:
10561   verifyFormat("x = (foo *const)&v;");
10562   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10563   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10564 
10565   // Check custom qualifiers:
10566   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10567   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10568   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10569   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10570   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10571                CustomQualifier);
10572   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10573                CustomQualifier);
10574 
10575   // Check that unknown identifiers result in binary operator parsing:
10576   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10577   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10578 }
10579 
10580 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10581   verifyFormat("SomeType s [[unused]] (InitValue);");
10582   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10583   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10584   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10585   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10586   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10587                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10588   verifyFormat("[[nodiscard]] bool f() { return false; }");
10589   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10590   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10591   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10592   verifyFormat("[[nodiscard]] ::qualified_type f();");
10593 
10594   // Make sure we do not mistake attributes for array subscripts.
10595   verifyFormat("int a() {}\n"
10596                "[[unused]] int b() {}\n");
10597   verifyFormat("NSArray *arr;\n"
10598                "arr[[Foo() bar]];");
10599 
10600   // On the other hand, we still need to correctly find array subscripts.
10601   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10602 
10603   // Make sure that we do not mistake Objective-C method inside array literals
10604   // as attributes, even if those method names are also keywords.
10605   verifyFormat("@[ [foo bar] ];");
10606   verifyFormat("@[ [NSArray class] ];");
10607   verifyFormat("@[ [foo enum] ];");
10608 
10609   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10610 
10611   // Make sure we do not parse attributes as lambda introducers.
10612   FormatStyle MultiLineFunctions = getLLVMStyle();
10613   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10614   verifyFormat("[[unused]] int b() {\n"
10615                "  return 42;\n"
10616                "}\n",
10617                MultiLineFunctions);
10618 }
10619 
10620 TEST_F(FormatTest, AttributeClass) {
10621   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10622   verifyFormat("class S {\n"
10623                "  S(S&&) = default;\n"
10624                "};",
10625                Style);
10626   verifyFormat("class [[nodiscard]] S {\n"
10627                "  S(S&&) = default;\n"
10628                "};",
10629                Style);
10630   verifyFormat("class __attribute((maybeunused)) S {\n"
10631                "  S(S&&) = default;\n"
10632                "};",
10633                Style);
10634   verifyFormat("struct S {\n"
10635                "  S(S&&) = default;\n"
10636                "};",
10637                Style);
10638   verifyFormat("struct [[nodiscard]] S {\n"
10639                "  S(S&&) = default;\n"
10640                "};",
10641                Style);
10642 }
10643 
10644 TEST_F(FormatTest, AttributesAfterMacro) {
10645   FormatStyle Style = getLLVMStyle();
10646   verifyFormat("MACRO;\n"
10647                "__attribute__((maybe_unused)) int foo() {\n"
10648                "  //...\n"
10649                "}");
10650 
10651   verifyFormat("MACRO;\n"
10652                "[[nodiscard]] int foo() {\n"
10653                "  //...\n"
10654                "}");
10655 
10656   EXPECT_EQ("MACRO\n\n"
10657             "__attribute__((maybe_unused)) int foo() {\n"
10658             "  //...\n"
10659             "}",
10660             format("MACRO\n\n"
10661                    "__attribute__((maybe_unused)) int foo() {\n"
10662                    "  //...\n"
10663                    "}"));
10664 
10665   EXPECT_EQ("MACRO\n\n"
10666             "[[nodiscard]] int foo() {\n"
10667             "  //...\n"
10668             "}",
10669             format("MACRO\n\n"
10670                    "[[nodiscard]] int foo() {\n"
10671                    "  //...\n"
10672                    "}"));
10673 }
10674 
10675 TEST_F(FormatTest, AttributePenaltyBreaking) {
10676   FormatStyle Style = getLLVMStyle();
10677   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10678                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10679                Style);
10680   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10681                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10682                Style);
10683   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10684                "shared_ptr<ALongTypeName> &C d) {\n}",
10685                Style);
10686 }
10687 
10688 TEST_F(FormatTest, UnderstandsEllipsis) {
10689   FormatStyle Style = getLLVMStyle();
10690   verifyFormat("int printf(const char *fmt, ...);");
10691   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10692   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10693 
10694   verifyFormat("template <int *...PP> a;", Style);
10695 
10696   Style.PointerAlignment = FormatStyle::PAS_Left;
10697   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10698 
10699   verifyFormat("template <int*... PP> a;", Style);
10700 
10701   Style.PointerAlignment = FormatStyle::PAS_Middle;
10702   verifyFormat("template <int *... PP> a;", Style);
10703 }
10704 
10705 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
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("int* a;\n"
10714             "int* a;\n"
10715             "int* a;",
10716             format("int* a;\n"
10717                    "int* a;\n"
10718                    "int *a;",
10719                    getGoogleStyle()));
10720   EXPECT_EQ("int *a;\n"
10721             "int *a;\n"
10722             "int *a;",
10723             format("int *a;\n"
10724                    "int * a;\n"
10725                    "int *  a;",
10726                    getGoogleStyle()));
10727   EXPECT_EQ("auto x = [] {\n"
10728             "  int *a;\n"
10729             "  int *a;\n"
10730             "  int *a;\n"
10731             "};",
10732             format("auto x=[]{int *a;\n"
10733                    "int * a;\n"
10734                    "int *  a;};",
10735                    getGoogleStyle()));
10736 }
10737 
10738 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10739   verifyFormat("int f(int &&a) {}");
10740   verifyFormat("int f(int a, char &&b) {}");
10741   verifyFormat("void f() { int &&a = b; }");
10742   verifyGoogleFormat("int f(int a, char&& b) {}");
10743   verifyGoogleFormat("void f() { int&& a = b; }");
10744 
10745   verifyIndependentOfContext("A<int &&> a;");
10746   verifyIndependentOfContext("A<int &&, int &&> a;");
10747   verifyGoogleFormat("A<int&&> a;");
10748   verifyGoogleFormat("A<int&&, int&&> a;");
10749 
10750   // Not rvalue references:
10751   verifyFormat("template <bool B, bool C> class A {\n"
10752                "  static_assert(B && C, \"Something is wrong\");\n"
10753                "};");
10754   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10755   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10756   verifyFormat("#define A(a, b) (a && b)");
10757 }
10758 
10759 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10760   verifyFormat("void f() {\n"
10761                "  x[aaaaaaaaa -\n"
10762                "    b] = 23;\n"
10763                "}",
10764                getLLVMStyleWithColumns(15));
10765 }
10766 
10767 TEST_F(FormatTest, FormatsCasts) {
10768   verifyFormat("Type *A = static_cast<Type *>(P);");
10769   verifyFormat("static_cast<Type *>(P);");
10770   verifyFormat("static_cast<Type &>(Fun)(Args);");
10771   verifyFormat("static_cast<Type &>(*Fun)(Args);");
10772   verifyFormat("if (static_cast<int>(A) + B >= 0)\n  ;");
10773   // Check that static_cast<...>(...) does not require the next token to be on
10774   // the same line.
10775   verifyFormat("some_loooong_output << something_something__ << "
10776                "static_cast<const void *>(R)\n"
10777                "                    << something;");
10778   verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
10779   verifyFormat("const_cast<Type &>(*Fun)(Args);");
10780   verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
10781   verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
10782   verifyFormat("Type *A = (Type *)P;");
10783   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10784   verifyFormat("int a = (int)(2.0f);");
10785   verifyFormat("int a = (int)2.0f;");
10786   verifyFormat("x[(int32)y];");
10787   verifyFormat("x = (int32)y;");
10788   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10789   verifyFormat("int a = (int)*b;");
10790   verifyFormat("int a = (int)2.0f;");
10791   verifyFormat("int a = (int)~0;");
10792   verifyFormat("int a = (int)++a;");
10793   verifyFormat("int a = (int)sizeof(int);");
10794   verifyFormat("int a = (int)+2;");
10795   verifyFormat("my_int a = (my_int)2.0f;");
10796   verifyFormat("my_int a = (my_int)sizeof(int);");
10797   verifyFormat("return (my_int)aaa;");
10798   verifyFormat("#define x ((int)-1)");
10799   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10800   verifyFormat("#define p(q) ((int *)&q)");
10801   verifyFormat("fn(a)(b) + 1;");
10802 
10803   verifyFormat("void f() { my_int a = (my_int)*b; }");
10804   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10805   verifyFormat("my_int a = (my_int)~0;");
10806   verifyFormat("my_int a = (my_int)++a;");
10807   verifyFormat("my_int a = (my_int)-2;");
10808   verifyFormat("my_int a = (my_int)1;");
10809   verifyFormat("my_int a = (my_int *)1;");
10810   verifyFormat("my_int a = (const my_int)-1;");
10811   verifyFormat("my_int a = (const my_int *)-1;");
10812   verifyFormat("my_int a = (my_int)(my_int)-1;");
10813   verifyFormat("my_int a = (ns::my_int)-2;");
10814   verifyFormat("case (my_int)ONE:");
10815   verifyFormat("auto x = (X)this;");
10816   // Casts in Obj-C style calls used to not be recognized as such.
10817   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10818 
10819   // FIXME: single value wrapped with paren will be treated as cast.
10820   verifyFormat("void f(int i = (kValue)*kMask) {}");
10821 
10822   verifyFormat("{ (void)F; }");
10823 
10824   // Don't break after a cast's
10825   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10826                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10827                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10828 
10829   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10830   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10831   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10832   verifyFormat("bool *y = (bool *)(void *)(x);");
10833   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10834   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10835   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10836   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10837 
10838   // These are not casts.
10839   verifyFormat("void f(int *) {}");
10840   verifyFormat("f(foo)->b;");
10841   verifyFormat("f(foo).b;");
10842   verifyFormat("f(foo)(b);");
10843   verifyFormat("f(foo)[b];");
10844   verifyFormat("[](foo) { return 4; }(bar);");
10845   verifyFormat("(*funptr)(foo)[4];");
10846   verifyFormat("funptrs[4](foo)[4];");
10847   verifyFormat("void f(int *);");
10848   verifyFormat("void f(int *) = 0;");
10849   verifyFormat("void f(SmallVector<int>) {}");
10850   verifyFormat("void f(SmallVector<int>);");
10851   verifyFormat("void f(SmallVector<int>) = 0;");
10852   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10853   verifyFormat("int a = sizeof(int) * b;");
10854   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10855   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10856   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10857   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10858 
10859   // These are not casts, but at some point were confused with casts.
10860   verifyFormat("virtual void foo(int *) override;");
10861   verifyFormat("virtual void foo(char &) const;");
10862   verifyFormat("virtual void foo(int *a, char *) const;");
10863   verifyFormat("int a = sizeof(int *) + b;");
10864   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10865   verifyFormat("bool b = f(g<int>) && c;");
10866   verifyFormat("typedef void (*f)(int i) func;");
10867   verifyFormat("void operator++(int) noexcept;");
10868   verifyFormat("void operator++(int &) noexcept;");
10869   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10870                "&) noexcept;");
10871   verifyFormat(
10872       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10873   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10874   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10875   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10876   verifyFormat("void operator delete(foo &) noexcept;");
10877   verifyFormat("void operator delete(foo) noexcept;");
10878   verifyFormat("void operator delete(int) noexcept;");
10879   verifyFormat("void operator delete(int &) noexcept;");
10880   verifyFormat("void operator delete(int &) volatile noexcept;");
10881   verifyFormat("void operator delete(int &) const");
10882   verifyFormat("void operator delete(int &) = default");
10883   verifyFormat("void operator delete(int &) = delete");
10884   verifyFormat("void operator delete(int &) [[noreturn]]");
10885   verifyFormat("void operator delete(int &) throw();");
10886   verifyFormat("void operator delete(int &) throw(int);");
10887   verifyFormat("auto operator delete(int &) -> int;");
10888   verifyFormat("auto operator delete(int &) override");
10889   verifyFormat("auto operator delete(int &) final");
10890 
10891   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10892                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10893   // FIXME: The indentation here is not ideal.
10894   verifyFormat(
10895       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10896       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10897       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10898 }
10899 
10900 TEST_F(FormatTest, FormatsFunctionTypes) {
10901   verifyFormat("A<bool()> a;");
10902   verifyFormat("A<SomeType()> a;");
10903   verifyFormat("A<void (*)(int, std::string)> a;");
10904   verifyFormat("A<void *(int)>;");
10905   verifyFormat("void *(*a)(int *, SomeType *);");
10906   verifyFormat("int (*func)(void *);");
10907   verifyFormat("void f() { int (*func)(void *); }");
10908   verifyFormat("template <class CallbackClass>\n"
10909                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10910 
10911   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10912   verifyGoogleFormat("void* (*a)(int);");
10913   verifyGoogleFormat(
10914       "template <class CallbackClass>\n"
10915       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10916 
10917   // Other constructs can look somewhat like function types:
10918   verifyFormat("A<sizeof(*x)> a;");
10919   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10920   verifyFormat("some_var = function(*some_pointer_var)[0];");
10921   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10922   verifyFormat("int x = f(&h)();");
10923   verifyFormat("returnsFunction(&param1, &param2)(param);");
10924   verifyFormat("std::function<\n"
10925                "    LooooooooooongTemplatedType<\n"
10926                "        SomeType>*(\n"
10927                "        LooooooooooooooooongType type)>\n"
10928                "    function;",
10929                getGoogleStyleWithColumns(40));
10930 }
10931 
10932 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10933   verifyFormat("A (*foo_)[6];");
10934   verifyFormat("vector<int> (*foo_)[6];");
10935 }
10936 
10937 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10938   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10939                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10940   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10941                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10942   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10943                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10944 
10945   // Different ways of ()-initializiation.
10946   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10947                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10948   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10949                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10950   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10951                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10952   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10953                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10954 
10955   // Lambdas should not confuse the variable declaration heuristic.
10956   verifyFormat("LooooooooooooooooongType\n"
10957                "    variable(nullptr, [](A *a) {});",
10958                getLLVMStyleWithColumns(40));
10959 }
10960 
10961 TEST_F(FormatTest, BreaksLongDeclarations) {
10962   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10963                "    AnotherNameForTheLongType;");
10964   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10965                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10966   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10967                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10968   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10969                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10970   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10971                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10972   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10973                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10974   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10975                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10976   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10977                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10978   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10979                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10980   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10981                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10982   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10983                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10984   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10985                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10986   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10987                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10988   FormatStyle Indented = getLLVMStyle();
10989   Indented.IndentWrappedFunctionNames = true;
10990   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10991                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10992                Indented);
10993   verifyFormat(
10994       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10995       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10996       Indented);
10997   verifyFormat(
10998       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10999       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11000       Indented);
11001   verifyFormat(
11002       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
11003       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11004       Indented);
11005 
11006   // FIXME: Without the comment, this breaks after "(".
11007   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
11008                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
11009                getGoogleStyle());
11010 
11011   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
11012                "                  int LoooooooooooooooooooongParam2) {}");
11013   verifyFormat(
11014       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
11015       "                                   SourceLocation L, IdentifierIn *II,\n"
11016       "                                   Type *T) {}");
11017   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
11018                "ReallyReaaallyLongFunctionName(\n"
11019                "    const std::string &SomeParameter,\n"
11020                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11021                "        &ReallyReallyLongParameterName,\n"
11022                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11023                "        &AnotherLongParameterName) {}");
11024   verifyFormat("template <typename A>\n"
11025                "SomeLoooooooooooooooooooooongType<\n"
11026                "    typename some_namespace::SomeOtherType<A>::Type>\n"
11027                "Function() {}");
11028 
11029   verifyGoogleFormat(
11030       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
11031       "    aaaaaaaaaaaaaaaaaaaaaaa;");
11032   verifyGoogleFormat(
11033       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
11034       "                                   SourceLocation L) {}");
11035   verifyGoogleFormat(
11036       "some_namespace::LongReturnType\n"
11037       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
11038       "    int first_long_parameter, int second_parameter) {}");
11039 
11040   verifyGoogleFormat("template <typename T>\n"
11041                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11042                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
11043   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11044                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
11045 
11046   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
11047                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11048                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11049   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11050                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11051                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
11052   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11053                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
11054                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
11055                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11056 
11057   verifyFormat("template <typename T> // Templates on own line.\n"
11058                "static int            // Some comment.\n"
11059                "MyFunction(int a);",
11060                getLLVMStyle());
11061 }
11062 
11063 TEST_F(FormatTest, FormatsAccessModifiers) {
11064   FormatStyle Style = getLLVMStyle();
11065   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
11066             FormatStyle::ELBAMS_LogicalBlock);
11067   verifyFormat("struct foo {\n"
11068                "private:\n"
11069                "  void f() {}\n"
11070                "\n"
11071                "private:\n"
11072                "  int i;\n"
11073                "\n"
11074                "protected:\n"
11075                "  int j;\n"
11076                "};\n",
11077                Style);
11078   verifyFormat("struct foo {\n"
11079                "private:\n"
11080                "  void f() {}\n"
11081                "\n"
11082                "private:\n"
11083                "  int i;\n"
11084                "\n"
11085                "protected:\n"
11086                "  int j;\n"
11087                "};\n",
11088                "struct foo {\n"
11089                "private:\n"
11090                "  void f() {}\n"
11091                "private:\n"
11092                "  int i;\n"
11093                "protected:\n"
11094                "  int j;\n"
11095                "};\n",
11096                Style);
11097   verifyFormat("struct foo { /* comment */\n"
11098                "private:\n"
11099                "  int i;\n"
11100                "  // comment\n"
11101                "private:\n"
11102                "  int j;\n"
11103                "};\n",
11104                Style);
11105   verifyFormat("struct foo {\n"
11106                "#ifdef FOO\n"
11107                "#endif\n"
11108                "private:\n"
11109                "  int i;\n"
11110                "#ifdef FOO\n"
11111                "private:\n"
11112                "#endif\n"
11113                "  int j;\n"
11114                "};\n",
11115                Style);
11116   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11117   verifyFormat("struct foo {\n"
11118                "private:\n"
11119                "  void f() {}\n"
11120                "private:\n"
11121                "  int i;\n"
11122                "protected:\n"
11123                "  int j;\n"
11124                "};\n",
11125                Style);
11126   verifyFormat("struct foo {\n"
11127                "private:\n"
11128                "  void f() {}\n"
11129                "private:\n"
11130                "  int i;\n"
11131                "protected:\n"
11132                "  int j;\n"
11133                "};\n",
11134                "struct foo {\n"
11135                "\n"
11136                "private:\n"
11137                "  void f() {}\n"
11138                "\n"
11139                "private:\n"
11140                "  int i;\n"
11141                "\n"
11142                "protected:\n"
11143                "  int j;\n"
11144                "};\n",
11145                Style);
11146   verifyFormat("struct foo { /* comment */\n"
11147                "private:\n"
11148                "  int i;\n"
11149                "  // comment\n"
11150                "private:\n"
11151                "  int j;\n"
11152                "};\n",
11153                "struct foo { /* comment */\n"
11154                "\n"
11155                "private:\n"
11156                "  int i;\n"
11157                "  // comment\n"
11158                "\n"
11159                "private:\n"
11160                "  int j;\n"
11161                "};\n",
11162                Style);
11163   verifyFormat("struct foo {\n"
11164                "#ifdef FOO\n"
11165                "#endif\n"
11166                "private:\n"
11167                "  int i;\n"
11168                "#ifdef FOO\n"
11169                "private:\n"
11170                "#endif\n"
11171                "  int j;\n"
11172                "};\n",
11173                "struct foo {\n"
11174                "#ifdef FOO\n"
11175                "#endif\n"
11176                "\n"
11177                "private:\n"
11178                "  int i;\n"
11179                "#ifdef FOO\n"
11180                "\n"
11181                "private:\n"
11182                "#endif\n"
11183                "  int j;\n"
11184                "};\n",
11185                Style);
11186   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11187   verifyFormat("struct foo {\n"
11188                "private:\n"
11189                "  void f() {}\n"
11190                "\n"
11191                "private:\n"
11192                "  int i;\n"
11193                "\n"
11194                "protected:\n"
11195                "  int j;\n"
11196                "};\n",
11197                Style);
11198   verifyFormat("struct foo {\n"
11199                "private:\n"
11200                "  void f() {}\n"
11201                "\n"
11202                "private:\n"
11203                "  int i;\n"
11204                "\n"
11205                "protected:\n"
11206                "  int j;\n"
11207                "};\n",
11208                "struct foo {\n"
11209                "private:\n"
11210                "  void f() {}\n"
11211                "private:\n"
11212                "  int i;\n"
11213                "protected:\n"
11214                "  int j;\n"
11215                "};\n",
11216                Style);
11217   verifyFormat("struct foo { /* comment */\n"
11218                "private:\n"
11219                "  int i;\n"
11220                "  // comment\n"
11221                "\n"
11222                "private:\n"
11223                "  int j;\n"
11224                "};\n",
11225                "struct foo { /* comment */\n"
11226                "private:\n"
11227                "  int i;\n"
11228                "  // comment\n"
11229                "\n"
11230                "private:\n"
11231                "  int j;\n"
11232                "};\n",
11233                Style);
11234   verifyFormat("struct foo {\n"
11235                "#ifdef FOO\n"
11236                "#endif\n"
11237                "\n"
11238                "private:\n"
11239                "  int i;\n"
11240                "#ifdef FOO\n"
11241                "\n"
11242                "private:\n"
11243                "#endif\n"
11244                "  int j;\n"
11245                "};\n",
11246                "struct foo {\n"
11247                "#ifdef FOO\n"
11248                "#endif\n"
11249                "private:\n"
11250                "  int i;\n"
11251                "#ifdef FOO\n"
11252                "private:\n"
11253                "#endif\n"
11254                "  int j;\n"
11255                "};\n",
11256                Style);
11257   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11258   EXPECT_EQ("struct foo {\n"
11259             "\n"
11260             "private:\n"
11261             "  void f() {}\n"
11262             "\n"
11263             "private:\n"
11264             "  int i;\n"
11265             "\n"
11266             "protected:\n"
11267             "  int j;\n"
11268             "};\n",
11269             format("struct foo {\n"
11270                    "\n"
11271                    "private:\n"
11272                    "  void f() {}\n"
11273                    "\n"
11274                    "private:\n"
11275                    "  int i;\n"
11276                    "\n"
11277                    "protected:\n"
11278                    "  int j;\n"
11279                    "};\n",
11280                    Style));
11281   verifyFormat("struct foo {\n"
11282                "private:\n"
11283                "  void f() {}\n"
11284                "private:\n"
11285                "  int i;\n"
11286                "protected:\n"
11287                "  int j;\n"
11288                "};\n",
11289                Style);
11290   EXPECT_EQ("struct foo { /* comment */\n"
11291             "\n"
11292             "private:\n"
11293             "  int i;\n"
11294             "  // comment\n"
11295             "\n"
11296             "private:\n"
11297             "  int j;\n"
11298             "};\n",
11299             format("struct foo { /* comment */\n"
11300                    "\n"
11301                    "private:\n"
11302                    "  int i;\n"
11303                    "  // comment\n"
11304                    "\n"
11305                    "private:\n"
11306                    "  int j;\n"
11307                    "};\n",
11308                    Style));
11309   verifyFormat("struct foo { /* comment */\n"
11310                "private:\n"
11311                "  int i;\n"
11312                "  // comment\n"
11313                "private:\n"
11314                "  int j;\n"
11315                "};\n",
11316                Style);
11317   EXPECT_EQ("struct foo {\n"
11318             "#ifdef FOO\n"
11319             "#endif\n"
11320             "\n"
11321             "private:\n"
11322             "  int i;\n"
11323             "#ifdef FOO\n"
11324             "\n"
11325             "private:\n"
11326             "#endif\n"
11327             "  int j;\n"
11328             "};\n",
11329             format("struct foo {\n"
11330                    "#ifdef FOO\n"
11331                    "#endif\n"
11332                    "\n"
11333                    "private:\n"
11334                    "  int i;\n"
11335                    "#ifdef FOO\n"
11336                    "\n"
11337                    "private:\n"
11338                    "#endif\n"
11339                    "  int j;\n"
11340                    "};\n",
11341                    Style));
11342   verifyFormat("struct foo {\n"
11343                "#ifdef FOO\n"
11344                "#endif\n"
11345                "private:\n"
11346                "  int i;\n"
11347                "#ifdef FOO\n"
11348                "private:\n"
11349                "#endif\n"
11350                "  int j;\n"
11351                "};\n",
11352                Style);
11353 
11354   FormatStyle NoEmptyLines = getLLVMStyle();
11355   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11356   verifyFormat("struct foo {\n"
11357                "private:\n"
11358                "  void f() {}\n"
11359                "\n"
11360                "private:\n"
11361                "  int i;\n"
11362                "\n"
11363                "public:\n"
11364                "protected:\n"
11365                "  int j;\n"
11366                "};\n",
11367                NoEmptyLines);
11368 
11369   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11370   verifyFormat("struct foo {\n"
11371                "private:\n"
11372                "  void f() {}\n"
11373                "private:\n"
11374                "  int i;\n"
11375                "public:\n"
11376                "protected:\n"
11377                "  int j;\n"
11378                "};\n",
11379                NoEmptyLines);
11380 
11381   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11382   verifyFormat("struct foo {\n"
11383                "private:\n"
11384                "  void f() {}\n"
11385                "\n"
11386                "private:\n"
11387                "  int i;\n"
11388                "\n"
11389                "public:\n"
11390                "\n"
11391                "protected:\n"
11392                "  int j;\n"
11393                "};\n",
11394                NoEmptyLines);
11395 }
11396 
11397 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
11398 
11399   FormatStyle Style = getLLVMStyle();
11400   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
11401   verifyFormat("struct foo {\n"
11402                "private:\n"
11403                "  void f() {}\n"
11404                "\n"
11405                "private:\n"
11406                "  int i;\n"
11407                "\n"
11408                "protected:\n"
11409                "  int j;\n"
11410                "};\n",
11411                Style);
11412 
11413   // Check if lines are removed.
11414   verifyFormat("struct foo {\n"
11415                "private:\n"
11416                "  void f() {}\n"
11417                "\n"
11418                "private:\n"
11419                "  int i;\n"
11420                "\n"
11421                "protected:\n"
11422                "  int j;\n"
11423                "};\n",
11424                "struct foo {\n"
11425                "private:\n"
11426                "\n"
11427                "  void f() {}\n"
11428                "\n"
11429                "private:\n"
11430                "\n"
11431                "  int i;\n"
11432                "\n"
11433                "protected:\n"
11434                "\n"
11435                "  int j;\n"
11436                "};\n",
11437                Style);
11438 
11439   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11440   verifyFormat("struct foo {\n"
11441                "private:\n"
11442                "\n"
11443                "  void f() {}\n"
11444                "\n"
11445                "private:\n"
11446                "\n"
11447                "  int i;\n"
11448                "\n"
11449                "protected:\n"
11450                "\n"
11451                "  int j;\n"
11452                "};\n",
11453                Style);
11454 
11455   // Check if lines are added.
11456   verifyFormat("struct foo {\n"
11457                "private:\n"
11458                "\n"
11459                "  void f() {}\n"
11460                "\n"
11461                "private:\n"
11462                "\n"
11463                "  int i;\n"
11464                "\n"
11465                "protected:\n"
11466                "\n"
11467                "  int j;\n"
11468                "};\n",
11469                "struct foo {\n"
11470                "private:\n"
11471                "  void f() {}\n"
11472                "\n"
11473                "private:\n"
11474                "  int i;\n"
11475                "\n"
11476                "protected:\n"
11477                "  int j;\n"
11478                "};\n",
11479                Style);
11480 
11481   // Leave tests rely on the code layout, test::messUp can not be used.
11482   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11483   Style.MaxEmptyLinesToKeep = 0u;
11484   verifyFormat("struct foo {\n"
11485                "private:\n"
11486                "  void f() {}\n"
11487                "\n"
11488                "private:\n"
11489                "  int i;\n"
11490                "\n"
11491                "protected:\n"
11492                "  int j;\n"
11493                "};\n",
11494                Style);
11495 
11496   // Check if MaxEmptyLinesToKeep is respected.
11497   EXPECT_EQ("struct foo {\n"
11498             "private:\n"
11499             "  void f() {}\n"
11500             "\n"
11501             "private:\n"
11502             "  int i;\n"
11503             "\n"
11504             "protected:\n"
11505             "  int j;\n"
11506             "};\n",
11507             format("struct foo {\n"
11508                    "private:\n"
11509                    "\n\n\n"
11510                    "  void f() {}\n"
11511                    "\n"
11512                    "private:\n"
11513                    "\n\n\n"
11514                    "  int i;\n"
11515                    "\n"
11516                    "protected:\n"
11517                    "\n\n\n"
11518                    "  int j;\n"
11519                    "};\n",
11520                    Style));
11521 
11522   Style.MaxEmptyLinesToKeep = 1u;
11523   EXPECT_EQ("struct foo {\n"
11524             "private:\n"
11525             "\n"
11526             "  void f() {}\n"
11527             "\n"
11528             "private:\n"
11529             "\n"
11530             "  int i;\n"
11531             "\n"
11532             "protected:\n"
11533             "\n"
11534             "  int j;\n"
11535             "};\n",
11536             format("struct foo {\n"
11537                    "private:\n"
11538                    "\n"
11539                    "  void f() {}\n"
11540                    "\n"
11541                    "private:\n"
11542                    "\n"
11543                    "  int i;\n"
11544                    "\n"
11545                    "protected:\n"
11546                    "\n"
11547                    "  int j;\n"
11548                    "};\n",
11549                    Style));
11550   // Check if no lines are kept.
11551   EXPECT_EQ("struct foo {\n"
11552             "private:\n"
11553             "  void f() {}\n"
11554             "\n"
11555             "private:\n"
11556             "  int i;\n"
11557             "\n"
11558             "protected:\n"
11559             "  int j;\n"
11560             "};\n",
11561             format("struct foo {\n"
11562                    "private:\n"
11563                    "  void f() {}\n"
11564                    "\n"
11565                    "private:\n"
11566                    "  int i;\n"
11567                    "\n"
11568                    "protected:\n"
11569                    "  int j;\n"
11570                    "};\n",
11571                    Style));
11572   // Check if MaxEmptyLinesToKeep is respected.
11573   EXPECT_EQ("struct foo {\n"
11574             "private:\n"
11575             "\n"
11576             "  void f() {}\n"
11577             "\n"
11578             "private:\n"
11579             "\n"
11580             "  int i;\n"
11581             "\n"
11582             "protected:\n"
11583             "\n"
11584             "  int j;\n"
11585             "};\n",
11586             format("struct foo {\n"
11587                    "private:\n"
11588                    "\n\n\n"
11589                    "  void f() {}\n"
11590                    "\n"
11591                    "private:\n"
11592                    "\n\n\n"
11593                    "  int i;\n"
11594                    "\n"
11595                    "protected:\n"
11596                    "\n\n\n"
11597                    "  int j;\n"
11598                    "};\n",
11599                    Style));
11600 
11601   Style.MaxEmptyLinesToKeep = 10u;
11602   EXPECT_EQ("struct foo {\n"
11603             "private:\n"
11604             "\n\n\n"
11605             "  void f() {}\n"
11606             "\n"
11607             "private:\n"
11608             "\n\n\n"
11609             "  int i;\n"
11610             "\n"
11611             "protected:\n"
11612             "\n\n\n"
11613             "  int j;\n"
11614             "};\n",
11615             format("struct foo {\n"
11616                    "private:\n"
11617                    "\n\n\n"
11618                    "  void f() {}\n"
11619                    "\n"
11620                    "private:\n"
11621                    "\n\n\n"
11622                    "  int i;\n"
11623                    "\n"
11624                    "protected:\n"
11625                    "\n\n\n"
11626                    "  int j;\n"
11627                    "};\n",
11628                    Style));
11629 
11630   // Test with comments.
11631   Style = getLLVMStyle();
11632   verifyFormat("struct foo {\n"
11633                "private:\n"
11634                "  // comment\n"
11635                "  void f() {}\n"
11636                "\n"
11637                "private: /* comment */\n"
11638                "  int i;\n"
11639                "};\n",
11640                Style);
11641   verifyFormat("struct foo {\n"
11642                "private:\n"
11643                "  // comment\n"
11644                "  void f() {}\n"
11645                "\n"
11646                "private: /* comment */\n"
11647                "  int i;\n"
11648                "};\n",
11649                "struct foo {\n"
11650                "private:\n"
11651                "\n"
11652                "  // comment\n"
11653                "  void f() {}\n"
11654                "\n"
11655                "private: /* comment */\n"
11656                "\n"
11657                "  int i;\n"
11658                "};\n",
11659                Style);
11660 
11661   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11662   verifyFormat("struct foo {\n"
11663                "private:\n"
11664                "\n"
11665                "  // comment\n"
11666                "  void f() {}\n"
11667                "\n"
11668                "private: /* comment */\n"
11669                "\n"
11670                "  int i;\n"
11671                "};\n",
11672                "struct foo {\n"
11673                "private:\n"
11674                "  // comment\n"
11675                "  void f() {}\n"
11676                "\n"
11677                "private: /* comment */\n"
11678                "  int i;\n"
11679                "};\n",
11680                Style);
11681   verifyFormat("struct foo {\n"
11682                "private:\n"
11683                "\n"
11684                "  // comment\n"
11685                "  void f() {}\n"
11686                "\n"
11687                "private: /* comment */\n"
11688                "\n"
11689                "  int i;\n"
11690                "};\n",
11691                Style);
11692 
11693   // Test with preprocessor defines.
11694   Style = getLLVMStyle();
11695   verifyFormat("struct foo {\n"
11696                "private:\n"
11697                "#ifdef FOO\n"
11698                "#endif\n"
11699                "  void f() {}\n"
11700                "};\n",
11701                Style);
11702   verifyFormat("struct foo {\n"
11703                "private:\n"
11704                "#ifdef FOO\n"
11705                "#endif\n"
11706                "  void f() {}\n"
11707                "};\n",
11708                "struct foo {\n"
11709                "private:\n"
11710                "\n"
11711                "#ifdef FOO\n"
11712                "#endif\n"
11713                "  void f() {}\n"
11714                "};\n",
11715                Style);
11716 
11717   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11718   verifyFormat("struct foo {\n"
11719                "private:\n"
11720                "\n"
11721                "#ifdef FOO\n"
11722                "#endif\n"
11723                "  void f() {}\n"
11724                "};\n",
11725                "struct foo {\n"
11726                "private:\n"
11727                "#ifdef FOO\n"
11728                "#endif\n"
11729                "  void f() {}\n"
11730                "};\n",
11731                Style);
11732   verifyFormat("struct foo {\n"
11733                "private:\n"
11734                "\n"
11735                "#ifdef FOO\n"
11736                "#endif\n"
11737                "  void f() {}\n"
11738                "};\n",
11739                Style);
11740 }
11741 
11742 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11743   // Combined tests of EmptyLineAfterAccessModifier and
11744   // EmptyLineBeforeAccessModifier.
11745   FormatStyle Style = getLLVMStyle();
11746   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11747   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11748   verifyFormat("struct foo {\n"
11749                "private:\n"
11750                "\n"
11751                "protected:\n"
11752                "};\n",
11753                Style);
11754 
11755   Style.MaxEmptyLinesToKeep = 10u;
11756   // Both remove all new lines.
11757   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11758   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11759   verifyFormat("struct foo {\n"
11760                "private:\n"
11761                "protected:\n"
11762                "};\n",
11763                "struct foo {\n"
11764                "private:\n"
11765                "\n\n\n"
11766                "protected:\n"
11767                "};\n",
11768                Style);
11769 
11770   // Leave tests rely on the code layout, test::messUp can not be used.
11771   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11772   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11773   Style.MaxEmptyLinesToKeep = 10u;
11774   EXPECT_EQ("struct foo {\n"
11775             "private:\n"
11776             "\n\n\n"
11777             "protected:\n"
11778             "};\n",
11779             format("struct foo {\n"
11780                    "private:\n"
11781                    "\n\n\n"
11782                    "protected:\n"
11783                    "};\n",
11784                    Style));
11785   Style.MaxEmptyLinesToKeep = 3u;
11786   EXPECT_EQ("struct foo {\n"
11787             "private:\n"
11788             "\n\n\n"
11789             "protected:\n"
11790             "};\n",
11791             format("struct foo {\n"
11792                    "private:\n"
11793                    "\n\n\n"
11794                    "protected:\n"
11795                    "};\n",
11796                    Style));
11797   Style.MaxEmptyLinesToKeep = 1u;
11798   EXPECT_EQ("struct foo {\n"
11799             "private:\n"
11800             "\n\n\n"
11801             "protected:\n"
11802             "};\n",
11803             format("struct foo {\n"
11804                    "private:\n"
11805                    "\n\n\n"
11806                    "protected:\n"
11807                    "};\n",
11808                    Style)); // Based on new lines in original document and not
11809                             // on the setting.
11810 
11811   Style.MaxEmptyLinesToKeep = 10u;
11812   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11813   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11814   // Newlines are kept if they are greater than zero,
11815   // test::messUp removes all new lines which changes the logic
11816   EXPECT_EQ("struct foo {\n"
11817             "private:\n"
11818             "\n\n\n"
11819             "protected:\n"
11820             "};\n",
11821             format("struct foo {\n"
11822                    "private:\n"
11823                    "\n\n\n"
11824                    "protected:\n"
11825                    "};\n",
11826                    Style));
11827 
11828   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11829   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11830   // test::messUp removes all new lines which changes the logic
11831   EXPECT_EQ("struct foo {\n"
11832             "private:\n"
11833             "\n\n\n"
11834             "protected:\n"
11835             "};\n",
11836             format("struct foo {\n"
11837                    "private:\n"
11838                    "\n\n\n"
11839                    "protected:\n"
11840                    "};\n",
11841                    Style));
11842 
11843   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11844   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11845   EXPECT_EQ("struct foo {\n"
11846             "private:\n"
11847             "\n\n\n"
11848             "protected:\n"
11849             "};\n",
11850             format("struct foo {\n"
11851                    "private:\n"
11852                    "\n\n\n"
11853                    "protected:\n"
11854                    "};\n",
11855                    Style)); // test::messUp removes all new lines which changes
11856                             // the logic.
11857 
11858   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11859   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11860   verifyFormat("struct foo {\n"
11861                "private:\n"
11862                "protected:\n"
11863                "};\n",
11864                "struct foo {\n"
11865                "private:\n"
11866                "\n\n\n"
11867                "protected:\n"
11868                "};\n",
11869                Style);
11870 
11871   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11872   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11873   EXPECT_EQ("struct foo {\n"
11874             "private:\n"
11875             "\n\n\n"
11876             "protected:\n"
11877             "};\n",
11878             format("struct foo {\n"
11879                    "private:\n"
11880                    "\n\n\n"
11881                    "protected:\n"
11882                    "};\n",
11883                    Style)); // test::messUp removes all new lines which changes
11884                             // the logic.
11885 
11886   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11887   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11888   verifyFormat("struct foo {\n"
11889                "private:\n"
11890                "protected:\n"
11891                "};\n",
11892                "struct foo {\n"
11893                "private:\n"
11894                "\n\n\n"
11895                "protected:\n"
11896                "};\n",
11897                Style);
11898 
11899   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11900   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11901   verifyFormat("struct foo {\n"
11902                "private:\n"
11903                "protected:\n"
11904                "};\n",
11905                "struct foo {\n"
11906                "private:\n"
11907                "\n\n\n"
11908                "protected:\n"
11909                "};\n",
11910                Style);
11911 
11912   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11913   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11914   verifyFormat("struct foo {\n"
11915                "private:\n"
11916                "protected:\n"
11917                "};\n",
11918                "struct foo {\n"
11919                "private:\n"
11920                "\n\n\n"
11921                "protected:\n"
11922                "};\n",
11923                Style);
11924 
11925   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11926   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11927   verifyFormat("struct foo {\n"
11928                "private:\n"
11929                "protected:\n"
11930                "};\n",
11931                "struct foo {\n"
11932                "private:\n"
11933                "\n\n\n"
11934                "protected:\n"
11935                "};\n",
11936                Style);
11937 }
11938 
11939 TEST_F(FormatTest, FormatsArrays) {
11940   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11941                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11942   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11943                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11944   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11945                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11946   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11947                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11948   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11949                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11950   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11951                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11952                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11953   verifyFormat(
11954       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11955       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11956       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11957   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11958                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11959 
11960   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11961                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11962   verifyFormat(
11963       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11964       "                                  .aaaaaaa[0]\n"
11965       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11966   verifyFormat("a[::b::c];");
11967 
11968   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11969 
11970   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11971   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11972 }
11973 
11974 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11975   verifyFormat("(a)->b();");
11976   verifyFormat("--a;");
11977 }
11978 
11979 TEST_F(FormatTest, HandlesIncludeDirectives) {
11980   verifyFormat("#include <string>\n"
11981                "#include <a/b/c.h>\n"
11982                "#include \"a/b/string\"\n"
11983                "#include \"string.h\"\n"
11984                "#include \"string.h\"\n"
11985                "#include <a-a>\n"
11986                "#include < path with space >\n"
11987                "#include_next <test.h>"
11988                "#include \"abc.h\" // this is included for ABC\n"
11989                "#include \"some long include\" // with a comment\n"
11990                "#include \"some very long include path\"\n"
11991                "#include <some/very/long/include/path>\n",
11992                getLLVMStyleWithColumns(35));
11993   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11994   EXPECT_EQ("#include <a>", format("#include<a>"));
11995 
11996   verifyFormat("#import <string>");
11997   verifyFormat("#import <a/b/c.h>");
11998   verifyFormat("#import \"a/b/string\"");
11999   verifyFormat("#import \"string.h\"");
12000   verifyFormat("#import \"string.h\"");
12001   verifyFormat("#if __has_include(<strstream>)\n"
12002                "#include <strstream>\n"
12003                "#endif");
12004 
12005   verifyFormat("#define MY_IMPORT <a/b>");
12006 
12007   verifyFormat("#if __has_include(<a/b>)");
12008   verifyFormat("#if __has_include_next(<a/b>)");
12009   verifyFormat("#define F __has_include(<a/b>)");
12010   verifyFormat("#define F __has_include_next(<a/b>)");
12011 
12012   // Protocol buffer definition or missing "#".
12013   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
12014                getLLVMStyleWithColumns(30));
12015 
12016   FormatStyle Style = getLLVMStyle();
12017   Style.AlwaysBreakBeforeMultilineStrings = true;
12018   Style.ColumnLimit = 0;
12019   verifyFormat("#import \"abc.h\"", Style);
12020 
12021   // But 'import' might also be a regular C++ namespace.
12022   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12023                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
12024 }
12025 
12026 //===----------------------------------------------------------------------===//
12027 // Error recovery tests.
12028 //===----------------------------------------------------------------------===//
12029 
12030 TEST_F(FormatTest, IncompleteParameterLists) {
12031   FormatStyle NoBinPacking = getLLVMStyle();
12032   NoBinPacking.BinPackParameters = false;
12033   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
12034                "                        double *min_x,\n"
12035                "                        double *max_x,\n"
12036                "                        double *min_y,\n"
12037                "                        double *max_y,\n"
12038                "                        double *min_z,\n"
12039                "                        double *max_z, ) {}",
12040                NoBinPacking);
12041 }
12042 
12043 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
12044   verifyFormat("void f() { return; }\n42");
12045   verifyFormat("void f() {\n"
12046                "  if (0)\n"
12047                "    return;\n"
12048                "}\n"
12049                "42");
12050   verifyFormat("void f() { return }\n42");
12051   verifyFormat("void f() {\n"
12052                "  if (0)\n"
12053                "    return\n"
12054                "}\n"
12055                "42");
12056 }
12057 
12058 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
12059   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
12060   EXPECT_EQ("void f() {\n"
12061             "  if (a)\n"
12062             "    return\n"
12063             "}",
12064             format("void  f  (  )  {  if  ( a )  return  }"));
12065   EXPECT_EQ("namespace N {\n"
12066             "void f()\n"
12067             "}",
12068             format("namespace  N  {  void f()  }"));
12069   EXPECT_EQ("namespace N {\n"
12070             "void f() {}\n"
12071             "void g()\n"
12072             "} // namespace N",
12073             format("namespace N  { void f( ) { } void g( ) }"));
12074 }
12075 
12076 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
12077   verifyFormat("int aaaaaaaa =\n"
12078                "    // Overlylongcomment\n"
12079                "    b;",
12080                getLLVMStyleWithColumns(20));
12081   verifyFormat("function(\n"
12082                "    ShortArgument,\n"
12083                "    LoooooooooooongArgument);\n",
12084                getLLVMStyleWithColumns(20));
12085 }
12086 
12087 TEST_F(FormatTest, IncorrectAccessSpecifier) {
12088   verifyFormat("public:");
12089   verifyFormat("class A {\n"
12090                "public\n"
12091                "  void f() {}\n"
12092                "};");
12093   verifyFormat("public\n"
12094                "int qwerty;");
12095   verifyFormat("public\n"
12096                "B {}");
12097   verifyFormat("public\n"
12098                "{}");
12099   verifyFormat("public\n"
12100                "B { int x; }");
12101 }
12102 
12103 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
12104   verifyFormat("{");
12105   verifyFormat("#})");
12106   verifyNoCrash("(/**/[:!] ?[).");
12107 }
12108 
12109 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
12110   // Found by oss-fuzz:
12111   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
12112   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
12113   Style.ColumnLimit = 60;
12114   verifyNoCrash(
12115       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
12116       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
12117       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
12118       Style);
12119 }
12120 
12121 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
12122   verifyFormat("do {\n}");
12123   verifyFormat("do {\n}\n"
12124                "f();");
12125   verifyFormat("do {\n}\n"
12126                "wheeee(fun);");
12127   verifyFormat("do {\n"
12128                "  f();\n"
12129                "}");
12130 }
12131 
12132 TEST_F(FormatTest, IncorrectCodeMissingParens) {
12133   verifyFormat("if {\n  foo;\n  foo();\n}");
12134   verifyFormat("switch {\n  foo;\n  foo();\n}");
12135   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
12136   verifyIncompleteFormat("ERROR: for target;");
12137   verifyFormat("while {\n  foo;\n  foo();\n}");
12138   verifyFormat("do {\n  foo;\n  foo();\n} while;");
12139 }
12140 
12141 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
12142   verifyIncompleteFormat("namespace {\n"
12143                          "class Foo { Foo (\n"
12144                          "};\n"
12145                          "} // namespace");
12146 }
12147 
12148 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
12149   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
12150   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
12151   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
12152   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
12153 
12154   EXPECT_EQ("{\n"
12155             "  {\n"
12156             "    breakme(\n"
12157             "        qwe);\n"
12158             "  }\n",
12159             format("{\n"
12160                    "    {\n"
12161                    " breakme(qwe);\n"
12162                    "}\n",
12163                    getLLVMStyleWithColumns(10)));
12164 }
12165 
12166 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
12167   verifyFormat("int x = {\n"
12168                "    avariable,\n"
12169                "    b(alongervariable)};",
12170                getLLVMStyleWithColumns(25));
12171 }
12172 
12173 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
12174   verifyFormat("return (a)(b){1, 2, 3};");
12175 }
12176 
12177 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
12178   verifyFormat("vector<int> x{1, 2, 3, 4};");
12179   verifyFormat("vector<int> x{\n"
12180                "    1,\n"
12181                "    2,\n"
12182                "    3,\n"
12183                "    4,\n"
12184                "};");
12185   verifyFormat("vector<T> x{{}, {}, {}, {}};");
12186   verifyFormat("f({1, 2});");
12187   verifyFormat("auto v = Foo{-1};");
12188   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
12189   verifyFormat("Class::Class : member{1, 2, 3} {}");
12190   verifyFormat("new vector<int>{1, 2, 3};");
12191   verifyFormat("new int[3]{1, 2, 3};");
12192   verifyFormat("new int{1};");
12193   verifyFormat("return {arg1, arg2};");
12194   verifyFormat("return {arg1, SomeType{parameter}};");
12195   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
12196   verifyFormat("new T{arg1, arg2};");
12197   verifyFormat("f(MyMap[{composite, key}]);");
12198   verifyFormat("class Class {\n"
12199                "  T member = {arg1, arg2};\n"
12200                "};");
12201   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
12202   verifyFormat("const struct A a = {.a = 1, .b = 2};");
12203   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
12204   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
12205   verifyFormat("int a = std::is_integral<int>{} + 0;");
12206 
12207   verifyFormat("int foo(int i) { return fo1{}(i); }");
12208   verifyFormat("int foo(int i) { return fo1{}(i); }");
12209   verifyFormat("auto i = decltype(x){};");
12210   verifyFormat("auto i = typeof(x){};");
12211   verifyFormat("auto i = _Atomic(x){};");
12212   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
12213   verifyFormat("Node n{1, Node{1000}, //\n"
12214                "       2};");
12215   verifyFormat("Aaaa aaaaaaa{\n"
12216                "    {\n"
12217                "        aaaa,\n"
12218                "    },\n"
12219                "};");
12220   verifyFormat("class C : public D {\n"
12221                "  SomeClass SC{2};\n"
12222                "};");
12223   verifyFormat("class C : public A {\n"
12224                "  class D : public B {\n"
12225                "    void f() { int i{2}; }\n"
12226                "  };\n"
12227                "};");
12228   verifyFormat("#define A {a, a},");
12229   // Don't confuse braced list initializers with compound statements.
12230   verifyFormat(
12231       "class A {\n"
12232       "  A() : a{} {}\n"
12233       "  A(int b) : b(b) {}\n"
12234       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
12235       "  int a, b;\n"
12236       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
12237       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
12238       "{}\n"
12239       "};");
12240 
12241   // Avoid breaking between equal sign and opening brace
12242   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
12243   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
12244   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
12245                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
12246                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
12247                "     {\"ccccccccccccccccccccc\", 2}};",
12248                AvoidBreakingFirstArgument);
12249 
12250   // Binpacking only if there is no trailing comma
12251   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
12252                "                      cccccccccc, dddddddddd};",
12253                getLLVMStyleWithColumns(50));
12254   verifyFormat("const Aaaaaa aaaaa = {\n"
12255                "    aaaaaaaaaaa,\n"
12256                "    bbbbbbbbbbb,\n"
12257                "    ccccccccccc,\n"
12258                "    ddddddddddd,\n"
12259                "};",
12260                getLLVMStyleWithColumns(50));
12261 
12262   // Cases where distinguising braced lists and blocks is hard.
12263   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
12264   verifyFormat("void f() {\n"
12265                "  return; // comment\n"
12266                "}\n"
12267                "SomeType t;");
12268   verifyFormat("void f() {\n"
12269                "  if (a) {\n"
12270                "    f();\n"
12271                "  }\n"
12272                "}\n"
12273                "SomeType t;");
12274 
12275   // In combination with BinPackArguments = false.
12276   FormatStyle NoBinPacking = getLLVMStyle();
12277   NoBinPacking.BinPackArguments = false;
12278   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
12279                "                      bbbbb,\n"
12280                "                      ccccc,\n"
12281                "                      ddddd,\n"
12282                "                      eeeee,\n"
12283                "                      ffffff,\n"
12284                "                      ggggg,\n"
12285                "                      hhhhhh,\n"
12286                "                      iiiiii,\n"
12287                "                      jjjjjj,\n"
12288                "                      kkkkkk};",
12289                NoBinPacking);
12290   verifyFormat("const Aaaaaa aaaaa = {\n"
12291                "    aaaaa,\n"
12292                "    bbbbb,\n"
12293                "    ccccc,\n"
12294                "    ddddd,\n"
12295                "    eeeee,\n"
12296                "    ffffff,\n"
12297                "    ggggg,\n"
12298                "    hhhhhh,\n"
12299                "    iiiiii,\n"
12300                "    jjjjjj,\n"
12301                "    kkkkkk,\n"
12302                "};",
12303                NoBinPacking);
12304   verifyFormat(
12305       "const Aaaaaa aaaaa = {\n"
12306       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
12307       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
12308       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
12309       "};",
12310       NoBinPacking);
12311 
12312   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12313   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
12314             "    CDDDP83848_BMCR_REGISTER,\n"
12315             "    CDDDP83848_BMSR_REGISTER,\n"
12316             "    CDDDP83848_RBR_REGISTER};",
12317             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
12318                    "                                CDDDP83848_BMSR_REGISTER,\n"
12319                    "                                CDDDP83848_RBR_REGISTER};",
12320                    NoBinPacking));
12321 
12322   // FIXME: The alignment of these trailing comments might be bad. Then again,
12323   // this might be utterly useless in real code.
12324   verifyFormat("Constructor::Constructor()\n"
12325                "    : some_value{         //\n"
12326                "                 aaaaaaa, //\n"
12327                "                 bbbbbbb} {}");
12328 
12329   // In braced lists, the first comment is always assumed to belong to the
12330   // first element. Thus, it can be moved to the next or previous line as
12331   // appropriate.
12332   EXPECT_EQ("function({// First element:\n"
12333             "          1,\n"
12334             "          // Second element:\n"
12335             "          2});",
12336             format("function({\n"
12337                    "    // First element:\n"
12338                    "    1,\n"
12339                    "    // Second element:\n"
12340                    "    2});"));
12341   EXPECT_EQ("std::vector<int> MyNumbers{\n"
12342             "    // First element:\n"
12343             "    1,\n"
12344             "    // Second element:\n"
12345             "    2};",
12346             format("std::vector<int> MyNumbers{// First element:\n"
12347                    "                           1,\n"
12348                    "                           // Second element:\n"
12349                    "                           2};",
12350                    getLLVMStyleWithColumns(30)));
12351   // A trailing comma should still lead to an enforced line break and no
12352   // binpacking.
12353   EXPECT_EQ("vector<int> SomeVector = {\n"
12354             "    // aaa\n"
12355             "    1,\n"
12356             "    2,\n"
12357             "};",
12358             format("vector<int> SomeVector = { // aaa\n"
12359                    "    1, 2, };"));
12360 
12361   // C++11 brace initializer list l-braces should not be treated any differently
12362   // when breaking before lambda bodies is enabled
12363   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
12364   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
12365   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
12366   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
12367   verifyFormat(
12368       "std::runtime_error{\n"
12369       "    \"Long string which will force a break onto the next line...\"};",
12370       BreakBeforeLambdaBody);
12371 
12372   FormatStyle ExtraSpaces = getLLVMStyle();
12373   ExtraSpaces.Cpp11BracedListStyle = false;
12374   ExtraSpaces.ColumnLimit = 75;
12375   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
12376   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
12377   verifyFormat("f({ 1, 2 });", ExtraSpaces);
12378   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
12379   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
12380   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
12381   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
12382   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
12383   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
12384   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
12385   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
12386   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
12387   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
12388   verifyFormat("class Class {\n"
12389                "  T member = { arg1, arg2 };\n"
12390                "};",
12391                ExtraSpaces);
12392   verifyFormat(
12393       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12394       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
12395       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
12396       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
12397       ExtraSpaces);
12398   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
12399   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
12400                ExtraSpaces);
12401   verifyFormat(
12402       "someFunction(OtherParam,\n"
12403       "             BracedList{ // comment 1 (Forcing interesting break)\n"
12404       "                         param1, param2,\n"
12405       "                         // comment 2\n"
12406       "                         param3, param4 });",
12407       ExtraSpaces);
12408   verifyFormat(
12409       "std::this_thread::sleep_for(\n"
12410       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
12411       ExtraSpaces);
12412   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
12413                "    aaaaaaa,\n"
12414                "    aaaaaaaaaa,\n"
12415                "    aaaaa,\n"
12416                "    aaaaaaaaaaaaaaa,\n"
12417                "    aaa,\n"
12418                "    aaaaaaaaaa,\n"
12419                "    a,\n"
12420                "    aaaaaaaaaaaaaaaaaaaaa,\n"
12421                "    aaaaaaaaaaaa,\n"
12422                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
12423                "    aaaaaaa,\n"
12424                "    a};");
12425   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
12426   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
12427   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
12428 
12429   // Avoid breaking between initializer/equal sign and opening brace
12430   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
12431   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
12432                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12433                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12434                "  { \"ccccccccccccccccccccc\", 2 }\n"
12435                "};",
12436                ExtraSpaces);
12437   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
12438                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12439                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12440                "  { \"ccccccccccccccccccccc\", 2 }\n"
12441                "};",
12442                ExtraSpaces);
12443 
12444   FormatStyle SpaceBeforeBrace = getLLVMStyle();
12445   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
12446   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
12447   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
12448 
12449   FormatStyle SpaceBetweenBraces = getLLVMStyle();
12450   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
12451   SpaceBetweenBraces.SpacesInParentheses = true;
12452   SpaceBetweenBraces.SpacesInSquareBrackets = true;
12453   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
12454   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
12455   verifyFormat("vector< int > x{ // comment 1\n"
12456                "                 1, 2, 3, 4 };",
12457                SpaceBetweenBraces);
12458   SpaceBetweenBraces.ColumnLimit = 20;
12459   EXPECT_EQ("vector< int > x{\n"
12460             "    1, 2, 3, 4 };",
12461             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12462   SpaceBetweenBraces.ColumnLimit = 24;
12463   EXPECT_EQ("vector< int > x{ 1, 2,\n"
12464             "                 3, 4 };",
12465             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12466   EXPECT_EQ("vector< int > x{\n"
12467             "    1,\n"
12468             "    2,\n"
12469             "    3,\n"
12470             "    4,\n"
12471             "};",
12472             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12473   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12474   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12475   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12476 }
12477 
12478 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12479   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12480                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12481                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12482                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12483                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12484                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12485   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12486                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12487                "                 1, 22, 333, 4444, 55555, //\n"
12488                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12489                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12490   verifyFormat(
12491       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12492       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12493       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12494       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12495       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12496       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12497       "                 7777777};");
12498   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12499                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12500                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12501   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12502                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12503                "    // Separating comment.\n"
12504                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12505   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12506                "    // Leading comment\n"
12507                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12508                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12509   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12510                "                 1, 1, 1, 1};",
12511                getLLVMStyleWithColumns(39));
12512   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12513                "                 1, 1, 1, 1};",
12514                getLLVMStyleWithColumns(38));
12515   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12516                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12517                getLLVMStyleWithColumns(43));
12518   verifyFormat(
12519       "static unsigned SomeValues[10][3] = {\n"
12520       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12521       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12522   verifyFormat("static auto fields = new vector<string>{\n"
12523                "    \"aaaaaaaaaaaaa\",\n"
12524                "    \"aaaaaaaaaaaaa\",\n"
12525                "    \"aaaaaaaaaaaa\",\n"
12526                "    \"aaaaaaaaaaaaaa\",\n"
12527                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12528                "    \"aaaaaaaaaaaa\",\n"
12529                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12530                "};");
12531   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12532   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12533                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12534                "                 3, cccccccccccccccccccccc};",
12535                getLLVMStyleWithColumns(60));
12536 
12537   // Trailing commas.
12538   verifyFormat("vector<int> x = {\n"
12539                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12540                "};",
12541                getLLVMStyleWithColumns(39));
12542   verifyFormat("vector<int> x = {\n"
12543                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12544                "};",
12545                getLLVMStyleWithColumns(39));
12546   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12547                "                 1, 1, 1, 1,\n"
12548                "                 /**/ /**/};",
12549                getLLVMStyleWithColumns(39));
12550 
12551   // Trailing comment in the first line.
12552   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12553                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12554                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12555                "    11111111,   22222222,   333333333,   44444444};");
12556   // Trailing comment in the last line.
12557   verifyFormat("int aaaaa[] = {\n"
12558                "    1, 2, 3, // comment\n"
12559                "    4, 5, 6  // comment\n"
12560                "};");
12561 
12562   // With nested lists, we should either format one item per line or all nested
12563   // lists one on line.
12564   // FIXME: For some nested lists, we can do better.
12565   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12566                "        {aaaaaaaaaaaaaaaaaaa},\n"
12567                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12568                "        {aaaaaaaaaaaaaaaaa}};",
12569                getLLVMStyleWithColumns(60));
12570   verifyFormat(
12571       "SomeStruct my_struct_array = {\n"
12572       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12573       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12574       "    {aaa, aaa},\n"
12575       "    {aaa, aaa},\n"
12576       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12577       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12578       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12579 
12580   // No column layout should be used here.
12581   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12582                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12583 
12584   verifyNoCrash("a<,");
12585 
12586   // No braced initializer here.
12587   verifyFormat("void f() {\n"
12588                "  struct Dummy {};\n"
12589                "  f(v);\n"
12590                "}");
12591 
12592   // Long lists should be formatted in columns even if they are nested.
12593   verifyFormat(
12594       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12595       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12596       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12597       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12598       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12599       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12600 
12601   // Allow "single-column" layout even if that violates the column limit. There
12602   // isn't going to be a better way.
12603   verifyFormat("std::vector<int> a = {\n"
12604                "    aaaaaaaa,\n"
12605                "    aaaaaaaa,\n"
12606                "    aaaaaaaa,\n"
12607                "    aaaaaaaa,\n"
12608                "    aaaaaaaaaa,\n"
12609                "    aaaaaaaa,\n"
12610                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12611                getLLVMStyleWithColumns(30));
12612   verifyFormat("vector<int> aaaa = {\n"
12613                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12614                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12615                "    aaaaaa.aaaaaaa,\n"
12616                "    aaaaaa.aaaaaaa,\n"
12617                "    aaaaaa.aaaaaaa,\n"
12618                "    aaaaaa.aaaaaaa,\n"
12619                "};");
12620 
12621   // Don't create hanging lists.
12622   verifyFormat("someFunction(Param, {List1, List2,\n"
12623                "                     List3});",
12624                getLLVMStyleWithColumns(35));
12625   verifyFormat("someFunction(Param, Param,\n"
12626                "             {List1, List2,\n"
12627                "              List3});",
12628                getLLVMStyleWithColumns(35));
12629   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12630                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12631 }
12632 
12633 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12634   FormatStyle DoNotMerge = getLLVMStyle();
12635   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12636 
12637   verifyFormat("void f() { return 42; }");
12638   verifyFormat("void f() {\n"
12639                "  return 42;\n"
12640                "}",
12641                DoNotMerge);
12642   verifyFormat("void f() {\n"
12643                "  // Comment\n"
12644                "}");
12645   verifyFormat("{\n"
12646                "#error {\n"
12647                "  int a;\n"
12648                "}");
12649   verifyFormat("{\n"
12650                "  int a;\n"
12651                "#error {\n"
12652                "}");
12653   verifyFormat("void f() {} // comment");
12654   verifyFormat("void f() { int a; } // comment");
12655   verifyFormat("void f() {\n"
12656                "} // comment",
12657                DoNotMerge);
12658   verifyFormat("void f() {\n"
12659                "  int a;\n"
12660                "} // comment",
12661                DoNotMerge);
12662   verifyFormat("void f() {\n"
12663                "} // comment",
12664                getLLVMStyleWithColumns(15));
12665 
12666   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12667   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12668 
12669   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12670   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12671   verifyFormat("class C {\n"
12672                "  C()\n"
12673                "      : iiiiiiii(nullptr),\n"
12674                "        kkkkkkk(nullptr),\n"
12675                "        mmmmmmm(nullptr),\n"
12676                "        nnnnnnn(nullptr) {}\n"
12677                "};",
12678                getGoogleStyle());
12679 
12680   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12681   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12682   EXPECT_EQ("class C {\n"
12683             "  A() : b(0) {}\n"
12684             "};",
12685             format("class C{A():b(0){}};", NoColumnLimit));
12686   EXPECT_EQ("A()\n"
12687             "    : b(0) {\n"
12688             "}",
12689             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12690 
12691   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12692   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12693       FormatStyle::SFS_None;
12694   EXPECT_EQ("A()\n"
12695             "    : b(0) {\n"
12696             "}",
12697             format("A():b(0){}", DoNotMergeNoColumnLimit));
12698   EXPECT_EQ("A()\n"
12699             "    : b(0) {\n"
12700             "}",
12701             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12702 
12703   verifyFormat("#define A          \\\n"
12704                "  void f() {       \\\n"
12705                "    int i;         \\\n"
12706                "  }",
12707                getLLVMStyleWithColumns(20));
12708   verifyFormat("#define A           \\\n"
12709                "  void f() { int i; }",
12710                getLLVMStyleWithColumns(21));
12711   verifyFormat("#define A            \\\n"
12712                "  void f() {         \\\n"
12713                "    int i;           \\\n"
12714                "  }                  \\\n"
12715                "  int j;",
12716                getLLVMStyleWithColumns(22));
12717   verifyFormat("#define A             \\\n"
12718                "  void f() { int i; } \\\n"
12719                "  int j;",
12720                getLLVMStyleWithColumns(23));
12721 }
12722 
12723 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12724   FormatStyle MergeEmptyOnly = getLLVMStyle();
12725   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12726   verifyFormat("class C {\n"
12727                "  int f() {}\n"
12728                "};",
12729                MergeEmptyOnly);
12730   verifyFormat("class C {\n"
12731                "  int f() {\n"
12732                "    return 42;\n"
12733                "  }\n"
12734                "};",
12735                MergeEmptyOnly);
12736   verifyFormat("int f() {}", MergeEmptyOnly);
12737   verifyFormat("int f() {\n"
12738                "  return 42;\n"
12739                "}",
12740                MergeEmptyOnly);
12741 
12742   // Also verify behavior when BraceWrapping.AfterFunction = true
12743   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12744   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12745   verifyFormat("int f() {}", MergeEmptyOnly);
12746   verifyFormat("class C {\n"
12747                "  int f() {}\n"
12748                "};",
12749                MergeEmptyOnly);
12750 }
12751 
12752 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12753   FormatStyle MergeInlineOnly = getLLVMStyle();
12754   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12755   verifyFormat("class C {\n"
12756                "  int f() { return 42; }\n"
12757                "};",
12758                MergeInlineOnly);
12759   verifyFormat("int f() {\n"
12760                "  return 42;\n"
12761                "}",
12762                MergeInlineOnly);
12763 
12764   // SFS_Inline implies SFS_Empty
12765   verifyFormat("class C {\n"
12766                "  int f() {}\n"
12767                "};",
12768                MergeInlineOnly);
12769   verifyFormat("int f() {}", MergeInlineOnly);
12770   // https://llvm.org/PR54147
12771   verifyFormat("auto lambda = []() {\n"
12772                "  // comment\n"
12773                "  f();\n"
12774                "  g();\n"
12775                "};",
12776                MergeInlineOnly);
12777 
12778   verifyFormat("class C {\n"
12779                "#ifdef A\n"
12780                "  int f() { return 42; }\n"
12781                "#endif\n"
12782                "};",
12783                MergeInlineOnly);
12784 
12785   verifyFormat("struct S {\n"
12786                "// comment\n"
12787                "#ifdef FOO\n"
12788                "  int foo() { bar(); }\n"
12789                "#endif\n"
12790                "};",
12791                MergeInlineOnly);
12792 
12793   // Also verify behavior when BraceWrapping.AfterFunction = true
12794   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12795   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12796   verifyFormat("class C {\n"
12797                "  int f() { return 42; }\n"
12798                "};",
12799                MergeInlineOnly);
12800   verifyFormat("int f()\n"
12801                "{\n"
12802                "  return 42;\n"
12803                "}",
12804                MergeInlineOnly);
12805 
12806   // SFS_Inline implies SFS_Empty
12807   verifyFormat("int f() {}", MergeInlineOnly);
12808   verifyFormat("class C {\n"
12809                "  int f() {}\n"
12810                "};",
12811                MergeInlineOnly);
12812 
12813   MergeInlineOnly.BraceWrapping.AfterClass = true;
12814   MergeInlineOnly.BraceWrapping.AfterStruct = true;
12815   verifyFormat("class C\n"
12816                "{\n"
12817                "  int f() { return 42; }\n"
12818                "};",
12819                MergeInlineOnly);
12820   verifyFormat("struct C\n"
12821                "{\n"
12822                "  int f() { return 42; }\n"
12823                "};",
12824                MergeInlineOnly);
12825   verifyFormat("int f()\n"
12826                "{\n"
12827                "  return 42;\n"
12828                "}",
12829                MergeInlineOnly);
12830   verifyFormat("int f() {}", MergeInlineOnly);
12831   verifyFormat("class C\n"
12832                "{\n"
12833                "  int f() { return 42; }\n"
12834                "};",
12835                MergeInlineOnly);
12836   verifyFormat("struct C\n"
12837                "{\n"
12838                "  int f() { return 42; }\n"
12839                "};",
12840                MergeInlineOnly);
12841   verifyFormat("struct C\n"
12842                "// comment\n"
12843                "/* comment */\n"
12844                "// comment\n"
12845                "{\n"
12846                "  int f() { return 42; }\n"
12847                "};",
12848                MergeInlineOnly);
12849   verifyFormat("/* comment */ struct C\n"
12850                "{\n"
12851                "  int f() { return 42; }\n"
12852                "};",
12853                MergeInlineOnly);
12854 }
12855 
12856 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12857   FormatStyle MergeInlineOnly = getLLVMStyle();
12858   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12859       FormatStyle::SFS_InlineOnly;
12860   verifyFormat("class C {\n"
12861                "  int f() { return 42; }\n"
12862                "};",
12863                MergeInlineOnly);
12864   verifyFormat("int f() {\n"
12865                "  return 42;\n"
12866                "}",
12867                MergeInlineOnly);
12868 
12869   // SFS_InlineOnly does not imply SFS_Empty
12870   verifyFormat("class C {\n"
12871                "  int f() {}\n"
12872                "};",
12873                MergeInlineOnly);
12874   verifyFormat("int f() {\n"
12875                "}",
12876                MergeInlineOnly);
12877 
12878   // Also verify behavior when BraceWrapping.AfterFunction = true
12879   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12880   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12881   verifyFormat("class C {\n"
12882                "  int f() { return 42; }\n"
12883                "};",
12884                MergeInlineOnly);
12885   verifyFormat("int f()\n"
12886                "{\n"
12887                "  return 42;\n"
12888                "}",
12889                MergeInlineOnly);
12890 
12891   // SFS_InlineOnly does not imply SFS_Empty
12892   verifyFormat("int f()\n"
12893                "{\n"
12894                "}",
12895                MergeInlineOnly);
12896   verifyFormat("class C {\n"
12897                "  int f() {}\n"
12898                "};",
12899                MergeInlineOnly);
12900 }
12901 
12902 TEST_F(FormatTest, SplitEmptyFunction) {
12903   FormatStyle Style = getLLVMStyleWithColumns(40);
12904   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12905   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12906   Style.BraceWrapping.AfterFunction = true;
12907   Style.BraceWrapping.SplitEmptyFunction = false;
12908 
12909   verifyFormat("int f()\n"
12910                "{}",
12911                Style);
12912   verifyFormat("int f()\n"
12913                "{\n"
12914                "  return 42;\n"
12915                "}",
12916                Style);
12917   verifyFormat("int f()\n"
12918                "{\n"
12919                "  // some comment\n"
12920                "}",
12921                Style);
12922 
12923   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12924   verifyFormat("int f() {}", Style);
12925   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12926                "{}",
12927                Style);
12928   verifyFormat("int f()\n"
12929                "{\n"
12930                "  return 0;\n"
12931                "}",
12932                Style);
12933 
12934   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12935   verifyFormat("class Foo {\n"
12936                "  int f() {}\n"
12937                "};\n",
12938                Style);
12939   verifyFormat("class Foo {\n"
12940                "  int f() { return 0; }\n"
12941                "};\n",
12942                Style);
12943   verifyFormat("class Foo {\n"
12944                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12945                "  {}\n"
12946                "};\n",
12947                Style);
12948   verifyFormat("class Foo {\n"
12949                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12950                "  {\n"
12951                "    return 0;\n"
12952                "  }\n"
12953                "};\n",
12954                Style);
12955 
12956   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12957   verifyFormat("int f() {}", Style);
12958   verifyFormat("int f() { return 0; }", Style);
12959   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12960                "{}",
12961                Style);
12962   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12963                "{\n"
12964                "  return 0;\n"
12965                "}",
12966                Style);
12967 }
12968 
12969 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12970   FormatStyle Style = getLLVMStyleWithColumns(40);
12971   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12972   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12973   Style.BraceWrapping.AfterFunction = true;
12974   Style.BraceWrapping.SplitEmptyFunction = true;
12975   Style.BraceWrapping.SplitEmptyRecord = false;
12976 
12977   verifyFormat("class C {};", Style);
12978   verifyFormat("struct C {};", Style);
12979   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12980                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12981                "{\n"
12982                "}",
12983                Style);
12984   verifyFormat("class C {\n"
12985                "  C()\n"
12986                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12987                "        bbbbbbbbbbbbbbbbbbb()\n"
12988                "  {\n"
12989                "  }\n"
12990                "  void\n"
12991                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12992                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12993                "  {\n"
12994                "  }\n"
12995                "};",
12996                Style);
12997 }
12998 
12999 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
13000   FormatStyle Style = getLLVMStyle();
13001   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
13002   verifyFormat("#ifdef A\n"
13003                "int f() {}\n"
13004                "#else\n"
13005                "int g() {}\n"
13006                "#endif",
13007                Style);
13008 }
13009 
13010 TEST_F(FormatTest, SplitEmptyClass) {
13011   FormatStyle Style = getLLVMStyle();
13012   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13013   Style.BraceWrapping.AfterClass = true;
13014   Style.BraceWrapping.SplitEmptyRecord = false;
13015 
13016   verifyFormat("class Foo\n"
13017                "{};",
13018                Style);
13019   verifyFormat("/* something */ class Foo\n"
13020                "{};",
13021                Style);
13022   verifyFormat("template <typename X> class Foo\n"
13023                "{};",
13024                Style);
13025   verifyFormat("class Foo\n"
13026                "{\n"
13027                "  Foo();\n"
13028                "};",
13029                Style);
13030   verifyFormat("typedef class Foo\n"
13031                "{\n"
13032                "} Foo_t;",
13033                Style);
13034 
13035   Style.BraceWrapping.SplitEmptyRecord = true;
13036   Style.BraceWrapping.AfterStruct = true;
13037   verifyFormat("class rep\n"
13038                "{\n"
13039                "};",
13040                Style);
13041   verifyFormat("struct rep\n"
13042                "{\n"
13043                "};",
13044                Style);
13045   verifyFormat("template <typename T> class rep\n"
13046                "{\n"
13047                "};",
13048                Style);
13049   verifyFormat("template <typename T> struct rep\n"
13050                "{\n"
13051                "};",
13052                Style);
13053   verifyFormat("class rep\n"
13054                "{\n"
13055                "  int x;\n"
13056                "};",
13057                Style);
13058   verifyFormat("struct rep\n"
13059                "{\n"
13060                "  int x;\n"
13061                "};",
13062                Style);
13063   verifyFormat("template <typename T> class rep\n"
13064                "{\n"
13065                "  int x;\n"
13066                "};",
13067                Style);
13068   verifyFormat("template <typename T> struct rep\n"
13069                "{\n"
13070                "  int x;\n"
13071                "};",
13072                Style);
13073   verifyFormat("template <typename T> class rep // Foo\n"
13074                "{\n"
13075                "  int x;\n"
13076                "};",
13077                Style);
13078   verifyFormat("template <typename T> struct rep // Bar\n"
13079                "{\n"
13080                "  int x;\n"
13081                "};",
13082                Style);
13083 
13084   verifyFormat("template <typename T> class rep<T>\n"
13085                "{\n"
13086                "  int x;\n"
13087                "};",
13088                Style);
13089 
13090   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13091                "{\n"
13092                "  int x;\n"
13093                "};",
13094                Style);
13095   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13096                "{\n"
13097                "};",
13098                Style);
13099 
13100   verifyFormat("#include \"stdint.h\"\n"
13101                "namespace rep {}",
13102                Style);
13103   verifyFormat("#include <stdint.h>\n"
13104                "namespace rep {}",
13105                Style);
13106   verifyFormat("#include <stdint.h>\n"
13107                "namespace rep {}",
13108                "#include <stdint.h>\n"
13109                "namespace rep {\n"
13110                "\n"
13111                "\n"
13112                "}",
13113                Style);
13114 }
13115 
13116 TEST_F(FormatTest, SplitEmptyStruct) {
13117   FormatStyle Style = getLLVMStyle();
13118   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13119   Style.BraceWrapping.AfterStruct = true;
13120   Style.BraceWrapping.SplitEmptyRecord = false;
13121 
13122   verifyFormat("struct Foo\n"
13123                "{};",
13124                Style);
13125   verifyFormat("/* something */ struct Foo\n"
13126                "{};",
13127                Style);
13128   verifyFormat("template <typename X> struct Foo\n"
13129                "{};",
13130                Style);
13131   verifyFormat("struct Foo\n"
13132                "{\n"
13133                "  Foo();\n"
13134                "};",
13135                Style);
13136   verifyFormat("typedef struct Foo\n"
13137                "{\n"
13138                "} Foo_t;",
13139                Style);
13140   // typedef struct Bar {} Bar_t;
13141 }
13142 
13143 TEST_F(FormatTest, SplitEmptyUnion) {
13144   FormatStyle Style = getLLVMStyle();
13145   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13146   Style.BraceWrapping.AfterUnion = true;
13147   Style.BraceWrapping.SplitEmptyRecord = false;
13148 
13149   verifyFormat("union Foo\n"
13150                "{};",
13151                Style);
13152   verifyFormat("/* something */ union Foo\n"
13153                "{};",
13154                Style);
13155   verifyFormat("union Foo\n"
13156                "{\n"
13157                "  A,\n"
13158                "};",
13159                Style);
13160   verifyFormat("typedef union Foo\n"
13161                "{\n"
13162                "} Foo_t;",
13163                Style);
13164 }
13165 
13166 TEST_F(FormatTest, SplitEmptyNamespace) {
13167   FormatStyle Style = getLLVMStyle();
13168   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13169   Style.BraceWrapping.AfterNamespace = true;
13170   Style.BraceWrapping.SplitEmptyNamespace = false;
13171 
13172   verifyFormat("namespace Foo\n"
13173                "{};",
13174                Style);
13175   verifyFormat("/* something */ namespace Foo\n"
13176                "{};",
13177                Style);
13178   verifyFormat("inline namespace Foo\n"
13179                "{};",
13180                Style);
13181   verifyFormat("/* something */ inline namespace Foo\n"
13182                "{};",
13183                Style);
13184   verifyFormat("export namespace Foo\n"
13185                "{};",
13186                Style);
13187   verifyFormat("namespace Foo\n"
13188                "{\n"
13189                "void Bar();\n"
13190                "};",
13191                Style);
13192 }
13193 
13194 TEST_F(FormatTest, NeverMergeShortRecords) {
13195   FormatStyle Style = getLLVMStyle();
13196 
13197   verifyFormat("class Foo {\n"
13198                "  Foo();\n"
13199                "};",
13200                Style);
13201   verifyFormat("typedef class Foo {\n"
13202                "  Foo();\n"
13203                "} Foo_t;",
13204                Style);
13205   verifyFormat("struct Foo {\n"
13206                "  Foo();\n"
13207                "};",
13208                Style);
13209   verifyFormat("typedef struct Foo {\n"
13210                "  Foo();\n"
13211                "} Foo_t;",
13212                Style);
13213   verifyFormat("union Foo {\n"
13214                "  A,\n"
13215                "};",
13216                Style);
13217   verifyFormat("typedef union Foo {\n"
13218                "  A,\n"
13219                "} Foo_t;",
13220                Style);
13221   verifyFormat("namespace Foo {\n"
13222                "void Bar();\n"
13223                "};",
13224                Style);
13225 
13226   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13227   Style.BraceWrapping.AfterClass = true;
13228   Style.BraceWrapping.AfterStruct = true;
13229   Style.BraceWrapping.AfterUnion = true;
13230   Style.BraceWrapping.AfterNamespace = true;
13231   verifyFormat("class Foo\n"
13232                "{\n"
13233                "  Foo();\n"
13234                "};",
13235                Style);
13236   verifyFormat("typedef class Foo\n"
13237                "{\n"
13238                "  Foo();\n"
13239                "} Foo_t;",
13240                Style);
13241   verifyFormat("struct Foo\n"
13242                "{\n"
13243                "  Foo();\n"
13244                "};",
13245                Style);
13246   verifyFormat("typedef struct Foo\n"
13247                "{\n"
13248                "  Foo();\n"
13249                "} Foo_t;",
13250                Style);
13251   verifyFormat("union Foo\n"
13252                "{\n"
13253                "  A,\n"
13254                "};",
13255                Style);
13256   verifyFormat("typedef union Foo\n"
13257                "{\n"
13258                "  A,\n"
13259                "} Foo_t;",
13260                Style);
13261   verifyFormat("namespace Foo\n"
13262                "{\n"
13263                "void Bar();\n"
13264                "};",
13265                Style);
13266 }
13267 
13268 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
13269   // Elaborate type variable declarations.
13270   verifyFormat("struct foo a = {bar};\nint n;");
13271   verifyFormat("class foo a = {bar};\nint n;");
13272   verifyFormat("union foo a = {bar};\nint n;");
13273 
13274   // Elaborate types inside function definitions.
13275   verifyFormat("struct foo f() {}\nint n;");
13276   verifyFormat("class foo f() {}\nint n;");
13277   verifyFormat("union foo f() {}\nint n;");
13278 
13279   // Templates.
13280   verifyFormat("template <class X> void f() {}\nint n;");
13281   verifyFormat("template <struct X> void f() {}\nint n;");
13282   verifyFormat("template <union X> void f() {}\nint n;");
13283 
13284   // Actual definitions...
13285   verifyFormat("struct {\n} n;");
13286   verifyFormat(
13287       "template <template <class T, class Y>, class Z> class X {\n} n;");
13288   verifyFormat("union Z {\n  int n;\n} x;");
13289   verifyFormat("class MACRO Z {\n} n;");
13290   verifyFormat("class MACRO(X) Z {\n} n;");
13291   verifyFormat("class __attribute__(X) Z {\n} n;");
13292   verifyFormat("class __declspec(X) Z {\n} n;");
13293   verifyFormat("class A##B##C {\n} n;");
13294   verifyFormat("class alignas(16) Z {\n} n;");
13295   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
13296   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
13297 
13298   // Redefinition from nested context:
13299   verifyFormat("class A::B::C {\n} n;");
13300 
13301   // Template definitions.
13302   verifyFormat(
13303       "template <typename F>\n"
13304       "Matcher(const Matcher<F> &Other,\n"
13305       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
13306       "                             !is_same<F, T>::value>::type * = 0)\n"
13307       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
13308 
13309   // FIXME: This is still incorrectly handled at the formatter side.
13310   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
13311   verifyFormat("int i = SomeFunction(a<b, a> b);");
13312 
13313   // FIXME:
13314   // This now gets parsed incorrectly as class definition.
13315   // verifyFormat("class A<int> f() {\n}\nint n;");
13316 
13317   // Elaborate types where incorrectly parsing the structural element would
13318   // break the indent.
13319   verifyFormat("if (true)\n"
13320                "  class X x;\n"
13321                "else\n"
13322                "  f();\n");
13323 
13324   // This is simply incomplete. Formatting is not important, but must not crash.
13325   verifyFormat("class A:");
13326 }
13327 
13328 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
13329   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
13330             format("#error Leave     all         white!!!!! space* alone!\n"));
13331   EXPECT_EQ(
13332       "#warning Leave     all         white!!!!! space* alone!\n",
13333       format("#warning Leave     all         white!!!!! space* alone!\n"));
13334   EXPECT_EQ("#error 1", format("  #  error   1"));
13335   EXPECT_EQ("#warning 1", format("  #  warning 1"));
13336 }
13337 
13338 TEST_F(FormatTest, FormatHashIfExpressions) {
13339   verifyFormat("#if AAAA && BBBB");
13340   verifyFormat("#if (AAAA && BBBB)");
13341   verifyFormat("#elif (AAAA && BBBB)");
13342   // FIXME: Come up with a better indentation for #elif.
13343   verifyFormat(
13344       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
13345       "    defined(BBBBBBBB)\n"
13346       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
13347       "    defined(BBBBBBBB)\n"
13348       "#endif",
13349       getLLVMStyleWithColumns(65));
13350 }
13351 
13352 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
13353   FormatStyle AllowsMergedIf = getGoogleStyle();
13354   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
13355       FormatStyle::SIS_WithoutElse;
13356   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
13357   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
13358   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
13359   EXPECT_EQ("if (true) return 42;",
13360             format("if (true)\nreturn 42;", AllowsMergedIf));
13361   FormatStyle ShortMergedIf = AllowsMergedIf;
13362   ShortMergedIf.ColumnLimit = 25;
13363   verifyFormat("#define A \\\n"
13364                "  if (true) return 42;",
13365                ShortMergedIf);
13366   verifyFormat("#define A \\\n"
13367                "  f();    \\\n"
13368                "  if (true)\n"
13369                "#define B",
13370                ShortMergedIf);
13371   verifyFormat("#define A \\\n"
13372                "  f();    \\\n"
13373                "  if (true)\n"
13374                "g();",
13375                ShortMergedIf);
13376   verifyFormat("{\n"
13377                "#ifdef A\n"
13378                "  // Comment\n"
13379                "  if (true) continue;\n"
13380                "#endif\n"
13381                "  // Comment\n"
13382                "  if (true) continue;\n"
13383                "}",
13384                ShortMergedIf);
13385   ShortMergedIf.ColumnLimit = 33;
13386   verifyFormat("#define A \\\n"
13387                "  if constexpr (true) return 42;",
13388                ShortMergedIf);
13389   verifyFormat("#define A \\\n"
13390                "  if CONSTEXPR (true) return 42;",
13391                ShortMergedIf);
13392   ShortMergedIf.ColumnLimit = 29;
13393   verifyFormat("#define A                   \\\n"
13394                "  if (aaaaaaaaaa) return 1; \\\n"
13395                "  return 2;",
13396                ShortMergedIf);
13397   ShortMergedIf.ColumnLimit = 28;
13398   verifyFormat("#define A         \\\n"
13399                "  if (aaaaaaaaaa) \\\n"
13400                "    return 1;     \\\n"
13401                "  return 2;",
13402                ShortMergedIf);
13403   verifyFormat("#define A                \\\n"
13404                "  if constexpr (aaaaaaa) \\\n"
13405                "    return 1;            \\\n"
13406                "  return 2;",
13407                ShortMergedIf);
13408   verifyFormat("#define A                \\\n"
13409                "  if CONSTEXPR (aaaaaaa) \\\n"
13410                "    return 1;            \\\n"
13411                "  return 2;",
13412                ShortMergedIf);
13413 
13414   verifyFormat("//\n"
13415                "#define a \\\n"
13416                "  if      \\\n"
13417                "  0",
13418                getChromiumStyle(FormatStyle::LK_Cpp));
13419 }
13420 
13421 TEST_F(FormatTest, FormatStarDependingOnContext) {
13422   verifyFormat("void f(int *a);");
13423   verifyFormat("void f() { f(fint * b); }");
13424   verifyFormat("class A {\n  void f(int *a);\n};");
13425   verifyFormat("class A {\n  int *a;\n};");
13426   verifyFormat("namespace a {\n"
13427                "namespace b {\n"
13428                "class A {\n"
13429                "  void f() {}\n"
13430                "  int *a;\n"
13431                "};\n"
13432                "} // namespace b\n"
13433                "} // namespace a");
13434 }
13435 
13436 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13437   verifyFormat("while");
13438   verifyFormat("operator");
13439 }
13440 
13441 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13442   // This code would be painfully slow to format if we didn't skip it.
13443   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
13444                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13445                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13446                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13447                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13448                    "A(1, 1)\n"
13449                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
13450                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13451                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13452                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13453                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13454                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13455                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13456                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13457                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13458                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
13459   // Deeply nested part is untouched, rest is formatted.
13460   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13461             format(std::string("int    i;\n") + Code + "int    j;\n",
13462                    getLLVMStyle(), SC_ExpectIncomplete));
13463 }
13464 
13465 //===----------------------------------------------------------------------===//
13466 // Objective-C tests.
13467 //===----------------------------------------------------------------------===//
13468 
13469 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13470   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13471   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13472             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13473   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13474   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13475   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13476             format("-(NSInteger)Method3:(id)anObject;"));
13477   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13478             format("-(NSInteger)Method4:(id)anObject;"));
13479   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13480             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13481   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13482             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13483   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13484             "forAllCells:(BOOL)flag;",
13485             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13486                    "forAllCells:(BOOL)flag;"));
13487 
13488   // Very long objectiveC method declaration.
13489   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13490                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13491   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13492                "                    inRange:(NSRange)range\n"
13493                "                   outRange:(NSRange)out_range\n"
13494                "                  outRange1:(NSRange)out_range1\n"
13495                "                  outRange2:(NSRange)out_range2\n"
13496                "                  outRange3:(NSRange)out_range3\n"
13497                "                  outRange4:(NSRange)out_range4\n"
13498                "                  outRange5:(NSRange)out_range5\n"
13499                "                  outRange6:(NSRange)out_range6\n"
13500                "                  outRange7:(NSRange)out_range7\n"
13501                "                  outRange8:(NSRange)out_range8\n"
13502                "                  outRange9:(NSRange)out_range9;");
13503 
13504   // When the function name has to be wrapped.
13505   FormatStyle Style = getLLVMStyle();
13506   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13507   // and always indents instead.
13508   Style.IndentWrappedFunctionNames = false;
13509   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13510                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13511                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13512                "}",
13513                Style);
13514   Style.IndentWrappedFunctionNames = true;
13515   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13516                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13517                "               anotherName:(NSString)dddddddddddddd {\n"
13518                "}",
13519                Style);
13520 
13521   verifyFormat("- (int)sum:(vector<int>)numbers;");
13522   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13523   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13524   // protocol lists (but not for template classes):
13525   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13526 
13527   verifyFormat("- (int (*)())foo:(int (*)())f;");
13528   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13529 
13530   // If there's no return type (very rare in practice!), LLVM and Google style
13531   // agree.
13532   verifyFormat("- foo;");
13533   verifyFormat("- foo:(int)f;");
13534   verifyGoogleFormat("- foo:(int)foo;");
13535 }
13536 
13537 TEST_F(FormatTest, BreaksStringLiterals) {
13538   EXPECT_EQ("\"some text \"\n"
13539             "\"other\";",
13540             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13541   EXPECT_EQ("\"some text \"\n"
13542             "\"other\";",
13543             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13544   EXPECT_EQ(
13545       "#define A  \\\n"
13546       "  \"some \"  \\\n"
13547       "  \"text \"  \\\n"
13548       "  \"other\";",
13549       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13550   EXPECT_EQ(
13551       "#define A  \\\n"
13552       "  \"so \"    \\\n"
13553       "  \"text \"  \\\n"
13554       "  \"other\";",
13555       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13556 
13557   EXPECT_EQ("\"some text\"",
13558             format("\"some text\"", getLLVMStyleWithColumns(1)));
13559   EXPECT_EQ("\"some text\"",
13560             format("\"some text\"", getLLVMStyleWithColumns(11)));
13561   EXPECT_EQ("\"some \"\n"
13562             "\"text\"",
13563             format("\"some text\"", getLLVMStyleWithColumns(10)));
13564   EXPECT_EQ("\"some \"\n"
13565             "\"text\"",
13566             format("\"some text\"", getLLVMStyleWithColumns(7)));
13567   EXPECT_EQ("\"some\"\n"
13568             "\" tex\"\n"
13569             "\"t\"",
13570             format("\"some text\"", getLLVMStyleWithColumns(6)));
13571   EXPECT_EQ("\"some\"\n"
13572             "\" tex\"\n"
13573             "\" and\"",
13574             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13575   EXPECT_EQ("\"some\"\n"
13576             "\"/tex\"\n"
13577             "\"/and\"",
13578             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13579 
13580   EXPECT_EQ("variable =\n"
13581             "    \"long string \"\n"
13582             "    \"literal\";",
13583             format("variable = \"long string literal\";",
13584                    getLLVMStyleWithColumns(20)));
13585 
13586   EXPECT_EQ("variable = f(\n"
13587             "    \"long string \"\n"
13588             "    \"literal\",\n"
13589             "    short,\n"
13590             "    loooooooooooooooooooong);",
13591             format("variable = f(\"long string literal\", short, "
13592                    "loooooooooooooooooooong);",
13593                    getLLVMStyleWithColumns(20)));
13594 
13595   EXPECT_EQ(
13596       "f(g(\"long string \"\n"
13597       "    \"literal\"),\n"
13598       "  b);",
13599       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13600   EXPECT_EQ("f(g(\"long string \"\n"
13601             "    \"literal\",\n"
13602             "    a),\n"
13603             "  b);",
13604             format("f(g(\"long string literal\", a), b);",
13605                    getLLVMStyleWithColumns(20)));
13606   EXPECT_EQ(
13607       "f(\"one two\".split(\n"
13608       "    variable));",
13609       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13610   EXPECT_EQ("f(\"one two three four five six \"\n"
13611             "  \"seven\".split(\n"
13612             "      really_looooong_variable));",
13613             format("f(\"one two three four five six seven\"."
13614                    "split(really_looooong_variable));",
13615                    getLLVMStyleWithColumns(33)));
13616 
13617   EXPECT_EQ("f(\"some \"\n"
13618             "  \"text\",\n"
13619             "  other);",
13620             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13621 
13622   // Only break as a last resort.
13623   verifyFormat(
13624       "aaaaaaaaaaaaaaaaaaaa(\n"
13625       "    aaaaaaaaaaaaaaaaaaaa,\n"
13626       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13627 
13628   EXPECT_EQ("\"splitmea\"\n"
13629             "\"trandomp\"\n"
13630             "\"oint\"",
13631             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13632 
13633   EXPECT_EQ("\"split/\"\n"
13634             "\"pathat/\"\n"
13635             "\"slashes\"",
13636             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13637 
13638   EXPECT_EQ("\"split/\"\n"
13639             "\"pathat/\"\n"
13640             "\"slashes\"",
13641             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13642   EXPECT_EQ("\"split at \"\n"
13643             "\"spaces/at/\"\n"
13644             "\"slashes.at.any$\"\n"
13645             "\"non-alphanumeric%\"\n"
13646             "\"1111111111characte\"\n"
13647             "\"rs\"",
13648             format("\"split at "
13649                    "spaces/at/"
13650                    "slashes.at."
13651                    "any$non-"
13652                    "alphanumeric%"
13653                    "1111111111characte"
13654                    "rs\"",
13655                    getLLVMStyleWithColumns(20)));
13656 
13657   // Verify that splitting the strings understands
13658   // Style::AlwaysBreakBeforeMultilineStrings.
13659   EXPECT_EQ("aaaaaaaaaaaa(\n"
13660             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13661             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13662             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13663                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13664                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13665                    getGoogleStyle()));
13666   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13667             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13668             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13669                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13670                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13671                    getGoogleStyle()));
13672   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13673             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13674             format("llvm::outs() << "
13675                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13676                    "aaaaaaaaaaaaaaaaaaa\";"));
13677   EXPECT_EQ("ffff(\n"
13678             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13679             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13680             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13681                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13682                    getGoogleStyle()));
13683 
13684   FormatStyle Style = getLLVMStyleWithColumns(12);
13685   Style.BreakStringLiterals = false;
13686   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13687 
13688   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13689   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13690   EXPECT_EQ("#define A \\\n"
13691             "  \"some \" \\\n"
13692             "  \"text \" \\\n"
13693             "  \"other\";",
13694             format("#define A \"some text other\";", AlignLeft));
13695 }
13696 
13697 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13698   EXPECT_EQ("C a = \"some more \"\n"
13699             "      \"text\";",
13700             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13701 }
13702 
13703 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13704   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13705   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13706   EXPECT_EQ("int i = a(b());",
13707             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13708 }
13709 
13710 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13711   EXPECT_EQ(
13712       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13713       "(\n"
13714       "    \"x\t\");",
13715       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13716              "aaaaaaa("
13717              "\"x\t\");"));
13718 }
13719 
13720 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13721   EXPECT_EQ(
13722       "u8\"utf8 string \"\n"
13723       "u8\"literal\";",
13724       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13725   EXPECT_EQ(
13726       "u\"utf16 string \"\n"
13727       "u\"literal\";",
13728       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13729   EXPECT_EQ(
13730       "U\"utf32 string \"\n"
13731       "U\"literal\";",
13732       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13733   EXPECT_EQ("L\"wide string \"\n"
13734             "L\"literal\";",
13735             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13736   EXPECT_EQ("@\"NSString \"\n"
13737             "@\"literal\";",
13738             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13739   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13740 
13741   // This input makes clang-format try to split the incomplete unicode escape
13742   // sequence, which used to lead to a crasher.
13743   verifyNoCrash(
13744       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13745       getLLVMStyleWithColumns(60));
13746 }
13747 
13748 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13749   FormatStyle Style = getGoogleStyleWithColumns(15);
13750   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13751   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13752   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13753   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13754   EXPECT_EQ("u8R\"x(raw literal)x\";",
13755             format("u8R\"x(raw literal)x\";", Style));
13756 }
13757 
13758 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13759   FormatStyle Style = getLLVMStyleWithColumns(20);
13760   EXPECT_EQ(
13761       "_T(\"aaaaaaaaaaaaaa\")\n"
13762       "_T(\"aaaaaaaaaaaaaa\")\n"
13763       "_T(\"aaaaaaaaaaaa\")",
13764       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13765   EXPECT_EQ("f(x,\n"
13766             "  _T(\"aaaaaaaaaaaa\")\n"
13767             "  _T(\"aaa\"),\n"
13768             "  z);",
13769             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13770 
13771   // FIXME: Handle embedded spaces in one iteration.
13772   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13773   //            "_T(\"aaaaaaaaaaaaa\")\n"
13774   //            "_T(\"aaaaaaaaaaaaa\")\n"
13775   //            "_T(\"a\")",
13776   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13777   //                   getLLVMStyleWithColumns(20)));
13778   EXPECT_EQ(
13779       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13780       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13781   EXPECT_EQ("f(\n"
13782             "#if !TEST\n"
13783             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13784             "#endif\n"
13785             ");",
13786             format("f(\n"
13787                    "#if !TEST\n"
13788                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13789                    "#endif\n"
13790                    ");"));
13791   EXPECT_EQ("f(\n"
13792             "\n"
13793             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13794             format("f(\n"
13795                    "\n"
13796                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13797   // Regression test for accessing tokens past the end of a vector in the
13798   // TokenLexer.
13799   verifyNoCrash(R"(_T(
13800 "
13801 )
13802 )");
13803 }
13804 
13805 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13806   // In a function call with two operands, the second can be broken with no line
13807   // break before it.
13808   EXPECT_EQ(
13809       "func(a, \"long long \"\n"
13810       "        \"long long\");",
13811       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13812   // In a function call with three operands, the second must be broken with a
13813   // line break before it.
13814   EXPECT_EQ("func(a,\n"
13815             "     \"long long long \"\n"
13816             "     \"long\",\n"
13817             "     c);",
13818             format("func(a, \"long long long long\", c);",
13819                    getLLVMStyleWithColumns(24)));
13820   // In a function call with three operands, the third must be broken with a
13821   // line break before it.
13822   EXPECT_EQ("func(a, b,\n"
13823             "     \"long long long \"\n"
13824             "     \"long\");",
13825             format("func(a, b, \"long long long long\");",
13826                    getLLVMStyleWithColumns(24)));
13827   // In a function call with three operands, both the second and the third must
13828   // be broken with a line break before them.
13829   EXPECT_EQ("func(a,\n"
13830             "     \"long long long \"\n"
13831             "     \"long\",\n"
13832             "     \"long long long \"\n"
13833             "     \"long\");",
13834             format("func(a, \"long long long long\", \"long long long long\");",
13835                    getLLVMStyleWithColumns(24)));
13836   // In a chain of << with two operands, the second can be broken with no line
13837   // break before it.
13838   EXPECT_EQ("a << \"line line \"\n"
13839             "     \"line\";",
13840             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13841   // In a chain of << with three operands, the second can be broken with no line
13842   // break before it.
13843   EXPECT_EQ(
13844       "abcde << \"line \"\n"
13845       "         \"line line\"\n"
13846       "      << c;",
13847       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13848   // In a chain of << with three operands, the third must be broken with a line
13849   // break before it.
13850   EXPECT_EQ(
13851       "a << b\n"
13852       "  << \"line line \"\n"
13853       "     \"line\";",
13854       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13855   // In a chain of << with three operands, the second can be broken with no line
13856   // break before it and the third must be broken with a line break before it.
13857   EXPECT_EQ("abcd << \"line line \"\n"
13858             "        \"line\"\n"
13859             "     << \"line line \"\n"
13860             "        \"line\";",
13861             format("abcd << \"line line line\" << \"line line line\";",
13862                    getLLVMStyleWithColumns(20)));
13863   // In a chain of binary operators with two operands, the second can be broken
13864   // with no line break before it.
13865   EXPECT_EQ(
13866       "abcd + \"line line \"\n"
13867       "       \"line line\";",
13868       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13869   // In a chain of binary operators with three operands, the second must be
13870   // broken with a line break before it.
13871   EXPECT_EQ("abcd +\n"
13872             "    \"line line \"\n"
13873             "    \"line line\" +\n"
13874             "    e;",
13875             format("abcd + \"line line line line\" + e;",
13876                    getLLVMStyleWithColumns(20)));
13877   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13878   // the first must be broken with a line break before it.
13879   FormatStyle Style = getLLVMStyleWithColumns(25);
13880   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13881   EXPECT_EQ("someFunction(\n"
13882             "    \"long long long \"\n"
13883             "    \"long\",\n"
13884             "    a);",
13885             format("someFunction(\"long long long long\", a);", Style));
13886 }
13887 
13888 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13889   EXPECT_EQ(
13890       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13891       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13892       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13893       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13894              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13895              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13896 }
13897 
13898 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13899   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13900             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13901   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13902             "multiline raw string literal xxxxxxxxxxxxxx\n"
13903             ")x\",\n"
13904             "              a),\n"
13905             "            b);",
13906             format("fffffffffff(g(R\"x(\n"
13907                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13908                    ")x\", a), b);",
13909                    getGoogleStyleWithColumns(20)));
13910   EXPECT_EQ("fffffffffff(\n"
13911             "    g(R\"x(qqq\n"
13912             "multiline raw string literal xxxxxxxxxxxxxx\n"
13913             ")x\",\n"
13914             "      a),\n"
13915             "    b);",
13916             format("fffffffffff(g(R\"x(qqq\n"
13917                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13918                    ")x\", a), b);",
13919                    getGoogleStyleWithColumns(20)));
13920 
13921   EXPECT_EQ("fffffffffff(R\"x(\n"
13922             "multiline raw string literal xxxxxxxxxxxxxx\n"
13923             ")x\");",
13924             format("fffffffffff(R\"x(\n"
13925                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13926                    ")x\");",
13927                    getGoogleStyleWithColumns(20)));
13928   EXPECT_EQ("fffffffffff(R\"x(\n"
13929             "multiline raw string literal xxxxxxxxxxxxxx\n"
13930             ")x\" + bbbbbb);",
13931             format("fffffffffff(R\"x(\n"
13932                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13933                    ")x\" +   bbbbbb);",
13934                    getGoogleStyleWithColumns(20)));
13935   EXPECT_EQ("fffffffffff(\n"
13936             "    R\"x(\n"
13937             "multiline raw string literal xxxxxxxxxxxxxx\n"
13938             ")x\" +\n"
13939             "    bbbbbb);",
13940             format("fffffffffff(\n"
13941                    " R\"x(\n"
13942                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13943                    ")x\" + bbbbbb);",
13944                    getGoogleStyleWithColumns(20)));
13945   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13946             format("fffffffffff(\n"
13947                    " R\"(single line raw string)\" + bbbbbb);"));
13948 }
13949 
13950 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13951   verifyFormat("string a = \"unterminated;");
13952   EXPECT_EQ("function(\"unterminated,\n"
13953             "         OtherParameter);",
13954             format("function(  \"unterminated,\n"
13955                    "    OtherParameter);"));
13956 }
13957 
13958 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13959   FormatStyle Style = getLLVMStyle();
13960   Style.Standard = FormatStyle::LS_Cpp03;
13961   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13962             format("#define x(_a) printf(\"foo\"_a);", Style));
13963 }
13964 
13965 TEST_F(FormatTest, CppLexVersion) {
13966   FormatStyle Style = getLLVMStyle();
13967   // Formatting of x * y differs if x is a type.
13968   verifyFormat("void foo() { MACRO(a * b); }", Style);
13969   verifyFormat("void foo() { MACRO(int *b); }", Style);
13970 
13971   // LLVM style uses latest lexer.
13972   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13973   Style.Standard = FormatStyle::LS_Cpp17;
13974   // But in c++17, char8_t isn't a keyword.
13975   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13976 }
13977 
13978 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13979 
13980 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13981   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13982             "             \"ddeeefff\");",
13983             format("someFunction(\"aaabbbcccdddeeefff\");",
13984                    getLLVMStyleWithColumns(25)));
13985   EXPECT_EQ("someFunction1234567890(\n"
13986             "    \"aaabbbcccdddeeefff\");",
13987             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13988                    getLLVMStyleWithColumns(26)));
13989   EXPECT_EQ("someFunction1234567890(\n"
13990             "    \"aaabbbcccdddeeeff\"\n"
13991             "    \"f\");",
13992             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13993                    getLLVMStyleWithColumns(25)));
13994   EXPECT_EQ("someFunction1234567890(\n"
13995             "    \"aaabbbcccdddeeeff\"\n"
13996             "    \"f\");",
13997             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13998                    getLLVMStyleWithColumns(24)));
13999   EXPECT_EQ("someFunction(\n"
14000             "    \"aaabbbcc ddde \"\n"
14001             "    \"efff\");",
14002             format("someFunction(\"aaabbbcc ddde efff\");",
14003                    getLLVMStyleWithColumns(25)));
14004   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
14005             "             \"ddeeefff\");",
14006             format("someFunction(\"aaabbbccc ddeeefff\");",
14007                    getLLVMStyleWithColumns(25)));
14008   EXPECT_EQ("someFunction1234567890(\n"
14009             "    \"aaabb \"\n"
14010             "    \"cccdddeeefff\");",
14011             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
14012                    getLLVMStyleWithColumns(25)));
14013   EXPECT_EQ("#define A          \\\n"
14014             "  string s =       \\\n"
14015             "      \"123456789\"  \\\n"
14016             "      \"0\";         \\\n"
14017             "  int i;",
14018             format("#define A string s = \"1234567890\"; int i;",
14019                    getLLVMStyleWithColumns(20)));
14020   EXPECT_EQ("someFunction(\n"
14021             "    \"aaabbbcc \"\n"
14022             "    \"dddeeefff\");",
14023             format("someFunction(\"aaabbbcc dddeeefff\");",
14024                    getLLVMStyleWithColumns(25)));
14025 }
14026 
14027 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
14028   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
14029   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
14030   EXPECT_EQ("\"test\"\n"
14031             "\"\\n\"",
14032             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
14033   EXPECT_EQ("\"tes\\\\\"\n"
14034             "\"n\"",
14035             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
14036   EXPECT_EQ("\"\\\\\\\\\"\n"
14037             "\"\\n\"",
14038             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
14039   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
14040   EXPECT_EQ("\"\\uff01\"\n"
14041             "\"test\"",
14042             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
14043   EXPECT_EQ("\"\\Uff01ff02\"",
14044             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
14045   EXPECT_EQ("\"\\x000000000001\"\n"
14046             "\"next\"",
14047             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
14048   EXPECT_EQ("\"\\x000000000001next\"",
14049             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
14050   EXPECT_EQ("\"\\x000000000001\"",
14051             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
14052   EXPECT_EQ("\"test\"\n"
14053             "\"\\000000\"\n"
14054             "\"000001\"",
14055             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
14056   EXPECT_EQ("\"test\\000\"\n"
14057             "\"00000000\"\n"
14058             "\"1\"",
14059             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
14060 }
14061 
14062 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
14063   verifyFormat("void f() {\n"
14064                "  return g() {}\n"
14065                "  void h() {}");
14066   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
14067                "g();\n"
14068                "}");
14069 }
14070 
14071 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
14072   verifyFormat(
14073       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
14074 }
14075 
14076 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
14077   verifyFormat("class X {\n"
14078                "  void f() {\n"
14079                "  }\n"
14080                "};",
14081                getLLVMStyleWithColumns(12));
14082 }
14083 
14084 TEST_F(FormatTest, ConfigurableIndentWidth) {
14085   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
14086   EightIndent.IndentWidth = 8;
14087   EightIndent.ContinuationIndentWidth = 8;
14088   verifyFormat("void f() {\n"
14089                "        someFunction();\n"
14090                "        if (true) {\n"
14091                "                f();\n"
14092                "        }\n"
14093                "}",
14094                EightIndent);
14095   verifyFormat("class X {\n"
14096                "        void f() {\n"
14097                "        }\n"
14098                "};",
14099                EightIndent);
14100   verifyFormat("int x[] = {\n"
14101                "        call(),\n"
14102                "        call()};",
14103                EightIndent);
14104 }
14105 
14106 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
14107   verifyFormat("double\n"
14108                "f();",
14109                getLLVMStyleWithColumns(8));
14110 }
14111 
14112 TEST_F(FormatTest, ConfigurableUseOfTab) {
14113   FormatStyle Tab = getLLVMStyleWithColumns(42);
14114   Tab.IndentWidth = 8;
14115   Tab.UseTab = FormatStyle::UT_Always;
14116   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14117 
14118   EXPECT_EQ("if (aaaaaaaa && // q\n"
14119             "    bb)\t\t// w\n"
14120             "\t;",
14121             format("if (aaaaaaaa &&// q\n"
14122                    "bb)// w\n"
14123                    ";",
14124                    Tab));
14125   EXPECT_EQ("if (aaa && bbb) // w\n"
14126             "\t;",
14127             format("if(aaa&&bbb)// w\n"
14128                    ";",
14129                    Tab));
14130 
14131   verifyFormat("class X {\n"
14132                "\tvoid f() {\n"
14133                "\t\tsomeFunction(parameter1,\n"
14134                "\t\t\t     parameter2);\n"
14135                "\t}\n"
14136                "};",
14137                Tab);
14138   verifyFormat("#define A                        \\\n"
14139                "\tvoid f() {               \\\n"
14140                "\t\tsomeFunction(    \\\n"
14141                "\t\t    parameter1,  \\\n"
14142                "\t\t    parameter2); \\\n"
14143                "\t}",
14144                Tab);
14145   verifyFormat("int a;\t      // x\n"
14146                "int bbbbbbbb; // x\n",
14147                Tab);
14148 
14149   Tab.TabWidth = 4;
14150   Tab.IndentWidth = 8;
14151   verifyFormat("class TabWidth4Indent8 {\n"
14152                "\t\tvoid f() {\n"
14153                "\t\t\t\tsomeFunction(parameter1,\n"
14154                "\t\t\t\t\t\t\t parameter2);\n"
14155                "\t\t}\n"
14156                "};",
14157                Tab);
14158 
14159   Tab.TabWidth = 4;
14160   Tab.IndentWidth = 4;
14161   verifyFormat("class TabWidth4Indent4 {\n"
14162                "\tvoid f() {\n"
14163                "\t\tsomeFunction(parameter1,\n"
14164                "\t\t\t\t\t parameter2);\n"
14165                "\t}\n"
14166                "};",
14167                Tab);
14168 
14169   Tab.TabWidth = 8;
14170   Tab.IndentWidth = 4;
14171   verifyFormat("class TabWidth8Indent4 {\n"
14172                "    void f() {\n"
14173                "\tsomeFunction(parameter1,\n"
14174                "\t\t     parameter2);\n"
14175                "    }\n"
14176                "};",
14177                Tab);
14178 
14179   Tab.TabWidth = 8;
14180   Tab.IndentWidth = 8;
14181   EXPECT_EQ("/*\n"
14182             "\t      a\t\tcomment\n"
14183             "\t      in multiple lines\n"
14184             "       */",
14185             format("   /*\t \t \n"
14186                    " \t \t a\t\tcomment\t \t\n"
14187                    " \t \t in multiple lines\t\n"
14188                    " \t  */",
14189                    Tab));
14190 
14191   Tab.UseTab = FormatStyle::UT_ForIndentation;
14192   verifyFormat("{\n"
14193                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14194                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14195                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14196                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14197                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14198                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14199                "};",
14200                Tab);
14201   verifyFormat("enum AA {\n"
14202                "\ta1, // Force multiple lines\n"
14203                "\ta2,\n"
14204                "\ta3\n"
14205                "};",
14206                Tab);
14207   EXPECT_EQ("if (aaaaaaaa && // q\n"
14208             "    bb)         // w\n"
14209             "\t;",
14210             format("if (aaaaaaaa &&// q\n"
14211                    "bb)// w\n"
14212                    ";",
14213                    Tab));
14214   verifyFormat("class X {\n"
14215                "\tvoid f() {\n"
14216                "\t\tsomeFunction(parameter1,\n"
14217                "\t\t             parameter2);\n"
14218                "\t}\n"
14219                "};",
14220                Tab);
14221   verifyFormat("{\n"
14222                "\tQ(\n"
14223                "\t    {\n"
14224                "\t\t    int a;\n"
14225                "\t\t    someFunction(aaaaaaaa,\n"
14226                "\t\t                 bbbbbbb);\n"
14227                "\t    },\n"
14228                "\t    p);\n"
14229                "}",
14230                Tab);
14231   EXPECT_EQ("{\n"
14232             "\t/* aaaa\n"
14233             "\t   bbbb */\n"
14234             "}",
14235             format("{\n"
14236                    "/* aaaa\n"
14237                    "   bbbb */\n"
14238                    "}",
14239                    Tab));
14240   EXPECT_EQ("{\n"
14241             "\t/*\n"
14242             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14243             "\t  bbbbbbbbbbbbb\n"
14244             "\t*/\n"
14245             "}",
14246             format("{\n"
14247                    "/*\n"
14248                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14249                    "*/\n"
14250                    "}",
14251                    Tab));
14252   EXPECT_EQ("{\n"
14253             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14254             "\t// bbbbbbbbbbbbb\n"
14255             "}",
14256             format("{\n"
14257                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14258                    "}",
14259                    Tab));
14260   EXPECT_EQ("{\n"
14261             "\t/*\n"
14262             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14263             "\t  bbbbbbbbbbbbb\n"
14264             "\t*/\n"
14265             "}",
14266             format("{\n"
14267                    "\t/*\n"
14268                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14269                    "\t*/\n"
14270                    "}",
14271                    Tab));
14272   EXPECT_EQ("{\n"
14273             "\t/*\n"
14274             "\n"
14275             "\t*/\n"
14276             "}",
14277             format("{\n"
14278                    "\t/*\n"
14279                    "\n"
14280                    "\t*/\n"
14281                    "}",
14282                    Tab));
14283   EXPECT_EQ("{\n"
14284             "\t/*\n"
14285             " asdf\n"
14286             "\t*/\n"
14287             "}",
14288             format("{\n"
14289                    "\t/*\n"
14290                    " asdf\n"
14291                    "\t*/\n"
14292                    "}",
14293                    Tab));
14294 
14295   verifyFormat("void f() {\n"
14296                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14297                "\t            : bbbbbbbbbbbbbbbbbb\n"
14298                "}",
14299                Tab);
14300   FormatStyle TabNoBreak = Tab;
14301   TabNoBreak.BreakBeforeTernaryOperators = false;
14302   verifyFormat("void f() {\n"
14303                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14304                "\t              bbbbbbbbbbbbbbbbbb\n"
14305                "}",
14306                TabNoBreak);
14307   verifyFormat("void f() {\n"
14308                "\treturn true ?\n"
14309                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14310                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14311                "}",
14312                TabNoBreak);
14313 
14314   Tab.UseTab = FormatStyle::UT_Never;
14315   EXPECT_EQ("/*\n"
14316             "              a\t\tcomment\n"
14317             "              in multiple lines\n"
14318             "       */",
14319             format("   /*\t \t \n"
14320                    " \t \t a\t\tcomment\t \t\n"
14321                    " \t \t in multiple lines\t\n"
14322                    " \t  */",
14323                    Tab));
14324   EXPECT_EQ("/* some\n"
14325             "   comment */",
14326             format(" \t \t /* some\n"
14327                    " \t \t    comment */",
14328                    Tab));
14329   EXPECT_EQ("int a; /* some\n"
14330             "   comment */",
14331             format(" \t \t int a; /* some\n"
14332                    " \t \t    comment */",
14333                    Tab));
14334 
14335   EXPECT_EQ("int a; /* some\n"
14336             "comment */",
14337             format(" \t \t int\ta; /* some\n"
14338                    " \t \t    comment */",
14339                    Tab));
14340   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14341             "    comment */",
14342             format(" \t \t f(\"\t\t\"); /* some\n"
14343                    " \t \t    comment */",
14344                    Tab));
14345   EXPECT_EQ("{\n"
14346             "        /*\n"
14347             "         * Comment\n"
14348             "         */\n"
14349             "        int i;\n"
14350             "}",
14351             format("{\n"
14352                    "\t/*\n"
14353                    "\t * Comment\n"
14354                    "\t */\n"
14355                    "\t int i;\n"
14356                    "}",
14357                    Tab));
14358 
14359   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14360   Tab.TabWidth = 8;
14361   Tab.IndentWidth = 8;
14362   EXPECT_EQ("if (aaaaaaaa && // q\n"
14363             "    bb)         // w\n"
14364             "\t;",
14365             format("if (aaaaaaaa &&// q\n"
14366                    "bb)// w\n"
14367                    ";",
14368                    Tab));
14369   EXPECT_EQ("if (aaa && bbb) // w\n"
14370             "\t;",
14371             format("if(aaa&&bbb)// w\n"
14372                    ";",
14373                    Tab));
14374   verifyFormat("class X {\n"
14375                "\tvoid f() {\n"
14376                "\t\tsomeFunction(parameter1,\n"
14377                "\t\t\t     parameter2);\n"
14378                "\t}\n"
14379                "};",
14380                Tab);
14381   verifyFormat("#define A                        \\\n"
14382                "\tvoid f() {               \\\n"
14383                "\t\tsomeFunction(    \\\n"
14384                "\t\t    parameter1,  \\\n"
14385                "\t\t    parameter2); \\\n"
14386                "\t}",
14387                Tab);
14388   Tab.TabWidth = 4;
14389   Tab.IndentWidth = 8;
14390   verifyFormat("class TabWidth4Indent8 {\n"
14391                "\t\tvoid f() {\n"
14392                "\t\t\t\tsomeFunction(parameter1,\n"
14393                "\t\t\t\t\t\t\t parameter2);\n"
14394                "\t\t}\n"
14395                "};",
14396                Tab);
14397   Tab.TabWidth = 4;
14398   Tab.IndentWidth = 4;
14399   verifyFormat("class TabWidth4Indent4 {\n"
14400                "\tvoid f() {\n"
14401                "\t\tsomeFunction(parameter1,\n"
14402                "\t\t\t\t\t parameter2);\n"
14403                "\t}\n"
14404                "};",
14405                Tab);
14406   Tab.TabWidth = 8;
14407   Tab.IndentWidth = 4;
14408   verifyFormat("class TabWidth8Indent4 {\n"
14409                "    void f() {\n"
14410                "\tsomeFunction(parameter1,\n"
14411                "\t\t     parameter2);\n"
14412                "    }\n"
14413                "};",
14414                Tab);
14415   Tab.TabWidth = 8;
14416   Tab.IndentWidth = 8;
14417   EXPECT_EQ("/*\n"
14418             "\t      a\t\tcomment\n"
14419             "\t      in multiple lines\n"
14420             "       */",
14421             format("   /*\t \t \n"
14422                    " \t \t a\t\tcomment\t \t\n"
14423                    " \t \t in multiple lines\t\n"
14424                    " \t  */",
14425                    Tab));
14426   verifyFormat("{\n"
14427                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14428                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14429                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14430                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14431                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14432                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14433                "};",
14434                Tab);
14435   verifyFormat("enum AA {\n"
14436                "\ta1, // Force multiple lines\n"
14437                "\ta2,\n"
14438                "\ta3\n"
14439                "};",
14440                Tab);
14441   EXPECT_EQ("if (aaaaaaaa && // q\n"
14442             "    bb)         // w\n"
14443             "\t;",
14444             format("if (aaaaaaaa &&// q\n"
14445                    "bb)// w\n"
14446                    ";",
14447                    Tab));
14448   verifyFormat("class X {\n"
14449                "\tvoid f() {\n"
14450                "\t\tsomeFunction(parameter1,\n"
14451                "\t\t\t     parameter2);\n"
14452                "\t}\n"
14453                "};",
14454                Tab);
14455   verifyFormat("{\n"
14456                "\tQ(\n"
14457                "\t    {\n"
14458                "\t\t    int a;\n"
14459                "\t\t    someFunction(aaaaaaaa,\n"
14460                "\t\t\t\t bbbbbbb);\n"
14461                "\t    },\n"
14462                "\t    p);\n"
14463                "}",
14464                Tab);
14465   EXPECT_EQ("{\n"
14466             "\t/* aaaa\n"
14467             "\t   bbbb */\n"
14468             "}",
14469             format("{\n"
14470                    "/* aaaa\n"
14471                    "   bbbb */\n"
14472                    "}",
14473                    Tab));
14474   EXPECT_EQ("{\n"
14475             "\t/*\n"
14476             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14477             "\t  bbbbbbbbbbbbb\n"
14478             "\t*/\n"
14479             "}",
14480             format("{\n"
14481                    "/*\n"
14482                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14483                    "*/\n"
14484                    "}",
14485                    Tab));
14486   EXPECT_EQ("{\n"
14487             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14488             "\t// bbbbbbbbbbbbb\n"
14489             "}",
14490             format("{\n"
14491                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14492                    "}",
14493                    Tab));
14494   EXPECT_EQ("{\n"
14495             "\t/*\n"
14496             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14497             "\t  bbbbbbbbbbbbb\n"
14498             "\t*/\n"
14499             "}",
14500             format("{\n"
14501                    "\t/*\n"
14502                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14503                    "\t*/\n"
14504                    "}",
14505                    Tab));
14506   EXPECT_EQ("{\n"
14507             "\t/*\n"
14508             "\n"
14509             "\t*/\n"
14510             "}",
14511             format("{\n"
14512                    "\t/*\n"
14513                    "\n"
14514                    "\t*/\n"
14515                    "}",
14516                    Tab));
14517   EXPECT_EQ("{\n"
14518             "\t/*\n"
14519             " asdf\n"
14520             "\t*/\n"
14521             "}",
14522             format("{\n"
14523                    "\t/*\n"
14524                    " asdf\n"
14525                    "\t*/\n"
14526                    "}",
14527                    Tab));
14528   EXPECT_EQ("/* some\n"
14529             "   comment */",
14530             format(" \t \t /* some\n"
14531                    " \t \t    comment */",
14532                    Tab));
14533   EXPECT_EQ("int a; /* some\n"
14534             "   comment */",
14535             format(" \t \t int a; /* some\n"
14536                    " \t \t    comment */",
14537                    Tab));
14538   EXPECT_EQ("int a; /* some\n"
14539             "comment */",
14540             format(" \t \t int\ta; /* some\n"
14541                    " \t \t    comment */",
14542                    Tab));
14543   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14544             "    comment */",
14545             format(" \t \t f(\"\t\t\"); /* some\n"
14546                    " \t \t    comment */",
14547                    Tab));
14548   EXPECT_EQ("{\n"
14549             "\t/*\n"
14550             "\t * Comment\n"
14551             "\t */\n"
14552             "\tint i;\n"
14553             "}",
14554             format("{\n"
14555                    "\t/*\n"
14556                    "\t * Comment\n"
14557                    "\t */\n"
14558                    "\t int i;\n"
14559                    "}",
14560                    Tab));
14561   Tab.TabWidth = 2;
14562   Tab.IndentWidth = 2;
14563   EXPECT_EQ("{\n"
14564             "\t/* aaaa\n"
14565             "\t\t bbbb */\n"
14566             "}",
14567             format("{\n"
14568                    "/* aaaa\n"
14569                    "\t bbbb */\n"
14570                    "}",
14571                    Tab));
14572   EXPECT_EQ("{\n"
14573             "\t/*\n"
14574             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14575             "\t\tbbbbbbbbbbbbb\n"
14576             "\t*/\n"
14577             "}",
14578             format("{\n"
14579                    "/*\n"
14580                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14581                    "*/\n"
14582                    "}",
14583                    Tab));
14584   Tab.AlignConsecutiveAssignments.Enabled = true;
14585   Tab.AlignConsecutiveDeclarations.Enabled = true;
14586   Tab.TabWidth = 4;
14587   Tab.IndentWidth = 4;
14588   verifyFormat("class Assign {\n"
14589                "\tvoid f() {\n"
14590                "\t\tint         x      = 123;\n"
14591                "\t\tint         random = 4;\n"
14592                "\t\tstd::string alphabet =\n"
14593                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14594                "\t}\n"
14595                "};",
14596                Tab);
14597 
14598   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14599   Tab.TabWidth = 8;
14600   Tab.IndentWidth = 8;
14601   EXPECT_EQ("if (aaaaaaaa && // q\n"
14602             "    bb)         // w\n"
14603             "\t;",
14604             format("if (aaaaaaaa &&// q\n"
14605                    "bb)// w\n"
14606                    ";",
14607                    Tab));
14608   EXPECT_EQ("if (aaa && bbb) // w\n"
14609             "\t;",
14610             format("if(aaa&&bbb)// w\n"
14611                    ";",
14612                    Tab));
14613   verifyFormat("class X {\n"
14614                "\tvoid f() {\n"
14615                "\t\tsomeFunction(parameter1,\n"
14616                "\t\t             parameter2);\n"
14617                "\t}\n"
14618                "};",
14619                Tab);
14620   verifyFormat("#define A                        \\\n"
14621                "\tvoid f() {               \\\n"
14622                "\t\tsomeFunction(    \\\n"
14623                "\t\t    parameter1,  \\\n"
14624                "\t\t    parameter2); \\\n"
14625                "\t}",
14626                Tab);
14627   Tab.TabWidth = 4;
14628   Tab.IndentWidth = 8;
14629   verifyFormat("class TabWidth4Indent8 {\n"
14630                "\t\tvoid f() {\n"
14631                "\t\t\t\tsomeFunction(parameter1,\n"
14632                "\t\t\t\t             parameter2);\n"
14633                "\t\t}\n"
14634                "};",
14635                Tab);
14636   Tab.TabWidth = 4;
14637   Tab.IndentWidth = 4;
14638   verifyFormat("class TabWidth4Indent4 {\n"
14639                "\tvoid f() {\n"
14640                "\t\tsomeFunction(parameter1,\n"
14641                "\t\t             parameter2);\n"
14642                "\t}\n"
14643                "};",
14644                Tab);
14645   Tab.TabWidth = 8;
14646   Tab.IndentWidth = 4;
14647   verifyFormat("class TabWidth8Indent4 {\n"
14648                "    void f() {\n"
14649                "\tsomeFunction(parameter1,\n"
14650                "\t             parameter2);\n"
14651                "    }\n"
14652                "};",
14653                Tab);
14654   Tab.TabWidth = 8;
14655   Tab.IndentWidth = 8;
14656   EXPECT_EQ("/*\n"
14657             "              a\t\tcomment\n"
14658             "              in multiple lines\n"
14659             "       */",
14660             format("   /*\t \t \n"
14661                    " \t \t a\t\tcomment\t \t\n"
14662                    " \t \t in multiple lines\t\n"
14663                    " \t  */",
14664                    Tab));
14665   verifyFormat("{\n"
14666                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14667                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14668                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14669                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14670                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14671                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14672                "};",
14673                Tab);
14674   verifyFormat("enum AA {\n"
14675                "\ta1, // Force multiple lines\n"
14676                "\ta2,\n"
14677                "\ta3\n"
14678                "};",
14679                Tab);
14680   EXPECT_EQ("if (aaaaaaaa && // q\n"
14681             "    bb)         // w\n"
14682             "\t;",
14683             format("if (aaaaaaaa &&// q\n"
14684                    "bb)// w\n"
14685                    ";",
14686                    Tab));
14687   verifyFormat("class X {\n"
14688                "\tvoid f() {\n"
14689                "\t\tsomeFunction(parameter1,\n"
14690                "\t\t             parameter2);\n"
14691                "\t}\n"
14692                "};",
14693                Tab);
14694   verifyFormat("{\n"
14695                "\tQ(\n"
14696                "\t    {\n"
14697                "\t\t    int a;\n"
14698                "\t\t    someFunction(aaaaaaaa,\n"
14699                "\t\t                 bbbbbbb);\n"
14700                "\t    },\n"
14701                "\t    p);\n"
14702                "}",
14703                Tab);
14704   EXPECT_EQ("{\n"
14705             "\t/* aaaa\n"
14706             "\t   bbbb */\n"
14707             "}",
14708             format("{\n"
14709                    "/* aaaa\n"
14710                    "   bbbb */\n"
14711                    "}",
14712                    Tab));
14713   EXPECT_EQ("{\n"
14714             "\t/*\n"
14715             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14716             "\t  bbbbbbbbbbbbb\n"
14717             "\t*/\n"
14718             "}",
14719             format("{\n"
14720                    "/*\n"
14721                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14722                    "*/\n"
14723                    "}",
14724                    Tab));
14725   EXPECT_EQ("{\n"
14726             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14727             "\t// bbbbbbbbbbbbb\n"
14728             "}",
14729             format("{\n"
14730                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14731                    "}",
14732                    Tab));
14733   EXPECT_EQ("{\n"
14734             "\t/*\n"
14735             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14736             "\t  bbbbbbbbbbbbb\n"
14737             "\t*/\n"
14738             "}",
14739             format("{\n"
14740                    "\t/*\n"
14741                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14742                    "\t*/\n"
14743                    "}",
14744                    Tab));
14745   EXPECT_EQ("{\n"
14746             "\t/*\n"
14747             "\n"
14748             "\t*/\n"
14749             "}",
14750             format("{\n"
14751                    "\t/*\n"
14752                    "\n"
14753                    "\t*/\n"
14754                    "}",
14755                    Tab));
14756   EXPECT_EQ("{\n"
14757             "\t/*\n"
14758             " asdf\n"
14759             "\t*/\n"
14760             "}",
14761             format("{\n"
14762                    "\t/*\n"
14763                    " asdf\n"
14764                    "\t*/\n"
14765                    "}",
14766                    Tab));
14767   EXPECT_EQ("/* some\n"
14768             "   comment */",
14769             format(" \t \t /* some\n"
14770                    " \t \t    comment */",
14771                    Tab));
14772   EXPECT_EQ("int a; /* some\n"
14773             "   comment */",
14774             format(" \t \t int a; /* some\n"
14775                    " \t \t    comment */",
14776                    Tab));
14777   EXPECT_EQ("int a; /* some\n"
14778             "comment */",
14779             format(" \t \t int\ta; /* some\n"
14780                    " \t \t    comment */",
14781                    Tab));
14782   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14783             "    comment */",
14784             format(" \t \t f(\"\t\t\"); /* some\n"
14785                    " \t \t    comment */",
14786                    Tab));
14787   EXPECT_EQ("{\n"
14788             "\t/*\n"
14789             "\t * Comment\n"
14790             "\t */\n"
14791             "\tint i;\n"
14792             "}",
14793             format("{\n"
14794                    "\t/*\n"
14795                    "\t * Comment\n"
14796                    "\t */\n"
14797                    "\t int i;\n"
14798                    "}",
14799                    Tab));
14800   Tab.TabWidth = 2;
14801   Tab.IndentWidth = 2;
14802   EXPECT_EQ("{\n"
14803             "\t/* aaaa\n"
14804             "\t   bbbb */\n"
14805             "}",
14806             format("{\n"
14807                    "/* aaaa\n"
14808                    "   bbbb */\n"
14809                    "}",
14810                    Tab));
14811   EXPECT_EQ("{\n"
14812             "\t/*\n"
14813             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14814             "\t  bbbbbbbbbbbbb\n"
14815             "\t*/\n"
14816             "}",
14817             format("{\n"
14818                    "/*\n"
14819                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14820                    "*/\n"
14821                    "}",
14822                    Tab));
14823   Tab.AlignConsecutiveAssignments.Enabled = true;
14824   Tab.AlignConsecutiveDeclarations.Enabled = true;
14825   Tab.TabWidth = 4;
14826   Tab.IndentWidth = 4;
14827   verifyFormat("class Assign {\n"
14828                "\tvoid f() {\n"
14829                "\t\tint         x      = 123;\n"
14830                "\t\tint         random = 4;\n"
14831                "\t\tstd::string alphabet =\n"
14832                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14833                "\t}\n"
14834                "};",
14835                Tab);
14836   Tab.AlignOperands = FormatStyle::OAS_Align;
14837   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14838                "                 cccccccccccccccccccc;",
14839                Tab);
14840   // no alignment
14841   verifyFormat("int aaaaaaaaaa =\n"
14842                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14843                Tab);
14844   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14845                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14846                "                        : 333333333333333;",
14847                Tab);
14848   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14849   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14850   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14851                "               + cccccccccccccccccccc;",
14852                Tab);
14853 }
14854 
14855 TEST_F(FormatTest, ZeroTabWidth) {
14856   FormatStyle Tab = getLLVMStyleWithColumns(42);
14857   Tab.IndentWidth = 8;
14858   Tab.UseTab = FormatStyle::UT_Never;
14859   Tab.TabWidth = 0;
14860   EXPECT_EQ("void a(){\n"
14861             "    // line starts with '\t'\n"
14862             "};",
14863             format("void a(){\n"
14864                    "\t// line starts with '\t'\n"
14865                    "};",
14866                    Tab));
14867 
14868   EXPECT_EQ("void a(){\n"
14869             "    // line starts with '\t'\n"
14870             "};",
14871             format("void a(){\n"
14872                    "\t\t// line starts with '\t'\n"
14873                    "};",
14874                    Tab));
14875 
14876   Tab.UseTab = FormatStyle::UT_ForIndentation;
14877   EXPECT_EQ("void a(){\n"
14878             "    // line starts with '\t'\n"
14879             "};",
14880             format("void a(){\n"
14881                    "\t// line starts with '\t'\n"
14882                    "};",
14883                    Tab));
14884 
14885   EXPECT_EQ("void a(){\n"
14886             "    // line starts with '\t'\n"
14887             "};",
14888             format("void a(){\n"
14889                    "\t\t// line starts with '\t'\n"
14890                    "};",
14891                    Tab));
14892 
14893   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14894   EXPECT_EQ("void a(){\n"
14895             "    // line starts with '\t'\n"
14896             "};",
14897             format("void a(){\n"
14898                    "\t// line starts with '\t'\n"
14899                    "};",
14900                    Tab));
14901 
14902   EXPECT_EQ("void a(){\n"
14903             "    // line starts with '\t'\n"
14904             "};",
14905             format("void a(){\n"
14906                    "\t\t// line starts with '\t'\n"
14907                    "};",
14908                    Tab));
14909 
14910   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14911   EXPECT_EQ("void a(){\n"
14912             "    // line starts with '\t'\n"
14913             "};",
14914             format("void a(){\n"
14915                    "\t// line starts with '\t'\n"
14916                    "};",
14917                    Tab));
14918 
14919   EXPECT_EQ("void a(){\n"
14920             "    // line starts with '\t'\n"
14921             "};",
14922             format("void a(){\n"
14923                    "\t\t// line starts with '\t'\n"
14924                    "};",
14925                    Tab));
14926 
14927   Tab.UseTab = FormatStyle::UT_Always;
14928   EXPECT_EQ("void a(){\n"
14929             "// line starts with '\t'\n"
14930             "};",
14931             format("void a(){\n"
14932                    "\t// line starts with '\t'\n"
14933                    "};",
14934                    Tab));
14935 
14936   EXPECT_EQ("void a(){\n"
14937             "// line starts with '\t'\n"
14938             "};",
14939             format("void a(){\n"
14940                    "\t\t// line starts with '\t'\n"
14941                    "};",
14942                    Tab));
14943 }
14944 
14945 TEST_F(FormatTest, CalculatesOriginalColumn) {
14946   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14947             "q\"; /* some\n"
14948             "       comment */",
14949             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14950                    "q\"; /* some\n"
14951                    "       comment */",
14952                    getLLVMStyle()));
14953   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14954             "/* some\n"
14955             "   comment */",
14956             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14957                    " /* some\n"
14958                    "    comment */",
14959                    getLLVMStyle()));
14960   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14961             "qqq\n"
14962             "/* some\n"
14963             "   comment */",
14964             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14965                    "qqq\n"
14966                    " /* some\n"
14967                    "    comment */",
14968                    getLLVMStyle()));
14969   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14970             "wwww; /* some\n"
14971             "         comment */",
14972             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14973                    "wwww; /* some\n"
14974                    "         comment */",
14975                    getLLVMStyle()));
14976 }
14977 
14978 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14979   FormatStyle NoSpace = getLLVMStyle();
14980   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14981 
14982   verifyFormat("while(true)\n"
14983                "  continue;",
14984                NoSpace);
14985   verifyFormat("for(;;)\n"
14986                "  continue;",
14987                NoSpace);
14988   verifyFormat("if(true)\n"
14989                "  f();\n"
14990                "else if(true)\n"
14991                "  f();",
14992                NoSpace);
14993   verifyFormat("do {\n"
14994                "  do_something();\n"
14995                "} while(something());",
14996                NoSpace);
14997   verifyFormat("switch(x) {\n"
14998                "default:\n"
14999                "  break;\n"
15000                "}",
15001                NoSpace);
15002   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
15003   verifyFormat("size_t x = sizeof(x);", NoSpace);
15004   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
15005   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
15006   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
15007   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
15008   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
15009   verifyFormat("alignas(128) char a[128];", NoSpace);
15010   verifyFormat("size_t x = alignof(MyType);", NoSpace);
15011   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
15012   verifyFormat("int f() throw(Deprecated);", NoSpace);
15013   verifyFormat("typedef void (*cb)(int);", NoSpace);
15014   verifyFormat("T A::operator()();", NoSpace);
15015   verifyFormat("X A::operator++(T);", NoSpace);
15016   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
15017 
15018   FormatStyle Space = getLLVMStyle();
15019   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
15020 
15021   verifyFormat("int f ();", Space);
15022   verifyFormat("void f (int a, T b) {\n"
15023                "  while (true)\n"
15024                "    continue;\n"
15025                "}",
15026                Space);
15027   verifyFormat("if (true)\n"
15028                "  f ();\n"
15029                "else if (true)\n"
15030                "  f ();",
15031                Space);
15032   verifyFormat("do {\n"
15033                "  do_something ();\n"
15034                "} while (something ());",
15035                Space);
15036   verifyFormat("switch (x) {\n"
15037                "default:\n"
15038                "  break;\n"
15039                "}",
15040                Space);
15041   verifyFormat("A::A () : a (1) {}", Space);
15042   verifyFormat("void f () __attribute__ ((asdf));", Space);
15043   verifyFormat("*(&a + 1);\n"
15044                "&((&a)[1]);\n"
15045                "a[(b + c) * d];\n"
15046                "(((a + 1) * 2) + 3) * 4;",
15047                Space);
15048   verifyFormat("#define A(x) x", Space);
15049   verifyFormat("#define A (x) x", Space);
15050   verifyFormat("#if defined(x)\n"
15051                "#endif",
15052                Space);
15053   verifyFormat("auto i = std::make_unique<int> (5);", Space);
15054   verifyFormat("size_t x = sizeof (x);", Space);
15055   verifyFormat("auto f (int x) -> decltype (x);", Space);
15056   verifyFormat("auto f (int x) -> typeof (x);", Space);
15057   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
15058   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
15059   verifyFormat("int f (T x) noexcept (x.create ());", Space);
15060   verifyFormat("alignas (128) char a[128];", Space);
15061   verifyFormat("size_t x = alignof (MyType);", Space);
15062   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
15063   verifyFormat("int f () throw (Deprecated);", Space);
15064   verifyFormat("typedef void (*cb) (int);", Space);
15065   // FIXME these tests regressed behaviour.
15066   // verifyFormat("T A::operator() ();", Space);
15067   // verifyFormat("X A::operator++ (T);", Space);
15068   verifyFormat("auto lambda = [] () { return 0; };", Space);
15069   verifyFormat("int x = int (y);", Space);
15070 
15071   FormatStyle SomeSpace = getLLVMStyle();
15072   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
15073 
15074   verifyFormat("[]() -> float {}", SomeSpace);
15075   verifyFormat("[] (auto foo) {}", SomeSpace);
15076   verifyFormat("[foo]() -> int {}", SomeSpace);
15077   verifyFormat("int f();", SomeSpace);
15078   verifyFormat("void f (int a, T b) {\n"
15079                "  while (true)\n"
15080                "    continue;\n"
15081                "}",
15082                SomeSpace);
15083   verifyFormat("if (true)\n"
15084                "  f();\n"
15085                "else if (true)\n"
15086                "  f();",
15087                SomeSpace);
15088   verifyFormat("do {\n"
15089                "  do_something();\n"
15090                "} while (something());",
15091                SomeSpace);
15092   verifyFormat("switch (x) {\n"
15093                "default:\n"
15094                "  break;\n"
15095                "}",
15096                SomeSpace);
15097   verifyFormat("A::A() : a (1) {}", SomeSpace);
15098   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
15099   verifyFormat("*(&a + 1);\n"
15100                "&((&a)[1]);\n"
15101                "a[(b + c) * d];\n"
15102                "(((a + 1) * 2) + 3) * 4;",
15103                SomeSpace);
15104   verifyFormat("#define A(x) x", SomeSpace);
15105   verifyFormat("#define A (x) x", SomeSpace);
15106   verifyFormat("#if defined(x)\n"
15107                "#endif",
15108                SomeSpace);
15109   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
15110   verifyFormat("size_t x = sizeof (x);", SomeSpace);
15111   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
15112   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
15113   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
15114   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
15115   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
15116   verifyFormat("alignas (128) char a[128];", SomeSpace);
15117   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
15118   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15119                SomeSpace);
15120   verifyFormat("int f() throw (Deprecated);", SomeSpace);
15121   verifyFormat("typedef void (*cb) (int);", SomeSpace);
15122   verifyFormat("T A::operator()();", SomeSpace);
15123   // FIXME these tests regressed behaviour.
15124   // verifyFormat("X A::operator++ (T);", SomeSpace);
15125   verifyFormat("int x = int (y);", SomeSpace);
15126   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
15127 
15128   FormatStyle SpaceControlStatements = getLLVMStyle();
15129   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15130   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
15131 
15132   verifyFormat("while (true)\n"
15133                "  continue;",
15134                SpaceControlStatements);
15135   verifyFormat("if (true)\n"
15136                "  f();\n"
15137                "else if (true)\n"
15138                "  f();",
15139                SpaceControlStatements);
15140   verifyFormat("for (;;) {\n"
15141                "  do_something();\n"
15142                "}",
15143                SpaceControlStatements);
15144   verifyFormat("do {\n"
15145                "  do_something();\n"
15146                "} while (something());",
15147                SpaceControlStatements);
15148   verifyFormat("switch (x) {\n"
15149                "default:\n"
15150                "  break;\n"
15151                "}",
15152                SpaceControlStatements);
15153 
15154   FormatStyle SpaceFuncDecl = getLLVMStyle();
15155   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15156   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
15157 
15158   verifyFormat("int f ();", SpaceFuncDecl);
15159   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
15160   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
15161   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
15162   verifyFormat("#define A(x) x", SpaceFuncDecl);
15163   verifyFormat("#define A (x) x", SpaceFuncDecl);
15164   verifyFormat("#if defined(x)\n"
15165                "#endif",
15166                SpaceFuncDecl);
15167   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
15168   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
15169   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
15170   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
15171   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
15172   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
15173   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
15174   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
15175   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
15176   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15177                SpaceFuncDecl);
15178   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
15179   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
15180   // FIXME these tests regressed behaviour.
15181   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
15182   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
15183   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
15184   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
15185   verifyFormat("int x = int(y);", SpaceFuncDecl);
15186   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15187                SpaceFuncDecl);
15188 
15189   FormatStyle SpaceFuncDef = getLLVMStyle();
15190   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15191   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
15192 
15193   verifyFormat("int f();", SpaceFuncDef);
15194   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
15195   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
15196   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
15197   verifyFormat("#define A(x) x", SpaceFuncDef);
15198   verifyFormat("#define A (x) x", SpaceFuncDef);
15199   verifyFormat("#if defined(x)\n"
15200                "#endif",
15201                SpaceFuncDef);
15202   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
15203   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
15204   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
15205   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
15206   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
15207   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
15208   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
15209   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
15210   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
15211   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15212                SpaceFuncDef);
15213   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
15214   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
15215   verifyFormat("T A::operator()();", SpaceFuncDef);
15216   verifyFormat("X A::operator++(T);", SpaceFuncDef);
15217   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
15218   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
15219   verifyFormat("int x = int(y);", SpaceFuncDef);
15220   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15221                SpaceFuncDef);
15222 
15223   FormatStyle SpaceIfMacros = getLLVMStyle();
15224   SpaceIfMacros.IfMacros.clear();
15225   SpaceIfMacros.IfMacros.push_back("MYIF");
15226   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15227   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
15228   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
15229   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
15230   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
15231 
15232   FormatStyle SpaceForeachMacros = getLLVMStyle();
15233   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
15234             FormatStyle::SBS_Never);
15235   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
15236   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15237   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
15238   verifyFormat("for (;;) {\n"
15239                "}",
15240                SpaceForeachMacros);
15241   verifyFormat("foreach (Item *item, itemlist) {\n"
15242                "}",
15243                SpaceForeachMacros);
15244   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15245                "}",
15246                SpaceForeachMacros);
15247   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15248                "}",
15249                SpaceForeachMacros);
15250   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15251 
15252   FormatStyle SomeSpace2 = getLLVMStyle();
15253   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15254   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15255   verifyFormat("[]() -> float {}", SomeSpace2);
15256   verifyFormat("[] (auto foo) {}", SomeSpace2);
15257   verifyFormat("[foo]() -> int {}", SomeSpace2);
15258   verifyFormat("int f();", SomeSpace2);
15259   verifyFormat("void f (int a, T b) {\n"
15260                "  while (true)\n"
15261                "    continue;\n"
15262                "}",
15263                SomeSpace2);
15264   verifyFormat("if (true)\n"
15265                "  f();\n"
15266                "else if (true)\n"
15267                "  f();",
15268                SomeSpace2);
15269   verifyFormat("do {\n"
15270                "  do_something();\n"
15271                "} while (something());",
15272                SomeSpace2);
15273   verifyFormat("switch (x) {\n"
15274                "default:\n"
15275                "  break;\n"
15276                "}",
15277                SomeSpace2);
15278   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15279   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15280   verifyFormat("*(&a + 1);\n"
15281                "&((&a)[1]);\n"
15282                "a[(b + c) * d];\n"
15283                "(((a + 1) * 2) + 3) * 4;",
15284                SomeSpace2);
15285   verifyFormat("#define A(x) x", SomeSpace2);
15286   verifyFormat("#define A (x) x", SomeSpace2);
15287   verifyFormat("#if defined(x)\n"
15288                "#endif",
15289                SomeSpace2);
15290   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15291   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15292   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15293   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15294   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15295   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15296   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15297   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15298   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15299   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15300                SomeSpace2);
15301   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15302   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15303   verifyFormat("T A::operator()();", SomeSpace2);
15304   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15305   verifyFormat("int x = int (y);", SomeSpace2);
15306   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15307 
15308   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15309   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15310   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15311       .AfterOverloadedOperator = true;
15312 
15313   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15314   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15315   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15316   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15317 
15318   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15319       .AfterOverloadedOperator = false;
15320 
15321   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15322   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15323   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15324   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15325 
15326   auto SpaceAfterRequires = getLLVMStyle();
15327   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15328   EXPECT_FALSE(
15329       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15330   EXPECT_FALSE(
15331       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15332   verifyFormat("void f(auto x)\n"
15333                "  requires requires(int i) { x + i; }\n"
15334                "{}",
15335                SpaceAfterRequires);
15336   verifyFormat("void f(auto x)\n"
15337                "  requires(requires(int i) { x + i; })\n"
15338                "{}",
15339                SpaceAfterRequires);
15340   verifyFormat("if (requires(int i) { x + i; })\n"
15341                "  return;",
15342                SpaceAfterRequires);
15343   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15344   verifyFormat("template <typename T>\n"
15345                "  requires(Foo<T>)\n"
15346                "class Bar;",
15347                SpaceAfterRequires);
15348 
15349   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15350   verifyFormat("void f(auto x)\n"
15351                "  requires requires(int i) { x + i; }\n"
15352                "{}",
15353                SpaceAfterRequires);
15354   verifyFormat("void f(auto x)\n"
15355                "  requires (requires(int i) { x + i; })\n"
15356                "{}",
15357                SpaceAfterRequires);
15358   verifyFormat("if (requires(int i) { x + i; })\n"
15359                "  return;",
15360                SpaceAfterRequires);
15361   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15362   verifyFormat("template <typename T>\n"
15363                "  requires (Foo<T>)\n"
15364                "class Bar;",
15365                SpaceAfterRequires);
15366 
15367   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15368   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15369   verifyFormat("void f(auto x)\n"
15370                "  requires requires (int i) { x + i; }\n"
15371                "{}",
15372                SpaceAfterRequires);
15373   verifyFormat("void f(auto x)\n"
15374                "  requires(requires (int i) { x + i; })\n"
15375                "{}",
15376                SpaceAfterRequires);
15377   verifyFormat("if (requires (int i) { x + i; })\n"
15378                "  return;",
15379                SpaceAfterRequires);
15380   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15381   verifyFormat("template <typename T>\n"
15382                "  requires(Foo<T>)\n"
15383                "class Bar;",
15384                SpaceAfterRequires);
15385 
15386   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15387   verifyFormat("void f(auto x)\n"
15388                "  requires requires (int i) { x + i; }\n"
15389                "{}",
15390                SpaceAfterRequires);
15391   verifyFormat("void f(auto x)\n"
15392                "  requires (requires (int i) { x + i; })\n"
15393                "{}",
15394                SpaceAfterRequires);
15395   verifyFormat("if (requires (int i) { x + i; })\n"
15396                "  return;",
15397                SpaceAfterRequires);
15398   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15399   verifyFormat("template <typename T>\n"
15400                "  requires (Foo<T>)\n"
15401                "class Bar;",
15402                SpaceAfterRequires);
15403 }
15404 
15405 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15406   FormatStyle Spaces = getLLVMStyle();
15407   Spaces.SpaceAfterLogicalNot = true;
15408 
15409   verifyFormat("bool x = ! y", Spaces);
15410   verifyFormat("if (! isFailure())", Spaces);
15411   verifyFormat("if (! (a && b))", Spaces);
15412   verifyFormat("\"Error!\"", Spaces);
15413   verifyFormat("! ! x", Spaces);
15414 }
15415 
15416 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15417   FormatStyle Spaces = getLLVMStyle();
15418 
15419   Spaces.SpacesInParentheses = true;
15420   verifyFormat("do_something( ::globalVar );", Spaces);
15421   verifyFormat("call( x, y, z );", Spaces);
15422   verifyFormat("call();", Spaces);
15423   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15424   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15425                Spaces);
15426   verifyFormat("while ( (bool)1 )\n"
15427                "  continue;",
15428                Spaces);
15429   verifyFormat("for ( ;; )\n"
15430                "  continue;",
15431                Spaces);
15432   verifyFormat("if ( true )\n"
15433                "  f();\n"
15434                "else if ( true )\n"
15435                "  f();",
15436                Spaces);
15437   verifyFormat("do {\n"
15438                "  do_something( (int)i );\n"
15439                "} while ( something() );",
15440                Spaces);
15441   verifyFormat("switch ( x ) {\n"
15442                "default:\n"
15443                "  break;\n"
15444                "}",
15445                Spaces);
15446 
15447   Spaces.SpacesInParentheses = false;
15448   Spaces.SpacesInCStyleCastParentheses = true;
15449   verifyFormat("Type *A = ( Type * )P;", Spaces);
15450   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15451   verifyFormat("x = ( int32 )y;", Spaces);
15452   verifyFormat("int a = ( int )(2.0f);", Spaces);
15453   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15454   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15455   verifyFormat("#define x (( int )-1)", Spaces);
15456 
15457   // Run the first set of tests again with:
15458   Spaces.SpacesInParentheses = false;
15459   Spaces.SpaceInEmptyParentheses = true;
15460   Spaces.SpacesInCStyleCastParentheses = true;
15461   verifyFormat("call(x, y, z);", Spaces);
15462   verifyFormat("call( );", Spaces);
15463   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15464   verifyFormat("while (( bool )1)\n"
15465                "  continue;",
15466                Spaces);
15467   verifyFormat("for (;;)\n"
15468                "  continue;",
15469                Spaces);
15470   verifyFormat("if (true)\n"
15471                "  f( );\n"
15472                "else if (true)\n"
15473                "  f( );",
15474                Spaces);
15475   verifyFormat("do {\n"
15476                "  do_something(( int )i);\n"
15477                "} while (something( ));",
15478                Spaces);
15479   verifyFormat("switch (x) {\n"
15480                "default:\n"
15481                "  break;\n"
15482                "}",
15483                Spaces);
15484 
15485   // Run the first set of tests again with:
15486   Spaces.SpaceAfterCStyleCast = true;
15487   verifyFormat("call(x, y, z);", Spaces);
15488   verifyFormat("call( );", Spaces);
15489   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15490   verifyFormat("while (( bool ) 1)\n"
15491                "  continue;",
15492                Spaces);
15493   verifyFormat("for (;;)\n"
15494                "  continue;",
15495                Spaces);
15496   verifyFormat("if (true)\n"
15497                "  f( );\n"
15498                "else if (true)\n"
15499                "  f( );",
15500                Spaces);
15501   verifyFormat("do {\n"
15502                "  do_something(( int ) i);\n"
15503                "} while (something( ));",
15504                Spaces);
15505   verifyFormat("switch (x) {\n"
15506                "default:\n"
15507                "  break;\n"
15508                "}",
15509                Spaces);
15510   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15511   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15512   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15513   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15514   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15515 
15516   // Run subset of tests again with:
15517   Spaces.SpacesInCStyleCastParentheses = false;
15518   Spaces.SpaceAfterCStyleCast = true;
15519   verifyFormat("while ((bool) 1)\n"
15520                "  continue;",
15521                Spaces);
15522   verifyFormat("do {\n"
15523                "  do_something((int) i);\n"
15524                "} while (something( ));",
15525                Spaces);
15526 
15527   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15528   verifyFormat("size_t idx = (size_t) a;", Spaces);
15529   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15530   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15531   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15532   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15533   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15534   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15535   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15536   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15537   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15538   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15539   Spaces.ColumnLimit = 80;
15540   Spaces.IndentWidth = 4;
15541   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15542   verifyFormat("void foo( ) {\n"
15543                "    size_t foo = (*(function))(\n"
15544                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15545                "BarrrrrrrrrrrrLong,\n"
15546                "        FoooooooooLooooong);\n"
15547                "}",
15548                Spaces);
15549   Spaces.SpaceAfterCStyleCast = false;
15550   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15551   verifyFormat("size_t idx = (size_t)a;", Spaces);
15552   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15553   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15554   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15555   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15556   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15557 
15558   verifyFormat("void foo( ) {\n"
15559                "    size_t foo = (*(function))(\n"
15560                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15561                "BarrrrrrrrrrrrLong,\n"
15562                "        FoooooooooLooooong);\n"
15563                "}",
15564                Spaces);
15565 }
15566 
15567 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15568   verifyFormat("int a[5];");
15569   verifyFormat("a[3] += 42;");
15570 
15571   FormatStyle Spaces = getLLVMStyle();
15572   Spaces.SpacesInSquareBrackets = true;
15573   // Not lambdas.
15574   verifyFormat("int a[ 5 ];", Spaces);
15575   verifyFormat("a[ 3 ] += 42;", Spaces);
15576   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15577   verifyFormat("double &operator[](int i) { return 0; }\n"
15578                "int i;",
15579                Spaces);
15580   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15581   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15582   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15583   // Lambdas.
15584   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15585   verifyFormat("return [ i, args... ] {};", Spaces);
15586   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15587   verifyFormat("int foo = [ = ]() {};", Spaces);
15588   verifyFormat("int foo = [ & ]() {};", Spaces);
15589   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15590   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15591 }
15592 
15593 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15594   FormatStyle NoSpaceStyle = getLLVMStyle();
15595   verifyFormat("int a[5];", NoSpaceStyle);
15596   verifyFormat("a[3] += 42;", NoSpaceStyle);
15597 
15598   verifyFormat("int a[1];", NoSpaceStyle);
15599   verifyFormat("int 1 [a];", NoSpaceStyle);
15600   verifyFormat("int a[1][2];", NoSpaceStyle);
15601   verifyFormat("a[7] = 5;", NoSpaceStyle);
15602   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15603   verifyFormat("f([] {})", NoSpaceStyle);
15604 
15605   FormatStyle Space = getLLVMStyle();
15606   Space.SpaceBeforeSquareBrackets = true;
15607   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15608   verifyFormat("return [i, args...] {};", Space);
15609 
15610   verifyFormat("int a [5];", Space);
15611   verifyFormat("a [3] += 42;", Space);
15612   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15613   verifyFormat("double &operator[](int i) { return 0; }\n"
15614                "int i;",
15615                Space);
15616   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15617   verifyFormat("int i = a [a][a]->f();", Space);
15618   verifyFormat("int i = (*b) [a]->f();", Space);
15619 
15620   verifyFormat("int a [1];", Space);
15621   verifyFormat("int 1 [a];", Space);
15622   verifyFormat("int a [1][2];", Space);
15623   verifyFormat("a [7] = 5;", Space);
15624   verifyFormat("int a = (f()) [23];", Space);
15625   verifyFormat("f([] {})", Space);
15626 }
15627 
15628 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15629   verifyFormat("int a = 5;");
15630   verifyFormat("a += 42;");
15631   verifyFormat("a or_eq 8;");
15632 
15633   FormatStyle Spaces = getLLVMStyle();
15634   Spaces.SpaceBeforeAssignmentOperators = false;
15635   verifyFormat("int a= 5;", Spaces);
15636   verifyFormat("a+= 42;", Spaces);
15637   verifyFormat("a or_eq 8;", Spaces);
15638 }
15639 
15640 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15641   verifyFormat("class Foo : public Bar {};");
15642   verifyFormat("Foo::Foo() : foo(1) {}");
15643   verifyFormat("for (auto a : b) {\n}");
15644   verifyFormat("int x = a ? b : c;");
15645   verifyFormat("{\n"
15646                "label0:\n"
15647                "  int x = 0;\n"
15648                "}");
15649   verifyFormat("switch (x) {\n"
15650                "case 1:\n"
15651                "default:\n"
15652                "}");
15653   verifyFormat("switch (allBraces) {\n"
15654                "case 1: {\n"
15655                "  break;\n"
15656                "}\n"
15657                "case 2: {\n"
15658                "  [[fallthrough]];\n"
15659                "}\n"
15660                "default: {\n"
15661                "  break;\n"
15662                "}\n"
15663                "}");
15664 
15665   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15666   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15667   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15668   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15669   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15670   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15671   verifyFormat("{\n"
15672                "label1:\n"
15673                "  int x = 0;\n"
15674                "}",
15675                CtorInitializerStyle);
15676   verifyFormat("switch (x) {\n"
15677                "case 1:\n"
15678                "default:\n"
15679                "}",
15680                CtorInitializerStyle);
15681   verifyFormat("switch (allBraces) {\n"
15682                "case 1: {\n"
15683                "  break;\n"
15684                "}\n"
15685                "case 2: {\n"
15686                "  [[fallthrough]];\n"
15687                "}\n"
15688                "default: {\n"
15689                "  break;\n"
15690                "}\n"
15691                "}",
15692                CtorInitializerStyle);
15693   CtorInitializerStyle.BreakConstructorInitializers =
15694       FormatStyle::BCIS_AfterColon;
15695   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15696                "    aaaaaaaaaaaaaaaa(1),\n"
15697                "    bbbbbbbbbbbbbbbb(2) {}",
15698                CtorInitializerStyle);
15699   CtorInitializerStyle.BreakConstructorInitializers =
15700       FormatStyle::BCIS_BeforeComma;
15701   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15702                "    : aaaaaaaaaaaaaaaa(1)\n"
15703                "    , bbbbbbbbbbbbbbbb(2) {}",
15704                CtorInitializerStyle);
15705   CtorInitializerStyle.BreakConstructorInitializers =
15706       FormatStyle::BCIS_BeforeColon;
15707   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15708                "    : aaaaaaaaaaaaaaaa(1),\n"
15709                "      bbbbbbbbbbbbbbbb(2) {}",
15710                CtorInitializerStyle);
15711   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15712   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15713                ": aaaaaaaaaaaaaaaa(1),\n"
15714                "  bbbbbbbbbbbbbbbb(2) {}",
15715                CtorInitializerStyle);
15716 
15717   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15718   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15719   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15720   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15721   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15722   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15723   verifyFormat("{\n"
15724                "label2:\n"
15725                "  int x = 0;\n"
15726                "}",
15727                InheritanceStyle);
15728   verifyFormat("switch (x) {\n"
15729                "case 1:\n"
15730                "default:\n"
15731                "}",
15732                InheritanceStyle);
15733   verifyFormat("switch (allBraces) {\n"
15734                "case 1: {\n"
15735                "  break;\n"
15736                "}\n"
15737                "case 2: {\n"
15738                "  [[fallthrough]];\n"
15739                "}\n"
15740                "default: {\n"
15741                "  break;\n"
15742                "}\n"
15743                "}",
15744                InheritanceStyle);
15745   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15746   verifyFormat("class Foooooooooooooooooooooo\n"
15747                "    : public aaaaaaaaaaaaaaaaaa,\n"
15748                "      public bbbbbbbbbbbbbbbbbb {\n"
15749                "}",
15750                InheritanceStyle);
15751   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15752   verifyFormat("class Foooooooooooooooooooooo:\n"
15753                "    public aaaaaaaaaaaaaaaaaa,\n"
15754                "    public bbbbbbbbbbbbbbbbbb {\n"
15755                "}",
15756                InheritanceStyle);
15757   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15758   verifyFormat("class Foooooooooooooooooooooo\n"
15759                "    : public aaaaaaaaaaaaaaaaaa\n"
15760                "    , public bbbbbbbbbbbbbbbbbb {\n"
15761                "}",
15762                InheritanceStyle);
15763   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15764   verifyFormat("class Foooooooooooooooooooooo\n"
15765                "    : public aaaaaaaaaaaaaaaaaa,\n"
15766                "      public bbbbbbbbbbbbbbbbbb {\n"
15767                "}",
15768                InheritanceStyle);
15769   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15770   verifyFormat("class Foooooooooooooooooooooo\n"
15771                ": public aaaaaaaaaaaaaaaaaa,\n"
15772                "  public bbbbbbbbbbbbbbbbbb {}",
15773                InheritanceStyle);
15774 
15775   FormatStyle ForLoopStyle = getLLVMStyle();
15776   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15777   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15778   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15779   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15780   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15781   verifyFormat("{\n"
15782                "label2:\n"
15783                "  int x = 0;\n"
15784                "}",
15785                ForLoopStyle);
15786   verifyFormat("switch (x) {\n"
15787                "case 1:\n"
15788                "default:\n"
15789                "}",
15790                ForLoopStyle);
15791   verifyFormat("switch (allBraces) {\n"
15792                "case 1: {\n"
15793                "  break;\n"
15794                "}\n"
15795                "case 2: {\n"
15796                "  [[fallthrough]];\n"
15797                "}\n"
15798                "default: {\n"
15799                "  break;\n"
15800                "}\n"
15801                "}",
15802                ForLoopStyle);
15803 
15804   FormatStyle CaseStyle = getLLVMStyle();
15805   CaseStyle.SpaceBeforeCaseColon = true;
15806   verifyFormat("class Foo : public Bar {};", CaseStyle);
15807   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15808   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15809   verifyFormat("int x = a ? b : c;", CaseStyle);
15810   verifyFormat("switch (x) {\n"
15811                "case 1 :\n"
15812                "default :\n"
15813                "}",
15814                CaseStyle);
15815   verifyFormat("switch (allBraces) {\n"
15816                "case 1 : {\n"
15817                "  break;\n"
15818                "}\n"
15819                "case 2 : {\n"
15820                "  [[fallthrough]];\n"
15821                "}\n"
15822                "default : {\n"
15823                "  break;\n"
15824                "}\n"
15825                "}",
15826                CaseStyle);
15827 
15828   FormatStyle NoSpaceStyle = getLLVMStyle();
15829   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15830   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15831   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15832   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15833   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15834   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15835   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15836   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15837   verifyFormat("{\n"
15838                "label3:\n"
15839                "  int x = 0;\n"
15840                "}",
15841                NoSpaceStyle);
15842   verifyFormat("switch (x) {\n"
15843                "case 1:\n"
15844                "default:\n"
15845                "}",
15846                NoSpaceStyle);
15847   verifyFormat("switch (allBraces) {\n"
15848                "case 1: {\n"
15849                "  break;\n"
15850                "}\n"
15851                "case 2: {\n"
15852                "  [[fallthrough]];\n"
15853                "}\n"
15854                "default: {\n"
15855                "  break;\n"
15856                "}\n"
15857                "}",
15858                NoSpaceStyle);
15859 
15860   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15861   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15862   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15863   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15864   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15865   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15866   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15867   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15868   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15869   verifyFormat("{\n"
15870                "label3:\n"
15871                "  int x = 0;\n"
15872                "}",
15873                InvertedSpaceStyle);
15874   verifyFormat("switch (x) {\n"
15875                "case 1 :\n"
15876                "case 2 : {\n"
15877                "  break;\n"
15878                "}\n"
15879                "default :\n"
15880                "  break;\n"
15881                "}",
15882                InvertedSpaceStyle);
15883   verifyFormat("switch (allBraces) {\n"
15884                "case 1 : {\n"
15885                "  break;\n"
15886                "}\n"
15887                "case 2 : {\n"
15888                "  [[fallthrough]];\n"
15889                "}\n"
15890                "default : {\n"
15891                "  break;\n"
15892                "}\n"
15893                "}",
15894                InvertedSpaceStyle);
15895 }
15896 
15897 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15898   FormatStyle Style = getLLVMStyle();
15899 
15900   Style.PointerAlignment = FormatStyle::PAS_Left;
15901   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15902   verifyFormat("void* const* x = NULL;", Style);
15903 
15904 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15905   do {                                                                         \
15906     Style.PointerAlignment = FormatStyle::Pointers;                            \
15907     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15908     verifyFormat(Code, Style);                                                 \
15909   } while (false)
15910 
15911   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15912   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15913   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15914 
15915   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15916   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15917   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15918 
15919   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15920   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15921   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15922 
15923   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15924   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15925   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15926 
15927   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15928   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15929                         SAPQ_Default);
15930   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15931                         SAPQ_Default);
15932 
15933   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15934   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15935                         SAPQ_Before);
15936   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15937                         SAPQ_Before);
15938 
15939   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15940   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15941   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15942                         SAPQ_After);
15943 
15944   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15945   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15946   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15947 
15948 #undef verifyQualifierSpaces
15949 
15950   FormatStyle Spaces = getLLVMStyle();
15951   Spaces.AttributeMacros.push_back("qualified");
15952   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15953   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15954   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15955   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15956   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15957   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15958   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15959   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15960   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15961   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15962   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15963   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15964   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15965 
15966   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15967   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15968   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15969   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15970   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15971   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15972   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15973   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15974   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15975   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15976   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15977   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15978   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15979   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15980   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15981 
15982   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15983   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15984   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15985   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15986   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15987   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15988   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15989   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15990 }
15991 
15992 TEST_F(FormatTest, AlignConsecutiveMacros) {
15993   FormatStyle Style = getLLVMStyle();
15994   Style.AlignConsecutiveAssignments.Enabled = true;
15995   Style.AlignConsecutiveDeclarations.Enabled = true;
15996 
15997   verifyFormat("#define a 3\n"
15998                "#define bbbb 4\n"
15999                "#define ccc (5)",
16000                Style);
16001 
16002   verifyFormat("#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 foo(x, y) (x + y)\n"
16008                "#define bar (5, 6)(2 + 2)",
16009                Style);
16010 
16011   verifyFormat("#define a 3\n"
16012                "#define bbbb 4\n"
16013                "#define ccc (5)\n"
16014                "#define f(x) (x * x)\n"
16015                "#define fff(x, y, z) (x * y + z)\n"
16016                "#define ffff(x, y) (x - y)",
16017                Style);
16018 
16019   Style.AlignConsecutiveMacros.Enabled = true;
16020   verifyFormat("#define a    3\n"
16021                "#define bbbb 4\n"
16022                "#define ccc  (5)",
16023                Style);
16024 
16025   verifyFormat("#define f(x)         (x * x)\n"
16026                "#define fff(x, y, z) (x * y + z)\n"
16027                "#define ffff(x, y)   (x - y)",
16028                Style);
16029 
16030   verifyFormat("#define foo(x, y) (x + y)\n"
16031                "#define bar       (5, 6)(2 + 2)",
16032                Style);
16033 
16034   verifyFormat("#define a            3\n"
16035                "#define bbbb         4\n"
16036                "#define ccc          (5)\n"
16037                "#define f(x)         (x * x)\n"
16038                "#define fff(x, y, z) (x * y + z)\n"
16039                "#define ffff(x, y)   (x - y)",
16040                Style);
16041 
16042   verifyFormat("#define a         5\n"
16043                "#define foo(x, y) (x + y)\n"
16044                "#define CCC       (6)\n"
16045                "auto lambda = []() {\n"
16046                "  auto  ii = 0;\n"
16047                "  float j  = 0;\n"
16048                "  return 0;\n"
16049                "};\n"
16050                "int   i  = 0;\n"
16051                "float i2 = 0;\n"
16052                "auto  v  = type{\n"
16053                "    i = 1,   //\n"
16054                "    (i = 2), //\n"
16055                "    i = 3    //\n"
16056                "};",
16057                Style);
16058 
16059   Style.AlignConsecutiveMacros.Enabled = false;
16060   Style.ColumnLimit = 20;
16061 
16062   verifyFormat("#define a          \\\n"
16063                "  \"aabbbbbbbbbbbb\"\n"
16064                "#define D          \\\n"
16065                "  \"aabbbbbbbbbbbb\" \\\n"
16066                "  \"ccddeeeeeeeee\"\n"
16067                "#define B          \\\n"
16068                "  \"QQQQQQQQQQQQQ\"  \\\n"
16069                "  \"FFFFFFFFFFFFF\"  \\\n"
16070                "  \"LLLLLLLL\"\n",
16071                Style);
16072 
16073   Style.AlignConsecutiveMacros.Enabled = true;
16074   verifyFormat("#define a          \\\n"
16075                "  \"aabbbbbbbbbbbb\"\n"
16076                "#define D          \\\n"
16077                "  \"aabbbbbbbbbbbb\" \\\n"
16078                "  \"ccddeeeeeeeee\"\n"
16079                "#define B          \\\n"
16080                "  \"QQQQQQQQQQQQQ\"  \\\n"
16081                "  \"FFFFFFFFFFFFF\"  \\\n"
16082                "  \"LLLLLLLL\"\n",
16083                Style);
16084 
16085   // Test across comments
16086   Style.MaxEmptyLinesToKeep = 10;
16087   Style.ReflowComments = false;
16088   Style.AlignConsecutiveMacros.AcrossComments = true;
16089   EXPECT_EQ("#define a    3\n"
16090             "// line comment\n"
16091             "#define bbbb 4\n"
16092             "#define ccc  (5)",
16093             format("#define a 3\n"
16094                    "// line comment\n"
16095                    "#define bbbb 4\n"
16096                    "#define ccc (5)",
16097                    Style));
16098 
16099   EXPECT_EQ("#define a    3\n"
16100             "/* block comment */\n"
16101             "#define bbbb 4\n"
16102             "#define ccc  (5)",
16103             format("#define a  3\n"
16104                    "/* block comment */\n"
16105                    "#define bbbb 4\n"
16106                    "#define ccc (5)",
16107                    Style));
16108 
16109   EXPECT_EQ("#define a    3\n"
16110             "/* multi-line *\n"
16111             " * block comment */\n"
16112             "#define bbbb 4\n"
16113             "#define ccc  (5)",
16114             format("#define a 3\n"
16115                    "/* multi-line *\n"
16116                    " * block comment */\n"
16117                    "#define bbbb 4\n"
16118                    "#define ccc (5)",
16119                    Style));
16120 
16121   EXPECT_EQ("#define a    3\n"
16122             "// multi-line line comment\n"
16123             "//\n"
16124             "#define bbbb 4\n"
16125             "#define ccc  (5)",
16126             format("#define a  3\n"
16127                    "// multi-line line comment\n"
16128                    "//\n"
16129                    "#define bbbb 4\n"
16130                    "#define ccc (5)",
16131                    Style));
16132 
16133   EXPECT_EQ("#define a 3\n"
16134             "// empty lines still break.\n"
16135             "\n"
16136             "#define bbbb 4\n"
16137             "#define ccc  (5)",
16138             format("#define a     3\n"
16139                    "// empty lines still break.\n"
16140                    "\n"
16141                    "#define bbbb     4\n"
16142                    "#define ccc  (5)",
16143                    Style));
16144 
16145   // Test across empty lines
16146   Style.AlignConsecutiveMacros.AcrossComments = false;
16147   Style.AlignConsecutiveMacros.AcrossEmptyLines = true;
16148   EXPECT_EQ("#define a    3\n"
16149             "\n"
16150             "#define bbbb 4\n"
16151             "#define ccc  (5)",
16152             format("#define a 3\n"
16153                    "\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             "\n"
16162             "#define bbbb 4\n"
16163             "#define ccc  (5)",
16164             format("#define a        3\n"
16165                    "\n"
16166                    "\n"
16167                    "\n"
16168                    "#define bbbb 4\n"
16169                    "#define ccc (5)",
16170                    Style));
16171 
16172   EXPECT_EQ("#define a 3\n"
16173             "// comments should break alignment\n"
16174             "//\n"
16175             "#define bbbb 4\n"
16176             "#define ccc  (5)",
16177             format("#define a        3\n"
16178                    "// comments should break alignment\n"
16179                    "//\n"
16180                    "#define bbbb 4\n"
16181                    "#define ccc (5)",
16182                    Style));
16183 
16184   // Test across empty lines and comments
16185   Style.AlignConsecutiveMacros.AcrossComments = true;
16186   verifyFormat("#define a    3\n"
16187                "\n"
16188                "// line comment\n"
16189                "#define bbbb 4\n"
16190                "#define ccc  (5)",
16191                Style);
16192 
16193   EXPECT_EQ("#define a    3\n"
16194             "\n"
16195             "\n"
16196             "/* multi-line *\n"
16197             " * block comment */\n"
16198             "\n"
16199             "\n"
16200             "#define bbbb 4\n"
16201             "#define ccc  (5)",
16202             format("#define a 3\n"
16203                    "\n"
16204                    "\n"
16205                    "/* multi-line *\n"
16206                    " * block comment */\n"
16207                    "\n"
16208                    "\n"
16209                    "#define bbbb 4\n"
16210                    "#define ccc (5)",
16211                    Style));
16212 
16213   EXPECT_EQ("#define a    3\n"
16214             "\n"
16215             "\n"
16216             "/* multi-line *\n"
16217             " * block comment */\n"
16218             "\n"
16219             "\n"
16220             "#define bbbb 4\n"
16221             "#define ccc  (5)",
16222             format("#define a 3\n"
16223                    "\n"
16224                    "\n"
16225                    "/* multi-line *\n"
16226                    " * block comment */\n"
16227                    "\n"
16228                    "\n"
16229                    "#define bbbb 4\n"
16230                    "#define ccc       (5)",
16231                    Style));
16232 }
16233 
16234 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
16235   FormatStyle Alignment = getLLVMStyle();
16236   Alignment.AlignConsecutiveMacros.Enabled = true;
16237   Alignment.AlignConsecutiveAssignments.Enabled = true;
16238   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16239 
16240   Alignment.MaxEmptyLinesToKeep = 10;
16241   /* Test alignment across empty lines */
16242   EXPECT_EQ("int a           = 5;\n"
16243             "\n"
16244             "int oneTwoThree = 123;",
16245             format("int a       = 5;\n"
16246                    "\n"
16247                    "int oneTwoThree= 123;",
16248                    Alignment));
16249   EXPECT_EQ("int a           = 5;\n"
16250             "int one         = 1;\n"
16251             "\n"
16252             "int oneTwoThree = 123;",
16253             format("int a = 5;\n"
16254                    "int one = 1;\n"
16255                    "\n"
16256                    "int oneTwoThree = 123;",
16257                    Alignment));
16258   EXPECT_EQ("int a           = 5;\n"
16259             "int one         = 1;\n"
16260             "\n"
16261             "int oneTwoThree = 123;\n"
16262             "int oneTwo      = 12;",
16263             format("int a = 5;\n"
16264                    "int one = 1;\n"
16265                    "\n"
16266                    "int oneTwoThree = 123;\n"
16267                    "int oneTwo = 12;",
16268                    Alignment));
16269 
16270   /* Test across comments */
16271   EXPECT_EQ("int a = 5;\n"
16272             "/* block comment */\n"
16273             "int oneTwoThree = 123;",
16274             format("int a = 5;\n"
16275                    "/* block comment */\n"
16276                    "int oneTwoThree=123;",
16277                    Alignment));
16278 
16279   EXPECT_EQ("int a = 5;\n"
16280             "// line comment\n"
16281             "int oneTwoThree = 123;",
16282             format("int a = 5;\n"
16283                    "// line comment\n"
16284                    "int oneTwoThree=123;",
16285                    Alignment));
16286 
16287   /* Test across comments and newlines */
16288   EXPECT_EQ("int a = 5;\n"
16289             "\n"
16290             "/* block comment */\n"
16291             "int oneTwoThree = 123;",
16292             format("int a = 5;\n"
16293                    "\n"
16294                    "/* block comment */\n"
16295                    "int oneTwoThree=123;",
16296                    Alignment));
16297 
16298   EXPECT_EQ("int a = 5;\n"
16299             "\n"
16300             "// line comment\n"
16301             "int oneTwoThree = 123;",
16302             format("int a = 5;\n"
16303                    "\n"
16304                    "// line comment\n"
16305                    "int oneTwoThree=123;",
16306                    Alignment));
16307 }
16308 
16309 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16310   FormatStyle Alignment = getLLVMStyle();
16311   Alignment.AlignConsecutiveDeclarations.Enabled = true;
16312   Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true;
16313   Alignment.AlignConsecutiveDeclarations.AcrossComments = true;
16314 
16315   Alignment.MaxEmptyLinesToKeep = 10;
16316   /* Test alignment across empty lines */
16317   EXPECT_EQ("int         a = 5;\n"
16318             "\n"
16319             "float const oneTwoThree = 123;",
16320             format("int a = 5;\n"
16321                    "\n"
16322                    "float const oneTwoThree = 123;",
16323                    Alignment));
16324   EXPECT_EQ("int         a = 5;\n"
16325             "float const one = 1;\n"
16326             "\n"
16327             "int         oneTwoThree = 123;",
16328             format("int a = 5;\n"
16329                    "float const one = 1;\n"
16330                    "\n"
16331                    "int oneTwoThree = 123;",
16332                    Alignment));
16333 
16334   /* Test across comments */
16335   EXPECT_EQ("float const a = 5;\n"
16336             "/* block comment */\n"
16337             "int         oneTwoThree = 123;",
16338             format("float const a = 5;\n"
16339                    "/* block comment */\n"
16340                    "int oneTwoThree=123;",
16341                    Alignment));
16342 
16343   EXPECT_EQ("float const a = 5;\n"
16344             "// line comment\n"
16345             "int         oneTwoThree = 123;",
16346             format("float const a = 5;\n"
16347                    "// line comment\n"
16348                    "int oneTwoThree=123;",
16349                    Alignment));
16350 
16351   /* Test across comments and newlines */
16352   EXPECT_EQ("float const a = 5;\n"
16353             "\n"
16354             "/* block comment */\n"
16355             "int         oneTwoThree = 123;",
16356             format("float const a = 5;\n"
16357                    "\n"
16358                    "/* block comment */\n"
16359                    "int         oneTwoThree=123;",
16360                    Alignment));
16361 
16362   EXPECT_EQ("float const a = 5;\n"
16363             "\n"
16364             "// line comment\n"
16365             "int         oneTwoThree = 123;",
16366             format("float const a = 5;\n"
16367                    "\n"
16368                    "// line comment\n"
16369                    "int oneTwoThree=123;",
16370                    Alignment));
16371 }
16372 
16373 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16374   FormatStyle Alignment = getLLVMStyle();
16375   Alignment.AlignConsecutiveBitFields.Enabled = true;
16376   Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true;
16377   Alignment.AlignConsecutiveBitFields.AcrossComments = true;
16378 
16379   Alignment.MaxEmptyLinesToKeep = 10;
16380   /* Test alignment across empty lines */
16381   EXPECT_EQ("int a            : 5;\n"
16382             "\n"
16383             "int longbitfield : 6;",
16384             format("int a : 5;\n"
16385                    "\n"
16386                    "int longbitfield : 6;",
16387                    Alignment));
16388   EXPECT_EQ("int a            : 5;\n"
16389             "int one          : 1;\n"
16390             "\n"
16391             "int longbitfield : 6;",
16392             format("int a : 5;\n"
16393                    "int one : 1;\n"
16394                    "\n"
16395                    "int longbitfield : 6;",
16396                    Alignment));
16397 
16398   /* Test across comments */
16399   EXPECT_EQ("int a            : 5;\n"
16400             "/* block comment */\n"
16401             "int longbitfield : 6;",
16402             format("int a : 5;\n"
16403                    "/* block comment */\n"
16404                    "int longbitfield : 6;",
16405                    Alignment));
16406   EXPECT_EQ("int a            : 5;\n"
16407             "int one          : 1;\n"
16408             "// line comment\n"
16409             "int longbitfield : 6;",
16410             format("int a : 5;\n"
16411                    "int one : 1;\n"
16412                    "// line comment\n"
16413                    "int longbitfield : 6;",
16414                    Alignment));
16415 
16416   /* Test across comments and newlines */
16417   EXPECT_EQ("int a            : 5;\n"
16418             "/* block comment */\n"
16419             "\n"
16420             "int longbitfield : 6;",
16421             format("int a : 5;\n"
16422                    "/* block comment */\n"
16423                    "\n"
16424                    "int longbitfield : 6;",
16425                    Alignment));
16426   EXPECT_EQ("int a            : 5;\n"
16427             "int one          : 1;\n"
16428             "\n"
16429             "// line comment\n"
16430             "\n"
16431             "int longbitfield : 6;",
16432             format("int a : 5;\n"
16433                    "int one : 1;\n"
16434                    "\n"
16435                    "// line comment \n"
16436                    "\n"
16437                    "int longbitfield : 6;",
16438                    Alignment));
16439 }
16440 
16441 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16442   FormatStyle Alignment = getLLVMStyle();
16443   Alignment.AlignConsecutiveMacros.Enabled = true;
16444   Alignment.AlignConsecutiveAssignments.Enabled = true;
16445   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16446 
16447   Alignment.MaxEmptyLinesToKeep = 10;
16448   /* Test alignment across empty lines */
16449   EXPECT_EQ("int a = 5;\n"
16450             "\n"
16451             "int oneTwoThree = 123;",
16452             format("int a       = 5;\n"
16453                    "\n"
16454                    "int oneTwoThree= 123;",
16455                    Alignment));
16456   EXPECT_EQ("int a   = 5;\n"
16457             "int one = 1;\n"
16458             "\n"
16459             "int oneTwoThree = 123;",
16460             format("int a = 5;\n"
16461                    "int one = 1;\n"
16462                    "\n"
16463                    "int oneTwoThree = 123;",
16464                    Alignment));
16465 
16466   /* Test across comments */
16467   EXPECT_EQ("int a           = 5;\n"
16468             "/* block comment */\n"
16469             "int oneTwoThree = 123;",
16470             format("int a = 5;\n"
16471                    "/* block comment */\n"
16472                    "int oneTwoThree=123;",
16473                    Alignment));
16474 
16475   EXPECT_EQ("int a           = 5;\n"
16476             "// line comment\n"
16477             "int oneTwoThree = 123;",
16478             format("int a = 5;\n"
16479                    "// line comment\n"
16480                    "int oneTwoThree=123;",
16481                    Alignment));
16482 
16483   EXPECT_EQ("int a           = 5;\n"
16484             "/*\n"
16485             " * multi-line block comment\n"
16486             " */\n"
16487             "int oneTwoThree = 123;",
16488             format("int a = 5;\n"
16489                    "/*\n"
16490                    " * multi-line block comment\n"
16491                    " */\n"
16492                    "int oneTwoThree=123;",
16493                    Alignment));
16494 
16495   EXPECT_EQ("int a           = 5;\n"
16496             "//\n"
16497             "// multi-line line comment\n"
16498             "//\n"
16499             "int oneTwoThree = 123;",
16500             format("int a = 5;\n"
16501                    "//\n"
16502                    "// multi-line line comment\n"
16503                    "//\n"
16504                    "int oneTwoThree=123;",
16505                    Alignment));
16506 
16507   /* Test across comments and newlines */
16508   EXPECT_EQ("int a = 5;\n"
16509             "\n"
16510             "/* block comment */\n"
16511             "int oneTwoThree = 123;",
16512             format("int a = 5;\n"
16513                    "\n"
16514                    "/* block comment */\n"
16515                    "int oneTwoThree=123;",
16516                    Alignment));
16517 
16518   EXPECT_EQ("int a = 5;\n"
16519             "\n"
16520             "// line comment\n"
16521             "int oneTwoThree = 123;",
16522             format("int a = 5;\n"
16523                    "\n"
16524                    "// line comment\n"
16525                    "int oneTwoThree=123;",
16526                    Alignment));
16527 }
16528 
16529 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16530   FormatStyle Alignment = getLLVMStyle();
16531   Alignment.AlignConsecutiveMacros.Enabled = true;
16532   Alignment.AlignConsecutiveAssignments.Enabled = true;
16533   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16534   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16535   verifyFormat("int a           = 5;\n"
16536                "int oneTwoThree = 123;",
16537                Alignment);
16538   verifyFormat("int a           = method();\n"
16539                "int oneTwoThree = 133;",
16540                Alignment);
16541   verifyFormat("a &= 5;\n"
16542                "bcd *= 5;\n"
16543                "ghtyf += 5;\n"
16544                "dvfvdb -= 5;\n"
16545                "a /= 5;\n"
16546                "vdsvsv %= 5;\n"
16547                "sfdbddfbdfbb ^= 5;\n"
16548                "dvsdsv |= 5;\n"
16549                "int dsvvdvsdvvv = 123;",
16550                Alignment);
16551   verifyFormat("int i = 1, j = 10;\n"
16552                "something = 2000;",
16553                Alignment);
16554   verifyFormat("something = 2000;\n"
16555                "int i = 1, j = 10;\n",
16556                Alignment);
16557   verifyFormat("something = 2000;\n"
16558                "another   = 911;\n"
16559                "int i = 1, j = 10;\n"
16560                "oneMore = 1;\n"
16561                "i       = 2;",
16562                Alignment);
16563   verifyFormat("int a   = 5;\n"
16564                "int one = 1;\n"
16565                "method();\n"
16566                "int oneTwoThree = 123;\n"
16567                "int oneTwo      = 12;",
16568                Alignment);
16569   verifyFormat("int oneTwoThree = 123;\n"
16570                "int oneTwo      = 12;\n"
16571                "method();\n",
16572                Alignment);
16573   verifyFormat("int oneTwoThree = 123; // comment\n"
16574                "int oneTwo      = 12;  // comment",
16575                Alignment);
16576 
16577   // Bug 25167
16578   /* Uncomment when fixed
16579     verifyFormat("#if A\n"
16580                  "#else\n"
16581                  "int aaaaaaaa = 12;\n"
16582                  "#endif\n"
16583                  "#if B\n"
16584                  "#else\n"
16585                  "int a = 12;\n"
16586                  "#endif\n",
16587                  Alignment);
16588     verifyFormat("enum foo {\n"
16589                  "#if A\n"
16590                  "#else\n"
16591                  "  aaaaaaaa = 12;\n"
16592                  "#endif\n"
16593                  "#if B\n"
16594                  "#else\n"
16595                  "  a = 12;\n"
16596                  "#endif\n"
16597                  "};\n",
16598                  Alignment);
16599   */
16600 
16601   Alignment.MaxEmptyLinesToKeep = 10;
16602   /* Test alignment across empty lines */
16603   EXPECT_EQ("int a           = 5;\n"
16604             "\n"
16605             "int oneTwoThree = 123;",
16606             format("int a       = 5;\n"
16607                    "\n"
16608                    "int oneTwoThree= 123;",
16609                    Alignment));
16610   EXPECT_EQ("int a           = 5;\n"
16611             "int one         = 1;\n"
16612             "\n"
16613             "int oneTwoThree = 123;",
16614             format("int a = 5;\n"
16615                    "int one = 1;\n"
16616                    "\n"
16617                    "int oneTwoThree = 123;",
16618                    Alignment));
16619   EXPECT_EQ("int a           = 5;\n"
16620             "int one         = 1;\n"
16621             "\n"
16622             "int oneTwoThree = 123;\n"
16623             "int oneTwo      = 12;",
16624             format("int a = 5;\n"
16625                    "int one = 1;\n"
16626                    "\n"
16627                    "int oneTwoThree = 123;\n"
16628                    "int oneTwo = 12;",
16629                    Alignment));
16630 
16631   /* Test across comments */
16632   EXPECT_EQ("int a           = 5;\n"
16633             "/* block comment */\n"
16634             "int oneTwoThree = 123;",
16635             format("int a = 5;\n"
16636                    "/* block comment */\n"
16637                    "int oneTwoThree=123;",
16638                    Alignment));
16639 
16640   EXPECT_EQ("int a           = 5;\n"
16641             "// line comment\n"
16642             "int oneTwoThree = 123;",
16643             format("int a = 5;\n"
16644                    "// line comment\n"
16645                    "int oneTwoThree=123;",
16646                    Alignment));
16647 
16648   /* Test across comments and newlines */
16649   EXPECT_EQ("int a           = 5;\n"
16650             "\n"
16651             "/* block comment */\n"
16652             "int oneTwoThree = 123;",
16653             format("int a = 5;\n"
16654                    "\n"
16655                    "/* block comment */\n"
16656                    "int oneTwoThree=123;",
16657                    Alignment));
16658 
16659   EXPECT_EQ("int a           = 5;\n"
16660             "\n"
16661             "// line comment\n"
16662             "int oneTwoThree = 123;",
16663             format("int a = 5;\n"
16664                    "\n"
16665                    "// line comment\n"
16666                    "int oneTwoThree=123;",
16667                    Alignment));
16668 
16669   EXPECT_EQ("int a           = 5;\n"
16670             "//\n"
16671             "// multi-line line comment\n"
16672             "//\n"
16673             "int oneTwoThree = 123;",
16674             format("int a = 5;\n"
16675                    "//\n"
16676                    "// multi-line line comment\n"
16677                    "//\n"
16678                    "int oneTwoThree=123;",
16679                    Alignment));
16680 
16681   EXPECT_EQ("int a           = 5;\n"
16682             "/*\n"
16683             " *  multi-line block comment\n"
16684             " */\n"
16685             "int oneTwoThree = 123;",
16686             format("int a = 5;\n"
16687                    "/*\n"
16688                    " *  multi-line block comment\n"
16689                    " */\n"
16690                    "int oneTwoThree=123;",
16691                    Alignment));
16692 
16693   EXPECT_EQ("int a           = 5;\n"
16694             "\n"
16695             "/* block comment */\n"
16696             "\n"
16697             "\n"
16698             "\n"
16699             "int oneTwoThree = 123;",
16700             format("int a = 5;\n"
16701                    "\n"
16702                    "/* block comment */\n"
16703                    "\n"
16704                    "\n"
16705                    "\n"
16706                    "int oneTwoThree=123;",
16707                    Alignment));
16708 
16709   EXPECT_EQ("int a           = 5;\n"
16710             "\n"
16711             "// line comment\n"
16712             "\n"
16713             "\n"
16714             "\n"
16715             "int oneTwoThree = 123;",
16716             format("int a = 5;\n"
16717                    "\n"
16718                    "// line comment\n"
16719                    "\n"
16720                    "\n"
16721                    "\n"
16722                    "int oneTwoThree=123;",
16723                    Alignment));
16724 
16725   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16726   verifyFormat("#define A \\\n"
16727                "  int aaaa       = 12; \\\n"
16728                "  int b          = 23; \\\n"
16729                "  int ccc        = 234; \\\n"
16730                "  int dddddddddd = 2345;",
16731                Alignment);
16732   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16733   verifyFormat("#define A               \\\n"
16734                "  int aaaa       = 12;  \\\n"
16735                "  int b          = 23;  \\\n"
16736                "  int ccc        = 234; \\\n"
16737                "  int dddddddddd = 2345;",
16738                Alignment);
16739   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16740   verifyFormat("#define A                                                      "
16741                "                \\\n"
16742                "  int aaaa       = 12;                                         "
16743                "                \\\n"
16744                "  int b          = 23;                                         "
16745                "                \\\n"
16746                "  int ccc        = 234;                                        "
16747                "                \\\n"
16748                "  int dddddddddd = 2345;",
16749                Alignment);
16750   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16751                "k = 4, int l = 5,\n"
16752                "                  int m = 6) {\n"
16753                "  int j      = 10;\n"
16754                "  otherThing = 1;\n"
16755                "}",
16756                Alignment);
16757   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16758                "  int i   = 1;\n"
16759                "  int j   = 2;\n"
16760                "  int big = 10000;\n"
16761                "}",
16762                Alignment);
16763   verifyFormat("class C {\n"
16764                "public:\n"
16765                "  int i            = 1;\n"
16766                "  virtual void f() = 0;\n"
16767                "};",
16768                Alignment);
16769   verifyFormat("int i = 1;\n"
16770                "if (SomeType t = getSomething()) {\n"
16771                "}\n"
16772                "int j   = 2;\n"
16773                "int big = 10000;",
16774                Alignment);
16775   verifyFormat("int j = 7;\n"
16776                "for (int k = 0; k < N; ++k) {\n"
16777                "}\n"
16778                "int j   = 2;\n"
16779                "int big = 10000;\n"
16780                "}",
16781                Alignment);
16782   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16783   verifyFormat("int i = 1;\n"
16784                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16785                "    = someLooooooooooooooooongFunction();\n"
16786                "int j = 2;",
16787                Alignment);
16788   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16789   verifyFormat("int i = 1;\n"
16790                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16791                "    someLooooooooooooooooongFunction();\n"
16792                "int j = 2;",
16793                Alignment);
16794 
16795   verifyFormat("auto lambda = []() {\n"
16796                "  auto i = 0;\n"
16797                "  return 0;\n"
16798                "};\n"
16799                "int i  = 0;\n"
16800                "auto v = type{\n"
16801                "    i = 1,   //\n"
16802                "    (i = 2), //\n"
16803                "    i = 3    //\n"
16804                "};",
16805                Alignment);
16806 
16807   verifyFormat(
16808       "int i      = 1;\n"
16809       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16810       "                          loooooooooooooooooooooongParameterB);\n"
16811       "int j      = 2;",
16812       Alignment);
16813 
16814   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16815                "          typename B   = very_long_type_name_1,\n"
16816                "          typename T_2 = very_long_type_name_2>\n"
16817                "auto foo() {}\n",
16818                Alignment);
16819   verifyFormat("int a, b = 1;\n"
16820                "int c  = 2;\n"
16821                "int dd = 3;\n",
16822                Alignment);
16823   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16824                "float b[1][] = {{3.f}};\n",
16825                Alignment);
16826   verifyFormat("for (int i = 0; i < 1; i++)\n"
16827                "  int x = 1;\n",
16828                Alignment);
16829   verifyFormat("for (i = 0; i < 1; i++)\n"
16830                "  x = 1;\n"
16831                "y = 1;\n",
16832                Alignment);
16833 
16834   Alignment.ReflowComments = true;
16835   Alignment.ColumnLimit = 50;
16836   EXPECT_EQ("int x   = 0;\n"
16837             "int yy  = 1; /// specificlennospace\n"
16838             "int zzz = 2;\n",
16839             format("int x   = 0;\n"
16840                    "int yy  = 1; ///specificlennospace\n"
16841                    "int zzz = 2;\n",
16842                    Alignment));
16843 }
16844 
16845 TEST_F(FormatTest, AlignCompoundAssignments) {
16846   FormatStyle Alignment = getLLVMStyle();
16847   Alignment.AlignConsecutiveAssignments.Enabled = true;
16848   Alignment.AlignConsecutiveAssignments.AlignCompound = true;
16849   Alignment.AlignConsecutiveAssignments.PadOperators = false;
16850   verifyFormat("sfdbddfbdfbb    = 5;\n"
16851                "dvsdsv          = 5;\n"
16852                "int dsvvdvsdvvv = 123;",
16853                Alignment);
16854   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16855                "dvsdsv         |= 5;\n"
16856                "int dsvvdvsdvvv = 123;",
16857                Alignment);
16858   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16859                "dvsdsv        <<= 5;\n"
16860                "int dsvvdvsdvvv = 123;",
16861                Alignment);
16862   // Test that `<=` is not treated as a compound assignment.
16863   verifyFormat("aa &= 5;\n"
16864                "b <= 10;\n"
16865                "c = 15;",
16866                Alignment);
16867   Alignment.AlignConsecutiveAssignments.PadOperators = true;
16868   verifyFormat("sfdbddfbdfbb    = 5;\n"
16869                "dvsdsv          = 5;\n"
16870                "int dsvvdvsdvvv = 123;",
16871                Alignment);
16872   verifyFormat("sfdbddfbdfbb    ^= 5;\n"
16873                "dvsdsv          |= 5;\n"
16874                "int dsvvdvsdvvv  = 123;",
16875                Alignment);
16876   verifyFormat("sfdbddfbdfbb     ^= 5;\n"
16877                "dvsdsv          <<= 5;\n"
16878                "int dsvvdvsdvvv   = 123;",
16879                Alignment);
16880   EXPECT_EQ("a   += 5;\n"
16881             "one  = 1;\n"
16882             "\n"
16883             "oneTwoThree = 123;\n",
16884             format("a += 5;\n"
16885                    "one = 1;\n"
16886                    "\n"
16887                    "oneTwoThree = 123;\n",
16888                    Alignment));
16889   EXPECT_EQ("a   += 5;\n"
16890             "one  = 1;\n"
16891             "//\n"
16892             "oneTwoThree = 123;\n",
16893             format("a += 5;\n"
16894                    "one = 1;\n"
16895                    "//\n"
16896                    "oneTwoThree = 123;\n",
16897                    Alignment));
16898   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16899   EXPECT_EQ("a           += 5;\n"
16900             "one          = 1;\n"
16901             "\n"
16902             "oneTwoThree  = 123;\n",
16903             format("a += 5;\n"
16904                    "one = 1;\n"
16905                    "\n"
16906                    "oneTwoThree = 123;\n",
16907                    Alignment));
16908   EXPECT_EQ("a   += 5;\n"
16909             "one  = 1;\n"
16910             "//\n"
16911             "oneTwoThree = 123;\n",
16912             format("a += 5;\n"
16913                    "one = 1;\n"
16914                    "//\n"
16915                    "oneTwoThree = 123;\n",
16916                    Alignment));
16917   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false;
16918   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16919   EXPECT_EQ("a   += 5;\n"
16920             "one  = 1;\n"
16921             "\n"
16922             "oneTwoThree = 123;\n",
16923             format("a += 5;\n"
16924                    "one = 1;\n"
16925                    "\n"
16926                    "oneTwoThree = 123;\n",
16927                    Alignment));
16928   EXPECT_EQ("a           += 5;\n"
16929             "one          = 1;\n"
16930             "//\n"
16931             "oneTwoThree  = 123;\n",
16932             format("a += 5;\n"
16933                    "one = 1;\n"
16934                    "//\n"
16935                    "oneTwoThree = 123;\n",
16936                    Alignment));
16937   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16938   EXPECT_EQ("a            += 5;\n"
16939             "one         >>= 1;\n"
16940             "\n"
16941             "oneTwoThree   = 123;\n",
16942             format("a += 5;\n"
16943                    "one >>= 1;\n"
16944                    "\n"
16945                    "oneTwoThree = 123;\n",
16946                    Alignment));
16947   EXPECT_EQ("a            += 5;\n"
16948             "one           = 1;\n"
16949             "//\n"
16950             "oneTwoThree <<= 123;\n",
16951             format("a += 5;\n"
16952                    "one = 1;\n"
16953                    "//\n"
16954                    "oneTwoThree <<= 123;\n",
16955                    Alignment));
16956 }
16957 
16958 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16959   FormatStyle Alignment = getLLVMStyle();
16960   Alignment.AlignConsecutiveMacros.Enabled = true;
16961   verifyFormat("int a = 5;\n"
16962                "int oneTwoThree = 123;",
16963                Alignment);
16964   verifyFormat("int a = 5;\n"
16965                "int oneTwoThree = 123;",
16966                Alignment);
16967 
16968   Alignment.AlignConsecutiveAssignments.Enabled = true;
16969   verifyFormat("int a           = 5;\n"
16970                "int oneTwoThree = 123;",
16971                Alignment);
16972   verifyFormat("int a           = method();\n"
16973                "int oneTwoThree = 133;",
16974                Alignment);
16975   verifyFormat("aa <= 5;\n"
16976                "a &= 5;\n"
16977                "bcd *= 5;\n"
16978                "ghtyf += 5;\n"
16979                "dvfvdb -= 5;\n"
16980                "a /= 5;\n"
16981                "vdsvsv %= 5;\n"
16982                "sfdbddfbdfbb ^= 5;\n"
16983                "dvsdsv |= 5;\n"
16984                "int dsvvdvsdvvv = 123;",
16985                Alignment);
16986   verifyFormat("int i = 1, j = 10;\n"
16987                "something = 2000;",
16988                Alignment);
16989   verifyFormat("something = 2000;\n"
16990                "int i = 1, j = 10;\n",
16991                Alignment);
16992   verifyFormat("something = 2000;\n"
16993                "another   = 911;\n"
16994                "int i = 1, j = 10;\n"
16995                "oneMore = 1;\n"
16996                "i       = 2;",
16997                Alignment);
16998   verifyFormat("int a   = 5;\n"
16999                "int one = 1;\n"
17000                "method();\n"
17001                "int oneTwoThree = 123;\n"
17002                "int oneTwo      = 12;",
17003                Alignment);
17004   verifyFormat("int oneTwoThree = 123;\n"
17005                "int oneTwo      = 12;\n"
17006                "method();\n",
17007                Alignment);
17008   verifyFormat("int oneTwoThree = 123; // comment\n"
17009                "int oneTwo      = 12;  // comment",
17010                Alignment);
17011   verifyFormat("int f()         = default;\n"
17012                "int &operator() = default;\n"
17013                "int &operator=() {",
17014                Alignment);
17015   verifyFormat("int f()         = delete;\n"
17016                "int &operator() = delete;\n"
17017                "int &operator=() {",
17018                Alignment);
17019   verifyFormat("int f()         = default; // comment\n"
17020                "int &operator() = default; // comment\n"
17021                "int &operator=() {",
17022                Alignment);
17023   verifyFormat("int f()         = default;\n"
17024                "int &operator() = default;\n"
17025                "int &operator==() {",
17026                Alignment);
17027   verifyFormat("int f()         = default;\n"
17028                "int &operator() = default;\n"
17029                "int &operator<=() {",
17030                Alignment);
17031   verifyFormat("int f()         = default;\n"
17032                "int &operator() = default;\n"
17033                "int &operator!=() {",
17034                Alignment);
17035   verifyFormat("int f()         = default;\n"
17036                "int &operator() = default;\n"
17037                "int &operator=();",
17038                Alignment);
17039   verifyFormat("int f()         = delete;\n"
17040                "int &operator() = delete;\n"
17041                "int &operator=();",
17042                Alignment);
17043   verifyFormat("/* long long padding */ int f() = default;\n"
17044                "int &operator()                 = default;\n"
17045                "int &operator/**/ =();",
17046                Alignment);
17047   // https://llvm.org/PR33697
17048   FormatStyle AlignmentWithPenalty = getLLVMStyle();
17049   AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true;
17050   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
17051   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
17052                "  void f() = delete;\n"
17053                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
17054                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
17055                "};\n",
17056                AlignmentWithPenalty);
17057 
17058   // Bug 25167
17059   /* Uncomment when fixed
17060     verifyFormat("#if A\n"
17061                  "#else\n"
17062                  "int aaaaaaaa = 12;\n"
17063                  "#endif\n"
17064                  "#if B\n"
17065                  "#else\n"
17066                  "int a = 12;\n"
17067                  "#endif\n",
17068                  Alignment);
17069     verifyFormat("enum foo {\n"
17070                  "#if A\n"
17071                  "#else\n"
17072                  "  aaaaaaaa = 12;\n"
17073                  "#endif\n"
17074                  "#if B\n"
17075                  "#else\n"
17076                  "  a = 12;\n"
17077                  "#endif\n"
17078                  "};\n",
17079                  Alignment);
17080   */
17081 
17082   EXPECT_EQ("int a = 5;\n"
17083             "\n"
17084             "int oneTwoThree = 123;",
17085             format("int a       = 5;\n"
17086                    "\n"
17087                    "int oneTwoThree= 123;",
17088                    Alignment));
17089   EXPECT_EQ("int a   = 5;\n"
17090             "int one = 1;\n"
17091             "\n"
17092             "int oneTwoThree = 123;",
17093             format("int a = 5;\n"
17094                    "int one = 1;\n"
17095                    "\n"
17096                    "int oneTwoThree = 123;",
17097                    Alignment));
17098   EXPECT_EQ("int a   = 5;\n"
17099             "int one = 1;\n"
17100             "\n"
17101             "int oneTwoThree = 123;\n"
17102             "int oneTwo      = 12;",
17103             format("int a = 5;\n"
17104                    "int one = 1;\n"
17105                    "\n"
17106                    "int oneTwoThree = 123;\n"
17107                    "int oneTwo = 12;",
17108                    Alignment));
17109   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17110   verifyFormat("#define A \\\n"
17111                "  int aaaa       = 12; \\\n"
17112                "  int b          = 23; \\\n"
17113                "  int ccc        = 234; \\\n"
17114                "  int dddddddddd = 2345;",
17115                Alignment);
17116   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17117   verifyFormat("#define A               \\\n"
17118                "  int aaaa       = 12;  \\\n"
17119                "  int b          = 23;  \\\n"
17120                "  int ccc        = 234; \\\n"
17121                "  int dddddddddd = 2345;",
17122                Alignment);
17123   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17124   verifyFormat("#define A                                                      "
17125                "                \\\n"
17126                "  int aaaa       = 12;                                         "
17127                "                \\\n"
17128                "  int b          = 23;                                         "
17129                "                \\\n"
17130                "  int ccc        = 234;                                        "
17131                "                \\\n"
17132                "  int dddddddddd = 2345;",
17133                Alignment);
17134   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17135                "k = 4, int l = 5,\n"
17136                "                  int m = 6) {\n"
17137                "  int j      = 10;\n"
17138                "  otherThing = 1;\n"
17139                "}",
17140                Alignment);
17141   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17142                "  int i   = 1;\n"
17143                "  int j   = 2;\n"
17144                "  int big = 10000;\n"
17145                "}",
17146                Alignment);
17147   verifyFormat("class C {\n"
17148                "public:\n"
17149                "  int i            = 1;\n"
17150                "  virtual void f() = 0;\n"
17151                "};",
17152                Alignment);
17153   verifyFormat("int i = 1;\n"
17154                "if (SomeType t = getSomething()) {\n"
17155                "}\n"
17156                "int j   = 2;\n"
17157                "int big = 10000;",
17158                Alignment);
17159   verifyFormat("int j = 7;\n"
17160                "for (int k = 0; k < N; ++k) {\n"
17161                "}\n"
17162                "int j   = 2;\n"
17163                "int big = 10000;\n"
17164                "}",
17165                Alignment);
17166   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17167   verifyFormat("int i = 1;\n"
17168                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17169                "    = someLooooooooooooooooongFunction();\n"
17170                "int j = 2;",
17171                Alignment);
17172   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17173   verifyFormat("int i = 1;\n"
17174                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17175                "    someLooooooooooooooooongFunction();\n"
17176                "int j = 2;",
17177                Alignment);
17178 
17179   verifyFormat("auto lambda = []() {\n"
17180                "  auto i = 0;\n"
17181                "  return 0;\n"
17182                "};\n"
17183                "int i  = 0;\n"
17184                "auto v = type{\n"
17185                "    i = 1,   //\n"
17186                "    (i = 2), //\n"
17187                "    i = 3    //\n"
17188                "};",
17189                Alignment);
17190 
17191   verifyFormat(
17192       "int i      = 1;\n"
17193       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17194       "                          loooooooooooooooooooooongParameterB);\n"
17195       "int j      = 2;",
17196       Alignment);
17197 
17198   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17199                "          typename B   = very_long_type_name_1,\n"
17200                "          typename T_2 = very_long_type_name_2>\n"
17201                "auto foo() {}\n",
17202                Alignment);
17203   verifyFormat("int a, b = 1;\n"
17204                "int c  = 2;\n"
17205                "int dd = 3;\n",
17206                Alignment);
17207   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17208                "float b[1][] = {{3.f}};\n",
17209                Alignment);
17210   verifyFormat("for (int i = 0; i < 1; i++)\n"
17211                "  int x = 1;\n",
17212                Alignment);
17213   verifyFormat("for (i = 0; i < 1; i++)\n"
17214                "  x = 1;\n"
17215                "y = 1;\n",
17216                Alignment);
17217 
17218   EXPECT_EQ(Alignment.ReflowComments, true);
17219   Alignment.ColumnLimit = 50;
17220   EXPECT_EQ("int x   = 0;\n"
17221             "int yy  = 1; /// specificlennospace\n"
17222             "int zzz = 2;\n",
17223             format("int x   = 0;\n"
17224                    "int yy  = 1; ///specificlennospace\n"
17225                    "int zzz = 2;\n",
17226                    Alignment));
17227 
17228   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17229                "auto b                     = [] {\n"
17230                "  f();\n"
17231                "  return;\n"
17232                "};",
17233                Alignment);
17234   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17235                "auto b                     = g([] {\n"
17236                "  f();\n"
17237                "  return;\n"
17238                "});",
17239                Alignment);
17240   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17241                "auto b                     = g(param, [] {\n"
17242                "  f();\n"
17243                "  return;\n"
17244                "});",
17245                Alignment);
17246   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17247                "auto b                     = [] {\n"
17248                "  if (condition) {\n"
17249                "    return;\n"
17250                "  }\n"
17251                "};",
17252                Alignment);
17253 
17254   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17255                "           ccc ? aaaaa : bbbbb,\n"
17256                "           dddddddddddddddddddddddddd);",
17257                Alignment);
17258   // FIXME: https://llvm.org/PR53497
17259   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
17260   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17261   //              "    ccc ? aaaaa : bbbbb,\n"
17262   //              "    dddddddddddddddddddddddddd);",
17263   //              Alignment);
17264 }
17265 
17266 TEST_F(FormatTest, AlignConsecutiveBitFields) {
17267   FormatStyle Alignment = getLLVMStyle();
17268   Alignment.AlignConsecutiveBitFields.Enabled = true;
17269   verifyFormat("int const a     : 5;\n"
17270                "int oneTwoThree : 23;",
17271                Alignment);
17272 
17273   // Initializers are allowed starting with c++2a
17274   verifyFormat("int const a     : 5 = 1;\n"
17275                "int oneTwoThree : 23 = 0;",
17276                Alignment);
17277 
17278   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17279   verifyFormat("int const a           : 5;\n"
17280                "int       oneTwoThree : 23;",
17281                Alignment);
17282 
17283   verifyFormat("int const a           : 5;  // comment\n"
17284                "int       oneTwoThree : 23; // comment",
17285                Alignment);
17286 
17287   verifyFormat("int const a           : 5 = 1;\n"
17288                "int       oneTwoThree : 23 = 0;",
17289                Alignment);
17290 
17291   Alignment.AlignConsecutiveAssignments.Enabled = true;
17292   verifyFormat("int const a           : 5  = 1;\n"
17293                "int       oneTwoThree : 23 = 0;",
17294                Alignment);
17295   verifyFormat("int const a           : 5  = {1};\n"
17296                "int       oneTwoThree : 23 = 0;",
17297                Alignment);
17298 
17299   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
17300   verifyFormat("int const a          :5;\n"
17301                "int       oneTwoThree:23;",
17302                Alignment);
17303 
17304   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
17305   verifyFormat("int const a           :5;\n"
17306                "int       oneTwoThree :23;",
17307                Alignment);
17308 
17309   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
17310   verifyFormat("int const a          : 5;\n"
17311                "int       oneTwoThree: 23;",
17312                Alignment);
17313 
17314   // Known limitations: ':' is only recognized as a bitfield colon when
17315   // followed by a number.
17316   /*
17317   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
17318                "int a           : 5;",
17319                Alignment);
17320   */
17321 }
17322 
17323 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
17324   FormatStyle Alignment = getLLVMStyle();
17325   Alignment.AlignConsecutiveMacros.Enabled = true;
17326   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17327   verifyFormat("float const a = 5;\n"
17328                "int oneTwoThree = 123;",
17329                Alignment);
17330   verifyFormat("int a = 5;\n"
17331                "float const oneTwoThree = 123;",
17332                Alignment);
17333 
17334   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17335   verifyFormat("float const a = 5;\n"
17336                "int         oneTwoThree = 123;",
17337                Alignment);
17338   verifyFormat("int         a = method();\n"
17339                "float const oneTwoThree = 133;",
17340                Alignment);
17341   verifyFormat("int i = 1, j = 10;\n"
17342                "something = 2000;",
17343                Alignment);
17344   verifyFormat("something = 2000;\n"
17345                "int i = 1, j = 10;\n",
17346                Alignment);
17347   verifyFormat("float      something = 2000;\n"
17348                "double     another = 911;\n"
17349                "int        i = 1, j = 10;\n"
17350                "const int *oneMore = 1;\n"
17351                "unsigned   i = 2;",
17352                Alignment);
17353   verifyFormat("float a = 5;\n"
17354                "int   one = 1;\n"
17355                "method();\n"
17356                "const double       oneTwoThree = 123;\n"
17357                "const unsigned int oneTwo = 12;",
17358                Alignment);
17359   verifyFormat("int      oneTwoThree{0}; // comment\n"
17360                "unsigned oneTwo;         // comment",
17361                Alignment);
17362   verifyFormat("unsigned int       *a;\n"
17363                "int                *b;\n"
17364                "unsigned int Const *c;\n"
17365                "unsigned int const *d;\n"
17366                "unsigned int Const &e;\n"
17367                "unsigned int const &f;",
17368                Alignment);
17369   verifyFormat("Const unsigned int *c;\n"
17370                "const unsigned int *d;\n"
17371                "Const unsigned int &e;\n"
17372                "const unsigned int &f;\n"
17373                "const unsigned      g;\n"
17374                "Const unsigned      h;",
17375                Alignment);
17376   EXPECT_EQ("float const a = 5;\n"
17377             "\n"
17378             "int oneTwoThree = 123;",
17379             format("float const   a = 5;\n"
17380                    "\n"
17381                    "int           oneTwoThree= 123;",
17382                    Alignment));
17383   EXPECT_EQ("float a = 5;\n"
17384             "int   one = 1;\n"
17385             "\n"
17386             "unsigned oneTwoThree = 123;",
17387             format("float    a = 5;\n"
17388                    "int      one = 1;\n"
17389                    "\n"
17390                    "unsigned oneTwoThree = 123;",
17391                    Alignment));
17392   EXPECT_EQ("float a = 5;\n"
17393             "int   one = 1;\n"
17394             "\n"
17395             "unsigned oneTwoThree = 123;\n"
17396             "int      oneTwo = 12;",
17397             format("float    a = 5;\n"
17398                    "int one = 1;\n"
17399                    "\n"
17400                    "unsigned oneTwoThree = 123;\n"
17401                    "int oneTwo = 12;",
17402                    Alignment));
17403   // Function prototype alignment
17404   verifyFormat("int    a();\n"
17405                "double b();",
17406                Alignment);
17407   verifyFormat("int    a(int x);\n"
17408                "double b();",
17409                Alignment);
17410   unsigned OldColumnLimit = Alignment.ColumnLimit;
17411   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17412   // otherwise the function parameters will be re-flowed onto a single line.
17413   Alignment.ColumnLimit = 0;
17414   EXPECT_EQ("int    a(int   x,\n"
17415             "         float y);\n"
17416             "double b(int    x,\n"
17417             "         double y);",
17418             format("int a(int x,\n"
17419                    " float y);\n"
17420                    "double b(int x,\n"
17421                    " double y);",
17422                    Alignment));
17423   // This ensures that function parameters of function declarations are
17424   // correctly indented when their owning functions are indented.
17425   // The failure case here is for 'double y' to not be indented enough.
17426   EXPECT_EQ("double a(int x);\n"
17427             "int    b(int    y,\n"
17428             "         double z);",
17429             format("double a(int x);\n"
17430                    "int b(int y,\n"
17431                    " double z);",
17432                    Alignment));
17433   // Set ColumnLimit low so that we induce wrapping immediately after
17434   // the function name and opening paren.
17435   Alignment.ColumnLimit = 13;
17436   verifyFormat("int function(\n"
17437                "    int  x,\n"
17438                "    bool y);",
17439                Alignment);
17440   Alignment.ColumnLimit = OldColumnLimit;
17441   // Ensure function pointers don't screw up recursive alignment
17442   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17443                "double b();",
17444                Alignment);
17445   Alignment.AlignConsecutiveAssignments.Enabled = true;
17446   // Ensure recursive alignment is broken by function braces, so that the
17447   // "a = 1" does not align with subsequent assignments inside the function
17448   // body.
17449   verifyFormat("int func(int a = 1) {\n"
17450                "  int b  = 2;\n"
17451                "  int cc = 3;\n"
17452                "}",
17453                Alignment);
17454   verifyFormat("float      something = 2000;\n"
17455                "double     another   = 911;\n"
17456                "int        i = 1, j = 10;\n"
17457                "const int *oneMore = 1;\n"
17458                "unsigned   i       = 2;",
17459                Alignment);
17460   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17461                "unsigned oneTwo      = 0;   // comment",
17462                Alignment);
17463   // Make sure that scope is correctly tracked, in the absence of braces
17464   verifyFormat("for (int i = 0; i < n; i++)\n"
17465                "  j = i;\n"
17466                "double x = 1;\n",
17467                Alignment);
17468   verifyFormat("if (int i = 0)\n"
17469                "  j = i;\n"
17470                "double x = 1;\n",
17471                Alignment);
17472   // Ensure operator[] and operator() are comprehended
17473   verifyFormat("struct test {\n"
17474                "  long long int foo();\n"
17475                "  int           operator[](int a);\n"
17476                "  double        bar();\n"
17477                "};\n",
17478                Alignment);
17479   verifyFormat("struct test {\n"
17480                "  long long int foo();\n"
17481                "  int           operator()(int a);\n"
17482                "  double        bar();\n"
17483                "};\n",
17484                Alignment);
17485   // http://llvm.org/PR52914
17486   verifyFormat("char *a[]     = {\"a\", // comment\n"
17487                "                 \"bb\"};\n"
17488                "int   bbbbbbb = 0;",
17489                Alignment);
17490 
17491   // PAS_Right
17492   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17493             "  int const i   = 1;\n"
17494             "  int      *j   = 2;\n"
17495             "  int       big = 10000;\n"
17496             "\n"
17497             "  unsigned oneTwoThree = 123;\n"
17498             "  int      oneTwo      = 12;\n"
17499             "  method();\n"
17500             "  float k  = 2;\n"
17501             "  int   ll = 10000;\n"
17502             "}",
17503             format("void SomeFunction(int parameter= 0) {\n"
17504                    " int const  i= 1;\n"
17505                    "  int *j=2;\n"
17506                    " int big  =  10000;\n"
17507                    "\n"
17508                    "unsigned oneTwoThree  =123;\n"
17509                    "int oneTwo = 12;\n"
17510                    "  method();\n"
17511                    "float k= 2;\n"
17512                    "int ll=10000;\n"
17513                    "}",
17514                    Alignment));
17515   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17516             "  int const i   = 1;\n"
17517             "  int     **j   = 2, ***k;\n"
17518             "  int      &k   = i;\n"
17519             "  int     &&l   = i + j;\n"
17520             "  int       big = 10000;\n"
17521             "\n"
17522             "  unsigned oneTwoThree = 123;\n"
17523             "  int      oneTwo      = 12;\n"
17524             "  method();\n"
17525             "  float k  = 2;\n"
17526             "  int   ll = 10000;\n"
17527             "}",
17528             format("void SomeFunction(int parameter= 0) {\n"
17529                    " int const  i= 1;\n"
17530                    "  int **j=2,***k;\n"
17531                    "int &k=i;\n"
17532                    "int &&l=i+j;\n"
17533                    " int big  =  10000;\n"
17534                    "\n"
17535                    "unsigned oneTwoThree  =123;\n"
17536                    "int oneTwo = 12;\n"
17537                    "  method();\n"
17538                    "float k= 2;\n"
17539                    "int ll=10000;\n"
17540                    "}",
17541                    Alignment));
17542   // variables are aligned at their name, pointers are at the right most
17543   // position
17544   verifyFormat("int   *a;\n"
17545                "int  **b;\n"
17546                "int ***c;\n"
17547                "int    foobar;\n",
17548                Alignment);
17549 
17550   // PAS_Left
17551   FormatStyle AlignmentLeft = Alignment;
17552   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17553   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17554             "  int const i   = 1;\n"
17555             "  int*      j   = 2;\n"
17556             "  int       big = 10000;\n"
17557             "\n"
17558             "  unsigned oneTwoThree = 123;\n"
17559             "  int      oneTwo      = 12;\n"
17560             "  method();\n"
17561             "  float k  = 2;\n"
17562             "  int   ll = 10000;\n"
17563             "}",
17564             format("void SomeFunction(int parameter= 0) {\n"
17565                    " int const  i= 1;\n"
17566                    "  int *j=2;\n"
17567                    " int big  =  10000;\n"
17568                    "\n"
17569                    "unsigned oneTwoThree  =123;\n"
17570                    "int oneTwo = 12;\n"
17571                    "  method();\n"
17572                    "float k= 2;\n"
17573                    "int ll=10000;\n"
17574                    "}",
17575                    AlignmentLeft));
17576   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17577             "  int const i   = 1;\n"
17578             "  int**     j   = 2;\n"
17579             "  int&      k   = i;\n"
17580             "  int&&     l   = i + j;\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 &k=i;\n"
17593                    "int &&l=i+j;\n"
17594                    " int big  =  10000;\n"
17595                    "\n"
17596                    "unsigned oneTwoThree  =123;\n"
17597                    "int oneTwo = 12;\n"
17598                    "  method();\n"
17599                    "float k= 2;\n"
17600                    "int ll=10000;\n"
17601                    "}",
17602                    AlignmentLeft));
17603   // variables are aligned at their name, pointers are at the left most position
17604   verifyFormat("int*   a;\n"
17605                "int**  b;\n"
17606                "int*** c;\n"
17607                "int    foobar;\n",
17608                AlignmentLeft);
17609 
17610   // PAS_Middle
17611   FormatStyle AlignmentMiddle = Alignment;
17612   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17613   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17614             "  int const i   = 1;\n"
17615             "  int *     j   = 2;\n"
17616             "  int       big = 10000;\n"
17617             "\n"
17618             "  unsigned oneTwoThree = 123;\n"
17619             "  int      oneTwo      = 12;\n"
17620             "  method();\n"
17621             "  float k  = 2;\n"
17622             "  int   ll = 10000;\n"
17623             "}",
17624             format("void SomeFunction(int parameter= 0) {\n"
17625                    " int const  i= 1;\n"
17626                    "  int *j=2;\n"
17627                    " int big  =  10000;\n"
17628                    "\n"
17629                    "unsigned oneTwoThree  =123;\n"
17630                    "int oneTwo = 12;\n"
17631                    "  method();\n"
17632                    "float k= 2;\n"
17633                    "int ll=10000;\n"
17634                    "}",
17635                    AlignmentMiddle));
17636   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17637             "  int const i   = 1;\n"
17638             "  int **    j   = 2, ***k;\n"
17639             "  int &     k   = i;\n"
17640             "  int &&    l   = i + j;\n"
17641             "  int       big = 10000;\n"
17642             "\n"
17643             "  unsigned oneTwoThree = 123;\n"
17644             "  int      oneTwo      = 12;\n"
17645             "  method();\n"
17646             "  float k  = 2;\n"
17647             "  int   ll = 10000;\n"
17648             "}",
17649             format("void SomeFunction(int parameter= 0) {\n"
17650                    " int const  i= 1;\n"
17651                    "  int **j=2,***k;\n"
17652                    "int &k=i;\n"
17653                    "int &&l=i+j;\n"
17654                    " int big  =  10000;\n"
17655                    "\n"
17656                    "unsigned oneTwoThree  =123;\n"
17657                    "int oneTwo = 12;\n"
17658                    "  method();\n"
17659                    "float k= 2;\n"
17660                    "int ll=10000;\n"
17661                    "}",
17662                    AlignmentMiddle));
17663   // variables are aligned at their name, pointers are in the middle
17664   verifyFormat("int *   a;\n"
17665                "int *   b;\n"
17666                "int *** c;\n"
17667                "int     foobar;\n",
17668                AlignmentMiddle);
17669 
17670   Alignment.AlignConsecutiveAssignments.Enabled = false;
17671   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17672   verifyFormat("#define A \\\n"
17673                "  int       aaaa = 12; \\\n"
17674                "  float     b = 23; \\\n"
17675                "  const int ccc = 234; \\\n"
17676                "  unsigned  dddddddddd = 2345;",
17677                Alignment);
17678   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17679   verifyFormat("#define A              \\\n"
17680                "  int       aaaa = 12; \\\n"
17681                "  float     b = 23;    \\\n"
17682                "  const int ccc = 234; \\\n"
17683                "  unsigned  dddddddddd = 2345;",
17684                Alignment);
17685   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17686   Alignment.ColumnLimit = 30;
17687   verifyFormat("#define A                    \\\n"
17688                "  int       aaaa = 12;       \\\n"
17689                "  float     b = 23;          \\\n"
17690                "  const int ccc = 234;       \\\n"
17691                "  int       dddddddddd = 2345;",
17692                Alignment);
17693   Alignment.ColumnLimit = 80;
17694   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17695                "k = 4, int l = 5,\n"
17696                "                  int m = 6) {\n"
17697                "  const int j = 10;\n"
17698                "  otherThing = 1;\n"
17699                "}",
17700                Alignment);
17701   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17702                "  int const i = 1;\n"
17703                "  int      *j = 2;\n"
17704                "  int       big = 10000;\n"
17705                "}",
17706                Alignment);
17707   verifyFormat("class C {\n"
17708                "public:\n"
17709                "  int          i = 1;\n"
17710                "  virtual void f() = 0;\n"
17711                "};",
17712                Alignment);
17713   verifyFormat("float i = 1;\n"
17714                "if (SomeType t = getSomething()) {\n"
17715                "}\n"
17716                "const unsigned j = 2;\n"
17717                "int            big = 10000;",
17718                Alignment);
17719   verifyFormat("float j = 7;\n"
17720                "for (int k = 0; k < N; ++k) {\n"
17721                "}\n"
17722                "unsigned j = 2;\n"
17723                "int      big = 10000;\n"
17724                "}",
17725                Alignment);
17726   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17727   verifyFormat("float              i = 1;\n"
17728                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17729                "    = someLooooooooooooooooongFunction();\n"
17730                "int j = 2;",
17731                Alignment);
17732   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17733   verifyFormat("int                i = 1;\n"
17734                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17735                "    someLooooooooooooooooongFunction();\n"
17736                "int j = 2;",
17737                Alignment);
17738 
17739   Alignment.AlignConsecutiveAssignments.Enabled = true;
17740   verifyFormat("auto lambda = []() {\n"
17741                "  auto  ii = 0;\n"
17742                "  float j  = 0;\n"
17743                "  return 0;\n"
17744                "};\n"
17745                "int   i  = 0;\n"
17746                "float i2 = 0;\n"
17747                "auto  v  = type{\n"
17748                "    i = 1,   //\n"
17749                "    (i = 2), //\n"
17750                "    i = 3    //\n"
17751                "};",
17752                Alignment);
17753   Alignment.AlignConsecutiveAssignments.Enabled = false;
17754 
17755   verifyFormat(
17756       "int      i = 1;\n"
17757       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17758       "                          loooooooooooooooooooooongParameterB);\n"
17759       "int      j = 2;",
17760       Alignment);
17761 
17762   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17763   // We expect declarations and assignments to align, as long as it doesn't
17764   // exceed the column limit, starting a new alignment sequence whenever it
17765   // happens.
17766   Alignment.AlignConsecutiveAssignments.Enabled = true;
17767   Alignment.ColumnLimit = 30;
17768   verifyFormat("float    ii              = 1;\n"
17769                "unsigned j               = 2;\n"
17770                "int someVerylongVariable = 1;\n"
17771                "AnotherLongType  ll = 123456;\n"
17772                "VeryVeryLongType k  = 2;\n"
17773                "int              myvar = 1;",
17774                Alignment);
17775   Alignment.ColumnLimit = 80;
17776   Alignment.AlignConsecutiveAssignments.Enabled = false;
17777 
17778   verifyFormat(
17779       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17780       "          typename LongType, typename B>\n"
17781       "auto foo() {}\n",
17782       Alignment);
17783   verifyFormat("float a, b = 1;\n"
17784                "int   c = 2;\n"
17785                "int   dd = 3;\n",
17786                Alignment);
17787   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17788                "float b[1][] = {{3.f}};\n",
17789                Alignment);
17790   Alignment.AlignConsecutiveAssignments.Enabled = true;
17791   verifyFormat("float a, b = 1;\n"
17792                "int   c  = 2;\n"
17793                "int   dd = 3;\n",
17794                Alignment);
17795   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17796                "float b[1][] = {{3.f}};\n",
17797                Alignment);
17798   Alignment.AlignConsecutiveAssignments.Enabled = false;
17799 
17800   Alignment.ColumnLimit = 30;
17801   Alignment.BinPackParameters = false;
17802   verifyFormat("void foo(float     a,\n"
17803                "         float     b,\n"
17804                "         int       c,\n"
17805                "         uint32_t *d) {\n"
17806                "  int   *e = 0;\n"
17807                "  float  f = 0;\n"
17808                "  double g = 0;\n"
17809                "}\n"
17810                "void bar(ino_t     a,\n"
17811                "         int       b,\n"
17812                "         uint32_t *c,\n"
17813                "         bool      d) {}\n",
17814                Alignment);
17815   Alignment.BinPackParameters = true;
17816   Alignment.ColumnLimit = 80;
17817 
17818   // Bug 33507
17819   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17820   verifyFormat(
17821       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
17822       "  static const Version verVs2017;\n"
17823       "  return true;\n"
17824       "});\n",
17825       Alignment);
17826   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17827 
17828   // See llvm.org/PR35641
17829   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17830   verifyFormat("int func() { //\n"
17831                "  int      b;\n"
17832                "  unsigned c;\n"
17833                "}",
17834                Alignment);
17835 
17836   // See PR37175
17837   FormatStyle Style = getMozillaStyle();
17838   Style.AlignConsecutiveDeclarations.Enabled = true;
17839   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
17840             "foo(int a);",
17841             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
17842 
17843   Alignment.PointerAlignment = FormatStyle::PAS_Left;
17844   verifyFormat("unsigned int*       a;\n"
17845                "int*                b;\n"
17846                "unsigned int Const* c;\n"
17847                "unsigned int const* d;\n"
17848                "unsigned int Const& e;\n"
17849                "unsigned int const& f;",
17850                Alignment);
17851   verifyFormat("Const unsigned int* c;\n"
17852                "const unsigned int* d;\n"
17853                "Const unsigned int& e;\n"
17854                "const unsigned int& f;\n"
17855                "const unsigned      g;\n"
17856                "Const unsigned      h;",
17857                Alignment);
17858 
17859   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17860   verifyFormat("unsigned int *       a;\n"
17861                "int *                b;\n"
17862                "unsigned int Const * c;\n"
17863                "unsigned int const * d;\n"
17864                "unsigned int Const & e;\n"
17865                "unsigned int const & f;",
17866                Alignment);
17867   verifyFormat("Const unsigned int * c;\n"
17868                "const unsigned int * d;\n"
17869                "Const unsigned int & e;\n"
17870                "const unsigned int & f;\n"
17871                "const unsigned       g;\n"
17872                "Const unsigned       h;",
17873                Alignment);
17874 
17875   // See PR46529
17876   FormatStyle BracedAlign = getLLVMStyle();
17877   BracedAlign.AlignConsecutiveDeclarations.Enabled = true;
17878   verifyFormat("const auto result{[]() {\n"
17879                "  const auto something = 1;\n"
17880                "  return 2;\n"
17881                "}};",
17882                BracedAlign);
17883   verifyFormat("int foo{[]() {\n"
17884                "  int bar{0};\n"
17885                "  return 0;\n"
17886                "}()};",
17887                BracedAlign);
17888   BracedAlign.Cpp11BracedListStyle = false;
17889   verifyFormat("const auto result{ []() {\n"
17890                "  const auto something = 1;\n"
17891                "  return 2;\n"
17892                "} };",
17893                BracedAlign);
17894   verifyFormat("int foo{ []() {\n"
17895                "  int bar{ 0 };\n"
17896                "  return 0;\n"
17897                "}() };",
17898                BracedAlign);
17899 }
17900 
17901 TEST_F(FormatTest, AlignWithLineBreaks) {
17902   auto Style = getLLVMStyleWithColumns(120);
17903 
17904   EXPECT_EQ(Style.AlignConsecutiveAssignments,
17905             FormatStyle::AlignConsecutiveStyle(
17906                 {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
17907                  /*AcrossComments=*/false, /*AlignCompound=*/false,
17908                  /*PadOperators=*/true}));
17909   EXPECT_EQ(Style.AlignConsecutiveDeclarations,
17910             FormatStyle::AlignConsecutiveStyle({}));
17911   verifyFormat("void foo() {\n"
17912                "  int myVar = 5;\n"
17913                "  double x = 3.14;\n"
17914                "  auto str = \"Hello \"\n"
17915                "             \"World\";\n"
17916                "  auto s = \"Hello \"\n"
17917                "           \"Again\";\n"
17918                "}",
17919                Style);
17920 
17921   // clang-format off
17922   verifyFormat("void foo() {\n"
17923                "  const int capacityBefore = Entries.capacity();\n"
17924                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17925                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17926                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17927                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17928                "}",
17929                Style);
17930   // clang-format on
17931 
17932   Style.AlignConsecutiveAssignments.Enabled = true;
17933   verifyFormat("void foo() {\n"
17934                "  int myVar = 5;\n"
17935                "  double x  = 3.14;\n"
17936                "  auto str  = \"Hello \"\n"
17937                "              \"World\";\n"
17938                "  auto s    = \"Hello \"\n"
17939                "              \"Again\";\n"
17940                "}",
17941                Style);
17942 
17943   // clang-format off
17944   verifyFormat("void foo() {\n"
17945                "  const int capacityBefore = Entries.capacity();\n"
17946                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17947                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17948                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17949                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17950                "}",
17951                Style);
17952   // clang-format on
17953 
17954   Style.AlignConsecutiveAssignments.Enabled = false;
17955   Style.AlignConsecutiveDeclarations.Enabled = true;
17956   verifyFormat("void foo() {\n"
17957                "  int    myVar = 5;\n"
17958                "  double x = 3.14;\n"
17959                "  auto   str = \"Hello \"\n"
17960                "               \"World\";\n"
17961                "  auto   s = \"Hello \"\n"
17962                "             \"Again\";\n"
17963                "}",
17964                Style);
17965 
17966   // clang-format off
17967   verifyFormat("void foo() {\n"
17968                "  const int  capacityBefore = Entries.capacity();\n"
17969                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17970                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17971                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17972                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17973                "}",
17974                Style);
17975   // clang-format on
17976 
17977   Style.AlignConsecutiveAssignments.Enabled = true;
17978   Style.AlignConsecutiveDeclarations.Enabled = true;
17979 
17980   verifyFormat("void foo() {\n"
17981                "  int    myVar = 5;\n"
17982                "  double x     = 3.14;\n"
17983                "  auto   str   = \"Hello \"\n"
17984                "                 \"World\";\n"
17985                "  auto   s     = \"Hello \"\n"
17986                "                 \"Again\";\n"
17987                "}",
17988                Style);
17989 
17990   // clang-format off
17991   verifyFormat("void foo() {\n"
17992                "  const int  capacityBefore = Entries.capacity();\n"
17993                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17994                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17995                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17996                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17997                "}",
17998                Style);
17999   // clang-format on
18000 
18001   Style = getLLVMStyleWithColumns(120);
18002   Style.AlignConsecutiveAssignments.Enabled = true;
18003   Style.ContinuationIndentWidth = 4;
18004   Style.IndentWidth = 4;
18005 
18006   // clang-format off
18007   verifyFormat("void SomeFunc() {\n"
18008                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18009                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18010                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18011                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18012                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18013                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18014                "}",
18015                Style);
18016   // clang-format on
18017 
18018   Style.BinPackArguments = false;
18019 
18020   // clang-format off
18021   verifyFormat("void SomeFunc() {\n"
18022                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
18023                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18024                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
18025                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18026                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
18027                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18028                "}",
18029                Style);
18030   // clang-format on
18031 }
18032 
18033 TEST_F(FormatTest, AlignWithInitializerPeriods) {
18034   auto Style = getLLVMStyleWithColumns(60);
18035 
18036   verifyFormat("void foo1(void) {\n"
18037                "  BYTE p[1] = 1;\n"
18038                "  A B = {.one_foooooooooooooooo = 2,\n"
18039                "         .two_fooooooooooooo = 3,\n"
18040                "         .three_fooooooooooooo = 4};\n"
18041                "  BYTE payload = 2;\n"
18042                "}",
18043                Style);
18044 
18045   Style.AlignConsecutiveAssignments.Enabled = true;
18046   Style.AlignConsecutiveDeclarations.Enabled = false;
18047   verifyFormat("void foo2(void) {\n"
18048                "  BYTE p[1]    = 1;\n"
18049                "  A B          = {.one_foooooooooooooooo = 2,\n"
18050                "                  .two_fooooooooooooo    = 3,\n"
18051                "                  .three_fooooooooooooo  = 4};\n"
18052                "  BYTE payload = 2;\n"
18053                "}",
18054                Style);
18055 
18056   Style.AlignConsecutiveAssignments.Enabled = false;
18057   Style.AlignConsecutiveDeclarations.Enabled = true;
18058   verifyFormat("void foo3(void) {\n"
18059                "  BYTE p[1] = 1;\n"
18060                "  A    B = {.one_foooooooooooooooo = 2,\n"
18061                "            .two_fooooooooooooo = 3,\n"
18062                "            .three_fooooooooooooo = 4};\n"
18063                "  BYTE payload = 2;\n"
18064                "}",
18065                Style);
18066 
18067   Style.AlignConsecutiveAssignments.Enabled = true;
18068   Style.AlignConsecutiveDeclarations.Enabled = true;
18069   verifyFormat("void foo4(void) {\n"
18070                "  BYTE p[1]    = 1;\n"
18071                "  A    B       = {.one_foooooooooooooooo = 2,\n"
18072                "                  .two_fooooooooooooo    = 3,\n"
18073                "                  .three_fooooooooooooo  = 4};\n"
18074                "  BYTE payload = 2;\n"
18075                "}",
18076                Style);
18077 }
18078 
18079 TEST_F(FormatTest, LinuxBraceBreaking) {
18080   FormatStyle LinuxBraceStyle = getLLVMStyle();
18081   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
18082   verifyFormat("namespace a\n"
18083                "{\n"
18084                "class A\n"
18085                "{\n"
18086                "  void f()\n"
18087                "  {\n"
18088                "    if (true) {\n"
18089                "      a();\n"
18090                "      b();\n"
18091                "    } else {\n"
18092                "      a();\n"
18093                "    }\n"
18094                "  }\n"
18095                "  void g() { return; }\n"
18096                "};\n"
18097                "struct B {\n"
18098                "  int x;\n"
18099                "};\n"
18100                "} // namespace a\n",
18101                LinuxBraceStyle);
18102   verifyFormat("enum X {\n"
18103                "  Y = 0,\n"
18104                "}\n",
18105                LinuxBraceStyle);
18106   verifyFormat("struct S {\n"
18107                "  int Type;\n"
18108                "  union {\n"
18109                "    int x;\n"
18110                "    double y;\n"
18111                "  } Value;\n"
18112                "  class C\n"
18113                "  {\n"
18114                "    MyFavoriteType Value;\n"
18115                "  } Class;\n"
18116                "}\n",
18117                LinuxBraceStyle);
18118 }
18119 
18120 TEST_F(FormatTest, MozillaBraceBreaking) {
18121   FormatStyle MozillaBraceStyle = getLLVMStyle();
18122   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
18123   MozillaBraceStyle.FixNamespaceComments = false;
18124   verifyFormat("namespace a {\n"
18125                "class A\n"
18126                "{\n"
18127                "  void f()\n"
18128                "  {\n"
18129                "    if (true) {\n"
18130                "      a();\n"
18131                "      b();\n"
18132                "    }\n"
18133                "  }\n"
18134                "  void g() { return; }\n"
18135                "};\n"
18136                "enum E\n"
18137                "{\n"
18138                "  A,\n"
18139                "  // foo\n"
18140                "  B,\n"
18141                "  C\n"
18142                "};\n"
18143                "struct B\n"
18144                "{\n"
18145                "  int x;\n"
18146                "};\n"
18147                "}\n",
18148                MozillaBraceStyle);
18149   verifyFormat("struct S\n"
18150                "{\n"
18151                "  int Type;\n"
18152                "  union\n"
18153                "  {\n"
18154                "    int x;\n"
18155                "    double y;\n"
18156                "  } Value;\n"
18157                "  class C\n"
18158                "  {\n"
18159                "    MyFavoriteType Value;\n"
18160                "  } Class;\n"
18161                "}\n",
18162                MozillaBraceStyle);
18163 }
18164 
18165 TEST_F(FormatTest, StroustrupBraceBreaking) {
18166   FormatStyle StroustrupBraceStyle = getLLVMStyle();
18167   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18168   verifyFormat("namespace a {\n"
18169                "class A {\n"
18170                "  void f()\n"
18171                "  {\n"
18172                "    if (true) {\n"
18173                "      a();\n"
18174                "      b();\n"
18175                "    }\n"
18176                "  }\n"
18177                "  void g() { return; }\n"
18178                "};\n"
18179                "struct B {\n"
18180                "  int x;\n"
18181                "};\n"
18182                "} // namespace a\n",
18183                StroustrupBraceStyle);
18184 
18185   verifyFormat("void foo()\n"
18186                "{\n"
18187                "  if (a) {\n"
18188                "    a();\n"
18189                "  }\n"
18190                "  else {\n"
18191                "    b();\n"
18192                "  }\n"
18193                "}\n",
18194                StroustrupBraceStyle);
18195 
18196   verifyFormat("#ifdef _DEBUG\n"
18197                "int foo(int i = 0)\n"
18198                "#else\n"
18199                "int foo(int i = 5)\n"
18200                "#endif\n"
18201                "{\n"
18202                "  return i;\n"
18203                "}",
18204                StroustrupBraceStyle);
18205 
18206   verifyFormat("void foo() {}\n"
18207                "void bar()\n"
18208                "#ifdef _DEBUG\n"
18209                "{\n"
18210                "  foo();\n"
18211                "}\n"
18212                "#else\n"
18213                "{\n"
18214                "}\n"
18215                "#endif",
18216                StroustrupBraceStyle);
18217 
18218   verifyFormat("void foobar() { int i = 5; }\n"
18219                "#ifdef _DEBUG\n"
18220                "void bar() {}\n"
18221                "#else\n"
18222                "void bar() { foobar(); }\n"
18223                "#endif",
18224                StroustrupBraceStyle);
18225 }
18226 
18227 TEST_F(FormatTest, AllmanBraceBreaking) {
18228   FormatStyle AllmanBraceStyle = getLLVMStyle();
18229   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
18230 
18231   EXPECT_EQ("namespace a\n"
18232             "{\n"
18233             "void f();\n"
18234             "void g();\n"
18235             "} // namespace a\n",
18236             format("namespace a\n"
18237                    "{\n"
18238                    "void f();\n"
18239                    "void g();\n"
18240                    "}\n",
18241                    AllmanBraceStyle));
18242 
18243   verifyFormat("namespace a\n"
18244                "{\n"
18245                "class A\n"
18246                "{\n"
18247                "  void f()\n"
18248                "  {\n"
18249                "    if (true)\n"
18250                "    {\n"
18251                "      a();\n"
18252                "      b();\n"
18253                "    }\n"
18254                "  }\n"
18255                "  void g() { return; }\n"
18256                "};\n"
18257                "struct B\n"
18258                "{\n"
18259                "  int x;\n"
18260                "};\n"
18261                "union C\n"
18262                "{\n"
18263                "};\n"
18264                "} // namespace a",
18265                AllmanBraceStyle);
18266 
18267   verifyFormat("void f()\n"
18268                "{\n"
18269                "  if (true)\n"
18270                "  {\n"
18271                "    a();\n"
18272                "  }\n"
18273                "  else if (false)\n"
18274                "  {\n"
18275                "    b();\n"
18276                "  }\n"
18277                "  else\n"
18278                "  {\n"
18279                "    c();\n"
18280                "  }\n"
18281                "}\n",
18282                AllmanBraceStyle);
18283 
18284   verifyFormat("void f()\n"
18285                "{\n"
18286                "  for (int i = 0; i < 10; ++i)\n"
18287                "  {\n"
18288                "    a();\n"
18289                "  }\n"
18290                "  while (false)\n"
18291                "  {\n"
18292                "    b();\n"
18293                "  }\n"
18294                "  do\n"
18295                "  {\n"
18296                "    c();\n"
18297                "  } while (false)\n"
18298                "}\n",
18299                AllmanBraceStyle);
18300 
18301   verifyFormat("void f(int a)\n"
18302                "{\n"
18303                "  switch (a)\n"
18304                "  {\n"
18305                "  case 0:\n"
18306                "    break;\n"
18307                "  case 1:\n"
18308                "  {\n"
18309                "    break;\n"
18310                "  }\n"
18311                "  case 2:\n"
18312                "  {\n"
18313                "  }\n"
18314                "  break;\n"
18315                "  default:\n"
18316                "    break;\n"
18317                "  }\n"
18318                "}\n",
18319                AllmanBraceStyle);
18320 
18321   verifyFormat("enum X\n"
18322                "{\n"
18323                "  Y = 0,\n"
18324                "}\n",
18325                AllmanBraceStyle);
18326   verifyFormat("enum X\n"
18327                "{\n"
18328                "  Y = 0\n"
18329                "}\n",
18330                AllmanBraceStyle);
18331 
18332   verifyFormat("@interface BSApplicationController ()\n"
18333                "{\n"
18334                "@private\n"
18335                "  id _extraIvar;\n"
18336                "}\n"
18337                "@end\n",
18338                AllmanBraceStyle);
18339 
18340   verifyFormat("#ifdef _DEBUG\n"
18341                "int foo(int i = 0)\n"
18342                "#else\n"
18343                "int foo(int i = 5)\n"
18344                "#endif\n"
18345                "{\n"
18346                "  return i;\n"
18347                "}",
18348                AllmanBraceStyle);
18349 
18350   verifyFormat("void foo() {}\n"
18351                "void bar()\n"
18352                "#ifdef _DEBUG\n"
18353                "{\n"
18354                "  foo();\n"
18355                "}\n"
18356                "#else\n"
18357                "{\n"
18358                "}\n"
18359                "#endif",
18360                AllmanBraceStyle);
18361 
18362   verifyFormat("void foobar() { int i = 5; }\n"
18363                "#ifdef _DEBUG\n"
18364                "void bar() {}\n"
18365                "#else\n"
18366                "void bar() { foobar(); }\n"
18367                "#endif",
18368                AllmanBraceStyle);
18369 
18370   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18371             FormatStyle::SLS_All);
18372 
18373   verifyFormat("[](int i) { return i + 2; };\n"
18374                "[](int i, int j)\n"
18375                "{\n"
18376                "  auto x = i + j;\n"
18377                "  auto y = i * j;\n"
18378                "  return x ^ y;\n"
18379                "};\n"
18380                "void foo()\n"
18381                "{\n"
18382                "  auto shortLambda = [](int i) { return i + 2; };\n"
18383                "  auto longLambda = [](int i, int j)\n"
18384                "  {\n"
18385                "    auto x = i + j;\n"
18386                "    auto y = i * j;\n"
18387                "    return x ^ y;\n"
18388                "  };\n"
18389                "}",
18390                AllmanBraceStyle);
18391 
18392   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18393 
18394   verifyFormat("[](int i)\n"
18395                "{\n"
18396                "  return i + 2;\n"
18397                "};\n"
18398                "[](int i, int j)\n"
18399                "{\n"
18400                "  auto x = i + j;\n"
18401                "  auto y = i * j;\n"
18402                "  return x ^ y;\n"
18403                "};\n"
18404                "void foo()\n"
18405                "{\n"
18406                "  auto shortLambda = [](int i)\n"
18407                "  {\n"
18408                "    return i + 2;\n"
18409                "  };\n"
18410                "  auto longLambda = [](int i, int j)\n"
18411                "  {\n"
18412                "    auto x = i + j;\n"
18413                "    auto y = i * j;\n"
18414                "    return x ^ y;\n"
18415                "  };\n"
18416                "}",
18417                AllmanBraceStyle);
18418 
18419   // Reset
18420   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18421 
18422   // This shouldn't affect ObjC blocks..
18423   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18424                "  // ...\n"
18425                "  int i;\n"
18426                "}];",
18427                AllmanBraceStyle);
18428   verifyFormat("void (^block)(void) = ^{\n"
18429                "  // ...\n"
18430                "  int i;\n"
18431                "};",
18432                AllmanBraceStyle);
18433   // .. or dict literals.
18434   verifyFormat("void f()\n"
18435                "{\n"
18436                "  // ...\n"
18437                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18438                "}",
18439                AllmanBraceStyle);
18440   verifyFormat("void f()\n"
18441                "{\n"
18442                "  // ...\n"
18443                "  [object someMethod:@{a : @\"b\"}];\n"
18444                "}",
18445                AllmanBraceStyle);
18446   verifyFormat("int f()\n"
18447                "{ // comment\n"
18448                "  return 42;\n"
18449                "}",
18450                AllmanBraceStyle);
18451 
18452   AllmanBraceStyle.ColumnLimit = 19;
18453   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18454   AllmanBraceStyle.ColumnLimit = 18;
18455   verifyFormat("void f()\n"
18456                "{\n"
18457                "  int i;\n"
18458                "}",
18459                AllmanBraceStyle);
18460   AllmanBraceStyle.ColumnLimit = 80;
18461 
18462   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18463   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18464       FormatStyle::SIS_WithoutElse;
18465   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18466   verifyFormat("void f(bool b)\n"
18467                "{\n"
18468                "  if (b)\n"
18469                "  {\n"
18470                "    return;\n"
18471                "  }\n"
18472                "}\n",
18473                BreakBeforeBraceShortIfs);
18474   verifyFormat("void f(bool b)\n"
18475                "{\n"
18476                "  if constexpr (b)\n"
18477                "  {\n"
18478                "    return;\n"
18479                "  }\n"
18480                "}\n",
18481                BreakBeforeBraceShortIfs);
18482   verifyFormat("void f(bool b)\n"
18483                "{\n"
18484                "  if CONSTEXPR (b)\n"
18485                "  {\n"
18486                "    return;\n"
18487                "  }\n"
18488                "}\n",
18489                BreakBeforeBraceShortIfs);
18490   verifyFormat("void f(bool b)\n"
18491                "{\n"
18492                "  if (b) return;\n"
18493                "}\n",
18494                BreakBeforeBraceShortIfs);
18495   verifyFormat("void f(bool b)\n"
18496                "{\n"
18497                "  if constexpr (b) return;\n"
18498                "}\n",
18499                BreakBeforeBraceShortIfs);
18500   verifyFormat("void f(bool b)\n"
18501                "{\n"
18502                "  if CONSTEXPR (b) return;\n"
18503                "}\n",
18504                BreakBeforeBraceShortIfs);
18505   verifyFormat("void f(bool b)\n"
18506                "{\n"
18507                "  while (b)\n"
18508                "  {\n"
18509                "    return;\n"
18510                "  }\n"
18511                "}\n",
18512                BreakBeforeBraceShortIfs);
18513 }
18514 
18515 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18516   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18517   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18518 
18519   // Make a few changes to the style for testing purposes
18520   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18521       FormatStyle::SFS_Empty;
18522   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18523 
18524   // FIXME: this test case can't decide whether there should be a blank line
18525   // after the ~D() line or not. It adds one if one doesn't exist in the test
18526   // and it removes the line if one exists.
18527   /*
18528   verifyFormat("class A;\n"
18529                "namespace B\n"
18530                "  {\n"
18531                "class C;\n"
18532                "// Comment\n"
18533                "class D\n"
18534                "  {\n"
18535                "public:\n"
18536                "  D();\n"
18537                "  ~D() {}\n"
18538                "private:\n"
18539                "  enum E\n"
18540                "    {\n"
18541                "    F\n"
18542                "    }\n"
18543                "  };\n"
18544                "  } // namespace B\n",
18545                WhitesmithsBraceStyle);
18546   */
18547 
18548   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18549   verifyFormat("namespace a\n"
18550                "  {\n"
18551                "class A\n"
18552                "  {\n"
18553                "  void f()\n"
18554                "    {\n"
18555                "    if (true)\n"
18556                "      {\n"
18557                "      a();\n"
18558                "      b();\n"
18559                "      }\n"
18560                "    }\n"
18561                "  void g()\n"
18562                "    {\n"
18563                "    return;\n"
18564                "    }\n"
18565                "  };\n"
18566                "struct B\n"
18567                "  {\n"
18568                "  int x;\n"
18569                "  };\n"
18570                "  } // namespace a",
18571                WhitesmithsBraceStyle);
18572 
18573   verifyFormat("namespace a\n"
18574                "  {\n"
18575                "namespace b\n"
18576                "  {\n"
18577                "class A\n"
18578                "  {\n"
18579                "  void f()\n"
18580                "    {\n"
18581                "    if (true)\n"
18582                "      {\n"
18583                "      a();\n"
18584                "      b();\n"
18585                "      }\n"
18586                "    }\n"
18587                "  void g()\n"
18588                "    {\n"
18589                "    return;\n"
18590                "    }\n"
18591                "  };\n"
18592                "struct B\n"
18593                "  {\n"
18594                "  int x;\n"
18595                "  };\n"
18596                "  } // namespace b\n"
18597                "  } // namespace a",
18598                WhitesmithsBraceStyle);
18599 
18600   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18601   verifyFormat("namespace a\n"
18602                "  {\n"
18603                "namespace b\n"
18604                "  {\n"
18605                "  class A\n"
18606                "    {\n"
18607                "    void f()\n"
18608                "      {\n"
18609                "      if (true)\n"
18610                "        {\n"
18611                "        a();\n"
18612                "        b();\n"
18613                "        }\n"
18614                "      }\n"
18615                "    void g()\n"
18616                "      {\n"
18617                "      return;\n"
18618                "      }\n"
18619                "    };\n"
18620                "  struct B\n"
18621                "    {\n"
18622                "    int x;\n"
18623                "    };\n"
18624                "  } // namespace b\n"
18625                "  } // namespace a",
18626                WhitesmithsBraceStyle);
18627 
18628   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18629   verifyFormat("namespace a\n"
18630                "  {\n"
18631                "  namespace b\n"
18632                "    {\n"
18633                "    class A\n"
18634                "      {\n"
18635                "      void f()\n"
18636                "        {\n"
18637                "        if (true)\n"
18638                "          {\n"
18639                "          a();\n"
18640                "          b();\n"
18641                "          }\n"
18642                "        }\n"
18643                "      void g()\n"
18644                "        {\n"
18645                "        return;\n"
18646                "        }\n"
18647                "      };\n"
18648                "    struct B\n"
18649                "      {\n"
18650                "      int x;\n"
18651                "      };\n"
18652                "    } // namespace b\n"
18653                "  }   // namespace a",
18654                WhitesmithsBraceStyle);
18655 
18656   verifyFormat("void f()\n"
18657                "  {\n"
18658                "  if (true)\n"
18659                "    {\n"
18660                "    a();\n"
18661                "    }\n"
18662                "  else if (false)\n"
18663                "    {\n"
18664                "    b();\n"
18665                "    }\n"
18666                "  else\n"
18667                "    {\n"
18668                "    c();\n"
18669                "    }\n"
18670                "  }\n",
18671                WhitesmithsBraceStyle);
18672 
18673   verifyFormat("void f()\n"
18674                "  {\n"
18675                "  for (int i = 0; i < 10; ++i)\n"
18676                "    {\n"
18677                "    a();\n"
18678                "    }\n"
18679                "  while (false)\n"
18680                "    {\n"
18681                "    b();\n"
18682                "    }\n"
18683                "  do\n"
18684                "    {\n"
18685                "    c();\n"
18686                "    } while (false)\n"
18687                "  }\n",
18688                WhitesmithsBraceStyle);
18689 
18690   WhitesmithsBraceStyle.IndentCaseLabels = true;
18691   verifyFormat("void switchTest1(int a)\n"
18692                "  {\n"
18693                "  switch (a)\n"
18694                "    {\n"
18695                "    case 2:\n"
18696                "      {\n"
18697                "      }\n"
18698                "      break;\n"
18699                "    }\n"
18700                "  }\n",
18701                WhitesmithsBraceStyle);
18702 
18703   verifyFormat("void switchTest2(int a)\n"
18704                "  {\n"
18705                "  switch (a)\n"
18706                "    {\n"
18707                "    case 0:\n"
18708                "      break;\n"
18709                "    case 1:\n"
18710                "      {\n"
18711                "      break;\n"
18712                "      }\n"
18713                "    case 2:\n"
18714                "      {\n"
18715                "      }\n"
18716                "      break;\n"
18717                "    default:\n"
18718                "      break;\n"
18719                "    }\n"
18720                "  }\n",
18721                WhitesmithsBraceStyle);
18722 
18723   verifyFormat("void switchTest3(int a)\n"
18724                "  {\n"
18725                "  switch (a)\n"
18726                "    {\n"
18727                "    case 0:\n"
18728                "      {\n"
18729                "      foo(x);\n"
18730                "      }\n"
18731                "      break;\n"
18732                "    default:\n"
18733                "      {\n"
18734                "      foo(1);\n"
18735                "      }\n"
18736                "      break;\n"
18737                "    }\n"
18738                "  }\n",
18739                WhitesmithsBraceStyle);
18740 
18741   WhitesmithsBraceStyle.IndentCaseLabels = false;
18742 
18743   verifyFormat("void switchTest4(int a)\n"
18744                "  {\n"
18745                "  switch (a)\n"
18746                "    {\n"
18747                "  case 2:\n"
18748                "    {\n"
18749                "    }\n"
18750                "    break;\n"
18751                "    }\n"
18752                "  }\n",
18753                WhitesmithsBraceStyle);
18754 
18755   verifyFormat("void switchTest5(int a)\n"
18756                "  {\n"
18757                "  switch (a)\n"
18758                "    {\n"
18759                "  case 0:\n"
18760                "    break;\n"
18761                "  case 1:\n"
18762                "    {\n"
18763                "    foo();\n"
18764                "    break;\n"
18765                "    }\n"
18766                "  case 2:\n"
18767                "    {\n"
18768                "    }\n"
18769                "    break;\n"
18770                "  default:\n"
18771                "    break;\n"
18772                "    }\n"
18773                "  }\n",
18774                WhitesmithsBraceStyle);
18775 
18776   verifyFormat("void switchTest6(int a)\n"
18777                "  {\n"
18778                "  switch (a)\n"
18779                "    {\n"
18780                "  case 0:\n"
18781                "    {\n"
18782                "    foo(x);\n"
18783                "    }\n"
18784                "    break;\n"
18785                "  default:\n"
18786                "    {\n"
18787                "    foo(1);\n"
18788                "    }\n"
18789                "    break;\n"
18790                "    }\n"
18791                "  }\n",
18792                WhitesmithsBraceStyle);
18793 
18794   verifyFormat("enum X\n"
18795                "  {\n"
18796                "  Y = 0, // testing\n"
18797                "  }\n",
18798                WhitesmithsBraceStyle);
18799 
18800   verifyFormat("enum X\n"
18801                "  {\n"
18802                "  Y = 0\n"
18803                "  }\n",
18804                WhitesmithsBraceStyle);
18805   verifyFormat("enum X\n"
18806                "  {\n"
18807                "  Y = 0,\n"
18808                "  Z = 1\n"
18809                "  };\n",
18810                WhitesmithsBraceStyle);
18811 
18812   verifyFormat("@interface BSApplicationController ()\n"
18813                "  {\n"
18814                "@private\n"
18815                "  id _extraIvar;\n"
18816                "  }\n"
18817                "@end\n",
18818                WhitesmithsBraceStyle);
18819 
18820   verifyFormat("#ifdef _DEBUG\n"
18821                "int foo(int i = 0)\n"
18822                "#else\n"
18823                "int foo(int i = 5)\n"
18824                "#endif\n"
18825                "  {\n"
18826                "  return i;\n"
18827                "  }",
18828                WhitesmithsBraceStyle);
18829 
18830   verifyFormat("void foo() {}\n"
18831                "void bar()\n"
18832                "#ifdef _DEBUG\n"
18833                "  {\n"
18834                "  foo();\n"
18835                "  }\n"
18836                "#else\n"
18837                "  {\n"
18838                "  }\n"
18839                "#endif",
18840                WhitesmithsBraceStyle);
18841 
18842   verifyFormat("void foobar()\n"
18843                "  {\n"
18844                "  int i = 5;\n"
18845                "  }\n"
18846                "#ifdef _DEBUG\n"
18847                "void bar()\n"
18848                "  {\n"
18849                "  }\n"
18850                "#else\n"
18851                "void bar()\n"
18852                "  {\n"
18853                "  foobar();\n"
18854                "  }\n"
18855                "#endif",
18856                WhitesmithsBraceStyle);
18857 
18858   // This shouldn't affect ObjC blocks..
18859   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18860                "  // ...\n"
18861                "  int i;\n"
18862                "}];",
18863                WhitesmithsBraceStyle);
18864   verifyFormat("void (^block)(void) = ^{\n"
18865                "  // ...\n"
18866                "  int i;\n"
18867                "};",
18868                WhitesmithsBraceStyle);
18869   // .. or dict literals.
18870   verifyFormat("void f()\n"
18871                "  {\n"
18872                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18873                "  }",
18874                WhitesmithsBraceStyle);
18875 
18876   verifyFormat("int f()\n"
18877                "  { // comment\n"
18878                "  return 42;\n"
18879                "  }",
18880                WhitesmithsBraceStyle);
18881 
18882   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
18883   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18884       FormatStyle::SIS_OnlyFirstIf;
18885   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18886   verifyFormat("void f(bool b)\n"
18887                "  {\n"
18888                "  if (b)\n"
18889                "    {\n"
18890                "    return;\n"
18891                "    }\n"
18892                "  }\n",
18893                BreakBeforeBraceShortIfs);
18894   verifyFormat("void f(bool b)\n"
18895                "  {\n"
18896                "  if (b) return;\n"
18897                "  }\n",
18898                BreakBeforeBraceShortIfs);
18899   verifyFormat("void f(bool b)\n"
18900                "  {\n"
18901                "  while (b)\n"
18902                "    {\n"
18903                "    return;\n"
18904                "    }\n"
18905                "  }\n",
18906                BreakBeforeBraceShortIfs);
18907 }
18908 
18909 TEST_F(FormatTest, GNUBraceBreaking) {
18910   FormatStyle GNUBraceStyle = getLLVMStyle();
18911   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
18912   verifyFormat("namespace a\n"
18913                "{\n"
18914                "class A\n"
18915                "{\n"
18916                "  void f()\n"
18917                "  {\n"
18918                "    int a;\n"
18919                "    {\n"
18920                "      int b;\n"
18921                "    }\n"
18922                "    if (true)\n"
18923                "      {\n"
18924                "        a();\n"
18925                "        b();\n"
18926                "      }\n"
18927                "  }\n"
18928                "  void g() { return; }\n"
18929                "}\n"
18930                "} // namespace a",
18931                GNUBraceStyle);
18932 
18933   verifyFormat("void f()\n"
18934                "{\n"
18935                "  if (true)\n"
18936                "    {\n"
18937                "      a();\n"
18938                "    }\n"
18939                "  else if (false)\n"
18940                "    {\n"
18941                "      b();\n"
18942                "    }\n"
18943                "  else\n"
18944                "    {\n"
18945                "      c();\n"
18946                "    }\n"
18947                "}\n",
18948                GNUBraceStyle);
18949 
18950   verifyFormat("void f()\n"
18951                "{\n"
18952                "  for (int i = 0; i < 10; ++i)\n"
18953                "    {\n"
18954                "      a();\n"
18955                "    }\n"
18956                "  while (false)\n"
18957                "    {\n"
18958                "      b();\n"
18959                "    }\n"
18960                "  do\n"
18961                "    {\n"
18962                "      c();\n"
18963                "    }\n"
18964                "  while (false);\n"
18965                "}\n",
18966                GNUBraceStyle);
18967 
18968   verifyFormat("void f(int a)\n"
18969                "{\n"
18970                "  switch (a)\n"
18971                "    {\n"
18972                "    case 0:\n"
18973                "      break;\n"
18974                "    case 1:\n"
18975                "      {\n"
18976                "        break;\n"
18977                "      }\n"
18978                "    case 2:\n"
18979                "      {\n"
18980                "      }\n"
18981                "      break;\n"
18982                "    default:\n"
18983                "      break;\n"
18984                "    }\n"
18985                "}\n",
18986                GNUBraceStyle);
18987 
18988   verifyFormat("enum X\n"
18989                "{\n"
18990                "  Y = 0,\n"
18991                "}\n",
18992                GNUBraceStyle);
18993 
18994   verifyFormat("@interface BSApplicationController ()\n"
18995                "{\n"
18996                "@private\n"
18997                "  id _extraIvar;\n"
18998                "}\n"
18999                "@end\n",
19000                GNUBraceStyle);
19001 
19002   verifyFormat("#ifdef _DEBUG\n"
19003                "int foo(int i = 0)\n"
19004                "#else\n"
19005                "int foo(int i = 5)\n"
19006                "#endif\n"
19007                "{\n"
19008                "  return i;\n"
19009                "}",
19010                GNUBraceStyle);
19011 
19012   verifyFormat("void foo() {}\n"
19013                "void bar()\n"
19014                "#ifdef _DEBUG\n"
19015                "{\n"
19016                "  foo();\n"
19017                "}\n"
19018                "#else\n"
19019                "{\n"
19020                "}\n"
19021                "#endif",
19022                GNUBraceStyle);
19023 
19024   verifyFormat("void foobar() { int i = 5; }\n"
19025                "#ifdef _DEBUG\n"
19026                "void bar() {}\n"
19027                "#else\n"
19028                "void bar() { foobar(); }\n"
19029                "#endif",
19030                GNUBraceStyle);
19031 }
19032 
19033 TEST_F(FormatTest, WebKitBraceBreaking) {
19034   FormatStyle WebKitBraceStyle = getLLVMStyle();
19035   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
19036   WebKitBraceStyle.FixNamespaceComments = false;
19037   verifyFormat("namespace a {\n"
19038                "class A {\n"
19039                "  void f()\n"
19040                "  {\n"
19041                "    if (true) {\n"
19042                "      a();\n"
19043                "      b();\n"
19044                "    }\n"
19045                "  }\n"
19046                "  void g() { return; }\n"
19047                "};\n"
19048                "enum E {\n"
19049                "  A,\n"
19050                "  // foo\n"
19051                "  B,\n"
19052                "  C\n"
19053                "};\n"
19054                "struct B {\n"
19055                "  int x;\n"
19056                "};\n"
19057                "}\n",
19058                WebKitBraceStyle);
19059   verifyFormat("struct S {\n"
19060                "  int Type;\n"
19061                "  union {\n"
19062                "    int x;\n"
19063                "    double y;\n"
19064                "  } Value;\n"
19065                "  class C {\n"
19066                "    MyFavoriteType Value;\n"
19067                "  } Class;\n"
19068                "};\n",
19069                WebKitBraceStyle);
19070 }
19071 
19072 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
19073   verifyFormat("void f() {\n"
19074                "  try {\n"
19075                "  } catch (const Exception &e) {\n"
19076                "  }\n"
19077                "}\n",
19078                getLLVMStyle());
19079 }
19080 
19081 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
19082   auto Style = getLLVMStyle();
19083   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19084   Style.AlignConsecutiveAssignments.Enabled = true;
19085   Style.AlignConsecutiveDeclarations.Enabled = true;
19086   verifyFormat("struct test demo[] = {\n"
19087                "    {56,    23, \"hello\"},\n"
19088                "    {-1, 93463, \"world\"},\n"
19089                "    { 7,     5,    \"!!\"}\n"
19090                "};\n",
19091                Style);
19092 
19093   verifyFormat("struct test demo[] = {\n"
19094                "    {56,    23, \"hello\"}, // first line\n"
19095                "    {-1, 93463, \"world\"}, // second line\n"
19096                "    { 7,     5,    \"!!\"}  // third line\n"
19097                "};\n",
19098                Style);
19099 
19100   verifyFormat("struct test demo[4] = {\n"
19101                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19102                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19103                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19104                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19105                "};\n",
19106                Style);
19107 
19108   verifyFormat("struct test demo[3] = {\n"
19109                "    {56,    23, \"hello\"},\n"
19110                "    {-1, 93463, \"world\"},\n"
19111                "    { 7,     5,    \"!!\"}\n"
19112                "};\n",
19113                Style);
19114 
19115   verifyFormat("struct test demo[3] = {\n"
19116                "    {int{56},    23, \"hello\"},\n"
19117                "    {int{-1}, 93463, \"world\"},\n"
19118                "    { int{7},     5,    \"!!\"}\n"
19119                "};\n",
19120                Style);
19121 
19122   verifyFormat("struct test demo[] = {\n"
19123                "    {56,    23, \"hello\"},\n"
19124                "    {-1, 93463, \"world\"},\n"
19125                "    { 7,     5,    \"!!\"},\n"
19126                "};\n",
19127                Style);
19128 
19129   verifyFormat("test demo[] = {\n"
19130                "    {56,    23, \"hello\"},\n"
19131                "    {-1, 93463, \"world\"},\n"
19132                "    { 7,     5,    \"!!\"},\n"
19133                "};\n",
19134                Style);
19135 
19136   verifyFormat("demo = std::array<struct test, 3>{\n"
19137                "    test{56,    23, \"hello\"},\n"
19138                "    test{-1, 93463, \"world\"},\n"
19139                "    test{ 7,     5,    \"!!\"},\n"
19140                "};\n",
19141                Style);
19142 
19143   verifyFormat("test demo[] = {\n"
19144                "    {56,    23, \"hello\"},\n"
19145                "#if X\n"
19146                "    {-1, 93463, \"world\"},\n"
19147                "#endif\n"
19148                "    { 7,     5,    \"!!\"}\n"
19149                "};\n",
19150                Style);
19151 
19152   verifyFormat(
19153       "test demo[] = {\n"
19154       "    { 7,    23,\n"
19155       "     \"hello world i am a very long line that really, in any\"\n"
19156       "     \"just world, ought to be split over multiple lines\"},\n"
19157       "    {-1, 93463,                                  \"world\"},\n"
19158       "    {56,     5,                                     \"!!\"}\n"
19159       "};\n",
19160       Style);
19161 
19162   verifyFormat("return GradForUnaryCwise(g, {\n"
19163                "                                {{\"sign\"}, \"Sign\",  "
19164                "  {\"x\", \"dy\"}},\n"
19165                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
19166                ", \"sign\"}},\n"
19167                "});\n",
19168                Style);
19169 
19170   Style.ColumnLimit = 0;
19171   EXPECT_EQ(
19172       "test demo[] = {\n"
19173       "    {56,    23, \"hello world i am a very long line that really, "
19174       "in any just world, ought to be split over multiple lines\"},\n"
19175       "    {-1, 93463,                                                  "
19176       "                                                 \"world\"},\n"
19177       "    { 7,     5,                                                  "
19178       "                                                    \"!!\"},\n"
19179       "};",
19180       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19181              "that really, in any just world, ought to be split over multiple "
19182              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19183              Style));
19184 
19185   Style.ColumnLimit = 80;
19186   verifyFormat("test demo[] = {\n"
19187                "    {56,    23, /* a comment */ \"hello\"},\n"
19188                "    {-1, 93463,                 \"world\"},\n"
19189                "    { 7,     5,                    \"!!\"}\n"
19190                "};\n",
19191                Style);
19192 
19193   verifyFormat("test demo[] = {\n"
19194                "    {56,    23,                    \"hello\"},\n"
19195                "    {-1, 93463, \"world\" /* comment here */},\n"
19196                "    { 7,     5,                       \"!!\"}\n"
19197                "};\n",
19198                Style);
19199 
19200   verifyFormat("test demo[] = {\n"
19201                "    {56, /* a comment */ 23, \"hello\"},\n"
19202                "    {-1,              93463, \"world\"},\n"
19203                "    { 7,                  5,    \"!!\"}\n"
19204                "};\n",
19205                Style);
19206 
19207   Style.ColumnLimit = 20;
19208   EXPECT_EQ(
19209       "demo = std::array<\n"
19210       "    struct test, 3>{\n"
19211       "    test{\n"
19212       "         56,    23,\n"
19213       "         \"hello \"\n"
19214       "         \"world i \"\n"
19215       "         \"am a very \"\n"
19216       "         \"long line \"\n"
19217       "         \"that \"\n"
19218       "         \"really, \"\n"
19219       "         \"in any \"\n"
19220       "         \"just \"\n"
19221       "         \"world, \"\n"
19222       "         \"ought to \"\n"
19223       "         \"be split \"\n"
19224       "         \"over \"\n"
19225       "         \"multiple \"\n"
19226       "         \"lines\"},\n"
19227       "    test{-1, 93463,\n"
19228       "         \"world\"},\n"
19229       "    test{ 7,     5,\n"
19230       "         \"!!\"   },\n"
19231       "};",
19232       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19233              "i am a very long line that really, in any just world, ought "
19234              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19235              "test{7, 5, \"!!\"},};",
19236              Style));
19237   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19238   Style = getLLVMStyleWithColumns(50);
19239   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19240   verifyFormat("static A x = {\n"
19241                "    {{init1, init2, init3, init4},\n"
19242                "     {init1, init2, init3, init4}}\n"
19243                "};",
19244                Style);
19245   // TODO: Fix the indentations below when this option is fully functional.
19246   verifyFormat("int a[][] = {\n"
19247                "    {\n"
19248                "     {0, 2}, //\n"
19249                " {1, 2}  //\n"
19250                "    }\n"
19251                "};",
19252                Style);
19253   Style.ColumnLimit = 100;
19254   EXPECT_EQ(
19255       "test demo[] = {\n"
19256       "    {56,    23,\n"
19257       "     \"hello world i am a very long line that really, in any just world"
19258       ", ought to be split over \"\n"
19259       "     \"multiple lines\"  },\n"
19260       "    {-1, 93463, \"world\"},\n"
19261       "    { 7,     5,    \"!!\"},\n"
19262       "};",
19263       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19264              "that really, in any just world, ought to be split over multiple "
19265              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19266              Style));
19267 
19268   Style = getLLVMStyleWithColumns(50);
19269   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19270   verifyFormat("struct test demo[] = {\n"
19271                "    {56,    23, \"hello\"},\n"
19272                "    {-1, 93463, \"world\"},\n"
19273                "    { 7,     5,    \"!!\"}\n"
19274                "};\n"
19275                "static A x = {\n"
19276                "    {{init1, init2, init3, init4},\n"
19277                "     {init1, init2, init3, init4}}\n"
19278                "};",
19279                Style);
19280   Style.ColumnLimit = 100;
19281   Style.AlignConsecutiveAssignments.AcrossComments = true;
19282   Style.AlignConsecutiveDeclarations.AcrossComments = true;
19283   verifyFormat("struct test demo[] = {\n"
19284                "    {56,    23, \"hello\"},\n"
19285                "    {-1, 93463, \"world\"},\n"
19286                "    { 7,     5,    \"!!\"}\n"
19287                "};\n"
19288                "struct test demo[4] = {\n"
19289                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19290                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19291                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19292                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19293                "};\n",
19294                Style);
19295   EXPECT_EQ(
19296       "test demo[] = {\n"
19297       "    {56,\n"
19298       "     \"hello world i am a very long line that really, in any just world"
19299       ", ought to be split over \"\n"
19300       "     \"multiple lines\",    23},\n"
19301       "    {-1,      \"world\", 93463},\n"
19302       "    { 7,         \"!!\",     5},\n"
19303       "};",
19304       format("test demo[] = {{56, \"hello world i am a very long line "
19305              "that really, in any just world, ought to be split over multiple "
19306              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
19307              Style));
19308 }
19309 
19310 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
19311   auto Style = getLLVMStyle();
19312   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19313   /* FIXME: This case gets misformatted.
19314   verifyFormat("auto foo = Items{\n"
19315                "    Section{0, bar(), },\n"
19316                "    Section{1, boo()  }\n"
19317                "};\n",
19318                Style);
19319   */
19320   verifyFormat("auto foo = Items{\n"
19321                "    Section{\n"
19322                "            0, bar(),\n"
19323                "            }\n"
19324                "};\n",
19325                Style);
19326   verifyFormat("struct test demo[] = {\n"
19327                "    {56, 23,    \"hello\"},\n"
19328                "    {-1, 93463, \"world\"},\n"
19329                "    {7,  5,     \"!!\"   }\n"
19330                "};\n",
19331                Style);
19332   verifyFormat("struct test demo[] = {\n"
19333                "    {56, 23,    \"hello\"}, // first line\n"
19334                "    {-1, 93463, \"world\"}, // second line\n"
19335                "    {7,  5,     \"!!\"   }  // third line\n"
19336                "};\n",
19337                Style);
19338   verifyFormat("struct test demo[4] = {\n"
19339                "    {56,  23,    21, \"oh\"      }, // first line\n"
19340                "    {-1,  93463, 22, \"my\"      }, // second line\n"
19341                "    {7,   5,     1,  \"goodness\"}  // third line\n"
19342                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
19343                "};\n",
19344                Style);
19345   verifyFormat("struct test demo[3] = {\n"
19346                "    {56, 23,    \"hello\"},\n"
19347                "    {-1, 93463, \"world\"},\n"
19348                "    {7,  5,     \"!!\"   }\n"
19349                "};\n",
19350                Style);
19351 
19352   verifyFormat("struct test demo[3] = {\n"
19353                "    {int{56}, 23,    \"hello\"},\n"
19354                "    {int{-1}, 93463, \"world\"},\n"
19355                "    {int{7},  5,     \"!!\"   }\n"
19356                "};\n",
19357                Style);
19358   verifyFormat("struct test demo[] = {\n"
19359                "    {56, 23,    \"hello\"},\n"
19360                "    {-1, 93463, \"world\"},\n"
19361                "    {7,  5,     \"!!\"   },\n"
19362                "};\n",
19363                Style);
19364   verifyFormat("test demo[] = {\n"
19365                "    {56, 23,    \"hello\"},\n"
19366                "    {-1, 93463, \"world\"},\n"
19367                "    {7,  5,     \"!!\"   },\n"
19368                "};\n",
19369                Style);
19370   verifyFormat("demo = std::array<struct test, 3>{\n"
19371                "    test{56, 23,    \"hello\"},\n"
19372                "    test{-1, 93463, \"world\"},\n"
19373                "    test{7,  5,     \"!!\"   },\n"
19374                "};\n",
19375                Style);
19376   verifyFormat("test demo[] = {\n"
19377                "    {56, 23,    \"hello\"},\n"
19378                "#if X\n"
19379                "    {-1, 93463, \"world\"},\n"
19380                "#endif\n"
19381                "    {7,  5,     \"!!\"   }\n"
19382                "};\n",
19383                Style);
19384   verifyFormat(
19385       "test demo[] = {\n"
19386       "    {7,  23,\n"
19387       "     \"hello world i am a very long line that really, in any\"\n"
19388       "     \"just world, ought to be split over multiple lines\"},\n"
19389       "    {-1, 93463, \"world\"                                 },\n"
19390       "    {56, 5,     \"!!\"                                    }\n"
19391       "};\n",
19392       Style);
19393 
19394   verifyFormat("return GradForUnaryCwise(g, {\n"
19395                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19396                "\"dy\"}   },\n"
19397                "                                {{\"dx\"},   \"Mul\",  "
19398                "{\"dy\", \"sign\"}},\n"
19399                "});\n",
19400                Style);
19401 
19402   Style.ColumnLimit = 0;
19403   EXPECT_EQ(
19404       "test demo[] = {\n"
19405       "    {56, 23,    \"hello world i am a very long line that really, in any "
19406       "just world, ought to be split over multiple lines\"},\n"
19407       "    {-1, 93463, \"world\"                                               "
19408       "                                                   },\n"
19409       "    {7,  5,     \"!!\"                                                  "
19410       "                                                   },\n"
19411       "};",
19412       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19413              "that really, in any just world, ought to be split over multiple "
19414              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19415              Style));
19416 
19417   Style.ColumnLimit = 80;
19418   verifyFormat("test demo[] = {\n"
19419                "    {56, 23,    /* a comment */ \"hello\"},\n"
19420                "    {-1, 93463, \"world\"                },\n"
19421                "    {7,  5,     \"!!\"                   }\n"
19422                "};\n",
19423                Style);
19424 
19425   verifyFormat("test demo[] = {\n"
19426                "    {56, 23,    \"hello\"                   },\n"
19427                "    {-1, 93463, \"world\" /* comment here */},\n"
19428                "    {7,  5,     \"!!\"                      }\n"
19429                "};\n",
19430                Style);
19431 
19432   verifyFormat("test demo[] = {\n"
19433                "    {56, /* a comment */ 23, \"hello\"},\n"
19434                "    {-1, 93463,              \"world\"},\n"
19435                "    {7,  5,                  \"!!\"   }\n"
19436                "};\n",
19437                Style);
19438 
19439   Style.ColumnLimit = 20;
19440   EXPECT_EQ(
19441       "demo = std::array<\n"
19442       "    struct test, 3>{\n"
19443       "    test{\n"
19444       "         56, 23,\n"
19445       "         \"hello \"\n"
19446       "         \"world i \"\n"
19447       "         \"am a very \"\n"
19448       "         \"long line \"\n"
19449       "         \"that \"\n"
19450       "         \"really, \"\n"
19451       "         \"in any \"\n"
19452       "         \"just \"\n"
19453       "         \"world, \"\n"
19454       "         \"ought to \"\n"
19455       "         \"be split \"\n"
19456       "         \"over \"\n"
19457       "         \"multiple \"\n"
19458       "         \"lines\"},\n"
19459       "    test{-1, 93463,\n"
19460       "         \"world\"},\n"
19461       "    test{7,  5,\n"
19462       "         \"!!\"   },\n"
19463       "};",
19464       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19465              "i am a very long line that really, in any just world, ought "
19466              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19467              "test{7, 5, \"!!\"},};",
19468              Style));
19469 
19470   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19471   Style = getLLVMStyleWithColumns(50);
19472   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19473   verifyFormat("static A x = {\n"
19474                "    {{init1, init2, init3, init4},\n"
19475                "     {init1, init2, init3, init4}}\n"
19476                "};",
19477                Style);
19478   Style.ColumnLimit = 100;
19479   EXPECT_EQ(
19480       "test demo[] = {\n"
19481       "    {56, 23,\n"
19482       "     \"hello world i am a very long line that really, in any just world"
19483       ", ought to be split over \"\n"
19484       "     \"multiple lines\"  },\n"
19485       "    {-1, 93463, \"world\"},\n"
19486       "    {7,  5,     \"!!\"   },\n"
19487       "};",
19488       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19489              "that really, in any just world, ought to be split over multiple "
19490              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19491              Style));
19492 }
19493 
19494 TEST_F(FormatTest, UnderstandsPragmas) {
19495   verifyFormat("#pragma omp reduction(| : var)");
19496   verifyFormat("#pragma omp reduction(+ : var)");
19497 
19498   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19499             "(including parentheses).",
19500             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19501                    "(including parentheses)."));
19502 }
19503 
19504 TEST_F(FormatTest, UnderstandPragmaOption) {
19505   verifyFormat("#pragma option -C -A");
19506 
19507   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19508 }
19509 
19510 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19511   FormatStyle Style = getLLVMStyleWithColumns(20);
19512 
19513   // See PR41213
19514   EXPECT_EQ("/*\n"
19515             " *\t9012345\n"
19516             " * /8901\n"
19517             " */",
19518             format("/*\n"
19519                    " *\t9012345 /8901\n"
19520                    " */",
19521                    Style));
19522   EXPECT_EQ("/*\n"
19523             " *345678\n"
19524             " *\t/8901\n"
19525             " */",
19526             format("/*\n"
19527                    " *345678\t/8901\n"
19528                    " */",
19529                    Style));
19530 
19531   verifyFormat("int a; // the\n"
19532                "       // comment",
19533                Style);
19534   EXPECT_EQ("int a; /* first line\n"
19535             "        * second\n"
19536             "        * line third\n"
19537             "        * line\n"
19538             "        */",
19539             format("int a; /* first line\n"
19540                    "        * second\n"
19541                    "        * line third\n"
19542                    "        * line\n"
19543                    "        */",
19544                    Style));
19545   EXPECT_EQ("int a; // first line\n"
19546             "       // second\n"
19547             "       // line third\n"
19548             "       // line",
19549             format("int a; // first line\n"
19550                    "       // second line\n"
19551                    "       // third line",
19552                    Style));
19553 
19554   Style.PenaltyExcessCharacter = 90;
19555   verifyFormat("int a; // the comment", Style);
19556   EXPECT_EQ("int a; // the comment\n"
19557             "       // aaa",
19558             format("int a; // the comment aaa", Style));
19559   EXPECT_EQ("int a; /* first line\n"
19560             "        * second line\n"
19561             "        * third line\n"
19562             "        */",
19563             format("int a; /* first line\n"
19564                    "        * second line\n"
19565                    "        * third line\n"
19566                    "        */",
19567                    Style));
19568   EXPECT_EQ("int a; // first line\n"
19569             "       // second line\n"
19570             "       // third line",
19571             format("int a; // first line\n"
19572                    "       // second line\n"
19573                    "       // third line",
19574                    Style));
19575   // FIXME: Investigate why this is not getting the same layout as the test
19576   // above.
19577   EXPECT_EQ("int a; /* first line\n"
19578             "        * second line\n"
19579             "        * third line\n"
19580             "        */",
19581             format("int a; /* first line second line third line"
19582                    "\n*/",
19583                    Style));
19584 
19585   EXPECT_EQ("// foo bar baz bazfoo\n"
19586             "// foo bar foo bar\n",
19587             format("// foo bar baz bazfoo\n"
19588                    "// foo bar foo           bar\n",
19589                    Style));
19590   EXPECT_EQ("// foo bar baz bazfoo\n"
19591             "// foo bar foo bar\n",
19592             format("// foo bar baz      bazfoo\n"
19593                    "// foo            bar foo bar\n",
19594                    Style));
19595 
19596   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19597   // next one.
19598   EXPECT_EQ("// foo bar baz bazfoo\n"
19599             "// bar foo bar\n",
19600             format("// foo bar baz      bazfoo bar\n"
19601                    "// foo            bar\n",
19602                    Style));
19603 
19604   EXPECT_EQ("// foo bar baz bazfoo\n"
19605             "// foo bar baz bazfoo\n"
19606             "// bar foo bar\n",
19607             format("// foo bar baz      bazfoo\n"
19608                    "// foo bar baz      bazfoo bar\n"
19609                    "// foo bar\n",
19610                    Style));
19611 
19612   EXPECT_EQ("// foo bar baz bazfoo\n"
19613             "// foo bar baz bazfoo\n"
19614             "// bar foo bar\n",
19615             format("// foo bar baz      bazfoo\n"
19616                    "// foo bar baz      bazfoo bar\n"
19617                    "// foo           bar\n",
19618                    Style));
19619 
19620   // Make sure we do not keep protruding characters if strict mode reflow is
19621   // cheaper than keeping protruding characters.
19622   Style.ColumnLimit = 21;
19623   EXPECT_EQ(
19624       "// foo foo foo foo\n"
19625       "// foo foo foo foo\n"
19626       "// foo foo foo foo\n",
19627       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19628 
19629   EXPECT_EQ("int a = /* long block\n"
19630             "           comment */\n"
19631             "    42;",
19632             format("int a = /* long block comment */ 42;", Style));
19633 }
19634 
19635 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19636   FormatStyle Style = getLLVMStyle();
19637   Style.ColumnLimit = 8;
19638   Style.PenaltyExcessCharacter = 15;
19639   verifyFormat("int foo(\n"
19640                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19641                Style);
19642   Style.PenaltyBreakOpenParenthesis = 200;
19643   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19644             format("int foo(\n"
19645                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19646                    Style));
19647 }
19648 
19649 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19650   FormatStyle Style = getLLVMStyle();
19651   Style.ColumnLimit = 5;
19652   Style.PenaltyExcessCharacter = 150;
19653   verifyFormat("foo((\n"
19654                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19655 
19656                Style);
19657   Style.PenaltyBreakOpenParenthesis = 100000;
19658   EXPECT_EQ("foo((int)\n"
19659             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19660             format("foo((\n"
19661                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19662                    Style));
19663 }
19664 
19665 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19666   FormatStyle Style = getLLVMStyle();
19667   Style.ColumnLimit = 4;
19668   Style.PenaltyExcessCharacter = 100;
19669   verifyFormat("for (\n"
19670                "    int iiiiiiiiiiiiiiiii =\n"
19671                "        0;\n"
19672                "    iiiiiiiiiiiiiiiii <\n"
19673                "    2;\n"
19674                "    iiiiiiiiiiiiiiiii++) {\n"
19675                "}",
19676 
19677                Style);
19678   Style.PenaltyBreakOpenParenthesis = 1250;
19679   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19680             "         0;\n"
19681             "     iiiiiiiiiiiiiiiii <\n"
19682             "     2;\n"
19683             "     iiiiiiiiiiiiiiiii++) {\n"
19684             "}",
19685             format("for (\n"
19686                    "    int iiiiiiiiiiiiiiiii =\n"
19687                    "        0;\n"
19688                    "    iiiiiiiiiiiiiiiii <\n"
19689                    "    2;\n"
19690                    "    iiiiiiiiiiiiiiiii++) {\n"
19691                    "}",
19692                    Style));
19693 }
19694 
19695 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19696   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19697   EXPECT_EQ(Styles[0], Styles[i])                                              \
19698       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19699 
19700 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19701   SmallVector<FormatStyle, 3> Styles;
19702   Styles.resize(3);
19703 
19704   Styles[0] = getLLVMStyle();
19705   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19706   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19707   EXPECT_ALL_STYLES_EQUAL(Styles);
19708 
19709   Styles[0] = getGoogleStyle();
19710   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19711   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19712   EXPECT_ALL_STYLES_EQUAL(Styles);
19713 
19714   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19715   EXPECT_TRUE(
19716       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19717   EXPECT_TRUE(
19718       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19719   EXPECT_ALL_STYLES_EQUAL(Styles);
19720 
19721   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19722   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19723   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19724   EXPECT_ALL_STYLES_EQUAL(Styles);
19725 
19726   Styles[0] = getMozillaStyle();
19727   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19728   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19729   EXPECT_ALL_STYLES_EQUAL(Styles);
19730 
19731   Styles[0] = getWebKitStyle();
19732   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19733   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19734   EXPECT_ALL_STYLES_EQUAL(Styles);
19735 
19736   Styles[0] = getGNUStyle();
19737   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19738   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19739   EXPECT_ALL_STYLES_EQUAL(Styles);
19740 
19741   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19742 }
19743 
19744 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19745   SmallVector<FormatStyle, 8> Styles;
19746   Styles.resize(2);
19747 
19748   Styles[0] = getGoogleStyle();
19749   Styles[1] = getLLVMStyle();
19750   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19751   EXPECT_ALL_STYLES_EQUAL(Styles);
19752 
19753   Styles.resize(5);
19754   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19755   Styles[1] = getLLVMStyle();
19756   Styles[1].Language = FormatStyle::LK_JavaScript;
19757   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19758 
19759   Styles[2] = getLLVMStyle();
19760   Styles[2].Language = FormatStyle::LK_JavaScript;
19761   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19762                                   "BasedOnStyle: Google",
19763                                   &Styles[2])
19764                    .value());
19765 
19766   Styles[3] = getLLVMStyle();
19767   Styles[3].Language = FormatStyle::LK_JavaScript;
19768   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19769                                   "Language: JavaScript",
19770                                   &Styles[3])
19771                    .value());
19772 
19773   Styles[4] = getLLVMStyle();
19774   Styles[4].Language = FormatStyle::LK_JavaScript;
19775   EXPECT_EQ(0, parseConfiguration("---\n"
19776                                   "BasedOnStyle: LLVM\n"
19777                                   "IndentWidth: 123\n"
19778                                   "---\n"
19779                                   "BasedOnStyle: Google\n"
19780                                   "Language: JavaScript",
19781                                   &Styles[4])
19782                    .value());
19783   EXPECT_ALL_STYLES_EQUAL(Styles);
19784 }
19785 
19786 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
19787   Style.FIELD = false;                                                         \
19788   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
19789   EXPECT_TRUE(Style.FIELD);                                                    \
19790   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
19791   EXPECT_FALSE(Style.FIELD);
19792 
19793 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
19794 
19795 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
19796   Style.STRUCT.FIELD = false;                                                  \
19797   EXPECT_EQ(0,                                                                 \
19798             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
19799                 .value());                                                     \
19800   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
19801   EXPECT_EQ(0,                                                                 \
19802             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
19803                 .value());                                                     \
19804   EXPECT_FALSE(Style.STRUCT.FIELD);
19805 
19806 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
19807   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
19808 
19809 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
19810   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
19811   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
19812   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
19813 
19814 TEST_F(FormatTest, ParsesConfigurationBools) {
19815   FormatStyle Style = {};
19816   Style.Language = FormatStyle::LK_Cpp;
19817   CHECK_PARSE_BOOL(AlignTrailingComments);
19818   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
19819   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
19820   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
19821   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
19822   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
19823   CHECK_PARSE_BOOL(BinPackArguments);
19824   CHECK_PARSE_BOOL(BinPackParameters);
19825   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
19826   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
19827   CHECK_PARSE_BOOL(BreakStringLiterals);
19828   CHECK_PARSE_BOOL(CompactNamespaces);
19829   CHECK_PARSE_BOOL(DeriveLineEnding);
19830   CHECK_PARSE_BOOL(DerivePointerAlignment);
19831   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
19832   CHECK_PARSE_BOOL(DisableFormat);
19833   CHECK_PARSE_BOOL(IndentAccessModifiers);
19834   CHECK_PARSE_BOOL(IndentCaseLabels);
19835   CHECK_PARSE_BOOL(IndentCaseBlocks);
19836   CHECK_PARSE_BOOL(IndentGotoLabels);
19837   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
19838   CHECK_PARSE_BOOL(IndentRequiresClause);
19839   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
19840   CHECK_PARSE_BOOL(InsertBraces);
19841   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
19842   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
19843   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
19844   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
19845   CHECK_PARSE_BOOL(ReflowComments);
19846   CHECK_PARSE_BOOL(RemoveBracesLLVM);
19847   CHECK_PARSE_BOOL(SortUsingDeclarations);
19848   CHECK_PARSE_BOOL(SpacesInParentheses);
19849   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
19850   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
19851   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
19852   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
19853   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
19854   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
19855   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
19856   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
19857   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
19858   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
19859   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
19860   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
19861   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
19862   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
19863   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
19864   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
19865   CHECK_PARSE_BOOL(UseCRLF);
19866 
19867   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
19868   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
19869   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
19870   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
19871   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
19872   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
19873   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
19874   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
19875   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
19876   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
19877   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
19878   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
19879   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
19880   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
19881   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
19882   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
19883   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
19884   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
19885   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
19886   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19887                           AfterFunctionDeclarationName);
19888   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19889                           AfterFunctionDefinitionName);
19890   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
19891   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
19892   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
19893 }
19894 
19895 #undef CHECK_PARSE_BOOL
19896 
19897 TEST_F(FormatTest, ParsesConfiguration) {
19898   FormatStyle Style = {};
19899   Style.Language = FormatStyle::LK_Cpp;
19900   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
19901   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
19902               ConstructorInitializerIndentWidth, 1234u);
19903   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
19904   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
19905   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
19906   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
19907   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
19908               PenaltyBreakBeforeFirstCallParameter, 1234u);
19909   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
19910               PenaltyBreakTemplateDeclaration, 1234u);
19911   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
19912               1234u);
19913   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
19914   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
19915               PenaltyReturnTypeOnItsOwnLine, 1234u);
19916   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
19917               SpacesBeforeTrailingComments, 1234u);
19918   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
19919   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
19920   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
19921 
19922   Style.QualifierAlignment = FormatStyle::QAS_Right;
19923   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
19924               FormatStyle::QAS_Leave);
19925   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
19926               FormatStyle::QAS_Right);
19927   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
19928               FormatStyle::QAS_Left);
19929   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
19930               FormatStyle::QAS_Custom);
19931 
19932   Style.QualifierOrder.clear();
19933   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
19934               std::vector<std::string>({"const", "volatile", "type"}));
19935   Style.QualifierOrder.clear();
19936   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
19937               std::vector<std::string>({"const", "type"}));
19938   Style.QualifierOrder.clear();
19939   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
19940               std::vector<std::string>({"volatile", "type"}));
19941 
19942 #define CHECK_ALIGN_CONSECUTIVE(FIELD)                                         \
19943   do {                                                                         \
19944     Style.FIELD.Enabled = true;                                                \
19945     CHECK_PARSE(#FIELD ": None", FIELD,                                        \
19946                 FormatStyle::AlignConsecutiveStyle(                            \
19947                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19948                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19949                      /*PadOperators=*/true}));                                 \
19950     CHECK_PARSE(#FIELD ": Consecutive", FIELD,                                 \
19951                 FormatStyle::AlignConsecutiveStyle(                            \
19952                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19953                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19954                      /*PadOperators=*/true}));                                 \
19955     CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD,                            \
19956                 FormatStyle::AlignConsecutiveStyle(                            \
19957                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19958                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19959                      /*PadOperators=*/true}));                                 \
19960     CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD,                 \
19961                 FormatStyle::AlignConsecutiveStyle(                            \
19962                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19963                      /*AcrossComments=*/true, /*AlignCompound=*/false,         \
19964                      /*PadOperators=*/true}));                                 \
19965     /* For backwards compability, false / true should still parse */           \
19966     CHECK_PARSE(#FIELD ": false", FIELD,                                       \
19967                 FormatStyle::AlignConsecutiveStyle(                            \
19968                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19969                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19970                      /*PadOperators=*/true}));                                 \
19971     CHECK_PARSE(#FIELD ": true", FIELD,                                        \
19972                 FormatStyle::AlignConsecutiveStyle(                            \
19973                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19974                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19975                      /*PadOperators=*/true}));                                 \
19976                                                                                \
19977     CHECK_PARSE_NESTED_BOOL(FIELD, Enabled);                                   \
19978     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines);                          \
19979     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments);                            \
19980     CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound);                             \
19981     CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators);                              \
19982   } while (false)
19983 
19984   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments);
19985   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields);
19986   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros);
19987   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations);
19988 
19989 #undef CHECK_ALIGN_CONSECUTIVE
19990 
19991   Style.PointerAlignment = FormatStyle::PAS_Middle;
19992   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
19993               FormatStyle::PAS_Left);
19994   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
19995               FormatStyle::PAS_Right);
19996   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
19997               FormatStyle::PAS_Middle);
19998   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
19999   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
20000               FormatStyle::RAS_Pointer);
20001   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
20002               FormatStyle::RAS_Left);
20003   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
20004               FormatStyle::RAS_Right);
20005   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
20006               FormatStyle::RAS_Middle);
20007   // For backward compatibility:
20008   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
20009               FormatStyle::PAS_Left);
20010   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
20011               FormatStyle::PAS_Right);
20012   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
20013               FormatStyle::PAS_Middle);
20014 
20015   Style.Standard = FormatStyle::LS_Auto;
20016   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
20017   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
20018   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
20019   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
20020   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
20021   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
20022   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
20023   // Legacy aliases:
20024   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
20025   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
20026   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
20027   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
20028 
20029   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
20030   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
20031               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
20032   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
20033               FormatStyle::BOS_None);
20034   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
20035               FormatStyle::BOS_All);
20036   // For backward compatibility:
20037   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
20038               FormatStyle::BOS_None);
20039   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
20040               FormatStyle::BOS_All);
20041 
20042   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
20043   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
20044               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20045   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
20046               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
20047   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
20048               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
20049   // For backward compatibility:
20050   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
20051               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20052 
20053   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
20054   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
20055               FormatStyle::BILS_AfterComma);
20056   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
20057               FormatStyle::BILS_BeforeComma);
20058   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
20059               FormatStyle::BILS_AfterColon);
20060   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
20061               FormatStyle::BILS_BeforeColon);
20062   // For backward compatibility:
20063   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
20064               FormatStyle::BILS_BeforeComma);
20065 
20066   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20067   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
20068               FormatStyle::PCIS_Never);
20069   CHECK_PARSE("PackConstructorInitializers: BinPack",
20070               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20071   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
20072               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20073   CHECK_PARSE("PackConstructorInitializers: NextLine",
20074               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20075   // For backward compatibility:
20076   CHECK_PARSE("BasedOnStyle: Google\n"
20077               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20078               "AllowAllConstructorInitializersOnNextLine: false",
20079               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20080   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20081   CHECK_PARSE("BasedOnStyle: Google\n"
20082               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
20083               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20084   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20085               "AllowAllConstructorInitializersOnNextLine: true",
20086               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20087   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20088   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20089               "AllowAllConstructorInitializersOnNextLine: false",
20090               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20091 
20092   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
20093   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
20094               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
20095   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
20096               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
20097   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
20098               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
20099   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
20100               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
20101 
20102   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20103   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
20104               FormatStyle::BAS_Align);
20105   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
20106               FormatStyle::BAS_DontAlign);
20107   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
20108               FormatStyle::BAS_AlwaysBreak);
20109   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
20110               FormatStyle::BAS_BlockIndent);
20111   // For backward compatibility:
20112   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
20113               FormatStyle::BAS_DontAlign);
20114   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
20115               FormatStyle::BAS_Align);
20116 
20117   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
20118   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
20119               FormatStyle::ENAS_DontAlign);
20120   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
20121               FormatStyle::ENAS_Left);
20122   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
20123               FormatStyle::ENAS_Right);
20124   // For backward compatibility:
20125   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
20126               FormatStyle::ENAS_Left);
20127   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
20128               FormatStyle::ENAS_Right);
20129 
20130   Style.AlignOperands = FormatStyle::OAS_Align;
20131   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
20132               FormatStyle::OAS_DontAlign);
20133   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
20134   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
20135               FormatStyle::OAS_AlignAfterOperator);
20136   // For backward compatibility:
20137   CHECK_PARSE("AlignOperands: false", AlignOperands,
20138               FormatStyle::OAS_DontAlign);
20139   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
20140 
20141   Style.UseTab = FormatStyle::UT_ForIndentation;
20142   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
20143   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
20144   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
20145   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
20146               FormatStyle::UT_ForContinuationAndIndentation);
20147   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
20148               FormatStyle::UT_AlignWithSpaces);
20149   // For backward compatibility:
20150   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
20151   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
20152 
20153   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
20154   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
20155               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20156   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
20157               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
20158   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
20159               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20160   // For backward compatibility:
20161   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
20162               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20163   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
20164               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20165 
20166   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
20167   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
20168               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20169   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
20170               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
20171   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
20172               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
20173   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
20174               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20175   // For backward compatibility:
20176   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
20177               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20178   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
20179               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20180 
20181   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
20182   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
20183               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
20184   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
20185               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
20186   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
20187               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
20188   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
20189               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
20190 
20191   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
20192   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
20193               FormatStyle::SBPO_Never);
20194   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
20195               FormatStyle::SBPO_Always);
20196   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
20197               FormatStyle::SBPO_ControlStatements);
20198   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
20199               SpaceBeforeParens,
20200               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20201   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
20202               FormatStyle::SBPO_NonEmptyParentheses);
20203   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
20204               FormatStyle::SBPO_Custom);
20205   // For backward compatibility:
20206   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
20207               FormatStyle::SBPO_Never);
20208   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
20209               FormatStyle::SBPO_ControlStatements);
20210   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
20211               SpaceBeforeParens,
20212               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20213 
20214   Style.ColumnLimit = 123;
20215   FormatStyle BaseStyle = getLLVMStyle();
20216   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
20217   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
20218 
20219   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
20220   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
20221               FormatStyle::BS_Attach);
20222   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
20223               FormatStyle::BS_Linux);
20224   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
20225               FormatStyle::BS_Mozilla);
20226   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
20227               FormatStyle::BS_Stroustrup);
20228   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
20229               FormatStyle::BS_Allman);
20230   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
20231               FormatStyle::BS_Whitesmiths);
20232   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
20233   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
20234               FormatStyle::BS_WebKit);
20235   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
20236               FormatStyle::BS_Custom);
20237 
20238   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
20239   CHECK_PARSE("BraceWrapping:\n"
20240               "  AfterControlStatement: MultiLine",
20241               BraceWrapping.AfterControlStatement,
20242               FormatStyle::BWACS_MultiLine);
20243   CHECK_PARSE("BraceWrapping:\n"
20244               "  AfterControlStatement: Always",
20245               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20246   CHECK_PARSE("BraceWrapping:\n"
20247               "  AfterControlStatement: Never",
20248               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20249   // For backward compatibility:
20250   CHECK_PARSE("BraceWrapping:\n"
20251               "  AfterControlStatement: true",
20252               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20253   CHECK_PARSE("BraceWrapping:\n"
20254               "  AfterControlStatement: false",
20255               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20256 
20257   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
20258   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
20259               FormatStyle::RTBS_None);
20260   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
20261               FormatStyle::RTBS_All);
20262   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
20263               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
20264   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
20265               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
20266   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
20267               AlwaysBreakAfterReturnType,
20268               FormatStyle::RTBS_TopLevelDefinitions);
20269 
20270   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
20271   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
20272               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
20273   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
20274               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20275   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
20276               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20277   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
20278               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20279   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
20280               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20281 
20282   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
20283   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
20284               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
20285   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
20286               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
20287   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
20288               AlwaysBreakAfterDefinitionReturnType,
20289               FormatStyle::DRTBS_TopLevel);
20290 
20291   Style.NamespaceIndentation = FormatStyle::NI_All;
20292   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
20293               FormatStyle::NI_None);
20294   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
20295               FormatStyle::NI_Inner);
20296   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
20297               FormatStyle::NI_All);
20298 
20299   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
20300   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
20301               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20302   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
20303               AllowShortIfStatementsOnASingleLine,
20304               FormatStyle::SIS_WithoutElse);
20305   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
20306               AllowShortIfStatementsOnASingleLine,
20307               FormatStyle::SIS_OnlyFirstIf);
20308   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
20309               AllowShortIfStatementsOnASingleLine,
20310               FormatStyle::SIS_AllIfsAndElse);
20311   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
20312               AllowShortIfStatementsOnASingleLine,
20313               FormatStyle::SIS_OnlyFirstIf);
20314   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
20315               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20316   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
20317               AllowShortIfStatementsOnASingleLine,
20318               FormatStyle::SIS_WithoutElse);
20319 
20320   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
20321   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
20322               FormatStyle::IEBS_AfterExternBlock);
20323   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
20324               FormatStyle::IEBS_Indent);
20325   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
20326               FormatStyle::IEBS_NoIndent);
20327   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
20328               FormatStyle::IEBS_Indent);
20329   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
20330               FormatStyle::IEBS_NoIndent);
20331 
20332   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
20333   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
20334               FormatStyle::BFCS_Both);
20335   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
20336               FormatStyle::BFCS_None);
20337   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
20338               FormatStyle::BFCS_Before);
20339   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
20340               FormatStyle::BFCS_After);
20341 
20342   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
20343   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
20344               FormatStyle::SJSIO_After);
20345   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
20346               FormatStyle::SJSIO_Before);
20347 
20348   // FIXME: This is required because parsing a configuration simply overwrites
20349   // the first N elements of the list instead of resetting it.
20350   Style.ForEachMacros.clear();
20351   std::vector<std::string> BoostForeach;
20352   BoostForeach.push_back("BOOST_FOREACH");
20353   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20354   std::vector<std::string> BoostAndQForeach;
20355   BoostAndQForeach.push_back("BOOST_FOREACH");
20356   BoostAndQForeach.push_back("Q_FOREACH");
20357   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20358               BoostAndQForeach);
20359 
20360   Style.IfMacros.clear();
20361   std::vector<std::string> CustomIfs;
20362   CustomIfs.push_back("MYIF");
20363   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20364 
20365   Style.AttributeMacros.clear();
20366   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20367               std::vector<std::string>{"__capability"});
20368   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20369               std::vector<std::string>({"attr1", "attr2"}));
20370 
20371   Style.StatementAttributeLikeMacros.clear();
20372   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20373               StatementAttributeLikeMacros,
20374               std::vector<std::string>({"emit", "Q_EMIT"}));
20375 
20376   Style.StatementMacros.clear();
20377   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20378               std::vector<std::string>{"QUNUSED"});
20379   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20380               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20381 
20382   Style.NamespaceMacros.clear();
20383   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20384               std::vector<std::string>{"TESTSUITE"});
20385   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20386               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20387 
20388   Style.WhitespaceSensitiveMacros.clear();
20389   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20390               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20391   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20392               WhitespaceSensitiveMacros,
20393               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20394   Style.WhitespaceSensitiveMacros.clear();
20395   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
20396               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20397   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
20398               WhitespaceSensitiveMacros,
20399               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20400 
20401   Style.IncludeStyle.IncludeCategories.clear();
20402   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20403       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20404   CHECK_PARSE("IncludeCategories:\n"
20405               "  - Regex: abc/.*\n"
20406               "    Priority: 2\n"
20407               "  - Regex: .*\n"
20408               "    Priority: 1\n"
20409               "    CaseSensitive: true\n",
20410               IncludeStyle.IncludeCategories, ExpectedCategories);
20411   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20412               "abc$");
20413   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20414               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20415 
20416   Style.SortIncludes = FormatStyle::SI_Never;
20417   CHECK_PARSE("SortIncludes: true", SortIncludes,
20418               FormatStyle::SI_CaseSensitive);
20419   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20420   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20421               FormatStyle::SI_CaseInsensitive);
20422   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20423               FormatStyle::SI_CaseSensitive);
20424   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20425 
20426   Style.RawStringFormats.clear();
20427   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20428       {
20429           FormatStyle::LK_TextProto,
20430           {"pb", "proto"},
20431           {"PARSE_TEXT_PROTO"},
20432           /*CanonicalDelimiter=*/"",
20433           "llvm",
20434       },
20435       {
20436           FormatStyle::LK_Cpp,
20437           {"cc", "cpp"},
20438           {"C_CODEBLOCK", "CPPEVAL"},
20439           /*CanonicalDelimiter=*/"cc",
20440           /*BasedOnStyle=*/"",
20441       },
20442   };
20443 
20444   CHECK_PARSE("RawStringFormats:\n"
20445               "  - Language: TextProto\n"
20446               "    Delimiters:\n"
20447               "      - 'pb'\n"
20448               "      - 'proto'\n"
20449               "    EnclosingFunctions:\n"
20450               "      - 'PARSE_TEXT_PROTO'\n"
20451               "    BasedOnStyle: llvm\n"
20452               "  - Language: Cpp\n"
20453               "    Delimiters:\n"
20454               "      - 'cc'\n"
20455               "      - 'cpp'\n"
20456               "    EnclosingFunctions:\n"
20457               "      - 'C_CODEBLOCK'\n"
20458               "      - 'CPPEVAL'\n"
20459               "    CanonicalDelimiter: 'cc'",
20460               RawStringFormats, ExpectedRawStringFormats);
20461 
20462   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20463               "  Minimum: 0\n"
20464               "  Maximum: 0",
20465               SpacesInLineCommentPrefix.Minimum, 0u);
20466   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20467   Style.SpacesInLineCommentPrefix.Minimum = 1;
20468   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20469               "  Minimum: 2",
20470               SpacesInLineCommentPrefix.Minimum, 0u);
20471   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20472               "  Maximum: -1",
20473               SpacesInLineCommentPrefix.Maximum, -1u);
20474   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20475               "  Minimum: 2",
20476               SpacesInLineCommentPrefix.Minimum, 2u);
20477   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20478               "  Maximum: 1",
20479               SpacesInLineCommentPrefix.Maximum, 1u);
20480   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20481 
20482   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20483   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20484   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20485               FormatStyle::SIAS_Always);
20486   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20487   // For backward compatibility:
20488   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20489   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20490 
20491   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20492               FormatStyle::RCPS_WithPreceding);
20493   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20494               FormatStyle::RCPS_WithFollowing);
20495   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20496               FormatStyle::RCPS_SingleLine);
20497   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20498               FormatStyle::RCPS_OwnLine);
20499 
20500   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20501               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20502   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20503               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20504   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20505               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20506   // For backward compatibility:
20507   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20508               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20509   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20510               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20511 }
20512 
20513 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20514   FormatStyle Style = {};
20515   Style.Language = FormatStyle::LK_Cpp;
20516   CHECK_PARSE("Language: Cpp\n"
20517               "IndentWidth: 12",
20518               IndentWidth, 12u);
20519   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20520                                "IndentWidth: 34",
20521                                &Style),
20522             ParseError::Unsuitable);
20523   FormatStyle BinPackedTCS = {};
20524   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20525   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20526                                "InsertTrailingCommas: Wrapped",
20527                                &BinPackedTCS),
20528             ParseError::BinPackTrailingCommaConflict);
20529   EXPECT_EQ(12u, Style.IndentWidth);
20530   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20531   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20532 
20533   Style.Language = FormatStyle::LK_JavaScript;
20534   CHECK_PARSE("Language: JavaScript\n"
20535               "IndentWidth: 12",
20536               IndentWidth, 12u);
20537   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20538   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20539                                "IndentWidth: 34",
20540                                &Style),
20541             ParseError::Unsuitable);
20542   EXPECT_EQ(23u, Style.IndentWidth);
20543   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20544   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20545 
20546   CHECK_PARSE("BasedOnStyle: LLVM\n"
20547               "IndentWidth: 67",
20548               IndentWidth, 67u);
20549 
20550   CHECK_PARSE("---\n"
20551               "Language: JavaScript\n"
20552               "IndentWidth: 12\n"
20553               "---\n"
20554               "Language: Cpp\n"
20555               "IndentWidth: 34\n"
20556               "...\n",
20557               IndentWidth, 12u);
20558 
20559   Style.Language = FormatStyle::LK_Cpp;
20560   CHECK_PARSE("---\n"
20561               "Language: JavaScript\n"
20562               "IndentWidth: 12\n"
20563               "---\n"
20564               "Language: Cpp\n"
20565               "IndentWidth: 34\n"
20566               "...\n",
20567               IndentWidth, 34u);
20568   CHECK_PARSE("---\n"
20569               "IndentWidth: 78\n"
20570               "---\n"
20571               "Language: JavaScript\n"
20572               "IndentWidth: 56\n"
20573               "...\n",
20574               IndentWidth, 78u);
20575 
20576   Style.ColumnLimit = 123;
20577   Style.IndentWidth = 234;
20578   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20579   Style.TabWidth = 345;
20580   EXPECT_FALSE(parseConfiguration("---\n"
20581                                   "IndentWidth: 456\n"
20582                                   "BreakBeforeBraces: Allman\n"
20583                                   "---\n"
20584                                   "Language: JavaScript\n"
20585                                   "IndentWidth: 111\n"
20586                                   "TabWidth: 111\n"
20587                                   "---\n"
20588                                   "Language: Cpp\n"
20589                                   "BreakBeforeBraces: Stroustrup\n"
20590                                   "TabWidth: 789\n"
20591                                   "...\n",
20592                                   &Style));
20593   EXPECT_EQ(123u, Style.ColumnLimit);
20594   EXPECT_EQ(456u, Style.IndentWidth);
20595   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20596   EXPECT_EQ(789u, Style.TabWidth);
20597 
20598   EXPECT_EQ(parseConfiguration("---\n"
20599                                "Language: JavaScript\n"
20600                                "IndentWidth: 56\n"
20601                                "---\n"
20602                                "IndentWidth: 78\n"
20603                                "...\n",
20604                                &Style),
20605             ParseError::Error);
20606   EXPECT_EQ(parseConfiguration("---\n"
20607                                "Language: JavaScript\n"
20608                                "IndentWidth: 56\n"
20609                                "---\n"
20610                                "Language: JavaScript\n"
20611                                "IndentWidth: 78\n"
20612                                "...\n",
20613                                &Style),
20614             ParseError::Error);
20615 
20616   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20617 }
20618 
20619 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20620   FormatStyle Style = {};
20621   Style.Language = FormatStyle::LK_JavaScript;
20622   Style.BreakBeforeTernaryOperators = true;
20623   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20624   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20625 
20626   Style.BreakBeforeTernaryOperators = true;
20627   EXPECT_EQ(0, parseConfiguration("---\n"
20628                                   "BasedOnStyle: Google\n"
20629                                   "---\n"
20630                                   "Language: JavaScript\n"
20631                                   "IndentWidth: 76\n"
20632                                   "...\n",
20633                                   &Style)
20634                    .value());
20635   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20636   EXPECT_EQ(76u, Style.IndentWidth);
20637   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20638 }
20639 
20640 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20641   FormatStyle Style = getLLVMStyle();
20642   std::string YAML = configurationAsText(Style);
20643   FormatStyle ParsedStyle = {};
20644   ParsedStyle.Language = FormatStyle::LK_Cpp;
20645   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20646   EXPECT_EQ(Style, ParsedStyle);
20647 }
20648 
20649 TEST_F(FormatTest, WorksFor8bitEncodings) {
20650   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20651             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20652             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20653             "\"\xef\xee\xf0\xf3...\"",
20654             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20655                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20656                    "\xef\xee\xf0\xf3...\"",
20657                    getLLVMStyleWithColumns(12)));
20658 }
20659 
20660 TEST_F(FormatTest, HandlesUTF8BOM) {
20661   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20662   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20663             format("\xef\xbb\xbf#include <iostream>"));
20664   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20665             format("\xef\xbb\xbf\n#include <iostream>"));
20666 }
20667 
20668 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20669 #if !defined(_MSC_VER)
20670 
20671 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20672   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20673                getLLVMStyleWithColumns(35));
20674   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20675                getLLVMStyleWithColumns(31));
20676   verifyFormat("// Однажды в студёную зимнюю пору...",
20677                getLLVMStyleWithColumns(36));
20678   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20679   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20680                getLLVMStyleWithColumns(39));
20681   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20682                getLLVMStyleWithColumns(35));
20683 }
20684 
20685 TEST_F(FormatTest, SplitsUTF8Strings) {
20686   // Non-printable characters' width is currently considered to be the length in
20687   // bytes in UTF8. The characters can be displayed in very different manner
20688   // (zero-width, single width with a substitution glyph, expanded to their code
20689   // (e.g. "<8d>"), so there's no single correct way to handle them.
20690   EXPECT_EQ("\"aaaaÄ\"\n"
20691             "\"\xc2\x8d\";",
20692             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20693   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20694             "\"\xc2\x8d\";",
20695             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20696   EXPECT_EQ("\"Однажды, в \"\n"
20697             "\"студёную \"\n"
20698             "\"зимнюю \"\n"
20699             "\"пору,\"",
20700             format("\"Однажды, в студёную зимнюю пору,\"",
20701                    getLLVMStyleWithColumns(13)));
20702   EXPECT_EQ(
20703       "\"一 二 三 \"\n"
20704       "\"四 五六 \"\n"
20705       "\"七 八 九 \"\n"
20706       "\"十\"",
20707       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20708   EXPECT_EQ("\"一\t\"\n"
20709             "\"二 \t\"\n"
20710             "\"三 四 \"\n"
20711             "\"五\t\"\n"
20712             "\"六 \t\"\n"
20713             "\"七 \"\n"
20714             "\"八九十\tqq\"",
20715             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20716                    getLLVMStyleWithColumns(11)));
20717 
20718   // UTF8 character in an escape sequence.
20719   EXPECT_EQ("\"aaaaaa\"\n"
20720             "\"\\\xC2\x8D\"",
20721             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20722 }
20723 
20724 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20725   EXPECT_EQ("const char *sssss =\n"
20726             "    \"一二三四五六七八\\\n"
20727             " 九 十\";",
20728             format("const char *sssss = \"一二三四五六七八\\\n"
20729                    " 九 十\";",
20730                    getLLVMStyleWithColumns(30)));
20731 }
20732 
20733 TEST_F(FormatTest, SplitsUTF8LineComments) {
20734   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20735             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20736   EXPECT_EQ("// Я из лесу\n"
20737             "// вышел; был\n"
20738             "// сильный\n"
20739             "// мороз.",
20740             format("// Я из лесу вышел; был сильный мороз.",
20741                    getLLVMStyleWithColumns(13)));
20742   EXPECT_EQ("// 一二三\n"
20743             "// 四五六七\n"
20744             "// 八  九\n"
20745             "// 十",
20746             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20747 }
20748 
20749 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20750   EXPECT_EQ("/* Гляжу,\n"
20751             " * поднимается\n"
20752             " * медленно в\n"
20753             " * гору\n"
20754             " * Лошадка,\n"
20755             " * везущая\n"
20756             " * хворосту\n"
20757             " * воз. */",
20758             format("/* Гляжу, поднимается медленно в гору\n"
20759                    " * Лошадка, везущая хворосту воз. */",
20760                    getLLVMStyleWithColumns(13)));
20761   EXPECT_EQ(
20762       "/* 一二三\n"
20763       " * 四五六七\n"
20764       " * 八  九\n"
20765       " * 十  */",
20766       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20767   EXPECT_EQ("/* �������� ��������\n"
20768             " * ��������\n"
20769             " * ������-�� */",
20770             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20771 }
20772 
20773 #endif // _MSC_VER
20774 
20775 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
20776   FormatStyle Style = getLLVMStyle();
20777 
20778   Style.ConstructorInitializerIndentWidth = 4;
20779   verifyFormat(
20780       "SomeClass::Constructor()\n"
20781       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20782       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20783       Style);
20784 
20785   Style.ConstructorInitializerIndentWidth = 2;
20786   verifyFormat(
20787       "SomeClass::Constructor()\n"
20788       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20789       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20790       Style);
20791 
20792   Style.ConstructorInitializerIndentWidth = 0;
20793   verifyFormat(
20794       "SomeClass::Constructor()\n"
20795       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20796       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20797       Style);
20798   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20799   verifyFormat(
20800       "SomeLongTemplateVariableName<\n"
20801       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
20802       Style);
20803   verifyFormat("bool smaller = 1 < "
20804                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
20805                "                       "
20806                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
20807                Style);
20808 
20809   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
20810   verifyFormat("SomeClass::Constructor() :\n"
20811                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
20812                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
20813                Style);
20814 }
20815 
20816 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
20817   FormatStyle Style = getLLVMStyle();
20818   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20819   Style.ConstructorInitializerIndentWidth = 4;
20820   verifyFormat("SomeClass::Constructor()\n"
20821                "    : a(a)\n"
20822                "    , b(b)\n"
20823                "    , c(c) {}",
20824                Style);
20825   verifyFormat("SomeClass::Constructor()\n"
20826                "    : a(a) {}",
20827                Style);
20828 
20829   Style.ColumnLimit = 0;
20830   verifyFormat("SomeClass::Constructor()\n"
20831                "    : a(a) {}",
20832                Style);
20833   verifyFormat("SomeClass::Constructor() noexcept\n"
20834                "    : a(a) {}",
20835                Style);
20836   verifyFormat("SomeClass::Constructor()\n"
20837                "    : a(a)\n"
20838                "    , b(b)\n"
20839                "    , c(c) {}",
20840                Style);
20841   verifyFormat("SomeClass::Constructor()\n"
20842                "    : a(a) {\n"
20843                "  foo();\n"
20844                "  bar();\n"
20845                "}",
20846                Style);
20847 
20848   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
20849   verifyFormat("SomeClass::Constructor()\n"
20850                "    : a(a)\n"
20851                "    , b(b)\n"
20852                "    , c(c) {\n}",
20853                Style);
20854   verifyFormat("SomeClass::Constructor()\n"
20855                "    : a(a) {\n}",
20856                Style);
20857 
20858   Style.ColumnLimit = 80;
20859   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
20860   Style.ConstructorInitializerIndentWidth = 2;
20861   verifyFormat("SomeClass::Constructor()\n"
20862                "  : a(a)\n"
20863                "  , b(b)\n"
20864                "  , c(c) {}",
20865                Style);
20866 
20867   Style.ConstructorInitializerIndentWidth = 0;
20868   verifyFormat("SomeClass::Constructor()\n"
20869                ": a(a)\n"
20870                ", b(b)\n"
20871                ", c(c) {}",
20872                Style);
20873 
20874   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20875   Style.ConstructorInitializerIndentWidth = 4;
20876   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
20877   verifyFormat(
20878       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
20879       Style);
20880   verifyFormat(
20881       "SomeClass::Constructor()\n"
20882       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
20883       Style);
20884   Style.ConstructorInitializerIndentWidth = 4;
20885   Style.ColumnLimit = 60;
20886   verifyFormat("SomeClass::Constructor()\n"
20887                "    : aaaaaaaa(aaaaaaaa)\n"
20888                "    , aaaaaaaa(aaaaaaaa)\n"
20889                "    , aaaaaaaa(aaaaaaaa) {}",
20890                Style);
20891 }
20892 
20893 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
20894   FormatStyle Style = getLLVMStyle();
20895   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20896   Style.ConstructorInitializerIndentWidth = 4;
20897   verifyFormat("SomeClass::Constructor()\n"
20898                "    : a{a}\n"
20899                "    , b{b} {}",
20900                Style);
20901   verifyFormat("SomeClass::Constructor()\n"
20902                "    : a{a}\n"
20903                "#if CONDITION\n"
20904                "    , b{b}\n"
20905                "#endif\n"
20906                "{\n}",
20907                Style);
20908   Style.ConstructorInitializerIndentWidth = 2;
20909   verifyFormat("SomeClass::Constructor()\n"
20910                "#if CONDITION\n"
20911                "  : a{a}\n"
20912                "#endif\n"
20913                "  , b{b}\n"
20914                "  , c{c} {\n}",
20915                Style);
20916   Style.ConstructorInitializerIndentWidth = 0;
20917   verifyFormat("SomeClass::Constructor()\n"
20918                ": a{a}\n"
20919                "#ifdef CONDITION\n"
20920                ", b{b}\n"
20921                "#else\n"
20922                ", c{c}\n"
20923                "#endif\n"
20924                ", d{d} {\n}",
20925                Style);
20926   Style.ConstructorInitializerIndentWidth = 4;
20927   verifyFormat("SomeClass::Constructor()\n"
20928                "    : a{a}\n"
20929                "#if WINDOWS\n"
20930                "#if DEBUG\n"
20931                "    , b{0}\n"
20932                "#else\n"
20933                "    , b{1}\n"
20934                "#endif\n"
20935                "#else\n"
20936                "#if DEBUG\n"
20937                "    , b{2}\n"
20938                "#else\n"
20939                "    , b{3}\n"
20940                "#endif\n"
20941                "#endif\n"
20942                "{\n}",
20943                Style);
20944   verifyFormat("SomeClass::Constructor()\n"
20945                "    : a{a}\n"
20946                "#if WINDOWS\n"
20947                "    , b{0}\n"
20948                "#if DEBUG\n"
20949                "    , c{0}\n"
20950                "#else\n"
20951                "    , c{1}\n"
20952                "#endif\n"
20953                "#else\n"
20954                "#if DEBUG\n"
20955                "    , c{2}\n"
20956                "#else\n"
20957                "    , c{3}\n"
20958                "#endif\n"
20959                "    , b{1}\n"
20960                "#endif\n"
20961                "{\n}",
20962                Style);
20963 }
20964 
20965 TEST_F(FormatTest, Destructors) {
20966   verifyFormat("void F(int &i) { i.~int(); }");
20967   verifyFormat("void F(int &i) { i->~int(); }");
20968 }
20969 
20970 TEST_F(FormatTest, FormatsWithWebKitStyle) {
20971   FormatStyle Style = getWebKitStyle();
20972 
20973   // Don't indent in outer namespaces.
20974   verifyFormat("namespace outer {\n"
20975                "int i;\n"
20976                "namespace inner {\n"
20977                "    int i;\n"
20978                "} // namespace inner\n"
20979                "} // namespace outer\n"
20980                "namespace other_outer {\n"
20981                "int i;\n"
20982                "}",
20983                Style);
20984 
20985   // Don't indent case labels.
20986   verifyFormat("switch (variable) {\n"
20987                "case 1:\n"
20988                "case 2:\n"
20989                "    doSomething();\n"
20990                "    break;\n"
20991                "default:\n"
20992                "    ++variable;\n"
20993                "}",
20994                Style);
20995 
20996   // Wrap before binary operators.
20997   EXPECT_EQ("void f()\n"
20998             "{\n"
20999             "    if (aaaaaaaaaaaaaaaa\n"
21000             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
21001             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21002             "        return;\n"
21003             "}",
21004             format("void f() {\n"
21005                    "if (aaaaaaaaaaaaaaaa\n"
21006                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
21007                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21008                    "return;\n"
21009                    "}",
21010                    Style));
21011 
21012   // Allow functions on a single line.
21013   verifyFormat("void f() { return; }", Style);
21014 
21015   // Allow empty blocks on a single line and insert a space in empty blocks.
21016   EXPECT_EQ("void f() { }", format("void f() {}", Style));
21017   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
21018   // However, don't merge non-empty short loops.
21019   EXPECT_EQ("while (true) {\n"
21020             "    continue;\n"
21021             "}",
21022             format("while (true) { continue; }", Style));
21023 
21024   // Constructor initializers are formatted one per line with the "," on the
21025   // new line.
21026   verifyFormat("Constructor()\n"
21027                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
21028                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
21029                "          aaaaaaaaaaaaaa)\n"
21030                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
21031                "{\n"
21032                "}",
21033                Style);
21034   verifyFormat("SomeClass::Constructor()\n"
21035                "    : a(a)\n"
21036                "{\n"
21037                "}",
21038                Style);
21039   EXPECT_EQ("SomeClass::Constructor()\n"
21040             "    : a(a)\n"
21041             "{\n"
21042             "}",
21043             format("SomeClass::Constructor():a(a){}", Style));
21044   verifyFormat("SomeClass::Constructor()\n"
21045                "    : a(a)\n"
21046                "    , b(b)\n"
21047                "    , c(c)\n"
21048                "{\n"
21049                "}",
21050                Style);
21051   verifyFormat("SomeClass::Constructor()\n"
21052                "    : a(a)\n"
21053                "{\n"
21054                "    foo();\n"
21055                "    bar();\n"
21056                "}",
21057                Style);
21058 
21059   // Access specifiers should be aligned left.
21060   verifyFormat("class C {\n"
21061                "public:\n"
21062                "    int i;\n"
21063                "};",
21064                Style);
21065 
21066   // Do not align comments.
21067   verifyFormat("int a; // Do not\n"
21068                "double b; // align comments.",
21069                Style);
21070 
21071   // Do not align operands.
21072   EXPECT_EQ("ASSERT(aaaa\n"
21073             "    || bbbb);",
21074             format("ASSERT ( aaaa\n||bbbb);", Style));
21075 
21076   // Accept input's line breaks.
21077   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
21078             "    || bbbbbbbbbbbbbbb) {\n"
21079             "    i++;\n"
21080             "}",
21081             format("if (aaaaaaaaaaaaaaa\n"
21082                    "|| bbbbbbbbbbbbbbb) { i++; }",
21083                    Style));
21084   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
21085             "    i++;\n"
21086             "}",
21087             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
21088 
21089   // Don't automatically break all macro definitions (llvm.org/PR17842).
21090   verifyFormat("#define aNumber 10", Style);
21091   // However, generally keep the line breaks that the user authored.
21092   EXPECT_EQ("#define aNumber \\\n"
21093             "    10",
21094             format("#define aNumber \\\n"
21095                    " 10",
21096                    Style));
21097 
21098   // Keep empty and one-element array literals on a single line.
21099   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
21100             "                                  copyItems:YES];",
21101             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
21102                    "copyItems:YES];",
21103                    Style));
21104   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
21105             "                                  copyItems:YES];",
21106             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
21107                    "             copyItems:YES];",
21108                    Style));
21109   // FIXME: This does not seem right, there should be more indentation before
21110   // the array literal's entries. Nested blocks have the same problem.
21111   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21112             "    @\"a\",\n"
21113             "    @\"a\"\n"
21114             "]\n"
21115             "                                  copyItems:YES];",
21116             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21117                    "     @\"a\",\n"
21118                    "     @\"a\"\n"
21119                    "     ]\n"
21120                    "       copyItems:YES];",
21121                    Style));
21122   EXPECT_EQ(
21123       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21124       "                                  copyItems:YES];",
21125       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21126              "   copyItems:YES];",
21127              Style));
21128 
21129   verifyFormat("[self.a b:c c:d];", Style);
21130   EXPECT_EQ("[self.a b:c\n"
21131             "        c:d];",
21132             format("[self.a b:c\n"
21133                    "c:d];",
21134                    Style));
21135 }
21136 
21137 TEST_F(FormatTest, FormatsLambdas) {
21138   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
21139   verifyFormat(
21140       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
21141   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
21142   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
21143   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
21144   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
21145   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
21146   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
21147   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
21148   verifyFormat("int x = f(*+[] {});");
21149   verifyFormat("void f() {\n"
21150                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
21151                "}\n");
21152   verifyFormat("void f() {\n"
21153                "  other(x.begin(), //\n"
21154                "        x.end(),   //\n"
21155                "        [&](int, int) { return 1; });\n"
21156                "}\n");
21157   verifyFormat("void f() {\n"
21158                "  other.other.other.other.other(\n"
21159                "      x.begin(), x.end(),\n"
21160                "      [something, rather](int, int, int, int, int, int, int) { "
21161                "return 1; });\n"
21162                "}\n");
21163   verifyFormat(
21164       "void f() {\n"
21165       "  other.other.other.other.other(\n"
21166       "      x.begin(), x.end(),\n"
21167       "      [something, rather](int, int, int, int, int, int, int) {\n"
21168       "        //\n"
21169       "      });\n"
21170       "}\n");
21171   verifyFormat("SomeFunction([]() { // A cool function...\n"
21172                "  return 43;\n"
21173                "});");
21174   EXPECT_EQ("SomeFunction([]() {\n"
21175             "#define A a\n"
21176             "  return 43;\n"
21177             "});",
21178             format("SomeFunction([](){\n"
21179                    "#define A a\n"
21180                    "return 43;\n"
21181                    "});"));
21182   verifyFormat("void f() {\n"
21183                "  SomeFunction([](decltype(x), A *a) {});\n"
21184                "  SomeFunction([](typeof(x), A *a) {});\n"
21185                "  SomeFunction([](_Atomic(x), A *a) {});\n"
21186                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
21187                "}");
21188   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21189                "    [](const aaaaaaaaaa &a) { return a; });");
21190   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
21191                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
21192                "});");
21193   verifyFormat("Constructor()\n"
21194                "    : Field([] { // comment\n"
21195                "        int i;\n"
21196                "      }) {}");
21197   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
21198                "  return some_parameter.size();\n"
21199                "};");
21200   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
21201                "    [](const string &s) { return s; };");
21202   verifyFormat("int i = aaaaaa ? 1 //\n"
21203                "               : [] {\n"
21204                "                   return 2; //\n"
21205                "                 }();");
21206   verifyFormat("llvm::errs() << \"number of twos is \"\n"
21207                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
21208                "                  return x == 2; // force break\n"
21209                "                });");
21210   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21211                "    [=](int iiiiiiiiiiii) {\n"
21212                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
21213                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
21214                "    });",
21215                getLLVMStyleWithColumns(60));
21216 
21217   verifyFormat("SomeFunction({[&] {\n"
21218                "                // comment\n"
21219                "              },\n"
21220                "              [&] {\n"
21221                "                // comment\n"
21222                "              }});");
21223   verifyFormat("SomeFunction({[&] {\n"
21224                "  // comment\n"
21225                "}});");
21226   verifyFormat(
21227       "virtual aaaaaaaaaaaaaaaa(\n"
21228       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
21229       "    aaaaa aaaaaaaaa);");
21230 
21231   // Lambdas with return types.
21232   verifyFormat("int c = []() -> int { return 2; }();\n");
21233   verifyFormat("int c = []() -> int * { return 2; }();\n");
21234   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
21235   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
21236   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
21237   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
21238   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
21239   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
21240   verifyFormat("[a, a]() -> a<1> {};");
21241   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
21242   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
21243   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
21244   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
21245   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
21246   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
21247   verifyFormat("[]() -> foo<!5> { return {}; };");
21248   verifyFormat("[]() -> foo<~5> { return {}; };");
21249   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
21250   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
21251   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
21252   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
21253   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
21254   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
21255   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
21256   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
21257   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
21258   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
21259   verifyFormat("namespace bar {\n"
21260                "// broken:\n"
21261                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
21262                "} // namespace bar");
21263   verifyFormat("namespace bar {\n"
21264                "// broken:\n"
21265                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
21266                "} // namespace bar");
21267   verifyFormat("namespace bar {\n"
21268                "// broken:\n"
21269                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
21270                "} // namespace bar");
21271   verifyFormat("namespace bar {\n"
21272                "// broken:\n"
21273                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
21274                "} // namespace bar");
21275   verifyFormat("namespace bar {\n"
21276                "// broken:\n"
21277                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
21278                "} // namespace bar");
21279   verifyFormat("namespace bar {\n"
21280                "// broken:\n"
21281                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
21282                "} // namespace bar");
21283   verifyFormat("namespace bar {\n"
21284                "// broken:\n"
21285                "auto foo{[]() -> foo<!5> { return {}; }};\n"
21286                "} // namespace bar");
21287   verifyFormat("namespace bar {\n"
21288                "// broken:\n"
21289                "auto foo{[]() -> foo<~5> { return {}; }};\n"
21290                "} // namespace bar");
21291   verifyFormat("namespace bar {\n"
21292                "// broken:\n"
21293                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
21294                "} // namespace bar");
21295   verifyFormat("namespace bar {\n"
21296                "// broken:\n"
21297                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
21298                "} // namespace bar");
21299   verifyFormat("namespace bar {\n"
21300                "// broken:\n"
21301                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
21302                "} // namespace bar");
21303   verifyFormat("namespace bar {\n"
21304                "// broken:\n"
21305                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
21306                "} // namespace bar");
21307   verifyFormat("namespace bar {\n"
21308                "// broken:\n"
21309                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
21310                "} // namespace bar");
21311   verifyFormat("namespace bar {\n"
21312                "// broken:\n"
21313                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
21314                "} // namespace bar");
21315   verifyFormat("namespace bar {\n"
21316                "// broken:\n"
21317                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
21318                "} // namespace bar");
21319   verifyFormat("namespace bar {\n"
21320                "// broken:\n"
21321                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
21322                "} // namespace bar");
21323   verifyFormat("namespace bar {\n"
21324                "// broken:\n"
21325                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
21326                "} // namespace bar");
21327   verifyFormat("namespace bar {\n"
21328                "// broken:\n"
21329                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
21330                "} // namespace bar");
21331   verifyFormat("[]() -> a<1> {};");
21332   verifyFormat("[]() -> a<1> { ; };");
21333   verifyFormat("[]() -> a<1> { ; }();");
21334   verifyFormat("[a, a]() -> a<true> {};");
21335   verifyFormat("[]() -> a<true> {};");
21336   verifyFormat("[]() -> a<true> { ; };");
21337   verifyFormat("[]() -> a<true> { ; }();");
21338   verifyFormat("[a, a]() -> a<false> {};");
21339   verifyFormat("[]() -> a<false> {};");
21340   verifyFormat("[]() -> a<false> { ; };");
21341   verifyFormat("[]() -> a<false> { ; }();");
21342   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
21343   verifyFormat("namespace bar {\n"
21344                "auto foo{[]() -> foo<false> { ; }};\n"
21345                "} // namespace bar");
21346   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
21347                "                   int j) -> int {\n"
21348                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21349                "};");
21350   verifyFormat(
21351       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21352       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21353       "      return aaaaaaaaaaaaaaaaa;\n"
21354       "    });",
21355       getLLVMStyleWithColumns(70));
21356   verifyFormat("[]() //\n"
21357                "    -> int {\n"
21358                "  return 1; //\n"
21359                "};");
21360   verifyFormat("[]() -> Void<T...> {};");
21361   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21362   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21363   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21364   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21365   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21366   verifyFormat("return int{[x = x]() { return x; }()};");
21367 
21368   // Lambdas with explicit template argument lists.
21369   verifyFormat(
21370       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21371   verifyFormat("auto L = []<class T>(T) {\n"
21372                "  {\n"
21373                "    f();\n"
21374                "    g();\n"
21375                "  }\n"
21376                "};\n");
21377   verifyFormat("auto L = []<class... T>(T...) {\n"
21378                "  {\n"
21379                "    f();\n"
21380                "    g();\n"
21381                "  }\n"
21382                "};\n");
21383   verifyFormat("auto L = []<typename... T>(T...) {\n"
21384                "  {\n"
21385                "    f();\n"
21386                "    g();\n"
21387                "  }\n"
21388                "};\n");
21389   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21390                "  {\n"
21391                "    f();\n"
21392                "    g();\n"
21393                "  }\n"
21394                "};\n");
21395   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21396                "  {\n"
21397                "    f();\n"
21398                "    g();\n"
21399                "  }\n"
21400                "};\n");
21401 
21402   // Multiple lambdas in the same parentheses change indentation rules. These
21403   // lambdas are forced to start on new lines.
21404   verifyFormat("SomeFunction(\n"
21405                "    []() {\n"
21406                "      //\n"
21407                "    },\n"
21408                "    []() {\n"
21409                "      //\n"
21410                "    });");
21411 
21412   // A lambda passed as arg0 is always pushed to the next line.
21413   verifyFormat("SomeFunction(\n"
21414                "    [this] {\n"
21415                "      //\n"
21416                "    },\n"
21417                "    1);\n");
21418 
21419   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21420   // the arg0 case above.
21421   auto Style = getGoogleStyle();
21422   Style.BinPackArguments = false;
21423   verifyFormat("SomeFunction(\n"
21424                "    a,\n"
21425                "    [this] {\n"
21426                "      //\n"
21427                "    },\n"
21428                "    b);\n",
21429                Style);
21430   verifyFormat("SomeFunction(\n"
21431                "    a,\n"
21432                "    [this] {\n"
21433                "      //\n"
21434                "    },\n"
21435                "    b);\n");
21436 
21437   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21438   // the BinPackArguments value (as long as the code is wide enough).
21439   verifyFormat(
21440       "something->SomeFunction(\n"
21441       "    a,\n"
21442       "    [this] {\n"
21443       "      "
21444       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21445       "    },\n"
21446       "    b);\n");
21447 
21448   // A multi-line lambda is pulled up as long as the introducer fits on the
21449   // previous line and there are no further args.
21450   verifyFormat("function(1, [this, that] {\n"
21451                "  //\n"
21452                "});\n");
21453   verifyFormat("function([this, that] {\n"
21454                "  //\n"
21455                "});\n");
21456   // FIXME: this format is not ideal and we should consider forcing the first
21457   // arg onto its own line.
21458   verifyFormat("function(a, b, c, //\n"
21459                "         d, [this, that] {\n"
21460                "           //\n"
21461                "         });\n");
21462 
21463   // Multiple lambdas are treated correctly even when there is a short arg0.
21464   verifyFormat("SomeFunction(\n"
21465                "    1,\n"
21466                "    [this] {\n"
21467                "      //\n"
21468                "    },\n"
21469                "    [this] {\n"
21470                "      //\n"
21471                "    },\n"
21472                "    1);\n");
21473 
21474   // More complex introducers.
21475   verifyFormat("return [i, args...] {};");
21476 
21477   // Not lambdas.
21478   verifyFormat("constexpr char hello[]{\"hello\"};");
21479   verifyFormat("double &operator[](int i) { return 0; }\n"
21480                "int i;");
21481   verifyFormat("std::unique_ptr<int[]> foo() {}");
21482   verifyFormat("int i = a[a][a]->f();");
21483   verifyFormat("int i = (*b)[a]->f();");
21484 
21485   // Other corner cases.
21486   verifyFormat("void f() {\n"
21487                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21488                "  );\n"
21489                "}");
21490 
21491   // Lambdas created through weird macros.
21492   verifyFormat("void f() {\n"
21493                "  MACRO((const AA &a) { return 1; });\n"
21494                "  MACRO((AA &a) { return 1; });\n"
21495                "}");
21496 
21497   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21498                "      doo_dah();\n"
21499                "      doo_dah();\n"
21500                "    })) {\n"
21501                "}");
21502   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21503                "                doo_dah();\n"
21504                "                doo_dah();\n"
21505                "              })) {\n"
21506                "}");
21507   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21508                "                doo_dah();\n"
21509                "                doo_dah();\n"
21510                "              })) {\n"
21511                "}");
21512   verifyFormat("auto lambda = []() {\n"
21513                "  int a = 2\n"
21514                "#if A\n"
21515                "          + 2\n"
21516                "#endif\n"
21517                "      ;\n"
21518                "};");
21519 
21520   // Lambdas with complex multiline introducers.
21521   verifyFormat(
21522       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21523       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21524       "        -> ::std::unordered_set<\n"
21525       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21526       "      //\n"
21527       "    });");
21528 
21529   FormatStyle DoNotMerge = getLLVMStyle();
21530   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21531   verifyFormat("auto c = []() {\n"
21532                "  return b;\n"
21533                "};",
21534                "auto c = []() { return b; };", DoNotMerge);
21535   verifyFormat("auto c = []() {\n"
21536                "};",
21537                " auto c = []() {};", DoNotMerge);
21538 
21539   FormatStyle MergeEmptyOnly = getLLVMStyle();
21540   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21541   verifyFormat("auto c = []() {\n"
21542                "  return b;\n"
21543                "};",
21544                "auto c = []() {\n"
21545                "  return b;\n"
21546                " };",
21547                MergeEmptyOnly);
21548   verifyFormat("auto c = []() {};",
21549                "auto c = []() {\n"
21550                "};",
21551                MergeEmptyOnly);
21552 
21553   FormatStyle MergeInline = getLLVMStyle();
21554   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21555   verifyFormat("auto c = []() {\n"
21556                "  return b;\n"
21557                "};",
21558                "auto c = []() { return b; };", MergeInline);
21559   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21560                MergeInline);
21561   verifyFormat("function([]() { return b; }, a)",
21562                "function([]() { return b; }, a)", MergeInline);
21563   verifyFormat("function(a, []() { return b; })",
21564                "function(a, []() { return b; })", MergeInline);
21565 
21566   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21567   // AllowShortLambdasOnASingleLine
21568   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21569   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21570   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21571   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21572       FormatStyle::ShortLambdaStyle::SLS_None;
21573   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21574                "    []()\n"
21575                "    {\n"
21576                "      return 17;\n"
21577                "    });",
21578                LLVMWithBeforeLambdaBody);
21579   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21580                "    []()\n"
21581                "    {\n"
21582                "    });",
21583                LLVMWithBeforeLambdaBody);
21584   verifyFormat("auto fct_SLS_None = []()\n"
21585                "{\n"
21586                "  return 17;\n"
21587                "};",
21588                LLVMWithBeforeLambdaBody);
21589   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21590                "    []()\n"
21591                "    {\n"
21592                "      return Call(\n"
21593                "          []()\n"
21594                "          {\n"
21595                "            return 17;\n"
21596                "          });\n"
21597                "    });",
21598                LLVMWithBeforeLambdaBody);
21599   verifyFormat("void Fct() {\n"
21600                "  return {[]()\n"
21601                "          {\n"
21602                "            return 17;\n"
21603                "          }};\n"
21604                "}",
21605                LLVMWithBeforeLambdaBody);
21606 
21607   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21608       FormatStyle::ShortLambdaStyle::SLS_Empty;
21609   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21610                "    []()\n"
21611                "    {\n"
21612                "      return 17;\n"
21613                "    });",
21614                LLVMWithBeforeLambdaBody);
21615   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21616                LLVMWithBeforeLambdaBody);
21617   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21618                "ongFunctionName_SLS_Empty(\n"
21619                "    []() {});",
21620                LLVMWithBeforeLambdaBody);
21621   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21622                "                                []()\n"
21623                "                                {\n"
21624                "                                  return 17;\n"
21625                "                                });",
21626                LLVMWithBeforeLambdaBody);
21627   verifyFormat("auto fct_SLS_Empty = []()\n"
21628                "{\n"
21629                "  return 17;\n"
21630                "};",
21631                LLVMWithBeforeLambdaBody);
21632   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21633                "    []()\n"
21634                "    {\n"
21635                "      return Call([]() {});\n"
21636                "    });",
21637                LLVMWithBeforeLambdaBody);
21638   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21639                "                           []()\n"
21640                "                           {\n"
21641                "                             return Call([]() {});\n"
21642                "                           });",
21643                LLVMWithBeforeLambdaBody);
21644   verifyFormat(
21645       "FctWithLongLineInLambda_SLS_Empty(\n"
21646       "    []()\n"
21647       "    {\n"
21648       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21649       "                               AndShouldNotBeConsiderAsInline,\n"
21650       "                               LambdaBodyMustBeBreak);\n"
21651       "    });",
21652       LLVMWithBeforeLambdaBody);
21653 
21654   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21655       FormatStyle::ShortLambdaStyle::SLS_Inline;
21656   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21657                LLVMWithBeforeLambdaBody);
21658   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21659                LLVMWithBeforeLambdaBody);
21660   verifyFormat("auto fct_SLS_Inline = []()\n"
21661                "{\n"
21662                "  return 17;\n"
21663                "};",
21664                LLVMWithBeforeLambdaBody);
21665   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21666                "17; }); });",
21667                LLVMWithBeforeLambdaBody);
21668   verifyFormat(
21669       "FctWithLongLineInLambda_SLS_Inline(\n"
21670       "    []()\n"
21671       "    {\n"
21672       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21673       "                               AndShouldNotBeConsiderAsInline,\n"
21674       "                               LambdaBodyMustBeBreak);\n"
21675       "    });",
21676       LLVMWithBeforeLambdaBody);
21677   verifyFormat("FctWithMultipleParams_SLS_Inline("
21678                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21679                "                                 []() { return 17; });",
21680                LLVMWithBeforeLambdaBody);
21681   verifyFormat(
21682       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21683       LLVMWithBeforeLambdaBody);
21684 
21685   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21686       FormatStyle::ShortLambdaStyle::SLS_All;
21687   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21688                LLVMWithBeforeLambdaBody);
21689   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21690                LLVMWithBeforeLambdaBody);
21691   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21692                LLVMWithBeforeLambdaBody);
21693   verifyFormat("FctWithOneParam_SLS_All(\n"
21694                "    []()\n"
21695                "    {\n"
21696                "      // A cool function...\n"
21697                "      return 43;\n"
21698                "    });",
21699                LLVMWithBeforeLambdaBody);
21700   verifyFormat("FctWithMultipleParams_SLS_All("
21701                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21702                "                              []() { return 17; });",
21703                LLVMWithBeforeLambdaBody);
21704   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21705                LLVMWithBeforeLambdaBody);
21706   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21707                LLVMWithBeforeLambdaBody);
21708   verifyFormat(
21709       "FctWithLongLineInLambda_SLS_All(\n"
21710       "    []()\n"
21711       "    {\n"
21712       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21713       "                               AndShouldNotBeConsiderAsInline,\n"
21714       "                               LambdaBodyMustBeBreak);\n"
21715       "    });",
21716       LLVMWithBeforeLambdaBody);
21717   verifyFormat(
21718       "auto fct_SLS_All = []()\n"
21719       "{\n"
21720       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21721       "                           AndShouldNotBeConsiderAsInline,\n"
21722       "                           LambdaBodyMustBeBreak);\n"
21723       "};",
21724       LLVMWithBeforeLambdaBody);
21725   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21726   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21727                LLVMWithBeforeLambdaBody);
21728   verifyFormat(
21729       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21730       "                                FirstParam,\n"
21731       "                                SecondParam,\n"
21732       "                                ThirdParam,\n"
21733       "                                FourthParam);",
21734       LLVMWithBeforeLambdaBody);
21735   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21736                "    []() { return "
21737                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21738                "    FirstParam,\n"
21739                "    SecondParam,\n"
21740                "    ThirdParam,\n"
21741                "    FourthParam);",
21742                LLVMWithBeforeLambdaBody);
21743   verifyFormat(
21744       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21745       "                                SecondParam,\n"
21746       "                                ThirdParam,\n"
21747       "                                FourthParam,\n"
21748       "                                []() { return SomeValueNotSoLong; });",
21749       LLVMWithBeforeLambdaBody);
21750   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21751                "    []()\n"
21752                "    {\n"
21753                "      return "
21754                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21755                "eConsiderAsInline;\n"
21756                "    });",
21757                LLVMWithBeforeLambdaBody);
21758   verifyFormat(
21759       "FctWithLongLineInLambda_SLS_All(\n"
21760       "    []()\n"
21761       "    {\n"
21762       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21763       "                               AndShouldNotBeConsiderAsInline,\n"
21764       "                               LambdaBodyMustBeBreak);\n"
21765       "    });",
21766       LLVMWithBeforeLambdaBody);
21767   verifyFormat("FctWithTwoParams_SLS_All(\n"
21768                "    []()\n"
21769                "    {\n"
21770                "      // A cool function...\n"
21771                "      return 43;\n"
21772                "    },\n"
21773                "    87);",
21774                LLVMWithBeforeLambdaBody);
21775   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
21776                LLVMWithBeforeLambdaBody);
21777   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
21778                LLVMWithBeforeLambdaBody);
21779   verifyFormat(
21780       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
21781       LLVMWithBeforeLambdaBody);
21782   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
21783                "}); }, x);",
21784                LLVMWithBeforeLambdaBody);
21785   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21786                "    []()\n"
21787                "    {\n"
21788                "      // A cool function...\n"
21789                "      return Call([]() { return 17; });\n"
21790                "    });",
21791                LLVMWithBeforeLambdaBody);
21792   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21793                "    []()\n"
21794                "    {\n"
21795                "      return Call(\n"
21796                "          []()\n"
21797                "          {\n"
21798                "            // A cool function...\n"
21799                "            return 17;\n"
21800                "          });\n"
21801                "    });",
21802                LLVMWithBeforeLambdaBody);
21803 
21804   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21805       FormatStyle::ShortLambdaStyle::SLS_None;
21806 
21807   verifyFormat("auto select = [this]() -> const Library::Object *\n"
21808                "{\n"
21809                "  return MyAssignment::SelectFromList(this);\n"
21810                "};\n",
21811                LLVMWithBeforeLambdaBody);
21812 
21813   verifyFormat("auto select = [this]() -> const Library::Object &\n"
21814                "{\n"
21815                "  return MyAssignment::SelectFromList(this);\n"
21816                "};\n",
21817                LLVMWithBeforeLambdaBody);
21818 
21819   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
21820                "{\n"
21821                "  return MyAssignment::SelectFromList(this);\n"
21822                "};\n",
21823                LLVMWithBeforeLambdaBody);
21824 
21825   verifyFormat("namespace test {\n"
21826                "class Test {\n"
21827                "public:\n"
21828                "  Test() = default;\n"
21829                "};\n"
21830                "} // namespace test",
21831                LLVMWithBeforeLambdaBody);
21832 
21833   // Lambdas with different indentation styles.
21834   Style = getLLVMStyleWithColumns(100);
21835   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21836             "  return promise.then(\n"
21837             "      [this, &someVariable, someObject = "
21838             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21839             "        return someObject.startAsyncAction().then(\n"
21840             "            [this, &someVariable](AsyncActionResult result) "
21841             "mutable { result.processMore(); });\n"
21842             "      });\n"
21843             "}\n",
21844             format("SomeResult doSomething(SomeObject promise) {\n"
21845                    "  return promise.then([this, &someVariable, someObject = "
21846                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21847                    "    return someObject.startAsyncAction().then([this, "
21848                    "&someVariable](AsyncActionResult result) mutable {\n"
21849                    "      result.processMore();\n"
21850                    "    });\n"
21851                    "  });\n"
21852                    "}\n",
21853                    Style));
21854   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21855   verifyFormat("test() {\n"
21856                "  ([]() -> {\n"
21857                "    int b = 32;\n"
21858                "    return 3;\n"
21859                "  }).foo();\n"
21860                "}",
21861                Style);
21862   verifyFormat("test() {\n"
21863                "  []() -> {\n"
21864                "    int b = 32;\n"
21865                "    return 3;\n"
21866                "  }\n"
21867                "}",
21868                Style);
21869   verifyFormat("std::sort(v.begin(), v.end(),\n"
21870                "          [](const auto &someLongArgumentName, const auto "
21871                "&someOtherLongArgumentName) {\n"
21872                "  return someLongArgumentName.someMemberVariable < "
21873                "someOtherLongArgumentName.someMemberVariable;\n"
21874                "});",
21875                Style);
21876   verifyFormat("test() {\n"
21877                "  (\n"
21878                "      []() -> {\n"
21879                "        int b = 32;\n"
21880                "        return 3;\n"
21881                "      },\n"
21882                "      foo, bar)\n"
21883                "      .foo();\n"
21884                "}",
21885                Style);
21886   verifyFormat("test() {\n"
21887                "  ([]() -> {\n"
21888                "    int b = 32;\n"
21889                "    return 3;\n"
21890                "  })\n"
21891                "      .foo()\n"
21892                "      .bar();\n"
21893                "}",
21894                Style);
21895   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21896             "  return promise.then(\n"
21897             "      [this, &someVariable, someObject = "
21898             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21899             "    return someObject.startAsyncAction().then(\n"
21900             "        [this, &someVariable](AsyncActionResult result) mutable { "
21901             "result.processMore(); });\n"
21902             "  });\n"
21903             "}\n",
21904             format("SomeResult doSomething(SomeObject promise) {\n"
21905                    "  return promise.then([this, &someVariable, someObject = "
21906                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21907                    "    return someObject.startAsyncAction().then([this, "
21908                    "&someVariable](AsyncActionResult result) mutable {\n"
21909                    "      result.processMore();\n"
21910                    "    });\n"
21911                    "  });\n"
21912                    "}\n",
21913                    Style));
21914   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21915             "  return promise.then([this, &someVariable] {\n"
21916             "    return someObject.startAsyncAction().then(\n"
21917             "        [this, &someVariable](AsyncActionResult result) mutable { "
21918             "result.processMore(); });\n"
21919             "  });\n"
21920             "}\n",
21921             format("SomeResult doSomething(SomeObject promise) {\n"
21922                    "  return promise.then([this, &someVariable] {\n"
21923                    "    return someObject.startAsyncAction().then([this, "
21924                    "&someVariable](AsyncActionResult result) mutable {\n"
21925                    "      result.processMore();\n"
21926                    "    });\n"
21927                    "  });\n"
21928                    "}\n",
21929                    Style));
21930   Style = getGoogleStyle();
21931   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21932   EXPECT_EQ("#define A                                       \\\n"
21933             "  [] {                                          \\\n"
21934             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
21935             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
21936             "      }",
21937             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
21938                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
21939                    Style));
21940   // TODO: The current formatting has a minor issue that's not worth fixing
21941   // right now whereby the closing brace is indented relative to the signature
21942   // instead of being aligned. This only happens with macros.
21943 }
21944 
21945 TEST_F(FormatTest, LambdaWithLineComments) {
21946   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21947   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21948   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21949   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21950       FormatStyle::ShortLambdaStyle::SLS_All;
21951 
21952   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
21953   verifyFormat("auto k = []() // comment\n"
21954                "{ return; }",
21955                LLVMWithBeforeLambdaBody);
21956   verifyFormat("auto k = []() /* comment */ { return; }",
21957                LLVMWithBeforeLambdaBody);
21958   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
21959                LLVMWithBeforeLambdaBody);
21960   verifyFormat("auto k = []() // X\n"
21961                "{ return; }",
21962                LLVMWithBeforeLambdaBody);
21963   verifyFormat(
21964       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
21965       "{ return; }",
21966       LLVMWithBeforeLambdaBody);
21967 
21968   LLVMWithBeforeLambdaBody.ColumnLimit = 0;
21969 
21970   verifyFormat("foo([]()\n"
21971                "    {\n"
21972                "      bar();    //\n"
21973                "      return 1; // comment\n"
21974                "    }());",
21975                "foo([]() {\n"
21976                "  bar(); //\n"
21977                "  return 1; // comment\n"
21978                "}());",
21979                LLVMWithBeforeLambdaBody);
21980   verifyFormat("foo(\n"
21981                "    1, MACRO {\n"
21982                "      baz();\n"
21983                "      bar(); // comment\n"
21984                "    },\n"
21985                "    []() {});",
21986                "foo(\n"
21987                "  1, MACRO { baz(); bar(); // comment\n"
21988                "  }, []() {}\n"
21989                ");",
21990                LLVMWithBeforeLambdaBody);
21991 }
21992 
21993 TEST_F(FormatTest, EmptyLinesInLambdas) {
21994   verifyFormat("auto lambda = []() {\n"
21995                "  x(); //\n"
21996                "};",
21997                "auto lambda = []() {\n"
21998                "\n"
21999                "  x(); //\n"
22000                "\n"
22001                "};");
22002 }
22003 
22004 TEST_F(FormatTest, FormatsBlocks) {
22005   FormatStyle ShortBlocks = getLLVMStyle();
22006   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22007   verifyFormat("int (^Block)(int, int);", ShortBlocks);
22008   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
22009   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
22010   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
22011   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
22012   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
22013 
22014   verifyFormat("foo(^{ bar(); });", ShortBlocks);
22015   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
22016   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
22017 
22018   verifyFormat("[operation setCompletionBlock:^{\n"
22019                "  [self onOperationDone];\n"
22020                "}];");
22021   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
22022                "  [self onOperationDone];\n"
22023                "}]};");
22024   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
22025                "  f();\n"
22026                "}];");
22027   verifyFormat("int a = [operation block:^int(int *i) {\n"
22028                "  return 1;\n"
22029                "}];");
22030   verifyFormat("[myObject doSomethingWith:arg1\n"
22031                "                      aaa:^int(int *a) {\n"
22032                "                        return 1;\n"
22033                "                      }\n"
22034                "                      bbb:f(a * bbbbbbbb)];");
22035 
22036   verifyFormat("[operation setCompletionBlock:^{\n"
22037                "  [self.delegate newDataAvailable];\n"
22038                "}];",
22039                getLLVMStyleWithColumns(60));
22040   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
22041                "  NSString *path = [self sessionFilePath];\n"
22042                "  if (path) {\n"
22043                "    // ...\n"
22044                "  }\n"
22045                "});");
22046   verifyFormat("[[SessionService sharedService]\n"
22047                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22048                "      if (window) {\n"
22049                "        [self windowDidLoad:window];\n"
22050                "      } else {\n"
22051                "        [self errorLoadingWindow];\n"
22052                "      }\n"
22053                "    }];");
22054   verifyFormat("void (^largeBlock)(void) = ^{\n"
22055                "  // ...\n"
22056                "};\n",
22057                getLLVMStyleWithColumns(40));
22058   verifyFormat("[[SessionService sharedService]\n"
22059                "    loadWindowWithCompletionBlock: //\n"
22060                "        ^(SessionWindow *window) {\n"
22061                "          if (window) {\n"
22062                "            [self windowDidLoad:window];\n"
22063                "          } else {\n"
22064                "            [self errorLoadingWindow];\n"
22065                "          }\n"
22066                "        }];",
22067                getLLVMStyleWithColumns(60));
22068   verifyFormat("[myObject doSomethingWith:arg1\n"
22069                "    firstBlock:^(Foo *a) {\n"
22070                "      // ...\n"
22071                "      int i;\n"
22072                "    }\n"
22073                "    secondBlock:^(Bar *b) {\n"
22074                "      // ...\n"
22075                "      int i;\n"
22076                "    }\n"
22077                "    thirdBlock:^Foo(Bar *b) {\n"
22078                "      // ...\n"
22079                "      int i;\n"
22080                "    }];");
22081   verifyFormat("[myObject doSomethingWith:arg1\n"
22082                "               firstBlock:-1\n"
22083                "              secondBlock:^(Bar *b) {\n"
22084                "                // ...\n"
22085                "                int i;\n"
22086                "              }];");
22087 
22088   verifyFormat("f(^{\n"
22089                "  @autoreleasepool {\n"
22090                "    if (a) {\n"
22091                "      g();\n"
22092                "    }\n"
22093                "  }\n"
22094                "});");
22095   verifyFormat("Block b = ^int *(A *a, B *b) {}");
22096   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
22097                "};");
22098 
22099   FormatStyle FourIndent = getLLVMStyle();
22100   FourIndent.ObjCBlockIndentWidth = 4;
22101   verifyFormat("[operation setCompletionBlock:^{\n"
22102                "    [self onOperationDone];\n"
22103                "}];",
22104                FourIndent);
22105 }
22106 
22107 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
22108   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
22109 
22110   verifyFormat("[[SessionService sharedService] "
22111                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22112                "  if (window) {\n"
22113                "    [self windowDidLoad:window];\n"
22114                "  } else {\n"
22115                "    [self errorLoadingWindow];\n"
22116                "  }\n"
22117                "}];",
22118                ZeroColumn);
22119   EXPECT_EQ("[[SessionService sharedService]\n"
22120             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22121             "      if (window) {\n"
22122             "        [self windowDidLoad:window];\n"
22123             "      } else {\n"
22124             "        [self errorLoadingWindow];\n"
22125             "      }\n"
22126             "    }];",
22127             format("[[SessionService sharedService]\n"
22128                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22129                    "                if (window) {\n"
22130                    "    [self windowDidLoad:window];\n"
22131                    "  } else {\n"
22132                    "    [self errorLoadingWindow];\n"
22133                    "  }\n"
22134                    "}];",
22135                    ZeroColumn));
22136   verifyFormat("[myObject doSomethingWith:arg1\n"
22137                "    firstBlock:^(Foo *a) {\n"
22138                "      // ...\n"
22139                "      int i;\n"
22140                "    }\n"
22141                "    secondBlock:^(Bar *b) {\n"
22142                "      // ...\n"
22143                "      int i;\n"
22144                "    }\n"
22145                "    thirdBlock:^Foo(Bar *b) {\n"
22146                "      // ...\n"
22147                "      int i;\n"
22148                "    }];",
22149                ZeroColumn);
22150   verifyFormat("f(^{\n"
22151                "  @autoreleasepool {\n"
22152                "    if (a) {\n"
22153                "      g();\n"
22154                "    }\n"
22155                "  }\n"
22156                "});",
22157                ZeroColumn);
22158   verifyFormat("void (^largeBlock)(void) = ^{\n"
22159                "  // ...\n"
22160                "};",
22161                ZeroColumn);
22162 
22163   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22164   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
22165             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22166   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
22167   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
22168             "  int i;\n"
22169             "};",
22170             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22171 }
22172 
22173 TEST_F(FormatTest, SupportsCRLF) {
22174   EXPECT_EQ("int a;\r\n"
22175             "int b;\r\n"
22176             "int c;\r\n",
22177             format("int a;\r\n"
22178                    "  int b;\r\n"
22179                    "    int c;\r\n",
22180                    getLLVMStyle()));
22181   EXPECT_EQ("int a;\r\n"
22182             "int b;\r\n"
22183             "int c;\r\n",
22184             format("int a;\r\n"
22185                    "  int b;\n"
22186                    "    int c;\r\n",
22187                    getLLVMStyle()));
22188   EXPECT_EQ("int a;\n"
22189             "int b;\n"
22190             "int c;\n",
22191             format("int a;\r\n"
22192                    "  int b;\n"
22193                    "    int c;\n",
22194                    getLLVMStyle()));
22195   EXPECT_EQ("\"aaaaaaa \"\r\n"
22196             "\"bbbbbbb\";\r\n",
22197             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
22198   EXPECT_EQ("#define A \\\r\n"
22199             "  b;      \\\r\n"
22200             "  c;      \\\r\n"
22201             "  d;\r\n",
22202             format("#define A \\\r\n"
22203                    "  b; \\\r\n"
22204                    "  c; d; \r\n",
22205                    getGoogleStyle()));
22206 
22207   EXPECT_EQ("/*\r\n"
22208             "multi line block comments\r\n"
22209             "should not introduce\r\n"
22210             "an extra carriage return\r\n"
22211             "*/\r\n",
22212             format("/*\r\n"
22213                    "multi line block comments\r\n"
22214                    "should not introduce\r\n"
22215                    "an extra carriage return\r\n"
22216                    "*/\r\n"));
22217   EXPECT_EQ("/*\r\n"
22218             "\r\n"
22219             "*/",
22220             format("/*\r\n"
22221                    "    \r\r\r\n"
22222                    "*/"));
22223 
22224   FormatStyle style = getLLVMStyle();
22225 
22226   style.DeriveLineEnding = true;
22227   style.UseCRLF = false;
22228   EXPECT_EQ("union FooBarBazQux {\n"
22229             "  int foo;\n"
22230             "  int bar;\n"
22231             "  int baz;\n"
22232             "};",
22233             format("union FooBarBazQux {\r\n"
22234                    "  int foo;\n"
22235                    "  int bar;\r\n"
22236                    "  int baz;\n"
22237                    "};",
22238                    style));
22239   style.UseCRLF = true;
22240   EXPECT_EQ("union FooBarBazQux {\r\n"
22241             "  int foo;\r\n"
22242             "  int bar;\r\n"
22243             "  int baz;\r\n"
22244             "};",
22245             format("union FooBarBazQux {\r\n"
22246                    "  int foo;\n"
22247                    "  int bar;\r\n"
22248                    "  int baz;\n"
22249                    "};",
22250                    style));
22251 
22252   style.DeriveLineEnding = false;
22253   style.UseCRLF = false;
22254   EXPECT_EQ("union FooBarBazQux {\n"
22255             "  int foo;\n"
22256             "  int bar;\n"
22257             "  int baz;\n"
22258             "  int qux;\n"
22259             "};",
22260             format("union FooBarBazQux {\r\n"
22261                    "  int foo;\n"
22262                    "  int bar;\r\n"
22263                    "  int baz;\n"
22264                    "  int qux;\r\n"
22265                    "};",
22266                    style));
22267   style.UseCRLF = true;
22268   EXPECT_EQ("union FooBarBazQux {\r\n"
22269             "  int foo;\r\n"
22270             "  int bar;\r\n"
22271             "  int baz;\r\n"
22272             "  int qux;\r\n"
22273             "};",
22274             format("union FooBarBazQux {\r\n"
22275                    "  int foo;\n"
22276                    "  int bar;\r\n"
22277                    "  int baz;\n"
22278                    "  int qux;\n"
22279                    "};",
22280                    style));
22281 
22282   style.DeriveLineEnding = true;
22283   style.UseCRLF = false;
22284   EXPECT_EQ("union FooBarBazQux {\r\n"
22285             "  int foo;\r\n"
22286             "  int bar;\r\n"
22287             "  int baz;\r\n"
22288             "  int qux;\r\n"
22289             "};",
22290             format("union FooBarBazQux {\r\n"
22291                    "  int foo;\n"
22292                    "  int bar;\r\n"
22293                    "  int baz;\n"
22294                    "  int qux;\r\n"
22295                    "};",
22296                    style));
22297   style.UseCRLF = true;
22298   EXPECT_EQ("union FooBarBazQux {\n"
22299             "  int foo;\n"
22300             "  int bar;\n"
22301             "  int baz;\n"
22302             "  int qux;\n"
22303             "};",
22304             format("union FooBarBazQux {\r\n"
22305                    "  int foo;\n"
22306                    "  int bar;\r\n"
22307                    "  int baz;\n"
22308                    "  int qux;\n"
22309                    "};",
22310                    style));
22311 }
22312 
22313 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
22314   verifyFormat("MY_CLASS(C) {\n"
22315                "  int i;\n"
22316                "  int j;\n"
22317                "};");
22318 }
22319 
22320 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
22321   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
22322   TwoIndent.ContinuationIndentWidth = 2;
22323 
22324   EXPECT_EQ("int i =\n"
22325             "  longFunction(\n"
22326             "    arg);",
22327             format("int i = longFunction(arg);", TwoIndent));
22328 
22329   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
22330   SixIndent.ContinuationIndentWidth = 6;
22331 
22332   EXPECT_EQ("int i =\n"
22333             "      longFunction(\n"
22334             "            arg);",
22335             format("int i = longFunction(arg);", SixIndent));
22336 }
22337 
22338 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
22339   FormatStyle Style = getLLVMStyle();
22340   verifyFormat("int Foo::getter(\n"
22341                "    //\n"
22342                ") const {\n"
22343                "  return foo;\n"
22344                "}",
22345                Style);
22346   verifyFormat("void Foo::setter(\n"
22347                "    //\n"
22348                ") {\n"
22349                "  foo = 1;\n"
22350                "}",
22351                Style);
22352 }
22353 
22354 TEST_F(FormatTest, SpacesInAngles) {
22355   FormatStyle Spaces = getLLVMStyle();
22356   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22357 
22358   verifyFormat("vector< ::std::string > x1;", Spaces);
22359   verifyFormat("Foo< int, Bar > x2;", Spaces);
22360   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
22361 
22362   verifyFormat("static_cast< int >(arg);", Spaces);
22363   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
22364   verifyFormat("f< int, float >();", Spaces);
22365   verifyFormat("template <> g() {}", Spaces);
22366   verifyFormat("template < std::vector< int > > f() {}", Spaces);
22367   verifyFormat("std::function< void(int, int) > fct;", Spaces);
22368   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
22369                Spaces);
22370 
22371   Spaces.Standard = FormatStyle::LS_Cpp03;
22372   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22373   verifyFormat("A< A< int > >();", Spaces);
22374 
22375   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22376   verifyFormat("A<A<int> >();", Spaces);
22377 
22378   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22379   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22380                Spaces);
22381   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22382                Spaces);
22383 
22384   verifyFormat("A<A<int> >();", Spaces);
22385   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22386   verifyFormat("A< A< int > >();", Spaces);
22387 
22388   Spaces.Standard = FormatStyle::LS_Cpp11;
22389   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22390   verifyFormat("A< A< int > >();", Spaces);
22391 
22392   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22393   verifyFormat("vector<::std::string> x4;", Spaces);
22394   verifyFormat("vector<int> x5;", Spaces);
22395   verifyFormat("Foo<int, Bar> x6;", Spaces);
22396   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22397 
22398   verifyFormat("A<A<int>>();", Spaces);
22399 
22400   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22401   verifyFormat("vector<::std::string> x4;", Spaces);
22402   verifyFormat("vector< ::std::string > x4;", Spaces);
22403   verifyFormat("vector<int> x5;", Spaces);
22404   verifyFormat("vector< int > x5;", Spaces);
22405   verifyFormat("Foo<int, Bar> x6;", Spaces);
22406   verifyFormat("Foo< int, Bar > x6;", Spaces);
22407   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22408   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22409 
22410   verifyFormat("A<A<int>>();", Spaces);
22411   verifyFormat("A< A< int > >();", Spaces);
22412   verifyFormat("A<A<int > >();", Spaces);
22413   verifyFormat("A< A< int>>();", Spaces);
22414 
22415   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22416   verifyFormat("// clang-format off\n"
22417                "foo<<<1, 1>>>();\n"
22418                "// clang-format on\n",
22419                Spaces);
22420   verifyFormat("// clang-format off\n"
22421                "foo< < <1, 1> > >();\n"
22422                "// clang-format on\n",
22423                Spaces);
22424 }
22425 
22426 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22427   FormatStyle Style = getLLVMStyle();
22428   Style.SpaceAfterTemplateKeyword = false;
22429   verifyFormat("template<int> void foo();", Style);
22430 }
22431 
22432 TEST_F(FormatTest, TripleAngleBrackets) {
22433   verifyFormat("f<<<1, 1>>>();");
22434   verifyFormat("f<<<1, 1, 1, s>>>();");
22435   verifyFormat("f<<<a, b, c, d>>>();");
22436   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22437   verifyFormat("f<param><<<1, 1>>>();");
22438   verifyFormat("f<1><<<1, 1>>>();");
22439   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22440   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22441                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22442   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22443                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22444 }
22445 
22446 TEST_F(FormatTest, MergeLessLessAtEnd) {
22447   verifyFormat("<<");
22448   EXPECT_EQ("< < <", format("\\\n<<<"));
22449   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22450                "aaallvm::outs() <<");
22451   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22452                "aaaallvm::outs()\n    <<");
22453 }
22454 
22455 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22456   std::string code = "#if A\n"
22457                      "#if B\n"
22458                      "a.\n"
22459                      "#endif\n"
22460                      "    a = 1;\n"
22461                      "#else\n"
22462                      "#endif\n"
22463                      "#if C\n"
22464                      "#else\n"
22465                      "#endif\n";
22466   EXPECT_EQ(code, format(code));
22467 }
22468 
22469 TEST_F(FormatTest, HandleConflictMarkers) {
22470   // Git/SVN conflict markers.
22471   EXPECT_EQ("int a;\n"
22472             "void f() {\n"
22473             "  callme(some(parameter1,\n"
22474             "<<<<<<< text by the vcs\n"
22475             "              parameter2),\n"
22476             "||||||| text by the vcs\n"
22477             "              parameter2),\n"
22478             "         parameter3,\n"
22479             "======= text by the vcs\n"
22480             "              parameter2, parameter3),\n"
22481             ">>>>>>> text by the vcs\n"
22482             "         otherparameter);\n",
22483             format("int a;\n"
22484                    "void f() {\n"
22485                    "  callme(some(parameter1,\n"
22486                    "<<<<<<< text by the vcs\n"
22487                    "  parameter2),\n"
22488                    "||||||| text by the vcs\n"
22489                    "  parameter2),\n"
22490                    "  parameter3,\n"
22491                    "======= text by the vcs\n"
22492                    "  parameter2,\n"
22493                    "  parameter3),\n"
22494                    ">>>>>>> text by the vcs\n"
22495                    "  otherparameter);\n"));
22496 
22497   // Perforce markers.
22498   EXPECT_EQ("void f() {\n"
22499             "  function(\n"
22500             ">>>> text by the vcs\n"
22501             "      parameter,\n"
22502             "==== text by the vcs\n"
22503             "      parameter,\n"
22504             "==== text by the vcs\n"
22505             "      parameter,\n"
22506             "<<<< text by the vcs\n"
22507             "      parameter);\n",
22508             format("void f() {\n"
22509                    "  function(\n"
22510                    ">>>> text by the vcs\n"
22511                    "  parameter,\n"
22512                    "==== text by the vcs\n"
22513                    "  parameter,\n"
22514                    "==== text by the vcs\n"
22515                    "  parameter,\n"
22516                    "<<<< text by the vcs\n"
22517                    "  parameter);\n"));
22518 
22519   EXPECT_EQ("<<<<<<<\n"
22520             "|||||||\n"
22521             "=======\n"
22522             ">>>>>>>",
22523             format("<<<<<<<\n"
22524                    "|||||||\n"
22525                    "=======\n"
22526                    ">>>>>>>"));
22527 
22528   EXPECT_EQ("<<<<<<<\n"
22529             "|||||||\n"
22530             "int i;\n"
22531             "=======\n"
22532             ">>>>>>>",
22533             format("<<<<<<<\n"
22534                    "|||||||\n"
22535                    "int i;\n"
22536                    "=======\n"
22537                    ">>>>>>>"));
22538 
22539   // FIXME: Handle parsing of macros around conflict markers correctly:
22540   EXPECT_EQ("#define Macro \\\n"
22541             "<<<<<<<\n"
22542             "Something \\\n"
22543             "|||||||\n"
22544             "Else \\\n"
22545             "=======\n"
22546             "Other \\\n"
22547             ">>>>>>>\n"
22548             "    End int i;\n",
22549             format("#define Macro \\\n"
22550                    "<<<<<<<\n"
22551                    "  Something \\\n"
22552                    "|||||||\n"
22553                    "  Else \\\n"
22554                    "=======\n"
22555                    "  Other \\\n"
22556                    ">>>>>>>\n"
22557                    "  End\n"
22558                    "int i;\n"));
22559 
22560   verifyFormat(R"(====
22561 #ifdef A
22562 a
22563 #else
22564 b
22565 #endif
22566 )");
22567 }
22568 
22569 TEST_F(FormatTest, DisableRegions) {
22570   EXPECT_EQ("int i;\n"
22571             "// clang-format off\n"
22572             "  int j;\n"
22573             "// clang-format on\n"
22574             "int k;",
22575             format(" int  i;\n"
22576                    "   // clang-format off\n"
22577                    "  int j;\n"
22578                    " // clang-format on\n"
22579                    "   int   k;"));
22580   EXPECT_EQ("int i;\n"
22581             "/* clang-format off */\n"
22582             "  int j;\n"
22583             "/* clang-format on */\n"
22584             "int k;",
22585             format(" int  i;\n"
22586                    "   /* clang-format off */\n"
22587                    "  int j;\n"
22588                    " /* clang-format on */\n"
22589                    "   int   k;"));
22590 
22591   // Don't reflow comments within disabled regions.
22592   EXPECT_EQ("// clang-format off\n"
22593             "// long long long long long long line\n"
22594             "/* clang-format on */\n"
22595             "/* long long long\n"
22596             " * long long long\n"
22597             " * line */\n"
22598             "int i;\n"
22599             "/* clang-format off */\n"
22600             "/* long long long long long long line */\n",
22601             format("// clang-format off\n"
22602                    "// long long long long long long line\n"
22603                    "/* clang-format on */\n"
22604                    "/* long long long long long long line */\n"
22605                    "int i;\n"
22606                    "/* clang-format off */\n"
22607                    "/* long long long long long long line */\n",
22608                    getLLVMStyleWithColumns(20)));
22609 }
22610 
22611 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22612   format("? ) =");
22613   verifyNoCrash("#define a\\\n /**/}");
22614 }
22615 
22616 TEST_F(FormatTest, FormatsTableGenCode) {
22617   FormatStyle Style = getLLVMStyle();
22618   Style.Language = FormatStyle::LK_TableGen;
22619   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22620 }
22621 
22622 TEST_F(FormatTest, ArrayOfTemplates) {
22623   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22624             format("auto a = new unique_ptr<int > [ 10];"));
22625 
22626   FormatStyle Spaces = getLLVMStyle();
22627   Spaces.SpacesInSquareBrackets = true;
22628   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22629             format("auto a = new unique_ptr<int > [10];", Spaces));
22630 }
22631 
22632 TEST_F(FormatTest, ArrayAsTemplateType) {
22633   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22634             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22635 
22636   FormatStyle Spaces = getLLVMStyle();
22637   Spaces.SpacesInSquareBrackets = true;
22638   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22639             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22640 }
22641 
22642 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22643 
22644 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22645   llvm::vfs::InMemoryFileSystem FS;
22646   auto Style1 = getStyle("file", "", "Google", "", &FS);
22647   ASSERT_TRUE((bool)Style1);
22648   ASSERT_EQ(*Style1, getGoogleStyle());
22649 }
22650 
22651 TEST(FormatStyle, GetStyleOfFile) {
22652   llvm::vfs::InMemoryFileSystem FS;
22653   // Test 1: format file in the same directory.
22654   ASSERT_TRUE(
22655       FS.addFile("/a/.clang-format", 0,
22656                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22657   ASSERT_TRUE(
22658       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22659   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22660   ASSERT_TRUE((bool)Style1);
22661   ASSERT_EQ(*Style1, getLLVMStyle());
22662 
22663   // Test 2.1: fallback to default.
22664   ASSERT_TRUE(
22665       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22666   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22667   ASSERT_TRUE((bool)Style2);
22668   ASSERT_EQ(*Style2, getMozillaStyle());
22669 
22670   // Test 2.2: no format on 'none' fallback style.
22671   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22672   ASSERT_TRUE((bool)Style2);
22673   ASSERT_EQ(*Style2, getNoStyle());
22674 
22675   // Test 2.3: format if config is found with no based style while fallback is
22676   // 'none'.
22677   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22678                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22679   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22680   ASSERT_TRUE((bool)Style2);
22681   ASSERT_EQ(*Style2, getLLVMStyle());
22682 
22683   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22684   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22685   ASSERT_TRUE((bool)Style2);
22686   ASSERT_EQ(*Style2, getLLVMStyle());
22687 
22688   // Test 3: format file in parent directory.
22689   ASSERT_TRUE(
22690       FS.addFile("/c/.clang-format", 0,
22691                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22692   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22693                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22694   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22695   ASSERT_TRUE((bool)Style3);
22696   ASSERT_EQ(*Style3, getGoogleStyle());
22697 
22698   // Test 4: error on invalid fallback style
22699   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22700   ASSERT_FALSE((bool)Style4);
22701   llvm::consumeError(Style4.takeError());
22702 
22703   // Test 5: error on invalid yaml on command line
22704   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22705   ASSERT_FALSE((bool)Style5);
22706   llvm::consumeError(Style5.takeError());
22707 
22708   // Test 6: error on invalid style
22709   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22710   ASSERT_FALSE((bool)Style6);
22711   llvm::consumeError(Style6.takeError());
22712 
22713   // Test 7: found config file, error on parsing it
22714   ASSERT_TRUE(
22715       FS.addFile("/d/.clang-format", 0,
22716                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22717                                                   "InvalidKey: InvalidValue")));
22718   ASSERT_TRUE(
22719       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22720   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22721   ASSERT_FALSE((bool)Style7a);
22722   llvm::consumeError(Style7a.takeError());
22723 
22724   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22725   ASSERT_TRUE((bool)Style7b);
22726 
22727   // Test 8: inferred per-language defaults apply.
22728   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22729   ASSERT_TRUE((bool)StyleTd);
22730   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22731 
22732   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22733   // fallback style.
22734   ASSERT_TRUE(FS.addFile(
22735       "/e/sub/.clang-format", 0,
22736       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22737                                        "ColumnLimit: 20")));
22738   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22739                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22740   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22741   ASSERT_TRUE(static_cast<bool>(Style9));
22742   ASSERT_EQ(*Style9, [] {
22743     auto Style = getNoStyle();
22744     Style.ColumnLimit = 20;
22745     return Style;
22746   }());
22747 
22748   // Test 9.1.2: propagate more than one level with no parent file.
22749   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22750                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22751   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22752                          llvm::MemoryBuffer::getMemBuffer(
22753                              "BasedOnStyle: InheritParentConfig\n"
22754                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22755   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22756 
22757   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22758   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22759   ASSERT_TRUE(static_cast<bool>(Style9));
22760   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22761     auto Style = getNoStyle();
22762     Style.ColumnLimit = 20;
22763     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22764     return Style;
22765   }());
22766 
22767   // Test 9.2: with LLVM fallback style
22768   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22769   ASSERT_TRUE(static_cast<bool>(Style9));
22770   ASSERT_EQ(*Style9, [] {
22771     auto Style = getLLVMStyle();
22772     Style.ColumnLimit = 20;
22773     return Style;
22774   }());
22775 
22776   // Test 9.3: with a parent file
22777   ASSERT_TRUE(
22778       FS.addFile("/e/.clang-format", 0,
22779                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
22780                                                   "UseTab: Always")));
22781   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22782   ASSERT_TRUE(static_cast<bool>(Style9));
22783   ASSERT_EQ(*Style9, [] {
22784     auto Style = getGoogleStyle();
22785     Style.ColumnLimit = 20;
22786     Style.UseTab = FormatStyle::UT_Always;
22787     return Style;
22788   }());
22789 
22790   // Test 9.4: propagate more than one level with a parent file.
22791   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
22792     auto Style = getGoogleStyle();
22793     Style.ColumnLimit = 20;
22794     Style.UseTab = FormatStyle::UT_Always;
22795     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22796     return Style;
22797   }();
22798 
22799   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22800   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22801   ASSERT_TRUE(static_cast<bool>(Style9));
22802   ASSERT_EQ(*Style9, SubSubStyle);
22803 
22804   // Test 9.5: use InheritParentConfig as style name
22805   Style9 =
22806       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
22807   ASSERT_TRUE(static_cast<bool>(Style9));
22808   ASSERT_EQ(*Style9, SubSubStyle);
22809 
22810   // Test 9.6: use command line style with inheritance
22811   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
22812                     "none", "", &FS);
22813   ASSERT_TRUE(static_cast<bool>(Style9));
22814   ASSERT_EQ(*Style9, SubSubStyle);
22815 
22816   // Test 9.7: use command line style with inheritance and own config
22817   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
22818                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
22819                     "/e/sub/code.cpp", "none", "", &FS);
22820   ASSERT_TRUE(static_cast<bool>(Style9));
22821   ASSERT_EQ(*Style9, SubSubStyle);
22822 
22823   // Test 9.8: use inheritance from a file without BasedOnStyle
22824   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
22825                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
22826   ASSERT_TRUE(
22827       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
22828                  llvm::MemoryBuffer::getMemBuffer(
22829                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
22830   // Make sure we do not use the fallback style
22831   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
22832   ASSERT_TRUE(static_cast<bool>(Style9));
22833   ASSERT_EQ(*Style9, [] {
22834     auto Style = getLLVMStyle();
22835     Style.ColumnLimit = 123;
22836     return Style;
22837   }());
22838 
22839   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
22840   ASSERT_TRUE(static_cast<bool>(Style9));
22841   ASSERT_EQ(*Style9, [] {
22842     auto Style = getLLVMStyle();
22843     Style.ColumnLimit = 123;
22844     Style.IndentWidth = 7;
22845     return Style;
22846   }());
22847 
22848   // Test 9.9: use inheritance from a specific config file.
22849   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
22850                     "none", "", &FS);
22851   ASSERT_TRUE(static_cast<bool>(Style9));
22852   ASSERT_EQ(*Style9, SubSubStyle);
22853 }
22854 
22855 TEST(FormatStyle, GetStyleOfSpecificFile) {
22856   llvm::vfs::InMemoryFileSystem FS;
22857   // Specify absolute path to a format file in a parent directory.
22858   ASSERT_TRUE(
22859       FS.addFile("/e/.clang-format", 0,
22860                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22861   ASSERT_TRUE(
22862       FS.addFile("/e/explicit.clang-format", 0,
22863                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22864   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
22865                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22866   auto Style = getStyle("file:/e/explicit.clang-format",
22867                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22868   ASSERT_TRUE(static_cast<bool>(Style));
22869   ASSERT_EQ(*Style, getGoogleStyle());
22870 
22871   // Specify relative path to a format file.
22872   ASSERT_TRUE(
22873       FS.addFile("../../e/explicit.clang-format", 0,
22874                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22875   Style = getStyle("file:../../e/explicit.clang-format",
22876                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22877   ASSERT_TRUE(static_cast<bool>(Style));
22878   ASSERT_EQ(*Style, getGoogleStyle());
22879 
22880   // Specify path to a format file that does not exist.
22881   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
22882                    "LLVM", "", &FS);
22883   ASSERT_FALSE(static_cast<bool>(Style));
22884   llvm::consumeError(Style.takeError());
22885 
22886   // Specify path to a file on the filesystem.
22887   SmallString<128> FormatFilePath;
22888   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
22889       "FormatFileTest", "tpl", FormatFilePath);
22890   EXPECT_FALSE((bool)ECF);
22891   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
22892   EXPECT_FALSE((bool)ECF);
22893   FormatFileTest << "BasedOnStyle: Google\n";
22894   FormatFileTest.close();
22895 
22896   SmallString<128> TestFilePath;
22897   std::error_code ECT =
22898       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
22899   EXPECT_FALSE((bool)ECT);
22900   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
22901   CodeFileTest << "int i;\n";
22902   CodeFileTest.close();
22903 
22904   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
22905   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
22906 
22907   llvm::sys::fs::remove(FormatFilePath.c_str());
22908   llvm::sys::fs::remove(TestFilePath.c_str());
22909   ASSERT_TRUE(static_cast<bool>(Style));
22910   ASSERT_EQ(*Style, getGoogleStyle());
22911 }
22912 
22913 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
22914   // Column limit is 20.
22915   std::string Code = "Type *a =\n"
22916                      "    new Type();\n"
22917                      "g(iiiii, 0, jjjjj,\n"
22918                      "  0, kkkkk, 0, mm);\n"
22919                      "int  bad     = format   ;";
22920   std::string Expected = "auto a = new Type();\n"
22921                          "g(iiiii, nullptr,\n"
22922                          "  jjjjj, nullptr,\n"
22923                          "  kkkkk, nullptr,\n"
22924                          "  mm);\n"
22925                          "int  bad     = format   ;";
22926   FileID ID = Context.createInMemoryFile("format.cpp", Code);
22927   tooling::Replacements Replaces = toReplacements(
22928       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
22929                             "auto "),
22930        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
22931                             "nullptr"),
22932        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
22933                             "nullptr"),
22934        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
22935                             "nullptr")});
22936 
22937   FormatStyle Style = getLLVMStyle();
22938   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
22939   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22940   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22941       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22942   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22943   EXPECT_TRUE(static_cast<bool>(Result));
22944   EXPECT_EQ(Expected, *Result);
22945 }
22946 
22947 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
22948   std::string Code = "#include \"a.h\"\n"
22949                      "#include \"c.h\"\n"
22950                      "\n"
22951                      "int main() {\n"
22952                      "  return 0;\n"
22953                      "}";
22954   std::string Expected = "#include \"a.h\"\n"
22955                          "#include \"b.h\"\n"
22956                          "#include \"c.h\"\n"
22957                          "\n"
22958                          "int main() {\n"
22959                          "  return 0;\n"
22960                          "}";
22961   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
22962   tooling::Replacements Replaces = toReplacements(
22963       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
22964                             "#include \"b.h\"\n")});
22965 
22966   FormatStyle Style = getLLVMStyle();
22967   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
22968   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22969   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22970       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22971   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22972   EXPECT_TRUE(static_cast<bool>(Result));
22973   EXPECT_EQ(Expected, *Result);
22974 }
22975 
22976 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
22977   EXPECT_EQ("using std::cin;\n"
22978             "using std::cout;",
22979             format("using std::cout;\n"
22980                    "using std::cin;",
22981                    getGoogleStyle()));
22982 }
22983 
22984 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
22985   FormatStyle Style = getLLVMStyle();
22986   Style.Standard = FormatStyle::LS_Cpp03;
22987   // cpp03 recognize this string as identifier u8 and literal character 'a'
22988   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
22989 }
22990 
22991 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
22992   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
22993   // all modes, including C++11, C++14 and C++17
22994   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
22995 }
22996 
22997 TEST_F(FormatTest, DoNotFormatLikelyXml) {
22998   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
22999   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
23000 }
23001 
23002 TEST_F(FormatTest, StructuredBindings) {
23003   // Structured bindings is a C++17 feature.
23004   // all modes, including C++11, C++14 and C++17
23005   verifyFormat("auto [a, b] = f();");
23006   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
23007   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
23008   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
23009   EXPECT_EQ("auto const volatile [a, b] = f();",
23010             format("auto  const   volatile[a, b] = f();"));
23011   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
23012   EXPECT_EQ("auto &[a, b, c] = f();",
23013             format("auto   &[  a  ,  b,c   ] = f();"));
23014   EXPECT_EQ("auto &&[a, b, c] = f();",
23015             format("auto   &&[  a  ,  b,c   ] = f();"));
23016   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
23017   EXPECT_EQ("auto const volatile &&[a, b] = f();",
23018             format("auto  const  volatile  &&[a, b] = f();"));
23019   EXPECT_EQ("auto const &&[a, b] = f();",
23020             format("auto  const   &&  [a, b] = f();"));
23021   EXPECT_EQ("const auto &[a, b] = f();",
23022             format("const  auto  &  [a, b] = f();"));
23023   EXPECT_EQ("const auto volatile &&[a, b] = f();",
23024             format("const  auto   volatile  &&[a, b] = f();"));
23025   EXPECT_EQ("volatile const auto &&[a, b] = f();",
23026             format("volatile  const  auto   &&[a, b] = f();"));
23027   EXPECT_EQ("const auto &&[a, b] = f();",
23028             format("const  auto  &&  [a, b] = f();"));
23029 
23030   // Make sure we don't mistake structured bindings for lambdas.
23031   FormatStyle PointerMiddle = getLLVMStyle();
23032   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
23033   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
23034   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
23035   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
23036   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
23037   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
23038   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
23039   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
23040   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
23041   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
23042   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
23043   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
23044   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
23045 
23046   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
23047             format("for (const auto   &&   [a, b] : some_range) {\n}"));
23048   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
23049             format("for (const auto   &   [a, b] : some_range) {\n}"));
23050   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
23051             format("for (const auto[a, b] : some_range) {\n}"));
23052   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
23053   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
23054   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
23055   EXPECT_EQ("auto const &[x, y](expr);",
23056             format("auto  const  &  [x,y]  (expr);"));
23057   EXPECT_EQ("auto const &&[x, y](expr);",
23058             format("auto  const  &&  [x,y]  (expr);"));
23059   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
23060   EXPECT_EQ("auto const &[x, y]{expr};",
23061             format("auto  const  &  [x,y]  {expr};"));
23062   EXPECT_EQ("auto const &&[x, y]{expr};",
23063             format("auto  const  &&  [x,y]  {expr};"));
23064 
23065   FormatStyle Spaces = getLLVMStyle();
23066   Spaces.SpacesInSquareBrackets = true;
23067   verifyFormat("auto [ a, b ] = f();", Spaces);
23068   verifyFormat("auto &&[ a, b ] = f();", Spaces);
23069   verifyFormat("auto &[ a, b ] = f();", Spaces);
23070   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
23071   verifyFormat("auto const &[ a, b ] = f();", Spaces);
23072 }
23073 
23074 TEST_F(FormatTest, FileAndCode) {
23075   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
23076   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
23077   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
23078   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
23079   EXPECT_EQ(FormatStyle::LK_ObjC,
23080             guessLanguage("foo.h", "@interface Foo\n@end\n"));
23081   EXPECT_EQ(
23082       FormatStyle::LK_ObjC,
23083       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
23084   EXPECT_EQ(FormatStyle::LK_ObjC,
23085             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
23086   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
23087   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
23088   EXPECT_EQ(FormatStyle::LK_ObjC,
23089             guessLanguage("foo", "@interface Foo\n@end\n"));
23090   EXPECT_EQ(FormatStyle::LK_ObjC,
23091             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
23092   EXPECT_EQ(
23093       FormatStyle::LK_ObjC,
23094       guessLanguage("foo.h",
23095                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
23096   EXPECT_EQ(
23097       FormatStyle::LK_Cpp,
23098       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
23099   // Only one of the two preprocessor regions has ObjC-like code.
23100   EXPECT_EQ(FormatStyle::LK_ObjC,
23101             guessLanguage("foo.h", "#if A\n"
23102                                    "#define B() C\n"
23103                                    "#else\n"
23104                                    "#define B() [NSString a:@\"\"]\n"
23105                                    "#endif\n"));
23106 }
23107 
23108 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
23109   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
23110   EXPECT_EQ(FormatStyle::LK_ObjC,
23111             guessLanguage("foo.h", "array[[calculator getIndex]];"));
23112   EXPECT_EQ(FormatStyle::LK_Cpp,
23113             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
23114   EXPECT_EQ(
23115       FormatStyle::LK_Cpp,
23116       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
23117   EXPECT_EQ(FormatStyle::LK_ObjC,
23118             guessLanguage("foo.h", "[[noreturn foo] bar];"));
23119   EXPECT_EQ(FormatStyle::LK_Cpp,
23120             guessLanguage("foo.h", "[[clang::fallthrough]];"));
23121   EXPECT_EQ(FormatStyle::LK_ObjC,
23122             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
23123   EXPECT_EQ(FormatStyle::LK_Cpp,
23124             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
23125   EXPECT_EQ(FormatStyle::LK_Cpp,
23126             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
23127   EXPECT_EQ(FormatStyle::LK_ObjC,
23128             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
23129   EXPECT_EQ(FormatStyle::LK_Cpp,
23130             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
23131   EXPECT_EQ(
23132       FormatStyle::LK_Cpp,
23133       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
23134   EXPECT_EQ(
23135       FormatStyle::LK_Cpp,
23136       guessLanguage("foo.h",
23137                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
23138   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
23139 }
23140 
23141 TEST_F(FormatTest, GuessLanguageWithCaret) {
23142   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
23143   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
23144   EXPECT_EQ(FormatStyle::LK_ObjC,
23145             guessLanguage("foo.h", "int(^)(char, float);"));
23146   EXPECT_EQ(FormatStyle::LK_ObjC,
23147             guessLanguage("foo.h", "int(^foo)(char, float);"));
23148   EXPECT_EQ(FormatStyle::LK_ObjC,
23149             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
23150   EXPECT_EQ(FormatStyle::LK_ObjC,
23151             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
23152   EXPECT_EQ(
23153       FormatStyle::LK_ObjC,
23154       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
23155 }
23156 
23157 TEST_F(FormatTest, GuessLanguageWithPragmas) {
23158   EXPECT_EQ(FormatStyle::LK_Cpp,
23159             guessLanguage("foo.h", "__pragma(warning(disable:))"));
23160   EXPECT_EQ(FormatStyle::LK_Cpp,
23161             guessLanguage("foo.h", "#pragma(warning(disable:))"));
23162   EXPECT_EQ(FormatStyle::LK_Cpp,
23163             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
23164 }
23165 
23166 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
23167   // ASM symbolic names are identifiers that must be surrounded by [] without
23168   // space in between:
23169   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
23170 
23171   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
23172   verifyFormat(R"(//
23173 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
23174 )");
23175 
23176   // A list of several ASM symbolic names.
23177   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
23178 
23179   // ASM symbolic names in inline ASM with inputs and outputs.
23180   verifyFormat(R"(//
23181 asm("cmoveq %1, %2, %[result]"
23182     : [result] "=r"(result)
23183     : "r"(test), "r"(new), "[result]"(old));
23184 )");
23185 
23186   // ASM symbolic names in inline ASM with no outputs.
23187   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
23188 }
23189 
23190 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
23191   EXPECT_EQ(FormatStyle::LK_Cpp,
23192             guessLanguage("foo.h", "void f() {\n"
23193                                    "  asm (\"mov %[e], %[d]\"\n"
23194                                    "     : [d] \"=rm\" (d)\n"
23195                                    "       [e] \"rm\" (*e));\n"
23196                                    "}"));
23197   EXPECT_EQ(FormatStyle::LK_Cpp,
23198             guessLanguage("foo.h", "void f() {\n"
23199                                    "  _asm (\"mov %[e], %[d]\"\n"
23200                                    "     : [d] \"=rm\" (d)\n"
23201                                    "       [e] \"rm\" (*e));\n"
23202                                    "}"));
23203   EXPECT_EQ(FormatStyle::LK_Cpp,
23204             guessLanguage("foo.h", "void f() {\n"
23205                                    "  __asm (\"mov %[e], %[d]\"\n"
23206                                    "     : [d] \"=rm\" (d)\n"
23207                                    "       [e] \"rm\" (*e));\n"
23208                                    "}"));
23209   EXPECT_EQ(FormatStyle::LK_Cpp,
23210             guessLanguage("foo.h", "void f() {\n"
23211                                    "  __asm__ (\"mov %[e], %[d]\"\n"
23212                                    "     : [d] \"=rm\" (d)\n"
23213                                    "       [e] \"rm\" (*e));\n"
23214                                    "}"));
23215   EXPECT_EQ(FormatStyle::LK_Cpp,
23216             guessLanguage("foo.h", "void f() {\n"
23217                                    "  asm (\"mov %[e], %[d]\"\n"
23218                                    "     : [d] \"=rm\" (d),\n"
23219                                    "       [e] \"rm\" (*e));\n"
23220                                    "}"));
23221   EXPECT_EQ(FormatStyle::LK_Cpp,
23222             guessLanguage("foo.h", "void f() {\n"
23223                                    "  asm volatile (\"mov %[e], %[d]\"\n"
23224                                    "     : [d] \"=rm\" (d)\n"
23225                                    "       [e] \"rm\" (*e));\n"
23226                                    "}"));
23227 }
23228 
23229 TEST_F(FormatTest, GuessLanguageWithChildLines) {
23230   EXPECT_EQ(FormatStyle::LK_Cpp,
23231             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
23232   EXPECT_EQ(FormatStyle::LK_ObjC,
23233             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
23234   EXPECT_EQ(
23235       FormatStyle::LK_Cpp,
23236       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
23237   EXPECT_EQ(
23238       FormatStyle::LK_ObjC,
23239       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
23240 }
23241 
23242 TEST_F(FormatTest, TypenameMacros) {
23243   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
23244 
23245   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
23246   FormatStyle Google = getGoogleStyleWithColumns(0);
23247   Google.TypenameMacros = TypenameMacros;
23248   verifyFormat("struct foo {\n"
23249                "  int bar;\n"
23250                "  TAILQ_ENTRY(a) bleh;\n"
23251                "};",
23252                Google);
23253 
23254   FormatStyle Macros = getLLVMStyle();
23255   Macros.TypenameMacros = TypenameMacros;
23256 
23257   verifyFormat("STACK_OF(int) a;", Macros);
23258   verifyFormat("STACK_OF(int) *a;", Macros);
23259   verifyFormat("STACK_OF(int const *) *a;", Macros);
23260   verifyFormat("STACK_OF(int *const) *a;", Macros);
23261   verifyFormat("STACK_OF(int, string) a;", Macros);
23262   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
23263   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
23264   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
23265   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
23266   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
23267   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
23268 
23269   Macros.PointerAlignment = FormatStyle::PAS_Left;
23270   verifyFormat("STACK_OF(int)* a;", Macros);
23271   verifyFormat("STACK_OF(int*)* a;", Macros);
23272   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
23273   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
23274   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
23275 }
23276 
23277 TEST_F(FormatTest, AtomicQualifier) {
23278   // Check that we treate _Atomic as a type and not a function call
23279   FormatStyle Google = getGoogleStyleWithColumns(0);
23280   verifyFormat("struct foo {\n"
23281                "  int a1;\n"
23282                "  _Atomic(a) a2;\n"
23283                "  _Atomic(_Atomic(int) *const) a3;\n"
23284                "};",
23285                Google);
23286   verifyFormat("_Atomic(uint64_t) a;");
23287   verifyFormat("_Atomic(uint64_t) *a;");
23288   verifyFormat("_Atomic(uint64_t const *) *a;");
23289   verifyFormat("_Atomic(uint64_t *const) *a;");
23290   verifyFormat("_Atomic(const uint64_t *) *a;");
23291   verifyFormat("_Atomic(uint64_t) a;");
23292   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
23293   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
23294   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
23295   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
23296 
23297   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
23298   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
23299   FormatStyle Style = getLLVMStyle();
23300   Style.PointerAlignment = FormatStyle::PAS_Left;
23301   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
23302   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
23303   verifyFormat("_Atomic(int)* a;", Style);
23304   verifyFormat("_Atomic(int*)* a;", Style);
23305   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
23306 
23307   Style.SpacesInCStyleCastParentheses = true;
23308   Style.SpacesInParentheses = false;
23309   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
23310   Style.SpacesInCStyleCastParentheses = false;
23311   Style.SpacesInParentheses = true;
23312   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
23313   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
23314 }
23315 
23316 TEST_F(FormatTest, AmbersandInLamda) {
23317   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
23318   FormatStyle AlignStyle = getLLVMStyle();
23319   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
23320   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23321   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
23322   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23323 }
23324 
23325 TEST_F(FormatTest, SpacesInConditionalStatement) {
23326   FormatStyle Spaces = getLLVMStyle();
23327   Spaces.IfMacros.clear();
23328   Spaces.IfMacros.push_back("MYIF");
23329   Spaces.SpacesInConditionalStatement = true;
23330   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
23331   verifyFormat("if ( !a )\n  return;", Spaces);
23332   verifyFormat("if ( a )\n  return;", Spaces);
23333   verifyFormat("if constexpr ( a )\n  return;", Spaces);
23334   verifyFormat("MYIF ( a )\n  return;", Spaces);
23335   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
23336   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
23337   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
23338   verifyFormat("while ( a )\n  return;", Spaces);
23339   verifyFormat("while ( (a && b) )\n  return;", Spaces);
23340   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
23341   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
23342   // Check that space on the left of "::" is inserted as expected at beginning
23343   // of condition.
23344   verifyFormat("while ( ::func() )\n  return;", Spaces);
23345 
23346   // Check impact of ControlStatementsExceptControlMacros is honored.
23347   Spaces.SpaceBeforeParens =
23348       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
23349   verifyFormat("MYIF( a )\n  return;", Spaces);
23350   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
23351   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
23352 }
23353 
23354 TEST_F(FormatTest, AlternativeOperators) {
23355   // Test case for ensuring alternate operators are not
23356   // combined with their right most neighbour.
23357   verifyFormat("int a and b;");
23358   verifyFormat("int a and_eq b;");
23359   verifyFormat("int a bitand b;");
23360   verifyFormat("int a bitor b;");
23361   verifyFormat("int a compl b;");
23362   verifyFormat("int a not b;");
23363   verifyFormat("int a not_eq b;");
23364   verifyFormat("int a or b;");
23365   verifyFormat("int a xor b;");
23366   verifyFormat("int a xor_eq b;");
23367   verifyFormat("return this not_eq bitand other;");
23368   verifyFormat("bool operator not_eq(const X bitand other)");
23369 
23370   verifyFormat("int a and 5;");
23371   verifyFormat("int a and_eq 5;");
23372   verifyFormat("int a bitand 5;");
23373   verifyFormat("int a bitor 5;");
23374   verifyFormat("int a compl 5;");
23375   verifyFormat("int a not 5;");
23376   verifyFormat("int a not_eq 5;");
23377   verifyFormat("int a or 5;");
23378   verifyFormat("int a xor 5;");
23379   verifyFormat("int a xor_eq 5;");
23380 
23381   verifyFormat("int a compl(5);");
23382   verifyFormat("int a not(5);");
23383 
23384   /* FIXME handle alternate tokens
23385    * https://en.cppreference.com/w/cpp/language/operator_alternative
23386   // alternative tokens
23387   verifyFormat("compl foo();");     //  ~foo();
23388   verifyFormat("foo() <%%>;");      // foo();
23389   verifyFormat("void foo() <%%>;"); // void foo(){}
23390   verifyFormat("int a <:1:>;");     // int a[1];[
23391   verifyFormat("%:define ABC abc"); // #define ABC abc
23392   verifyFormat("%:%:");             // ##
23393   */
23394 }
23395 
23396 TEST_F(FormatTest, STLWhileNotDefineChed) {
23397   verifyFormat("#if defined(while)\n"
23398                "#define while EMIT WARNING C4005\n"
23399                "#endif // while");
23400 }
23401 
23402 TEST_F(FormatTest, OperatorSpacing) {
23403   FormatStyle Style = getLLVMStyle();
23404   Style.PointerAlignment = FormatStyle::PAS_Right;
23405   verifyFormat("Foo::operator*();", Style);
23406   verifyFormat("Foo::operator void *();", Style);
23407   verifyFormat("Foo::operator void **();", Style);
23408   verifyFormat("Foo::operator void *&();", Style);
23409   verifyFormat("Foo::operator void *&&();", Style);
23410   verifyFormat("Foo::operator void const *();", Style);
23411   verifyFormat("Foo::operator void const **();", Style);
23412   verifyFormat("Foo::operator void const *&();", Style);
23413   verifyFormat("Foo::operator void const *&&();", Style);
23414   verifyFormat("Foo::operator()(void *);", Style);
23415   verifyFormat("Foo::operator*(void *);", Style);
23416   verifyFormat("Foo::operator*();", Style);
23417   verifyFormat("Foo::operator**();", Style);
23418   verifyFormat("Foo::operator&();", Style);
23419   verifyFormat("Foo::operator<int> *();", Style);
23420   verifyFormat("Foo::operator<Foo> *();", Style);
23421   verifyFormat("Foo::operator<int> **();", 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("Foo::operator<int> *&&();", Style);
23430   verifyFormat("Foo::operator<Foo> *&&();", Style);
23431   verifyFormat("operator*(int (*)(), class Foo);", Style);
23432 
23433   verifyFormat("Foo::operator&();", Style);
23434   verifyFormat("Foo::operator void &();", Style);
23435   verifyFormat("Foo::operator void const &();", Style);
23436   verifyFormat("Foo::operator()(void &);", Style);
23437   verifyFormat("Foo::operator&(void &);", Style);
23438   verifyFormat("Foo::operator&();", Style);
23439   verifyFormat("operator&(int (&)(), class Foo);", Style);
23440   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23441 
23442   verifyFormat("Foo::operator&&();", Style);
23443   verifyFormat("Foo::operator**();", Style);
23444   verifyFormat("Foo::operator void &&();", Style);
23445   verifyFormat("Foo::operator void const &&();", Style);
23446   verifyFormat("Foo::operator()(void &&);", Style);
23447   verifyFormat("Foo::operator&&(void &&);", Style);
23448   verifyFormat("Foo::operator&&();", Style);
23449   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23450   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23451   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23452                Style);
23453   verifyFormat("operator void **()", Style);
23454   verifyFormat("operator const FooRight<Object> &()", Style);
23455   verifyFormat("operator const FooRight<Object> *()", Style);
23456   verifyFormat("operator const FooRight<Object> **()", Style);
23457   verifyFormat("operator const FooRight<Object> *&()", Style);
23458   verifyFormat("operator const FooRight<Object> *&&()", Style);
23459 
23460   Style.PointerAlignment = FormatStyle::PAS_Left;
23461   verifyFormat("Foo::operator*();", Style);
23462   verifyFormat("Foo::operator**();", Style);
23463   verifyFormat("Foo::operator void*();", Style);
23464   verifyFormat("Foo::operator void**();", Style);
23465   verifyFormat("Foo::operator void*&();", Style);
23466   verifyFormat("Foo::operator void*&&();", Style);
23467   verifyFormat("Foo::operator void const*();", Style);
23468   verifyFormat("Foo::operator void const**();", Style);
23469   verifyFormat("Foo::operator void const*&();", Style);
23470   verifyFormat("Foo::operator void const*&&();", Style);
23471   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23472   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23473   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23474   verifyFormat("Foo::operator()(void*);", Style);
23475   verifyFormat("Foo::operator*(void*);", Style);
23476   verifyFormat("Foo::operator*();", Style);
23477   verifyFormat("Foo::operator<int>*();", Style);
23478   verifyFormat("Foo::operator<Foo>*();", Style);
23479   verifyFormat("Foo::operator<int>**();", Style);
23480   verifyFormat("Foo::operator<Foo>**();", Style);
23481   verifyFormat("Foo::operator<Foo>*&();", Style);
23482   verifyFormat("Foo::operator<int>&();", Style);
23483   verifyFormat("Foo::operator<Foo>&();", Style);
23484   verifyFormat("Foo::operator<int>&&();", Style);
23485   verifyFormat("Foo::operator<Foo>&&();", Style);
23486   verifyFormat("Foo::operator<int>*&();", Style);
23487   verifyFormat("Foo::operator<Foo>*&();", Style);
23488   verifyFormat("operator*(int (*)(), class Foo);", Style);
23489 
23490   verifyFormat("Foo::operator&();", Style);
23491   verifyFormat("Foo::operator void&();", Style);
23492   verifyFormat("Foo::operator void const&();", Style);
23493   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23494   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23495   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
23496   verifyFormat("Foo::operator()(void&);", Style);
23497   verifyFormat("Foo::operator&(void&);", Style);
23498   verifyFormat("Foo::operator&();", Style);
23499   verifyFormat("operator&(int (&)(), class Foo);", Style);
23500   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23501   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23502 
23503   verifyFormat("Foo::operator&&();", Style);
23504   verifyFormat("Foo::operator void&&();", Style);
23505   verifyFormat("Foo::operator void const&&();", Style);
23506   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23507   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23508   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23509   verifyFormat("Foo::operator()(void&&);", Style);
23510   verifyFormat("Foo::operator&&(void&&);", Style);
23511   verifyFormat("Foo::operator&&();", Style);
23512   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23513   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23514   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23515                Style);
23516   verifyFormat("operator void**()", Style);
23517   verifyFormat("operator const FooLeft<Object>&()", Style);
23518   verifyFormat("operator const FooLeft<Object>*()", Style);
23519   verifyFormat("operator const FooLeft<Object>**()", Style);
23520   verifyFormat("operator const FooLeft<Object>*&()", Style);
23521   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23522 
23523   // PR45107
23524   verifyFormat("operator Vector<String>&();", Style);
23525   verifyFormat("operator const Vector<String>&();", Style);
23526   verifyFormat("operator foo::Bar*();", Style);
23527   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23528   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23529                Style);
23530 
23531   Style.PointerAlignment = FormatStyle::PAS_Middle;
23532   verifyFormat("Foo::operator*();", Style);
23533   verifyFormat("Foo::operator void *();", Style);
23534   verifyFormat("Foo::operator()(void *);", Style);
23535   verifyFormat("Foo::operator*(void *);", Style);
23536   verifyFormat("Foo::operator*();", Style);
23537   verifyFormat("operator*(int (*)(), class Foo);", Style);
23538 
23539   verifyFormat("Foo::operator&();", Style);
23540   verifyFormat("Foo::operator void &();", Style);
23541   verifyFormat("Foo::operator void const &();", Style);
23542   verifyFormat("Foo::operator()(void &);", Style);
23543   verifyFormat("Foo::operator&(void &);", Style);
23544   verifyFormat("Foo::operator&();", Style);
23545   verifyFormat("operator&(int (&)(), class Foo);", Style);
23546 
23547   verifyFormat("Foo::operator&&();", Style);
23548   verifyFormat("Foo::operator void &&();", Style);
23549   verifyFormat("Foo::operator void const &&();", Style);
23550   verifyFormat("Foo::operator()(void &&);", Style);
23551   verifyFormat("Foo::operator&&(void &&);", Style);
23552   verifyFormat("Foo::operator&&();", Style);
23553   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23554 }
23555 
23556 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23557   FormatStyle Style = getLLVMStyle();
23558   // PR46157
23559   verifyFormat("foo(operator+, -42);", Style);
23560   verifyFormat("foo(operator++, -42);", Style);
23561   verifyFormat("foo(operator--, -42);", Style);
23562   verifyFormat("foo(-42, operator--);", Style);
23563   verifyFormat("foo(-42, operator, );", Style);
23564   verifyFormat("foo(operator, , -42);", Style);
23565 }
23566 
23567 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23568   FormatStyle Style = getLLVMStyle();
23569   Style.WhitespaceSensitiveMacros.push_back("FOO");
23570 
23571   // Don't use the helpers here, since 'mess up' will change the whitespace
23572   // and these are all whitespace sensitive by definition
23573   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23574             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23575   EXPECT_EQ(
23576       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23577       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23578   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23579             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23580   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23581             "       Still=Intentional);",
23582             format("FOO(String-ized&Messy+But,: :\n"
23583                    "       Still=Intentional);",
23584                    Style));
23585   Style.AlignConsecutiveAssignments.Enabled = true;
23586   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
23587             "       Still=Intentional);",
23588             format("FOO(String-ized=&Messy+But,: :\n"
23589                    "       Still=Intentional);",
23590                    Style));
23591 
23592   Style.ColumnLimit = 21;
23593   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23594             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23595 }
23596 
23597 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23598   // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
23599   // test its interaction with line wrapping
23600   FormatStyle Style = getLLVMStyleWithColumns(80);
23601   verifyFormat("namespace {\n"
23602                "int i;\n"
23603                "int j;\n"
23604                "} // namespace",
23605                Style);
23606 
23607   verifyFormat("namespace AAA {\n"
23608                "int i;\n"
23609                "int j;\n"
23610                "} // namespace AAA",
23611                Style);
23612 
23613   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23614             "int i;\n"
23615             "int j;\n"
23616             "} // namespace Averyveryveryverylongnamespace",
23617             format("namespace Averyveryveryverylongnamespace {\n"
23618                    "int i;\n"
23619                    "int j;\n"
23620                    "}",
23621                    Style));
23622 
23623   EXPECT_EQ(
23624       "namespace "
23625       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23626       "    went::mad::now {\n"
23627       "int i;\n"
23628       "int j;\n"
23629       "} // namespace\n"
23630       "  // "
23631       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23632       "went::mad::now",
23633       format("namespace "
23634              "would::it::save::you::a::lot::of::time::if_::i::"
23635              "just::gave::up::and_::went::mad::now {\n"
23636              "int i;\n"
23637              "int j;\n"
23638              "}",
23639              Style));
23640 
23641   // This used to duplicate the comment again and again on subsequent runs
23642   EXPECT_EQ(
23643       "namespace "
23644       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23645       "    went::mad::now {\n"
23646       "int i;\n"
23647       "int j;\n"
23648       "} // namespace\n"
23649       "  // "
23650       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23651       "went::mad::now",
23652       format("namespace "
23653              "would::it::save::you::a::lot::of::time::if_::i::"
23654              "just::gave::up::and_::went::mad::now {\n"
23655              "int i;\n"
23656              "int j;\n"
23657              "} // namespace\n"
23658              "  // "
23659              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23660              "and_::went::mad::now",
23661              Style));
23662 }
23663 
23664 TEST_F(FormatTest, LikelyUnlikely) {
23665   FormatStyle Style = getLLVMStyle();
23666 
23667   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23668                "  return 29;\n"
23669                "}",
23670                Style);
23671 
23672   verifyFormat("if (argc > 5) [[likely]] {\n"
23673                "  return 29;\n"
23674                "}",
23675                Style);
23676 
23677   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23678                "  return 29;\n"
23679                "} else [[likely]] {\n"
23680                "  return 42;\n"
23681                "}\n",
23682                Style);
23683 
23684   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23685                "  return 29;\n"
23686                "} else if (argc > 10) [[likely]] {\n"
23687                "  return 99;\n"
23688                "} else {\n"
23689                "  return 42;\n"
23690                "}\n",
23691                Style);
23692 
23693   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23694                "  return 29;\n"
23695                "}",
23696                Style);
23697 
23698   verifyFormat("if (argc > 5) [[unlikely]]\n"
23699                "  return 29;\n",
23700                Style);
23701   verifyFormat("if (argc > 5) [[likely]]\n"
23702                "  return 29;\n",
23703                Style);
23704 
23705   Style.AttributeMacros.push_back("UNLIKELY");
23706   Style.AttributeMacros.push_back("LIKELY");
23707   verifyFormat("if (argc > 5) UNLIKELY\n"
23708                "  return 29;\n",
23709                Style);
23710 
23711   verifyFormat("if (argc > 5) UNLIKELY {\n"
23712                "  return 29;\n"
23713                "}",
23714                Style);
23715   verifyFormat("if (argc > 5) UNLIKELY {\n"
23716                "  return 29;\n"
23717                "} else [[likely]] {\n"
23718                "  return 42;\n"
23719                "}\n",
23720                Style);
23721   verifyFormat("if (argc > 5) UNLIKELY {\n"
23722                "  return 29;\n"
23723                "} else LIKELY {\n"
23724                "  return 42;\n"
23725                "}\n",
23726                Style);
23727   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23728                "  return 29;\n"
23729                "} else LIKELY {\n"
23730                "  return 42;\n"
23731                "}\n",
23732                Style);
23733 }
23734 
23735 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23736   verifyFormat("Constructor()\n"
23737                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23738                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
23739                "aaaaaaaaaaaaaaaaaat))");
23740   verifyFormat("Constructor()\n"
23741                "    : aaaaaaaaaaaaa(aaaaaa), "
23742                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
23743 
23744   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
23745   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
23746   verifyFormat("Constructor()\n"
23747                "    : aaaaaa(aaaaaa),\n"
23748                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23749                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
23750                StyleWithWhitespacePenalty);
23751   verifyFormat("Constructor()\n"
23752                "    : aaaaaaaaaaaaa(aaaaaa), "
23753                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
23754                StyleWithWhitespacePenalty);
23755 }
23756 
23757 TEST_F(FormatTest, LLVMDefaultStyle) {
23758   FormatStyle Style = getLLVMStyle();
23759   verifyFormat("extern \"C\" {\n"
23760                "int foo();\n"
23761                "}",
23762                Style);
23763 }
23764 TEST_F(FormatTest, GNUDefaultStyle) {
23765   FormatStyle Style = getGNUStyle();
23766   verifyFormat("extern \"C\"\n"
23767                "{\n"
23768                "  int foo ();\n"
23769                "}",
23770                Style);
23771 }
23772 TEST_F(FormatTest, MozillaDefaultStyle) {
23773   FormatStyle Style = getMozillaStyle();
23774   verifyFormat("extern \"C\"\n"
23775                "{\n"
23776                "  int foo();\n"
23777                "}",
23778                Style);
23779 }
23780 TEST_F(FormatTest, GoogleDefaultStyle) {
23781   FormatStyle Style = getGoogleStyle();
23782   verifyFormat("extern \"C\" {\n"
23783                "int foo();\n"
23784                "}",
23785                Style);
23786 }
23787 TEST_F(FormatTest, ChromiumDefaultStyle) {
23788   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
23789   verifyFormat("extern \"C\" {\n"
23790                "int foo();\n"
23791                "}",
23792                Style);
23793 }
23794 TEST_F(FormatTest, MicrosoftDefaultStyle) {
23795   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
23796   verifyFormat("extern \"C\"\n"
23797                "{\n"
23798                "    int foo();\n"
23799                "}",
23800                Style);
23801 }
23802 TEST_F(FormatTest, WebKitDefaultStyle) {
23803   FormatStyle Style = getWebKitStyle();
23804   verifyFormat("extern \"C\" {\n"
23805                "int foo();\n"
23806                "}",
23807                Style);
23808 }
23809 
23810 TEST_F(FormatTest, Concepts) {
23811   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
23812             FormatStyle::BBCDS_Always);
23813   verifyFormat("template <typename T>\n"
23814                "concept True = true;");
23815 
23816   verifyFormat("template <typename T>\n"
23817                "concept C = ((false || foo()) && C2<T>) ||\n"
23818                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
23819                getLLVMStyleWithColumns(60));
23820 
23821   verifyFormat("template <typename T>\n"
23822                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
23823                "sizeof(T) <= 8;");
23824 
23825   verifyFormat("template <typename T>\n"
23826                "concept DelayedCheck = true && requires(T t) {\n"
23827                "                                 t.bar();\n"
23828                "                                 t.baz();\n"
23829                "                               } && sizeof(T) <= 8;");
23830 
23831   verifyFormat("template <typename T>\n"
23832                "concept DelayedCheck = true && requires(T t) { // Comment\n"
23833                "                                 t.bar();\n"
23834                "                                 t.baz();\n"
23835                "                               } && sizeof(T) <= 8;");
23836 
23837   verifyFormat("template <typename T>\n"
23838                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
23839                "sizeof(T) <= 8;");
23840 
23841   verifyFormat("template <typename T>\n"
23842                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
23843                "&& sizeof(T) <= 8;");
23844 
23845   verifyFormat(
23846       "template <typename T>\n"
23847       "concept DelayedCheck = static_cast<bool>(0) ||\n"
23848       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23849 
23850   verifyFormat("template <typename T>\n"
23851                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
23852                "&& sizeof(T) <= 8;");
23853 
23854   verifyFormat(
23855       "template <typename T>\n"
23856       "concept DelayedCheck = (bool)(0) ||\n"
23857       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23858 
23859   verifyFormat("template <typename T>\n"
23860                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
23861                "&& sizeof(T) <= 8;");
23862 
23863   verifyFormat("template <typename T>\n"
23864                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
23865                "sizeof(T) <= 8;");
23866 
23867   verifyFormat("template <typename T>\n"
23868                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
23869                "               requires(T t) {\n"
23870                "                 t.bar();\n"
23871                "                 t.baz();\n"
23872                "               } && sizeof(T) <= 8 && !(4 < 3);",
23873                getLLVMStyleWithColumns(60));
23874 
23875   verifyFormat("template <typename T>\n"
23876                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
23877 
23878   verifyFormat("template <typename T>\n"
23879                "concept C = foo();");
23880 
23881   verifyFormat("template <typename T>\n"
23882                "concept C = foo(T());");
23883 
23884   verifyFormat("template <typename T>\n"
23885                "concept C = foo(T{});");
23886 
23887   verifyFormat("template <typename T>\n"
23888                "concept Size = V<sizeof(T)>::Value > 5;");
23889 
23890   verifyFormat("template <typename T>\n"
23891                "concept True = S<T>::Value;");
23892 
23893   verifyFormat(
23894       "template <typename T>\n"
23895       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
23896       "            sizeof(T) <= 8;");
23897 
23898   // FIXME: This is misformatted because the fake l paren starts at bool, not at
23899   // the lambda l square.
23900   verifyFormat("template <typename T>\n"
23901                "concept C = [] -> bool { return true; }() && requires(T t) { "
23902                "t.bar(); } &&\n"
23903                "                      sizeof(T) <= 8;");
23904 
23905   verifyFormat(
23906       "template <typename T>\n"
23907       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
23908       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23909 
23910   verifyFormat("template <typename T>\n"
23911                "concept C = decltype([]() { return std::true_type{}; "
23912                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
23913                getLLVMStyleWithColumns(120));
23914 
23915   verifyFormat("template <typename T>\n"
23916                "concept C = decltype([]() -> std::true_type { return {}; "
23917                "}())::value &&\n"
23918                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23919 
23920   verifyFormat("template <typename T>\n"
23921                "concept C = true;\n"
23922                "Foo Bar;");
23923 
23924   verifyFormat("template <typename T>\n"
23925                "concept Hashable = requires(T a) {\n"
23926                "                     { std::hash<T>{}(a) } -> "
23927                "std::convertible_to<std::size_t>;\n"
23928                "                   };");
23929 
23930   verifyFormat(
23931       "template <typename T>\n"
23932       "concept EqualityComparable = requires(T a, T b) {\n"
23933       "                               { a == b } -> std::same_as<bool>;\n"
23934       "                             };");
23935 
23936   verifyFormat(
23937       "template <typename T>\n"
23938       "concept EqualityComparable = requires(T a, T b) {\n"
23939       "                               { a == b } -> std::same_as<bool>;\n"
23940       "                               { a != b } -> std::same_as<bool>;\n"
23941       "                             };");
23942 
23943   verifyFormat("template <typename T>\n"
23944                "concept WeakEqualityComparable = requires(T a, T b) {\n"
23945                "                                   { a == b };\n"
23946                "                                   { a != b };\n"
23947                "                                 };");
23948 
23949   verifyFormat("template <typename T>\n"
23950                "concept HasSizeT = requires { typename T::size_t; };");
23951 
23952   verifyFormat("template <typename T>\n"
23953                "concept Semiregular =\n"
23954                "    DefaultConstructible<T> && CopyConstructible<T> && "
23955                "CopyAssignable<T> &&\n"
23956                "    requires(T a, std::size_t n) {\n"
23957                "      requires Same<T *, decltype(&a)>;\n"
23958                "      { a.~T() } noexcept;\n"
23959                "      requires Same<T *, decltype(new T)>;\n"
23960                "      requires Same<T *, decltype(new T[n])>;\n"
23961                "      { delete new T; };\n"
23962                "      { delete new T[n]; };\n"
23963                "    };");
23964 
23965   verifyFormat("template <typename T>\n"
23966                "concept Semiregular =\n"
23967                "    requires(T a, std::size_t n) {\n"
23968                "      requires Same<T *, decltype(&a)>;\n"
23969                "      { a.~T() } noexcept;\n"
23970                "      requires Same<T *, decltype(new T)>;\n"
23971                "      requires Same<T *, decltype(new T[n])>;\n"
23972                "      { delete new T; };\n"
23973                "      { delete new T[n]; };\n"
23974                "      { new T } -> std::same_as<T *>;\n"
23975                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
23976                "CopyAssignable<T>;");
23977 
23978   verifyFormat(
23979       "template <typename T>\n"
23980       "concept Semiregular =\n"
23981       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
23982       "                                 requires Same<T *, decltype(&a)>;\n"
23983       "                                 { a.~T() } noexcept;\n"
23984       "                                 requires Same<T *, decltype(new T)>;\n"
23985       "                                 requires Same<T *, decltype(new "
23986       "T[n])>;\n"
23987       "                                 { delete new T; };\n"
23988       "                                 { delete new T[n]; };\n"
23989       "                               } && CopyConstructible<T> && "
23990       "CopyAssignable<T>;");
23991 
23992   verifyFormat("template <typename T>\n"
23993                "concept Two = requires(T t) {\n"
23994                "                { t.foo() } -> std::same_as<Bar>;\n"
23995                "              } && requires(T &&t) {\n"
23996                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
23997                "                   };");
23998 
23999   verifyFormat(
24000       "template <typename T>\n"
24001       "concept C = requires(T x) {\n"
24002       "              { *x } -> std::convertible_to<typename T::inner>;\n"
24003       "              { x + 1 } noexcept -> std::same_as<int>;\n"
24004       "              { x * 1 } -> std::convertible_to<T>;\n"
24005       "            };");
24006 
24007   verifyFormat(
24008       "template <typename T, typename U = T>\n"
24009       "concept Swappable = requires(T &&t, U &&u) {\n"
24010       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
24011       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
24012       "                    };");
24013 
24014   verifyFormat("template <typename T, typename U>\n"
24015                "concept Common = requires(T &&t, U &&u) {\n"
24016                "                   typename CommonType<T, U>;\n"
24017                "                   { CommonType<T, U>(std::forward<T>(t)) };\n"
24018                "                 };");
24019 
24020   verifyFormat("template <typename T, typename U>\n"
24021                "concept Common = requires(T &&t, U &&u) {\n"
24022                "                   typename CommonType<T, U>;\n"
24023                "                   { CommonType<T, U>{std::forward<T>(t)} };\n"
24024                "                 };");
24025 
24026   verifyFormat(
24027       "template <typename T>\n"
24028       "concept C = requires(T t) {\n"
24029       "              requires Bar<T> && Foo<T>;\n"
24030       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24031       "            };");
24032 
24033   verifyFormat("template <typename T>\n"
24034                "concept HasFoo = requires(T t) {\n"
24035                "                   { t.foo() };\n"
24036                "                   t.foo();\n"
24037                "                 };\n"
24038                "template <typename T>\n"
24039                "concept HasBar = requires(T t) {\n"
24040                "                   { t.bar() };\n"
24041                "                   t.bar();\n"
24042                "                 };");
24043 
24044   verifyFormat("template <typename T>\n"
24045                "concept Large = sizeof(T) > 10;");
24046 
24047   verifyFormat("template <typename T, typename U>\n"
24048                "concept FooableWith = requires(T t, U u) {\n"
24049                "                        typename T::foo_type;\n"
24050                "                        { t.foo(u) } -> typename T::foo_type;\n"
24051                "                        t++;\n"
24052                "                      };\n"
24053                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
24054 
24055   verifyFormat("template <typename T>\n"
24056                "concept Context = is_specialization_of_v<context, T>;");
24057 
24058   verifyFormat("template <typename T>\n"
24059                "concept Node = std::is_object_v<T>;");
24060 
24061   verifyFormat("template <class T>\n"
24062                "concept integral = __is_integral(T);");
24063 
24064   verifyFormat("template <class T>\n"
24065                "concept is2D = __array_extent(T, 1) == 2;");
24066 
24067   verifyFormat("template <class T>\n"
24068                "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
24069 
24070   verifyFormat("template <class T, class T2>\n"
24071                "concept Same = __is_same_as<T, T2>;");
24072 
24073   auto Style = getLLVMStyle();
24074   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
24075 
24076   verifyFormat(
24077       "template <typename T>\n"
24078       "concept C = requires(T t) {\n"
24079       "              requires Bar<T> && Foo<T>;\n"
24080       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24081       "            };",
24082       Style);
24083 
24084   verifyFormat("template <typename T>\n"
24085                "concept HasFoo = requires(T t) {\n"
24086                "                   { t.foo() };\n"
24087                "                   t.foo();\n"
24088                "                 };\n"
24089                "template <typename T>\n"
24090                "concept HasBar = requires(T t) {\n"
24091                "                   { t.bar() };\n"
24092                "                   t.bar();\n"
24093                "                 };",
24094                Style);
24095 
24096   verifyFormat("template <typename T> concept True = true;", Style);
24097 
24098   verifyFormat("template <typename T>\n"
24099                "concept C = decltype([]() -> std::true_type { return {}; "
24100                "}())::value &&\n"
24101                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24102                Style);
24103 
24104   verifyFormat("template <typename T>\n"
24105                "concept Semiregular =\n"
24106                "    DefaultConstructible<T> && CopyConstructible<T> && "
24107                "CopyAssignable<T> &&\n"
24108                "    requires(T a, std::size_t n) {\n"
24109                "      requires Same<T *, decltype(&a)>;\n"
24110                "      { a.~T() } noexcept;\n"
24111                "      requires Same<T *, decltype(new T)>;\n"
24112                "      requires Same<T *, decltype(new T[n])>;\n"
24113                "      { delete new T; };\n"
24114                "      { delete new T[n]; };\n"
24115                "    };",
24116                Style);
24117 
24118   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
24119 
24120   verifyFormat("template <typename T> concept C =\n"
24121                "    requires(T t) {\n"
24122                "      requires Bar<T> && Foo<T>;\n"
24123                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24124                "    };",
24125                Style);
24126 
24127   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
24128                "                                         { t.foo() };\n"
24129                "                                         t.foo();\n"
24130                "                                       };\n"
24131                "template <typename T> concept HasBar = requires(T t) {\n"
24132                "                                         { t.bar() };\n"
24133                "                                         t.bar();\n"
24134                "                                       };",
24135                Style);
24136 
24137   verifyFormat("template <typename T> concept True = true;", Style);
24138 
24139   verifyFormat(
24140       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
24141       "                                    return {};\n"
24142       "                                  }())::value &&\n"
24143       "                                  requires(T t) { t.bar(); } && "
24144       "sizeof(T) <= 8;",
24145       Style);
24146 
24147   verifyFormat("template <typename T> concept Semiregular =\n"
24148                "    DefaultConstructible<T> && CopyConstructible<T> && "
24149                "CopyAssignable<T> &&\n"
24150                "    requires(T a, std::size_t n) {\n"
24151                "      requires Same<T *, decltype(&a)>;\n"
24152                "      { a.~T() } noexcept;\n"
24153                "      requires Same<T *, decltype(new T)>;\n"
24154                "      requires Same<T *, decltype(new T[n])>;\n"
24155                "      { delete new T; };\n"
24156                "      { delete new T[n]; };\n"
24157                "    };",
24158                Style);
24159 
24160   // The following tests are invalid C++, we just want to make sure we don't
24161   // assert.
24162   verifyFormat("template <typename T>\n"
24163                "concept C = requires C2<T>;");
24164 
24165   verifyFormat("template <typename T>\n"
24166                "concept C = 5 + 4;");
24167 
24168   verifyFormat("template <typename T>\n"
24169                "concept C =\n"
24170                "class X;");
24171 
24172   verifyFormat("template <typename T>\n"
24173                "concept C = [] && true;");
24174 
24175   verifyFormat("template <typename T>\n"
24176                "concept C = [] && requires(T t) { typename T::size_type; };");
24177 }
24178 
24179 TEST_F(FormatTest, RequiresClausesPositions) {
24180   auto Style = getLLVMStyle();
24181   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
24182   EXPECT_EQ(Style.IndentRequiresClause, true);
24183 
24184   verifyFormat("template <typename T>\n"
24185                "  requires(Foo<T> && std::trait<T>)\n"
24186                "struct Bar;",
24187                Style);
24188 
24189   verifyFormat("template <typename T>\n"
24190                "  requires(Foo<T> && std::trait<T>)\n"
24191                "class Bar {\n"
24192                "public:\n"
24193                "  Bar(T t);\n"
24194                "  bool baz();\n"
24195                "};",
24196                Style);
24197 
24198   verifyFormat(
24199       "template <typename T>\n"
24200       "  requires requires(T &&t) {\n"
24201       "             typename T::I;\n"
24202       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
24203       "           }\n"
24204       "Bar(T) -> Bar<typename T::I>;",
24205       Style);
24206 
24207   verifyFormat("template <typename T>\n"
24208                "  requires(Foo<T> && std::trait<T>)\n"
24209                "constexpr T MyGlobal;",
24210                Style);
24211 
24212   verifyFormat("template <typename T>\n"
24213                "  requires Foo<T> && requires(T t) {\n"
24214                "                       { t.baz() } -> std::same_as<bool>;\n"
24215                "                       requires std::same_as<T::Factor, int>;\n"
24216                "                     }\n"
24217                "inline int bar(T t) {\n"
24218                "  return t.baz() ? T::Factor : 5;\n"
24219                "}",
24220                Style);
24221 
24222   verifyFormat("template <typename T>\n"
24223                "inline int bar(T t)\n"
24224                "  requires Foo<T> && requires(T t) {\n"
24225                "                       { t.baz() } -> std::same_as<bool>;\n"
24226                "                       requires std::same_as<T::Factor, int>;\n"
24227                "                     }\n"
24228                "{\n"
24229                "  return t.baz() ? T::Factor : 5;\n"
24230                "}",
24231                Style);
24232 
24233   verifyFormat("template <typename T>\n"
24234                "  requires F<T>\n"
24235                "int bar(T t) {\n"
24236                "  return 5;\n"
24237                "}",
24238                Style);
24239 
24240   verifyFormat("template <typename T>\n"
24241                "int bar(T t)\n"
24242                "  requires F<T>\n"
24243                "{\n"
24244                "  return 5;\n"
24245                "}",
24246                Style);
24247 
24248   verifyFormat("template <typename T>\n"
24249                "int bar(T t)\n"
24250                "  requires F<T>;",
24251                Style);
24252 
24253   Style.IndentRequiresClause = false;
24254   verifyFormat("template <typename T>\n"
24255                "requires F<T>\n"
24256                "int bar(T t) {\n"
24257                "  return 5;\n"
24258                "}",
24259                Style);
24260 
24261   verifyFormat("template <typename T>\n"
24262                "int bar(T t)\n"
24263                "requires F<T>\n"
24264                "{\n"
24265                "  return 5;\n"
24266                "}",
24267                Style);
24268 
24269   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
24270   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
24271                "template <typename T> requires Foo<T> void bar() {}\n"
24272                "template <typename T> void bar() requires Foo<T> {}\n"
24273                "template <typename T> void bar() requires Foo<T>;\n"
24274                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
24275                Style);
24276 
24277   auto ColumnStyle = Style;
24278   ColumnStyle.ColumnLimit = 40;
24279   verifyFormat("template <typename AAAAAAA>\n"
24280                "requires Foo<T> struct Bar {};\n"
24281                "template <typename AAAAAAA>\n"
24282                "requires Foo<T> void bar() {}\n"
24283                "template <typename AAAAAAA>\n"
24284                "void bar() requires Foo<T> {}\n"
24285                "template <typename AAAAAAA>\n"
24286                "requires Foo<T> Baz(T) -> Baz<T>;",
24287                ColumnStyle);
24288 
24289   verifyFormat("template <typename T>\n"
24290                "requires Foo<AAAAAAA> struct Bar {};\n"
24291                "template <typename T>\n"
24292                "requires Foo<AAAAAAA> void bar() {}\n"
24293                "template <typename T>\n"
24294                "void bar() requires Foo<AAAAAAA> {}\n"
24295                "template <typename T>\n"
24296                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
24297                ColumnStyle);
24298 
24299   verifyFormat("template <typename AAAAAAA>\n"
24300                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24301                "struct Bar {};\n"
24302                "template <typename AAAAAAA>\n"
24303                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24304                "void bar() {}\n"
24305                "template <typename AAAAAAA>\n"
24306                "void bar()\n"
24307                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24308                "template <typename AAAAAAA>\n"
24309                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24310                "template <typename AAAAAAA>\n"
24311                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24312                "Bar(T) -> Bar<T>;",
24313                ColumnStyle);
24314 
24315   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24316   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24317 
24318   verifyFormat("template <typename T>\n"
24319                "requires Foo<T> struct Bar {};\n"
24320                "template <typename T>\n"
24321                "requires Foo<T> void bar() {}\n"
24322                "template <typename T>\n"
24323                "void bar()\n"
24324                "requires Foo<T> {}\n"
24325                "template <typename T>\n"
24326                "void bar()\n"
24327                "requires Foo<T>;\n"
24328                "template <typename T>\n"
24329                "requires Foo<T> Bar(T) -> Bar<T>;",
24330                Style);
24331 
24332   verifyFormat("template <typename AAAAAAA>\n"
24333                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24334                "struct Bar {};\n"
24335                "template <typename AAAAAAA>\n"
24336                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24337                "void bar() {}\n"
24338                "template <typename AAAAAAA>\n"
24339                "void bar()\n"
24340                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24341                "template <typename AAAAAAA>\n"
24342                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24343                "template <typename AAAAAAA>\n"
24344                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24345                "Bar(T) -> Bar<T>;",
24346                ColumnStyle);
24347 
24348   Style.IndentRequiresClause = true;
24349   ColumnStyle.IndentRequiresClause = true;
24350 
24351   verifyFormat("template <typename T>\n"
24352                "  requires Foo<T> struct Bar {};\n"
24353                "template <typename T>\n"
24354                "  requires Foo<T> void bar() {}\n"
24355                "template <typename T>\n"
24356                "void bar()\n"
24357                "  requires Foo<T> {}\n"
24358                "template <typename T>\n"
24359                "  requires Foo<T> Bar(T) -> Bar<T>;",
24360                Style);
24361 
24362   verifyFormat("template <typename AAAAAAA>\n"
24363                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24364                "struct Bar {};\n"
24365                "template <typename AAAAAAA>\n"
24366                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24367                "void bar() {}\n"
24368                "template <typename AAAAAAA>\n"
24369                "void bar()\n"
24370                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24371                "template <typename AAAAAAA>\n"
24372                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
24373                "template <typename AAAAAAA>\n"
24374                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24375                "Bar(T) -> Bar<T>;",
24376                ColumnStyle);
24377 
24378   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24379   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24380 
24381   verifyFormat("template <typename T> requires Foo<T>\n"
24382                "struct Bar {};\n"
24383                "template <typename T> requires Foo<T>\n"
24384                "void bar() {}\n"
24385                "template <typename T>\n"
24386                "void bar() requires Foo<T>\n"
24387                "{}\n"
24388                "template <typename T> void bar() requires Foo<T>;\n"
24389                "template <typename T> requires Foo<T>\n"
24390                "Bar(T) -> Bar<T>;",
24391                Style);
24392 
24393   verifyFormat("template <typename AAAAAAA>\n"
24394                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24395                "struct Bar {};\n"
24396                "template <typename AAAAAAA>\n"
24397                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24398                "void bar() {}\n"
24399                "template <typename AAAAAAA>\n"
24400                "void bar()\n"
24401                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24402                "{}\n"
24403                "template <typename AAAAAAA>\n"
24404                "requires Foo<AAAAAAAA>\n"
24405                "Bar(T) -> Bar<T>;\n"
24406                "template <typename AAAAAAA>\n"
24407                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24408                "Bar(T) -> Bar<T>;",
24409                ColumnStyle);
24410 }
24411 
24412 TEST_F(FormatTest, RequiresClauses) {
24413   verifyFormat("struct [[nodiscard]] zero_t {\n"
24414                "  template <class T>\n"
24415                "    requires requires { number_zero_v<T>; }\n"
24416                "  [[nodiscard]] constexpr operator T() const {\n"
24417                "    return number_zero_v<T>;\n"
24418                "  }\n"
24419                "};");
24420 
24421   auto Style = getLLVMStyle();
24422 
24423   verifyFormat(
24424       "template <typename T>\n"
24425       "  requires is_default_constructible_v<hash<T>> and\n"
24426       "           is_copy_constructible_v<hash<T>> and\n"
24427       "           is_move_constructible_v<hash<T>> and\n"
24428       "           is_copy_assignable_v<hash<T>> and "
24429       "is_move_assignable_v<hash<T>> and\n"
24430       "           is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
24431       "           is_callable_v<hash<T>(T)> and\n"
24432       "           is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n"
24433       "           is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n"
24434       "           is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
24435       "struct S {};",
24436       Style);
24437 
24438   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
24439   verifyFormat(
24440       "template <typename T>\n"
24441       "  requires is_default_constructible_v<hash<T>>\n"
24442       "           and is_copy_constructible_v<hash<T>>\n"
24443       "           and is_move_constructible_v<hash<T>>\n"
24444       "           and is_copy_assignable_v<hash<T>> and "
24445       "is_move_assignable_v<hash<T>>\n"
24446       "           and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
24447       "           and is_callable_v<hash<T>(T)>\n"
24448       "           and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n"
24449       "           and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n"
24450       "           and is_same_v<size_t, decltype(hash<T>(declval<const T "
24451       "&>()))>\n"
24452       "struct S {};",
24453       Style);
24454 
24455   // Not a clause, but we once hit an assert.
24456   verifyFormat("#if 0\n"
24457                "#else\n"
24458                "foo();\n"
24459                "#endif\n"
24460                "bar(requires);");
24461 }
24462 
24463 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24464   FormatStyle Style = getLLVMStyle();
24465   StringRef Source = "void Foo::slot() {\n"
24466                      "  unsigned char MyChar = 'x';\n"
24467                      "  emit signal(MyChar);\n"
24468                      "  Q_EMIT signal(MyChar);\n"
24469                      "}";
24470 
24471   EXPECT_EQ(Source, format(Source, Style));
24472 
24473   Style.AlignConsecutiveDeclarations.Enabled = true;
24474   EXPECT_EQ("void Foo::slot() {\n"
24475             "  unsigned char MyChar = 'x';\n"
24476             "  emit          signal(MyChar);\n"
24477             "  Q_EMIT signal(MyChar);\n"
24478             "}",
24479             format(Source, Style));
24480 
24481   Style.StatementAttributeLikeMacros.push_back("emit");
24482   EXPECT_EQ(Source, format(Source, Style));
24483 
24484   Style.StatementAttributeLikeMacros = {};
24485   EXPECT_EQ("void Foo::slot() {\n"
24486             "  unsigned char MyChar = 'x';\n"
24487             "  emit          signal(MyChar);\n"
24488             "  Q_EMIT        signal(MyChar);\n"
24489             "}",
24490             format(Source, Style));
24491 }
24492 
24493 TEST_F(FormatTest, IndentAccessModifiers) {
24494   FormatStyle Style = getLLVMStyle();
24495   Style.IndentAccessModifiers = true;
24496   // Members are *two* levels below the record;
24497   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24498   verifyFormat("class C {\n"
24499                "    int i;\n"
24500                "};\n",
24501                Style);
24502   verifyFormat("union C {\n"
24503                "    int i;\n"
24504                "    unsigned u;\n"
24505                "};\n",
24506                Style);
24507   // Access modifiers should be indented one level below the record.
24508   verifyFormat("class C {\n"
24509                "  public:\n"
24510                "    int i;\n"
24511                "};\n",
24512                Style);
24513   verifyFormat("struct S {\n"
24514                "  private:\n"
24515                "    class C {\n"
24516                "        int j;\n"
24517                "\n"
24518                "      public:\n"
24519                "        C();\n"
24520                "    };\n"
24521                "\n"
24522                "  public:\n"
24523                "    int i;\n"
24524                "};\n",
24525                Style);
24526   // Enumerations are not records and should be unaffected.
24527   Style.AllowShortEnumsOnASingleLine = false;
24528   verifyFormat("enum class E {\n"
24529                "  A,\n"
24530                "  B\n"
24531                "};\n",
24532                Style);
24533   // Test with a different indentation width;
24534   // also proves that the result is Style.AccessModifierOffset agnostic.
24535   Style.IndentWidth = 3;
24536   verifyFormat("class C {\n"
24537                "   public:\n"
24538                "      int i;\n"
24539                "};\n",
24540                Style);
24541 }
24542 
24543 TEST_F(FormatTest, LimitlessStringsAndComments) {
24544   auto Style = getLLVMStyleWithColumns(0);
24545   constexpr StringRef Code =
24546       "/**\n"
24547       " * This is a multiline comment with quite some long lines, at least for "
24548       "the LLVM Style.\n"
24549       " * We will redo this with strings and line comments. Just to  check if "
24550       "everything is working.\n"
24551       " */\n"
24552       "bool foo() {\n"
24553       "  /* Single line multi line comment. */\n"
24554       "  const std::string String = \"This is a multiline string with quite "
24555       "some long lines, at least for the LLVM Style.\"\n"
24556       "                             \"We already did it with multi line "
24557       "comments, and we will do it with line comments. Just to check if "
24558       "everything is working.\";\n"
24559       "  // This is a line comment (block) with quite some long lines, at "
24560       "least for the LLVM Style.\n"
24561       "  // We already did this with multi line comments and strings. Just to "
24562       "check if everything is working.\n"
24563       "  const std::string SmallString = \"Hello World\";\n"
24564       "  // Small line comment\n"
24565       "  return String.size() > SmallString.size();\n"
24566       "}";
24567   EXPECT_EQ(Code, format(Code, Style));
24568 }
24569 
24570 TEST_F(FormatTest, FormatDecayCopy) {
24571   // error cases from unit tests
24572   verifyFormat("foo(auto())");
24573   verifyFormat("foo(auto{})");
24574   verifyFormat("foo(auto({}))");
24575   verifyFormat("foo(auto{{}})");
24576 
24577   verifyFormat("foo(auto(1))");
24578   verifyFormat("foo(auto{1})");
24579   verifyFormat("foo(new auto(1))");
24580   verifyFormat("foo(new auto{1})");
24581   verifyFormat("decltype(auto(1)) x;");
24582   verifyFormat("decltype(auto{1}) x;");
24583   verifyFormat("auto(x);");
24584   verifyFormat("auto{x};");
24585   verifyFormat("new auto{x};");
24586   verifyFormat("auto{x} = y;");
24587   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24588                                 // the user's own fault
24589   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24590                                          // clearly the user's own fault
24591   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24592 }
24593 
24594 TEST_F(FormatTest, Cpp20ModulesSupport) {
24595   FormatStyle Style = getLLVMStyle();
24596   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24597   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24598 
24599   verifyFormat("export import foo;", Style);
24600   verifyFormat("export import foo:bar;", Style);
24601   verifyFormat("export import foo.bar;", Style);
24602   verifyFormat("export import foo.bar:baz;", Style);
24603   verifyFormat("export import :bar;", Style);
24604   verifyFormat("export module foo:bar;", Style);
24605   verifyFormat("export module foo;", Style);
24606   verifyFormat("export module foo.bar;", Style);
24607   verifyFormat("export module foo.bar:baz;", Style);
24608   verifyFormat("export import <string_view>;", Style);
24609 
24610   verifyFormat("export type_name var;", Style);
24611   verifyFormat("template <class T> export using A = B<T>;", Style);
24612   verifyFormat("export using A = B;", Style);
24613   verifyFormat("export int func() {\n"
24614                "  foo();\n"
24615                "}",
24616                Style);
24617   verifyFormat("export struct {\n"
24618                "  int foo;\n"
24619                "};",
24620                Style);
24621   verifyFormat("export {\n"
24622                "  int foo;\n"
24623                "};",
24624                Style);
24625   verifyFormat("export export char const *hello() { return \"hello\"; }");
24626 
24627   verifyFormat("import bar;", Style);
24628   verifyFormat("import foo.bar;", Style);
24629   verifyFormat("import foo:bar;", Style);
24630   verifyFormat("import :bar;", Style);
24631   verifyFormat("import <ctime>;", Style);
24632   verifyFormat("import \"header\";", Style);
24633 
24634   verifyFormat("module foo;", Style);
24635   verifyFormat("module foo:bar;", Style);
24636   verifyFormat("module foo.bar;", Style);
24637   verifyFormat("module;", Style);
24638 
24639   verifyFormat("export namespace hi {\n"
24640                "const char *sayhi();\n"
24641                "}",
24642                Style);
24643 
24644   verifyFormat("module :private;", Style);
24645   verifyFormat("import <foo/bar.h>;", Style);
24646   verifyFormat("import foo...bar;", Style);
24647   verifyFormat("import ..........;", Style);
24648   verifyFormat("module foo:private;", Style);
24649   verifyFormat("import a", Style);
24650   verifyFormat("module a", Style);
24651   verifyFormat("export import a", Style);
24652   verifyFormat("export module a", Style);
24653 
24654   verifyFormat("import", Style);
24655   verifyFormat("module", Style);
24656   verifyFormat("export", Style);
24657 }
24658 
24659 TEST_F(FormatTest, CoroutineForCoawait) {
24660   FormatStyle Style = getLLVMStyle();
24661   verifyFormat("for co_await (auto x : range())\n  ;");
24662   verifyFormat("for (auto i : arr) {\n"
24663                "}",
24664                Style);
24665   verifyFormat("for co_await (auto i : arr) {\n"
24666                "}",
24667                Style);
24668   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24669                "}",
24670                Style);
24671 }
24672 
24673 TEST_F(FormatTest, CoroutineCoAwait) {
24674   verifyFormat("int x = co_await foo();");
24675   verifyFormat("int x = (co_await foo());");
24676   verifyFormat("co_await (42);");
24677   verifyFormat("void operator co_await(int);");
24678   verifyFormat("void operator co_await(a);");
24679   verifyFormat("co_await a;");
24680   verifyFormat("co_await missing_await_resume{};");
24681   verifyFormat("co_await a; // comment");
24682   verifyFormat("void test0() { co_await a; }");
24683   verifyFormat("co_await co_await co_await foo();");
24684   verifyFormat("co_await foo().bar();");
24685   verifyFormat("co_await [this]() -> Task { co_return x; }");
24686   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24687                "foo(); }(x, y);");
24688 
24689   FormatStyle Style = getLLVMStyleWithColumns(40);
24690   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24691                "  co_return co_await foo();\n"
24692                "}(x, y);",
24693                Style);
24694   verifyFormat("co_await;");
24695 }
24696 
24697 TEST_F(FormatTest, CoroutineCoYield) {
24698   verifyFormat("int x = co_yield foo();");
24699   verifyFormat("int x = (co_yield foo());");
24700   verifyFormat("co_yield (42);");
24701   verifyFormat("co_yield {42};");
24702   verifyFormat("co_yield 42;");
24703   verifyFormat("co_yield n++;");
24704   verifyFormat("co_yield ++n;");
24705   verifyFormat("co_yield;");
24706 }
24707 
24708 TEST_F(FormatTest, CoroutineCoReturn) {
24709   verifyFormat("co_return (42);");
24710   verifyFormat("co_return;");
24711   verifyFormat("co_return {};");
24712   verifyFormat("co_return x;");
24713   verifyFormat("co_return co_await foo();");
24714   verifyFormat("co_return co_yield foo();");
24715 }
24716 
24717 TEST_F(FormatTest, EmptyShortBlock) {
24718   auto Style = getLLVMStyle();
24719   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24720 
24721   verifyFormat("try {\n"
24722                "  doA();\n"
24723                "} catch (Exception &e) {\n"
24724                "  e.printStackTrace();\n"
24725                "}\n",
24726                Style);
24727 
24728   verifyFormat("try {\n"
24729                "  doA();\n"
24730                "} catch (Exception &e) {}\n",
24731                Style);
24732 }
24733 
24734 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
24735   auto Style = getLLVMStyle();
24736 
24737   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
24738   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
24739   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
24740   verifyFormat("struct Y<[] { return 0; }> {};", Style);
24741 
24742   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
24743   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
24744 }
24745 
24746 TEST_F(FormatTest, InsertBraces) {
24747   FormatStyle Style = getLLVMStyle();
24748   Style.InsertBraces = true;
24749 
24750   verifyFormat("// clang-format off\n"
24751                "// comment\n"
24752                "if (a) f();\n"
24753                "// clang-format on\n"
24754                "if (b) {\n"
24755                "  g();\n"
24756                "}",
24757                "// clang-format off\n"
24758                "// comment\n"
24759                "if (a) f();\n"
24760                "// clang-format on\n"
24761                "if (b) g();",
24762                Style);
24763 
24764   verifyFormat("if (a) {\n"
24765                "  switch (b) {\n"
24766                "  case 1:\n"
24767                "    c = 0;\n"
24768                "    break;\n"
24769                "  default:\n"
24770                "    c = 1;\n"
24771                "  }\n"
24772                "}",
24773                "if (a)\n"
24774                "  switch (b) {\n"
24775                "  case 1:\n"
24776                "    c = 0;\n"
24777                "    break;\n"
24778                "  default:\n"
24779                "    c = 1;\n"
24780                "  }",
24781                Style);
24782 
24783   verifyFormat("for (auto node : nodes) {\n"
24784                "  if (node) {\n"
24785                "    break;\n"
24786                "  }\n"
24787                "}",
24788                "for (auto node : nodes)\n"
24789                "  if (node)\n"
24790                "    break;",
24791                Style);
24792 
24793   verifyFormat("for (auto node : nodes) {\n"
24794                "  if (node)\n"
24795                "}",
24796                "for (auto node : nodes)\n"
24797                "  if (node)",
24798                Style);
24799 
24800   verifyFormat("do {\n"
24801                "  --a;\n"
24802                "} while (a);",
24803                "do\n"
24804                "  --a;\n"
24805                "while (a);",
24806                Style);
24807 
24808   verifyFormat("if (i) {\n"
24809                "  ++i;\n"
24810                "} else {\n"
24811                "  --i;\n"
24812                "}",
24813                "if (i)\n"
24814                "  ++i;\n"
24815                "else {\n"
24816                "  --i;\n"
24817                "}",
24818                Style);
24819 
24820   verifyFormat("void f() {\n"
24821                "  while (j--) {\n"
24822                "    while (i) {\n"
24823                "      --i;\n"
24824                "    }\n"
24825                "  }\n"
24826                "}",
24827                "void f() {\n"
24828                "  while (j--)\n"
24829                "    while (i)\n"
24830                "      --i;\n"
24831                "}",
24832                Style);
24833 
24834   verifyFormat("f({\n"
24835                "  if (a) {\n"
24836                "    g();\n"
24837                "  }\n"
24838                "});",
24839                "f({\n"
24840                "  if (a)\n"
24841                "    g();\n"
24842                "});",
24843                Style);
24844 
24845   verifyFormat("if (a) {\n"
24846                "  f();\n"
24847                "} else if (b) {\n"
24848                "  g();\n"
24849                "} else {\n"
24850                "  h();\n"
24851                "}",
24852                "if (a)\n"
24853                "  f();\n"
24854                "else if (b)\n"
24855                "  g();\n"
24856                "else\n"
24857                "  h();",
24858                Style);
24859 
24860   verifyFormat("if (a) {\n"
24861                "  f();\n"
24862                "}\n"
24863                "// comment\n"
24864                "/* comment */",
24865                "if (a)\n"
24866                "  f();\n"
24867                "// comment\n"
24868                "/* comment */",
24869                Style);
24870 
24871   verifyFormat("if (a) {\n"
24872                "  // foo\n"
24873                "  // bar\n"
24874                "  f();\n"
24875                "}",
24876                "if (a)\n"
24877                "  // foo\n"
24878                "  // bar\n"
24879                "  f();",
24880                Style);
24881 
24882   verifyFormat("if (a) { // comment\n"
24883                "  // comment\n"
24884                "  f();\n"
24885                "}",
24886                "if (a) // comment\n"
24887                "  // comment\n"
24888                "  f();",
24889                Style);
24890 
24891   verifyFormat("if (a) {\n"
24892                "  f(); // comment\n"
24893                "}",
24894                "if (a)\n"
24895                "  f(); // comment",
24896                Style);
24897 
24898   verifyFormat("if (a) {\n"
24899                "  f();\n"
24900                "}\n"
24901                "#undef A\n"
24902                "#undef B",
24903                "if (a)\n"
24904                "  f();\n"
24905                "#undef A\n"
24906                "#undef B",
24907                Style);
24908 
24909   verifyFormat("if (a)\n"
24910                "#ifdef A\n"
24911                "  f();\n"
24912                "#else\n"
24913                "  g();\n"
24914                "#endif",
24915                Style);
24916 
24917   verifyFormat("#if 0\n"
24918                "#elif 1\n"
24919                "#endif\n"
24920                "void f() {\n"
24921                "  if (a) {\n"
24922                "    g();\n"
24923                "  }\n"
24924                "}",
24925                "#if 0\n"
24926                "#elif 1\n"
24927                "#endif\n"
24928                "void f() {\n"
24929                "  if (a) g();\n"
24930                "}",
24931                Style);
24932 
24933   Style.ColumnLimit = 15;
24934 
24935   verifyFormat("#define A     \\\n"
24936                "  if (a)      \\\n"
24937                "    f();",
24938                Style);
24939 
24940   verifyFormat("if (a + b >\n"
24941                "    c) {\n"
24942                "  f();\n"
24943                "}",
24944                "if (a + b > c)\n"
24945                "  f();",
24946                Style);
24947 }
24948 
24949 TEST_F(FormatTest, RemoveBraces) {
24950   FormatStyle Style = getLLVMStyle();
24951   Style.RemoveBracesLLVM = true;
24952 
24953   // The following eight test cases are fully-braced versions of the examples at
24954   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
24955   // statement-bodies-of-if-else-loop-statements".
24956 
24957   // 1. Omit the braces, since the body is simple and clearly associated with
24958   // the if.
24959   verifyFormat("if (isa<FunctionDecl>(D))\n"
24960                "  handleFunctionDecl(D);\n"
24961                "else if (isa<VarDecl>(D))\n"
24962                "  handleVarDecl(D);",
24963                "if (isa<FunctionDecl>(D)) {\n"
24964                "  handleFunctionDecl(D);\n"
24965                "} else if (isa<VarDecl>(D)) {\n"
24966                "  handleVarDecl(D);\n"
24967                "}",
24968                Style);
24969 
24970   // 2. Here we document the condition itself and not the body.
24971   verifyFormat("if (isa<VarDecl>(D)) {\n"
24972                "  // It is necessary that we explain the situation with this\n"
24973                "  // surprisingly long comment, so it would be unclear\n"
24974                "  // without the braces whether the following statement is in\n"
24975                "  // the scope of the `if`.\n"
24976                "  // Because the condition is documented, we can't really\n"
24977                "  // hoist this comment that applies to the body above the\n"
24978                "  // if.\n"
24979                "  handleOtherDecl(D);\n"
24980                "}",
24981                Style);
24982 
24983   // 3. Use braces on the outer `if` to avoid a potential dangling else
24984   // situation.
24985   verifyFormat("if (isa<VarDecl>(D)) {\n"
24986                "  for (auto *A : D.attrs())\n"
24987                "    if (shouldProcessAttr(A))\n"
24988                "      handleAttr(A);\n"
24989                "}",
24990                "if (isa<VarDecl>(D)) {\n"
24991                "  for (auto *A : D.attrs()) {\n"
24992                "    if (shouldProcessAttr(A)) {\n"
24993                "      handleAttr(A);\n"
24994                "    }\n"
24995                "  }\n"
24996                "}",
24997                Style);
24998 
24999   // 4. Use braces for the `if` block to keep it uniform with the else block.
25000   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25001                "  handleFunctionDecl(D);\n"
25002                "} else {\n"
25003                "  // In this else case, it is necessary that we explain the\n"
25004                "  // situation with this surprisingly long comment, so it\n"
25005                "  // would be unclear without the braces whether the\n"
25006                "  // following statement is in the scope of the `if`.\n"
25007                "  handleOtherDecl(D);\n"
25008                "}",
25009                Style);
25010 
25011   // 5. This should also omit braces.  The `for` loop contains only a single
25012   // statement, so it shouldn't have braces.  The `if` also only contains a
25013   // single simple statement (the for loop), so it also should omit braces.
25014   verifyFormat("if (isa<FunctionDecl>(D))\n"
25015                "  for (auto *A : D.attrs())\n"
25016                "    handleAttr(A);",
25017                "if (isa<FunctionDecl>(D)) {\n"
25018                "  for (auto *A : D.attrs()) {\n"
25019                "    handleAttr(A);\n"
25020                "  }\n"
25021                "}",
25022                Style);
25023 
25024   // 6. Use braces for the outer `if` since the nested `for` is braced.
25025   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25026                "  for (auto *A : D.attrs()) {\n"
25027                "    // In this for loop body, it is necessary that we explain\n"
25028                "    // the situation with this surprisingly long comment,\n"
25029                "    // forcing braces on the `for` block.\n"
25030                "    handleAttr(A);\n"
25031                "  }\n"
25032                "}",
25033                Style);
25034 
25035   // 7. Use braces on the outer block because there are more than two levels of
25036   // nesting.
25037   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25038                "  for (auto *A : D.attrs())\n"
25039                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
25040                "      handleAttrOnDecl(D, A, i);\n"
25041                "}",
25042                "if (isa<FunctionDecl>(D)) {\n"
25043                "  for (auto *A : D.attrs()) {\n"
25044                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
25045                "      handleAttrOnDecl(D, A, i);\n"
25046                "    }\n"
25047                "  }\n"
25048                "}",
25049                Style);
25050 
25051   // 8. Use braces on the outer block because of a nested `if`, otherwise the
25052   // compiler would warn: `add explicit braces to avoid dangling else`
25053   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25054                "  if (shouldProcess(D))\n"
25055                "    handleVarDecl(D);\n"
25056                "  else\n"
25057                "    markAsIgnored(D);\n"
25058                "}",
25059                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25060                "  if (shouldProcess(D)) {\n"
25061                "    handleVarDecl(D);\n"
25062                "  } else {\n"
25063                "    markAsIgnored(D);\n"
25064                "  }\n"
25065                "}",
25066                Style);
25067 
25068   verifyFormat("// clang-format off\n"
25069                "// comment\n"
25070                "while (i > 0) { --i; }\n"
25071                "// clang-format on\n"
25072                "while (j < 0)\n"
25073                "  ++j;",
25074                "// clang-format off\n"
25075                "// comment\n"
25076                "while (i > 0) { --i; }\n"
25077                "// clang-format on\n"
25078                "while (j < 0) { ++j; }",
25079                Style);
25080 
25081   verifyFormat("if (a)\n"
25082                "  b; // comment\n"
25083                "else if (c)\n"
25084                "  d; /* comment */\n"
25085                "else\n"
25086                "  e;",
25087                "if (a) {\n"
25088                "  b; // comment\n"
25089                "} else if (c) {\n"
25090                "  d; /* comment */\n"
25091                "} else {\n"
25092                "  e;\n"
25093                "}",
25094                Style);
25095 
25096   verifyFormat("if (a) {\n"
25097                "  b;\n"
25098                "  c;\n"
25099                "} else if (d) {\n"
25100                "  e;\n"
25101                "}",
25102                Style);
25103 
25104   verifyFormat("if (a) {\n"
25105                "#undef NDEBUG\n"
25106                "  b;\n"
25107                "} else {\n"
25108                "  c;\n"
25109                "}",
25110                Style);
25111 
25112   verifyFormat("if (a) {\n"
25113                "  // comment\n"
25114                "} else if (b) {\n"
25115                "  c;\n"
25116                "}",
25117                Style);
25118 
25119   verifyFormat("if (a) {\n"
25120                "  b;\n"
25121                "} else {\n"
25122                "  { c; }\n"
25123                "}",
25124                Style);
25125 
25126   verifyFormat("if (a) {\n"
25127                "  if (b) // comment\n"
25128                "    c;\n"
25129                "} else if (d) {\n"
25130                "  e;\n"
25131                "}",
25132                "if (a) {\n"
25133                "  if (b) { // comment\n"
25134                "    c;\n"
25135                "  }\n"
25136                "} else if (d) {\n"
25137                "  e;\n"
25138                "}",
25139                Style);
25140 
25141   verifyFormat("if (a) {\n"
25142                "  if (b) {\n"
25143                "    c;\n"
25144                "    // comment\n"
25145                "  } else if (d) {\n"
25146                "    e;\n"
25147                "  }\n"
25148                "}",
25149                Style);
25150 
25151   verifyFormat("if (a) {\n"
25152                "  if (b)\n"
25153                "    c;\n"
25154                "}",
25155                "if (a) {\n"
25156                "  if (b) {\n"
25157                "    c;\n"
25158                "  }\n"
25159                "}",
25160                Style);
25161 
25162   verifyFormat("if (a)\n"
25163                "  if (b)\n"
25164                "    c;\n"
25165                "  else\n"
25166                "    d;\n"
25167                "else\n"
25168                "  e;",
25169                "if (a) {\n"
25170                "  if (b) {\n"
25171                "    c;\n"
25172                "  } else {\n"
25173                "    d;\n"
25174                "  }\n"
25175                "} else {\n"
25176                "  e;\n"
25177                "}",
25178                Style);
25179 
25180   verifyFormat("if (a) {\n"
25181                "  // comment\n"
25182                "  if (b)\n"
25183                "    c;\n"
25184                "  else if (d)\n"
25185                "    e;\n"
25186                "} else {\n"
25187                "  g;\n"
25188                "}",
25189                "if (a) {\n"
25190                "  // comment\n"
25191                "  if (b) {\n"
25192                "    c;\n"
25193                "  } else if (d) {\n"
25194                "    e;\n"
25195                "  }\n"
25196                "} else {\n"
25197                "  g;\n"
25198                "}",
25199                Style);
25200 
25201   verifyFormat("if (a)\n"
25202                "  b;\n"
25203                "else if (c)\n"
25204                "  d;\n"
25205                "else\n"
25206                "  e;",
25207                "if (a) {\n"
25208                "  b;\n"
25209                "} else {\n"
25210                "  if (c) {\n"
25211                "    d;\n"
25212                "  } else {\n"
25213                "    e;\n"
25214                "  }\n"
25215                "}",
25216                Style);
25217 
25218   verifyFormat("if (a) {\n"
25219                "  if (b)\n"
25220                "    c;\n"
25221                "  else if (d)\n"
25222                "    e;\n"
25223                "} else {\n"
25224                "  g;\n"
25225                "}",
25226                "if (a) {\n"
25227                "  if (b)\n"
25228                "    c;\n"
25229                "  else {\n"
25230                "    if (d)\n"
25231                "      e;\n"
25232                "  }\n"
25233                "} else {\n"
25234                "  g;\n"
25235                "}",
25236                Style);
25237 
25238   verifyFormat("if (a)\n"
25239                "  b;\n"
25240                "else if (c)\n"
25241                "  while (d)\n"
25242                "    e;\n"
25243                "// comment",
25244                "if (a)\n"
25245                "{\n"
25246                "  b;\n"
25247                "} else if (c) {\n"
25248                "  while (d) {\n"
25249                "    e;\n"
25250                "  }\n"
25251                "}\n"
25252                "// comment",
25253                Style);
25254 
25255   verifyFormat("if (a) {\n"
25256                "  b;\n"
25257                "} else if (c) {\n"
25258                "  d;\n"
25259                "} else {\n"
25260                "  e;\n"
25261                "  g;\n"
25262                "}",
25263                Style);
25264 
25265   verifyFormat("if (a) {\n"
25266                "  b;\n"
25267                "} else if (c) {\n"
25268                "  d;\n"
25269                "} else {\n"
25270                "  e;\n"
25271                "} // comment",
25272                Style);
25273 
25274   verifyFormat("int abs = [](int i) {\n"
25275                "  if (i >= 0)\n"
25276                "    return i;\n"
25277                "  return -i;\n"
25278                "};",
25279                "int abs = [](int i) {\n"
25280                "  if (i >= 0) {\n"
25281                "    return i;\n"
25282                "  }\n"
25283                "  return -i;\n"
25284                "};",
25285                Style);
25286 
25287   verifyFormat("if (a)\n"
25288                "  foo();\n"
25289                "else\n"
25290                "  bar();",
25291                "if (a)\n"
25292                "{\n"
25293                "  foo();\n"
25294                "}\n"
25295                "else\n"
25296                "{\n"
25297                "  bar();\n"
25298                "}",
25299                Style);
25300 
25301   verifyFormat("if (a) {\n"
25302                "Label:\n"
25303                "}",
25304                Style);
25305 
25306   verifyFormat("if (a) {\n"
25307                "Label:\n"
25308                "  f();\n"
25309                "}",
25310                Style);
25311 
25312   verifyFormat("if (a) {\n"
25313                "  f();\n"
25314                "Label:\n"
25315                "}",
25316                Style);
25317 
25318   // FIXME: See https://github.com/llvm/llvm-project/issues/53543.
25319 #if 0
25320   Style.ColumnLimit = 65;
25321 
25322   verifyFormat("if (condition) {\n"
25323                "  ff(Indices,\n"
25324                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25325                "} else {\n"
25326                "  ff(Indices,\n"
25327                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25328                "}",
25329                Style);
25330 
25331   Style.ColumnLimit = 20;
25332 
25333   verifyFormat("if (a) {\n"
25334                "  b = c + // 1 -\n"
25335                "      d;\n"
25336                "}",
25337                Style);
25338 
25339   verifyFormat("if (a) {\n"
25340                "  b = c >= 0 ? d\n"
25341                "             : e;\n"
25342                "}",
25343                "if (a) {\n"
25344                "  b = c >= 0 ? d : e;\n"
25345                "}",
25346                Style);
25347 #endif
25348 
25349   Style.ColumnLimit = 20;
25350 
25351   verifyFormat("if (a)\n"
25352                "  b = c > 0 ? d : e;",
25353                "if (a) {\n"
25354                "  b = c > 0 ? d : e;\n"
25355                "}",
25356                Style);
25357 
25358   Style.ColumnLimit = 0;
25359 
25360   verifyFormat("if (a)\n"
25361                "  b234567890223456789032345678904234567890 = "
25362                "c234567890223456789032345678904234567890;",
25363                "if (a) {\n"
25364                "  b234567890223456789032345678904234567890 = "
25365                "c234567890223456789032345678904234567890;\n"
25366                "}",
25367                Style);
25368 }
25369 
25370 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
25371   auto Style = getLLVMStyle();
25372 
25373   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
25374                     "void functionDecl(int a, int b, int c);";
25375 
25376   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25377                      "paramF, paramG, paramH, paramI);\n"
25378                      "void functionDecl(int argumentA, int argumentB, int "
25379                      "argumentC, int argumentD, int argumentE);";
25380 
25381   verifyFormat(Short, Style);
25382 
25383   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25384                       "paramF, paramG, paramH,\n"
25385                       "             paramI);\n"
25386                       "void functionDecl(int argumentA, int argumentB, int "
25387                       "argumentC, int argumentD,\n"
25388                       "                  int argumentE);";
25389 
25390   verifyFormat(NoBreak, Medium, Style);
25391   verifyFormat(NoBreak,
25392                "functionCall(\n"
25393                "    paramA,\n"
25394                "    paramB,\n"
25395                "    paramC,\n"
25396                "    paramD,\n"
25397                "    paramE,\n"
25398                "    paramF,\n"
25399                "    paramG,\n"
25400                "    paramH,\n"
25401                "    paramI\n"
25402                ");\n"
25403                "void functionDecl(\n"
25404                "    int argumentA,\n"
25405                "    int argumentB,\n"
25406                "    int argumentC,\n"
25407                "    int argumentD,\n"
25408                "    int argumentE\n"
25409                ");",
25410                Style);
25411 
25412   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
25413                "                  nestedLongFunctionCall(argument1, "
25414                "argument2, argument3,\n"
25415                "                                         argument4, "
25416                "argument5));",
25417                Style);
25418 
25419   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25420 
25421   verifyFormat(Short, Style);
25422   verifyFormat(
25423       "functionCall(\n"
25424       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25425       "paramI\n"
25426       ");\n"
25427       "void functionDecl(\n"
25428       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25429       "argumentE\n"
25430       ");",
25431       Medium, Style);
25432 
25433   Style.AllowAllArgumentsOnNextLine = false;
25434   Style.AllowAllParametersOfDeclarationOnNextLine = false;
25435 
25436   verifyFormat(Short, Style);
25437   verifyFormat(
25438       "functionCall(\n"
25439       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25440       "paramI\n"
25441       ");\n"
25442       "void functionDecl(\n"
25443       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25444       "argumentE\n"
25445       ");",
25446       Medium, Style);
25447 
25448   Style.BinPackArguments = false;
25449   Style.BinPackParameters = false;
25450 
25451   verifyFormat(Short, Style);
25452 
25453   verifyFormat("functionCall(\n"
25454                "    paramA,\n"
25455                "    paramB,\n"
25456                "    paramC,\n"
25457                "    paramD,\n"
25458                "    paramE,\n"
25459                "    paramF,\n"
25460                "    paramG,\n"
25461                "    paramH,\n"
25462                "    paramI\n"
25463                ");\n"
25464                "void functionDecl(\n"
25465                "    int argumentA,\n"
25466                "    int argumentB,\n"
25467                "    int argumentC,\n"
25468                "    int argumentD,\n"
25469                "    int argumentE\n"
25470                ");",
25471                Medium, Style);
25472 
25473   verifyFormat("outerFunctionCall(\n"
25474                "    nestedFunctionCall(argument1),\n"
25475                "    nestedLongFunctionCall(\n"
25476                "        argument1,\n"
25477                "        argument2,\n"
25478                "        argument3,\n"
25479                "        argument4,\n"
25480                "        argument5\n"
25481                "    )\n"
25482                ");",
25483                Style);
25484 
25485   verifyFormat("int a = (int)b;", Style);
25486   verifyFormat("int a = (int)b;",
25487                "int a = (\n"
25488                "    int\n"
25489                ") b;",
25490                Style);
25491 
25492   verifyFormat("return (true);", Style);
25493   verifyFormat("return (true);",
25494                "return (\n"
25495                "    true\n"
25496                ");",
25497                Style);
25498 
25499   verifyFormat("void foo();", Style);
25500   verifyFormat("void foo();",
25501                "void foo(\n"
25502                ");",
25503                Style);
25504 
25505   verifyFormat("void foo() {}", Style);
25506   verifyFormat("void foo() {}",
25507                "void foo(\n"
25508                ") {\n"
25509                "}",
25510                Style);
25511 
25512   verifyFormat("auto string = std::string();", Style);
25513   verifyFormat("auto string = std::string();",
25514                "auto string = std::string(\n"
25515                ");",
25516                Style);
25517 
25518   verifyFormat("void (*functionPointer)() = nullptr;", Style);
25519   verifyFormat("void (*functionPointer)() = nullptr;",
25520                "void (\n"
25521                "    *functionPointer\n"
25522                ")\n"
25523                "(\n"
25524                ") = nullptr;",
25525                Style);
25526 }
25527 
25528 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
25529   auto Style = getLLVMStyle();
25530 
25531   verifyFormat("if (foo()) {\n"
25532                "  return;\n"
25533                "}",
25534                Style);
25535 
25536   verifyFormat("if (quitelongarg !=\n"
25537                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25538                "comment\n"
25539                "  return;\n"
25540                "}",
25541                Style);
25542 
25543   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25544 
25545   verifyFormat("if (foo()) {\n"
25546                "  return;\n"
25547                "}",
25548                Style);
25549 
25550   verifyFormat("if (quitelongarg !=\n"
25551                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25552                "comment\n"
25553                "  return;\n"
25554                "}",
25555                Style);
25556 }
25557 
25558 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
25559   auto Style = getLLVMStyle();
25560 
25561   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25562                "  doSomething();\n"
25563                "}",
25564                Style);
25565 
25566   verifyFormat("for (int myReallyLongCountVariable = 0; "
25567                "myReallyLongCountVariable < count;\n"
25568                "     myReallyLongCountVariable++) {\n"
25569                "  doSomething();\n"
25570                "}",
25571                Style);
25572 
25573   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25574 
25575   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25576                "  doSomething();\n"
25577                "}",
25578                Style);
25579 
25580   verifyFormat("for (int myReallyLongCountVariable = 0; "
25581                "myReallyLongCountVariable < count;\n"
25582                "     myReallyLongCountVariable++) {\n"
25583                "  doSomething();\n"
25584                "}",
25585                Style);
25586 }
25587 
25588 TEST_F(FormatTest, UnderstandsDigraphs) {
25589   verifyFormat("int arr<:5:> = {};");
25590   verifyFormat("int arr[5] = <%%>;");
25591   verifyFormat("int arr<:::qualified_variable:> = {};");
25592   verifyFormat("int arr[::qualified_variable] = <%%>;");
25593   verifyFormat("%:include <header>");
25594   verifyFormat("%:define A x##y");
25595   verifyFormat("#define A x%:%:y");
25596 }
25597 
25598 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
25599   auto Style = getLLVMStyle();
25600   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
25601   Style.AlignConsecutiveAssignments.Enabled = true;
25602   Style.AlignConsecutiveDeclarations.Enabled = true;
25603 
25604   // The AlignArray code is incorrect for non square Arrays and can cause
25605   // crashes, these tests assert that the array is not changed but will
25606   // also act as regression tests for when it is properly fixed
25607   verifyFormat("struct test demo[] = {\n"
25608                "    {1, 2},\n"
25609                "    {3, 4, 5},\n"
25610                "    {6, 7, 8}\n"
25611                "};",
25612                Style);
25613   verifyFormat("struct test demo[] = {\n"
25614                "    {1, 2, 3, 4, 5},\n"
25615                "    {3, 4, 5},\n"
25616                "    {6, 7, 8}\n"
25617                "};",
25618                Style);
25619   verifyFormat("struct test demo[] = {\n"
25620                "    {1, 2, 3, 4, 5},\n"
25621                "    {3, 4, 5},\n"
25622                "    {6, 7, 8, 9, 10, 11, 12}\n"
25623                "};",
25624                Style);
25625   verifyFormat("struct test demo[] = {\n"
25626                "    {1, 2, 3},\n"
25627                "    {3, 4, 5},\n"
25628                "    {6, 7, 8, 9, 10, 11, 12}\n"
25629                "};",
25630                Style);
25631 
25632   verifyFormat("S{\n"
25633                "    {},\n"
25634                "    {},\n"
25635                "    {a, b}\n"
25636                "};",
25637                Style);
25638   verifyFormat("S{\n"
25639                "    {},\n"
25640                "    {},\n"
25641                "    {a, b},\n"
25642                "};",
25643                Style);
25644   verifyFormat("void foo() {\n"
25645                "  auto thing = test{\n"
25646                "      {\n"
25647                "       {13}, {something}, // A\n"
25648                "      }\n"
25649                "  };\n"
25650                "}",
25651                "void foo() {\n"
25652                "  auto thing = test{\n"
25653                "      {\n"
25654                "       {13},\n"
25655                "       {something}, // A\n"
25656                "      }\n"
25657                "  };\n"
25658                "}",
25659                Style);
25660 }
25661 
25662 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
25663   auto Style = getLLVMStyle();
25664   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
25665   Style.AlignConsecutiveAssignments.Enabled = true;
25666   Style.AlignConsecutiveDeclarations.Enabled = true;
25667 
25668   // The AlignArray code is incorrect for non square Arrays and can cause
25669   // crashes, these tests assert that the array is not changed but will
25670   // also act as regression tests for when it is properly fixed
25671   verifyFormat("struct test demo[] = {\n"
25672                "    {1, 2},\n"
25673                "    {3, 4, 5},\n"
25674                "    {6, 7, 8}\n"
25675                "};",
25676                Style);
25677   verifyFormat("struct test demo[] = {\n"
25678                "    {1, 2, 3, 4, 5},\n"
25679                "    {3, 4, 5},\n"
25680                "    {6, 7, 8}\n"
25681                "};",
25682                Style);
25683   verifyFormat("struct test demo[] = {\n"
25684                "    {1, 2, 3, 4, 5},\n"
25685                "    {3, 4, 5},\n"
25686                "    {6, 7, 8, 9, 10, 11, 12}\n"
25687                "};",
25688                Style);
25689   verifyFormat("struct test demo[] = {\n"
25690                "    {1, 2, 3},\n"
25691                "    {3, 4, 5},\n"
25692                "    {6, 7, 8, 9, 10, 11, 12}\n"
25693                "};",
25694                Style);
25695 
25696   verifyFormat("S{\n"
25697                "    {},\n"
25698                "    {},\n"
25699                "    {a, b}\n"
25700                "};",
25701                Style);
25702   verifyFormat("S{\n"
25703                "    {},\n"
25704                "    {},\n"
25705                "    {a, b},\n"
25706                "};",
25707                Style);
25708   verifyFormat("void foo() {\n"
25709                "  auto thing = test{\n"
25710                "      {\n"
25711                "       {13}, {something}, // A\n"
25712                "      }\n"
25713                "  };\n"
25714                "}",
25715                "void foo() {\n"
25716                "  auto thing = test{\n"
25717                "      {\n"
25718                "       {13},\n"
25719                "       {something}, // A\n"
25720                "      }\n"
25721                "  };\n"
25722                "}",
25723                Style);
25724 }
25725 
25726 TEST_F(FormatTest, FormatsVariableTemplates) {
25727   verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
25728   verifyFormat("template <typename T> "
25729                "inline bool var = is_integral_v<T> && is_signed_v<T>;");
25730 }
25731 
25732 } // namespace
25733 } // namespace format
25734 } // namespace clang
25735