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 
9758   verifyFormat("a-- > b;");
9759   verifyFormat("b ? -a : c;");
9760   verifyFormat("n * sizeof char16;");
9761   verifyFormat("n * alignof char16;", getGoogleStyle());
9762   verifyFormat("sizeof(char);");
9763   verifyFormat("alignof(char);", getGoogleStyle());
9764 
9765   verifyFormat("return -1;");
9766   verifyFormat("throw -1;");
9767   verifyFormat("switch (a) {\n"
9768                "case -1:\n"
9769                "  break;\n"
9770                "}");
9771   verifyFormat("#define X -1");
9772   verifyFormat("#define X -kConstant");
9773 
9774   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9775   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9776 
9777   verifyFormat("int a = /* confusing comment */ -1;");
9778   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9779   verifyFormat("int a = i /* confusing comment */++;");
9780 
9781   verifyFormat("co_yield -1;");
9782   verifyFormat("co_return -1;");
9783 
9784   // Check that * is not treated as a binary operator when we set
9785   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9786   FormatStyle PASLeftStyle = getLLVMStyle();
9787   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9788   verifyFormat("co_return *a;", PASLeftStyle);
9789   verifyFormat("co_await *a;", PASLeftStyle);
9790   verifyFormat("co_yield *a", PASLeftStyle);
9791   verifyFormat("return *a;", PASLeftStyle);
9792 }
9793 
9794 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9795   verifyFormat("if (!aaaaaaaaaa( // break\n"
9796                "        aaaaa)) {\n"
9797                "}");
9798   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9799                "    aaaaa));");
9800   verifyFormat("*aaa = aaaaaaa( // break\n"
9801                "    bbbbbb);");
9802 }
9803 
9804 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9805   verifyFormat("bool operator<();");
9806   verifyFormat("bool operator>();");
9807   verifyFormat("bool operator=();");
9808   verifyFormat("bool operator==();");
9809   verifyFormat("bool operator!=();");
9810   verifyFormat("int operator+();");
9811   verifyFormat("int operator++();");
9812   verifyFormat("int operator++(int) volatile noexcept;");
9813   verifyFormat("bool operator,();");
9814   verifyFormat("bool operator();");
9815   verifyFormat("bool operator()();");
9816   verifyFormat("bool operator[]();");
9817   verifyFormat("operator bool();");
9818   verifyFormat("operator int();");
9819   verifyFormat("operator void *();");
9820   verifyFormat("operator SomeType<int>();");
9821   verifyFormat("operator SomeType<int, int>();");
9822   verifyFormat("operator SomeType<SomeType<int>>();");
9823   verifyFormat("operator< <>();");
9824   verifyFormat("operator<< <>();");
9825   verifyFormat("< <>");
9826 
9827   verifyFormat("void *operator new(std::size_t size);");
9828   verifyFormat("void *operator new[](std::size_t size);");
9829   verifyFormat("void operator delete(void *ptr);");
9830   verifyFormat("void operator delete[](void *ptr);");
9831   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9832                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9833   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9834                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9835 
9836   verifyFormat(
9837       "ostream &operator<<(ostream &OutputStream,\n"
9838       "                    SomeReallyLongType WithSomeReallyLongValue);");
9839   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9840                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9841                "  return left.group < right.group;\n"
9842                "}");
9843   verifyFormat("SomeType &operator=(const SomeType &S);");
9844   verifyFormat("f.template operator()<int>();");
9845 
9846   verifyGoogleFormat("operator void*();");
9847   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9848   verifyGoogleFormat("operator ::A();");
9849 
9850   verifyFormat("using A::operator+;");
9851   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9852                "int i;");
9853 
9854   // Calling an operator as a member function.
9855   verifyFormat("void f() { a.operator*(); }");
9856   verifyFormat("void f() { a.operator*(b & b); }");
9857   verifyFormat("void f() { a->operator&(a * b); }");
9858   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9859   // TODO: Calling an operator as a non-member function is hard to distinguish.
9860   // https://llvm.org/PR50629
9861   // verifyFormat("void f() { operator*(a & a); }");
9862   // verifyFormat("void f() { operator&(a, b * b); }");
9863 
9864   verifyFormat("::operator delete(foo);");
9865   verifyFormat("::operator new(n * sizeof(foo));");
9866   verifyFormat("foo() { ::operator delete(foo); }");
9867   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9868 }
9869 
9870 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9871   verifyFormat("void A::b() && {}");
9872   verifyFormat("void A::b() &&noexcept {}");
9873   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9874   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9875   verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
9876   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9877   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9878   verifyFormat("Deleted &operator=(const Deleted &) &;");
9879   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9880   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9881   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9882   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9883   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9884   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9885   verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
9886   verifyFormat("void Fn(T const &) const &;");
9887   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9888   verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
9889   verifyFormat("template <typename T>\n"
9890                "void F(T) && = delete;",
9891                getGoogleStyle());
9892   verifyFormat("template <typename T> void operator=(T) &;");
9893   verifyFormat("template <typename T> void operator=(T) const &;");
9894   verifyFormat("template <typename T> void operator=(T) &noexcept;");
9895   verifyFormat("template <typename T> void operator=(T) & = default;");
9896   verifyFormat("template <typename T> void operator=(T) &&;");
9897   verifyFormat("template <typename T> void operator=(T) && = delete;");
9898   verifyFormat("template <typename T> void operator=(T) & {}");
9899   verifyFormat("template <typename T> void operator=(T) && {}");
9900 
9901   FormatStyle AlignLeft = getLLVMStyle();
9902   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9903   verifyFormat("void A::b() && {}", AlignLeft);
9904   verifyFormat("void A::b() && noexcept {}", AlignLeft);
9905   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9906   verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
9907                AlignLeft);
9908   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9909                AlignLeft);
9910   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9911   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9912   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9913   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9914   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9915   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9916   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9917   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9918   verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
9919                AlignLeft);
9920   verifyFormat("template <typename T> void operator=(T) &;", AlignLeft);
9921   verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft);
9922   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9923                AlignLeft);
9924   verifyFormat("template <typename T> void operator=(T) & = default;",
9925                AlignLeft);
9926   verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft);
9927   verifyFormat("template <typename T> void operator=(T) && = delete;",
9928                AlignLeft);
9929   verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft);
9930   verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft);
9931 
9932   FormatStyle AlignMiddle = getLLVMStyle();
9933   AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9934   verifyFormat("void A::b() && {}", AlignMiddle);
9935   verifyFormat("void A::b() && noexcept {}", AlignMiddle);
9936   verifyFormat("Deleted & operator=(const Deleted &) & = default;",
9937                AlignMiddle);
9938   verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
9939                AlignMiddle);
9940   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
9941                AlignMiddle);
9942   verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
9943   verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
9944   verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
9945   verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
9946   verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
9947   verifyFormat("auto Function(T) & -> void;", AlignMiddle);
9948   verifyFormat("void Fn(T const &) const &;", AlignMiddle);
9949   verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
9950   verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
9951                AlignMiddle);
9952   verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle);
9953   verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle);
9954   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9955                AlignMiddle);
9956   verifyFormat("template <typename T> void operator=(T) & = default;",
9957                AlignMiddle);
9958   verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle);
9959   verifyFormat("template <typename T> void operator=(T) && = delete;",
9960                AlignMiddle);
9961   verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle);
9962   verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle);
9963 
9964   FormatStyle Spaces = getLLVMStyle();
9965   Spaces.SpacesInCStyleCastParentheses = true;
9966   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9967   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9968   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9969   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9970 
9971   Spaces.SpacesInCStyleCastParentheses = false;
9972   Spaces.SpacesInParentheses = true;
9973   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9974   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9975                Spaces);
9976   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9977   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9978 
9979   FormatStyle BreakTemplate = getLLVMStyle();
9980   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9981 
9982   verifyFormat("struct f {\n"
9983                "  template <class T>\n"
9984                "  int &foo(const std::string &str) &noexcept {}\n"
9985                "};",
9986                BreakTemplate);
9987 
9988   verifyFormat("struct f {\n"
9989                "  template <class T>\n"
9990                "  int &foo(const std::string &str) &&noexcept {}\n"
9991                "};",
9992                BreakTemplate);
9993 
9994   verifyFormat("struct f {\n"
9995                "  template <class T>\n"
9996                "  int &foo(const std::string &str) const &noexcept {}\n"
9997                "};",
9998                BreakTemplate);
9999 
10000   verifyFormat("struct f {\n"
10001                "  template <class T>\n"
10002                "  int &foo(const std::string &str) const &noexcept {}\n"
10003                "};",
10004                BreakTemplate);
10005 
10006   verifyFormat("struct f {\n"
10007                "  template <class T>\n"
10008                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
10009                "};",
10010                BreakTemplate);
10011 
10012   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
10013   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
10014       FormatStyle::BTDS_Yes;
10015   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
10016 
10017   verifyFormat("struct f {\n"
10018                "  template <class T>\n"
10019                "  int& foo(const std::string& str) & noexcept {}\n"
10020                "};",
10021                AlignLeftBreakTemplate);
10022 
10023   verifyFormat("struct f {\n"
10024                "  template <class T>\n"
10025                "  int& foo(const std::string& str) && noexcept {}\n"
10026                "};",
10027                AlignLeftBreakTemplate);
10028 
10029   verifyFormat("struct f {\n"
10030                "  template <class T>\n"
10031                "  int& foo(const std::string& str) const& noexcept {}\n"
10032                "};",
10033                AlignLeftBreakTemplate);
10034 
10035   verifyFormat("struct f {\n"
10036                "  template <class T>\n"
10037                "  int& foo(const std::string& str) const&& noexcept {}\n"
10038                "};",
10039                AlignLeftBreakTemplate);
10040 
10041   verifyFormat("struct f {\n"
10042                "  template <class T>\n"
10043                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
10044                "};",
10045                AlignLeftBreakTemplate);
10046 
10047   // The `&` in `Type&` should not be confused with a trailing `&` of
10048   // DEPRECATED(reason) member function.
10049   verifyFormat("struct f {\n"
10050                "  template <class T>\n"
10051                "  DEPRECATED(reason)\n"
10052                "  Type &foo(arguments) {}\n"
10053                "};",
10054                BreakTemplate);
10055 
10056   verifyFormat("struct f {\n"
10057                "  template <class T>\n"
10058                "  DEPRECATED(reason)\n"
10059                "  Type& foo(arguments) {}\n"
10060                "};",
10061                AlignLeftBreakTemplate);
10062 
10063   verifyFormat("void (*foopt)(int) = &func;");
10064 
10065   FormatStyle DerivePointerAlignment = getLLVMStyle();
10066   DerivePointerAlignment.DerivePointerAlignment = true;
10067   // There's always a space between the function and its trailing qualifiers.
10068   // This isn't evidence for PAS_Right (or for PAS_Left).
10069   std::string Prefix = "void a() &;\n"
10070                        "void b() &;\n";
10071   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10072   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10073   // Same if the function is an overloaded operator, and with &&.
10074   Prefix = "void operator()() &&;\n"
10075            "void operator()() &&;\n";
10076   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10077   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10078   // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
10079   Prefix = "void a() const &;\n"
10080            "void b() const &;\n";
10081   EXPECT_EQ(Prefix + "int *x;",
10082             format(Prefix + "int* x;", DerivePointerAlignment));
10083 }
10084 
10085 TEST_F(FormatTest, UnderstandsNewAndDelete) {
10086   verifyFormat("void f() {\n"
10087                "  A *a = new A;\n"
10088                "  A *a = new (placement) A;\n"
10089                "  delete a;\n"
10090                "  delete (A *)a;\n"
10091                "}");
10092   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10093                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10094   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10095                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10096                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10097   verifyFormat("delete[] h->p;");
10098   verifyFormat("delete[] (void *)p;");
10099 
10100   verifyFormat("void operator delete(void *foo) ATTRIB;");
10101   verifyFormat("void operator new(void *foo) ATTRIB;");
10102   verifyFormat("void operator delete[](void *foo) ATTRIB;");
10103   verifyFormat("void operator delete(void *ptr) noexcept;");
10104 
10105   EXPECT_EQ("void new(link p);\n"
10106             "void delete(link p);\n",
10107             format("void new (link p);\n"
10108                    "void delete (link p);\n"));
10109 }
10110 
10111 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
10112   verifyFormat("int *f(int *a) {}");
10113   verifyFormat("int main(int argc, char **argv) {}");
10114   verifyFormat("Test::Test(int b) : a(b * b) {}");
10115   verifyIndependentOfContext("f(a, *a);");
10116   verifyFormat("void g() { f(*a); }");
10117   verifyIndependentOfContext("int a = b * 10;");
10118   verifyIndependentOfContext("int a = 10 * b;");
10119   verifyIndependentOfContext("int a = b * c;");
10120   verifyIndependentOfContext("int a += b * c;");
10121   verifyIndependentOfContext("int a -= b * c;");
10122   verifyIndependentOfContext("int a *= b * c;");
10123   verifyIndependentOfContext("int a /= b * c;");
10124   verifyIndependentOfContext("int a = *b;");
10125   verifyIndependentOfContext("int a = *b * c;");
10126   verifyIndependentOfContext("int a = b * *c;");
10127   verifyIndependentOfContext("int a = b * (10);");
10128   verifyIndependentOfContext("S << b * (10);");
10129   verifyIndependentOfContext("return 10 * b;");
10130   verifyIndependentOfContext("return *b * *c;");
10131   verifyIndependentOfContext("return a & ~b;");
10132   verifyIndependentOfContext("f(b ? *c : *d);");
10133   verifyIndependentOfContext("int a = b ? *c : *d;");
10134   verifyIndependentOfContext("*b = a;");
10135   verifyIndependentOfContext("a * ~b;");
10136   verifyIndependentOfContext("a * !b;");
10137   verifyIndependentOfContext("a * +b;");
10138   verifyIndependentOfContext("a * -b;");
10139   verifyIndependentOfContext("a * ++b;");
10140   verifyIndependentOfContext("a * --b;");
10141   verifyIndependentOfContext("a[4] * b;");
10142   verifyIndependentOfContext("a[a * a] = 1;");
10143   verifyIndependentOfContext("f() * b;");
10144   verifyIndependentOfContext("a * [self dostuff];");
10145   verifyIndependentOfContext("int x = a * (a + b);");
10146   verifyIndependentOfContext("(a *)(a + b);");
10147   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
10148   verifyIndependentOfContext("int *pa = (int *)&a;");
10149   verifyIndependentOfContext("return sizeof(int **);");
10150   verifyIndependentOfContext("return sizeof(int ******);");
10151   verifyIndependentOfContext("return (int **&)a;");
10152   verifyIndependentOfContext("f((*PointerToArray)[10]);");
10153   verifyFormat("void f(Type (*parameter)[10]) {}");
10154   verifyFormat("void f(Type (&parameter)[10]) {}");
10155   verifyGoogleFormat("return sizeof(int**);");
10156   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
10157   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
10158   verifyFormat("auto a = [](int **&, int ***) {};");
10159   verifyFormat("auto PointerBinding = [](const char *S) {};");
10160   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
10161   verifyFormat("[](const decltype(*a) &value) {}");
10162   verifyFormat("[](const typeof(*a) &value) {}");
10163   verifyFormat("[](const _Atomic(a *) &value) {}");
10164   verifyFormat("[](const __underlying_type(a) &value) {}");
10165   verifyFormat("decltype(a * b) F();");
10166   verifyFormat("typeof(a * b) F();");
10167   verifyFormat("#define MACRO() [](A *a) { return 1; }");
10168   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
10169   verifyIndependentOfContext("typedef void (*f)(int *a);");
10170   verifyIndependentOfContext("int i{a * b};");
10171   verifyIndependentOfContext("aaa && aaa->f();");
10172   verifyIndependentOfContext("int x = ~*p;");
10173   verifyFormat("Constructor() : a(a), area(width * height) {}");
10174   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
10175   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
10176   verifyFormat("void f() { f(a, c * d); }");
10177   verifyFormat("void f() { f(new a(), c * d); }");
10178   verifyFormat("void f(const MyOverride &override);");
10179   verifyFormat("void f(const MyFinal &final);");
10180   verifyIndependentOfContext("bool a = f() && override.f();");
10181   verifyIndependentOfContext("bool a = f() && final.f();");
10182 
10183   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
10184 
10185   verifyIndependentOfContext("A<int *> a;");
10186   verifyIndependentOfContext("A<int **> a;");
10187   verifyIndependentOfContext("A<int *, int *> a;");
10188   verifyIndependentOfContext("A<int *[]> a;");
10189   verifyIndependentOfContext(
10190       "const char *const p = reinterpret_cast<const char *const>(q);");
10191   verifyIndependentOfContext("A<int **, int **> a;");
10192   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
10193   verifyFormat("for (char **a = b; *a; ++a) {\n}");
10194   verifyFormat("for (; a && b;) {\n}");
10195   verifyFormat("bool foo = true && [] { return false; }();");
10196 
10197   verifyFormat(
10198       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10199       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10200 
10201   verifyGoogleFormat("int const* a = &b;");
10202   verifyGoogleFormat("**outparam = 1;");
10203   verifyGoogleFormat("*outparam = a * b;");
10204   verifyGoogleFormat("int main(int argc, char** argv) {}");
10205   verifyGoogleFormat("A<int*> a;");
10206   verifyGoogleFormat("A<int**> a;");
10207   verifyGoogleFormat("A<int*, int*> a;");
10208   verifyGoogleFormat("A<int**, int**> a;");
10209   verifyGoogleFormat("f(b ? *c : *d);");
10210   verifyGoogleFormat("int a = b ? *c : *d;");
10211   verifyGoogleFormat("Type* t = **x;");
10212   verifyGoogleFormat("Type* t = *++*x;");
10213   verifyGoogleFormat("*++*x;");
10214   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
10215   verifyGoogleFormat("Type* t = x++ * y;");
10216   verifyGoogleFormat(
10217       "const char* const p = reinterpret_cast<const char* const>(q);");
10218   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
10219   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
10220   verifyGoogleFormat("template <typename T>\n"
10221                      "void f(int i = 0, SomeType** temps = NULL);");
10222 
10223   FormatStyle Left = getLLVMStyle();
10224   Left.PointerAlignment = FormatStyle::PAS_Left;
10225   verifyFormat("x = *a(x) = *a(y);", Left);
10226   verifyFormat("for (;; *a = b) {\n}", Left);
10227   verifyFormat("return *this += 1;", Left);
10228   verifyFormat("throw *x;", Left);
10229   verifyFormat("delete *x;", Left);
10230   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
10231   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
10232   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
10233   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
10234   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
10235   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
10236   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
10237   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
10238   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
10239 
10240   verifyIndependentOfContext("a = *(x + y);");
10241   verifyIndependentOfContext("a = &(x + y);");
10242   verifyIndependentOfContext("*(x + y).call();");
10243   verifyIndependentOfContext("&(x + y)->call();");
10244   verifyFormat("void f() { &(*I).first; }");
10245 
10246   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
10247   verifyFormat("f(* /* confusing comment */ foo);");
10248   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
10249   verifyFormat("void foo(int * // this is the first paramters\n"
10250                "         ,\n"
10251                "         int second);");
10252   verifyFormat("double term = a * // first\n"
10253                "              b;");
10254   verifyFormat(
10255       "int *MyValues = {\n"
10256       "    *A, // Operator detection might be confused by the '{'\n"
10257       "    *BB // Operator detection might be confused by previous comment\n"
10258       "};");
10259 
10260   verifyIndependentOfContext("if (int *a = &b)");
10261   verifyIndependentOfContext("if (int &a = *b)");
10262   verifyIndependentOfContext("if (a & b[i])");
10263   verifyIndependentOfContext("if constexpr (a & b[i])");
10264   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
10265   verifyIndependentOfContext("if (a * (b * c))");
10266   verifyIndependentOfContext("if constexpr (a * (b * c))");
10267   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
10268   verifyIndependentOfContext("if (a::b::c::d & b[i])");
10269   verifyIndependentOfContext("if (*b[i])");
10270   verifyIndependentOfContext("if (int *a = (&b))");
10271   verifyIndependentOfContext("while (int *a = &b)");
10272   verifyIndependentOfContext("while (a * (b * c))");
10273   verifyIndependentOfContext("size = sizeof *a;");
10274   verifyIndependentOfContext("if (a && (b = c))");
10275   verifyFormat("void f() {\n"
10276                "  for (const int &v : Values) {\n"
10277                "  }\n"
10278                "}");
10279   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
10280   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
10281   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
10282 
10283   verifyFormat("#define A (!a * b)");
10284   verifyFormat("#define MACRO     \\\n"
10285                "  int *i = a * b; \\\n"
10286                "  void f(a *b);",
10287                getLLVMStyleWithColumns(19));
10288 
10289   verifyIndependentOfContext("A = new SomeType *[Length];");
10290   verifyIndependentOfContext("A = new SomeType *[Length]();");
10291   verifyIndependentOfContext("T **t = new T *;");
10292   verifyIndependentOfContext("T **t = new T *();");
10293   verifyGoogleFormat("A = new SomeType*[Length]();");
10294   verifyGoogleFormat("A = new SomeType*[Length];");
10295   verifyGoogleFormat("T** t = new T*;");
10296   verifyGoogleFormat("T** t = new T*();");
10297 
10298   verifyFormat("STATIC_ASSERT((a & b) == 0);");
10299   verifyFormat("STATIC_ASSERT(0 == (a & b));");
10300   verifyFormat("template <bool a, bool b> "
10301                "typename t::if<x && y>::type f() {}");
10302   verifyFormat("template <int *y> f() {}");
10303   verifyFormat("vector<int *> v;");
10304   verifyFormat("vector<int *const> v;");
10305   verifyFormat("vector<int *const **const *> v;");
10306   verifyFormat("vector<int *volatile> v;");
10307   verifyFormat("vector<a *_Nonnull> v;");
10308   verifyFormat("vector<a *_Nullable> v;");
10309   verifyFormat("vector<a *_Null_unspecified> v;");
10310   verifyFormat("vector<a *__ptr32> v;");
10311   verifyFormat("vector<a *__ptr64> v;");
10312   verifyFormat("vector<a *__capability> v;");
10313   FormatStyle TypeMacros = getLLVMStyle();
10314   TypeMacros.TypenameMacros = {"LIST"};
10315   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
10316   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
10317   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
10318   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
10319   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
10320 
10321   FormatStyle CustomQualifier = getLLVMStyle();
10322   // Add identifiers that should not be parsed as a qualifier by default.
10323   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10324   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
10325   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
10326   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
10327   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
10328   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
10329   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
10330   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
10331   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
10332   verifyFormat("vector<a * _NotAQualifier> v;");
10333   verifyFormat("vector<a * __not_a_qualifier> v;");
10334   verifyFormat("vector<a * b> v;");
10335   verifyFormat("foo<b && false>();");
10336   verifyFormat("foo<b & 1>();");
10337   verifyFormat("foo<b & (1)>();");
10338   verifyFormat("foo<b & (~0)>();");
10339   verifyFormat("foo<b & (true)>();");
10340   verifyFormat("foo<b & ((1))>();");
10341   verifyFormat("foo<b & (/*comment*/ 1)>();");
10342   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
10343   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
10344   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
10345   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
10346   verifyFormat(
10347       "template <class T, class = typename std::enable_if<\n"
10348       "                       std::is_integral<T>::value &&\n"
10349       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
10350       "void F();",
10351       getLLVMStyleWithColumns(70));
10352   verifyFormat("template <class T,\n"
10353                "          class = typename std::enable_if<\n"
10354                "              std::is_integral<T>::value &&\n"
10355                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
10356                "          class U>\n"
10357                "void F();",
10358                getLLVMStyleWithColumns(70));
10359   verifyFormat(
10360       "template <class T,\n"
10361       "          class = typename ::std::enable_if<\n"
10362       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
10363       "void F();",
10364       getGoogleStyleWithColumns(68));
10365 
10366   verifyIndependentOfContext("MACRO(int *i);");
10367   verifyIndependentOfContext("MACRO(auto *a);");
10368   verifyIndependentOfContext("MACRO(const A *a);");
10369   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
10370   verifyIndependentOfContext("MACRO(decltype(A) *a);");
10371   verifyIndependentOfContext("MACRO(typeof(A) *a);");
10372   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
10373   verifyIndependentOfContext("MACRO(A *const a);");
10374   verifyIndependentOfContext("MACRO(A *restrict a);");
10375   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
10376   verifyIndependentOfContext("MACRO(A *__restrict a);");
10377   verifyIndependentOfContext("MACRO(A *volatile a);");
10378   verifyIndependentOfContext("MACRO(A *__volatile a);");
10379   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
10380   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
10381   verifyIndependentOfContext("MACRO(A *_Nullable a);");
10382   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
10383   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
10384   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
10385   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
10386   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
10387   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
10388   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
10389   verifyIndependentOfContext("MACRO(A *__capability);");
10390   verifyIndependentOfContext("MACRO(A &__capability);");
10391   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
10392   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
10393   // If we add __my_qualifier to AttributeMacros it should always be parsed as
10394   // a type declaration:
10395   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
10396   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
10397   // Also check that TypenameMacros prevents parsing it as multiplication:
10398   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
10399   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
10400 
10401   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
10402   verifyFormat("void f() { f(float{1}, a * a); }");
10403   verifyFormat("void f() { f(float(1), a * a); }");
10404 
10405   verifyFormat("f((void (*)(int))g);");
10406   verifyFormat("f((void (&)(int))g);");
10407   verifyFormat("f((void (^)(int))g);");
10408 
10409   // FIXME: Is there a way to make this work?
10410   // verifyIndependentOfContext("MACRO(A *a);");
10411   verifyFormat("MACRO(A &B);");
10412   verifyFormat("MACRO(A *B);");
10413   verifyFormat("void f() { MACRO(A * B); }");
10414   verifyFormat("void f() { MACRO(A & B); }");
10415 
10416   // This lambda was mis-formatted after D88956 (treating it as a binop):
10417   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
10418   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
10419   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
10420   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
10421 
10422   verifyFormat("DatumHandle const *operator->() const { return input_; }");
10423   verifyFormat("return options != nullptr && operator==(*options);");
10424 
10425   EXPECT_EQ("#define OP(x)                                    \\\n"
10426             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
10427             "    return s << a.DebugString();                 \\\n"
10428             "  }",
10429             format("#define OP(x) \\\n"
10430                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
10431                    "    return s << a.DebugString(); \\\n"
10432                    "  }",
10433                    getLLVMStyleWithColumns(50)));
10434 
10435   // FIXME: We cannot handle this case yet; we might be able to figure out that
10436   // foo<x> d > v; doesn't make sense.
10437   verifyFormat("foo<a<b && c> d> v;");
10438 
10439   FormatStyle PointerMiddle = getLLVMStyle();
10440   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10441   verifyFormat("delete *x;", PointerMiddle);
10442   verifyFormat("int * x;", PointerMiddle);
10443   verifyFormat("int *[] x;", PointerMiddle);
10444   verifyFormat("template <int * y> f() {}", PointerMiddle);
10445   verifyFormat("int * f(int * a) {}", PointerMiddle);
10446   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
10447   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10448   verifyFormat("A<int *> a;", PointerMiddle);
10449   verifyFormat("A<int **> a;", PointerMiddle);
10450   verifyFormat("A<int *, int *> a;", PointerMiddle);
10451   verifyFormat("A<int *[]> a;", PointerMiddle);
10452   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10453   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10454   verifyFormat("T ** t = new T *;", PointerMiddle);
10455 
10456   // Member function reference qualifiers aren't binary operators.
10457   verifyFormat("string // break\n"
10458                "operator()() & {}");
10459   verifyFormat("string // break\n"
10460                "operator()() && {}");
10461   verifyGoogleFormat("template <typename T>\n"
10462                      "auto x() & -> int {}");
10463 
10464   // Should be binary operators when used as an argument expression (overloaded
10465   // operator invoked as a member function).
10466   verifyFormat("void f() { a.operator()(a * a); }");
10467   verifyFormat("void f() { a->operator()(a & a); }");
10468   verifyFormat("void f() { a.operator()(*a & *a); }");
10469   verifyFormat("void f() { a->operator()(*a * *a); }");
10470 
10471   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10472   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10473 }
10474 
10475 TEST_F(FormatTest, UnderstandsAttributes) {
10476   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10477   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10478                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10479   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10480   FormatStyle AfterType = getLLVMStyle();
10481   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10482   verifyFormat("__attribute__((nodebug)) void\n"
10483                "foo() {}\n",
10484                AfterType);
10485   verifyFormat("__unused void\n"
10486                "foo() {}",
10487                AfterType);
10488 
10489   FormatStyle CustomAttrs = getLLVMStyle();
10490   CustomAttrs.AttributeMacros.push_back("__unused");
10491   CustomAttrs.AttributeMacros.push_back("__attr1");
10492   CustomAttrs.AttributeMacros.push_back("__attr2");
10493   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10494   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10495   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10496   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10497   // Check that it is parsed as a multiplication without AttributeMacros and
10498   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10499   verifyFormat("vector<SomeType * __attr1> v;");
10500   verifyFormat("vector<SomeType __attr1 *> v;");
10501   verifyFormat("vector<SomeType __attr1 *const> v;");
10502   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10503   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10504   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10505   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10506   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10507   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10508   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10509   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10510 
10511   // Check that these are not parsed as function declarations:
10512   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10513   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10514   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10515   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10516   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10517   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10518   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10519   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10520   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10521   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10522 }
10523 
10524 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10525   // Check that qualifiers on pointers don't break parsing of casts.
10526   verifyFormat("x = (foo *const)*v;");
10527   verifyFormat("x = (foo *volatile)*v;");
10528   verifyFormat("x = (foo *restrict)*v;");
10529   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10530   verifyFormat("x = (foo *_Nonnull)*v;");
10531   verifyFormat("x = (foo *_Nullable)*v;");
10532   verifyFormat("x = (foo *_Null_unspecified)*v;");
10533   verifyFormat("x = (foo *_Nonnull)*v;");
10534   verifyFormat("x = (foo *[[clang::attr]])*v;");
10535   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10536   verifyFormat("x = (foo *__ptr32)*v;");
10537   verifyFormat("x = (foo *__ptr64)*v;");
10538   verifyFormat("x = (foo *__capability)*v;");
10539 
10540   // Check that we handle multiple trailing qualifiers and skip them all to
10541   // determine that the expression is a cast to a pointer type.
10542   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10543   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10544   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10545   StringRef AllQualifiers =
10546       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10547       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10548   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10549   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10550 
10551   // Also check that address-of is not parsed as a binary bitwise-and:
10552   verifyFormat("x = (foo *const)&v;");
10553   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10554   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10555 
10556   // Check custom qualifiers:
10557   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10558   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10559   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10560   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10561   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10562                CustomQualifier);
10563   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10564                CustomQualifier);
10565 
10566   // Check that unknown identifiers result in binary operator parsing:
10567   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10568   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10569 }
10570 
10571 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10572   verifyFormat("SomeType s [[unused]] (InitValue);");
10573   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10574   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10575   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10576   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10577   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10578                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10579   verifyFormat("[[nodiscard]] bool f() { return false; }");
10580   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10581   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10582   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10583   verifyFormat("[[nodiscard]] ::qualified_type f();");
10584 
10585   // Make sure we do not mistake attributes for array subscripts.
10586   verifyFormat("int a() {}\n"
10587                "[[unused]] int b() {}\n");
10588   verifyFormat("NSArray *arr;\n"
10589                "arr[[Foo() bar]];");
10590 
10591   // On the other hand, we still need to correctly find array subscripts.
10592   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10593 
10594   // Make sure that we do not mistake Objective-C method inside array literals
10595   // as attributes, even if those method names are also keywords.
10596   verifyFormat("@[ [foo bar] ];");
10597   verifyFormat("@[ [NSArray class] ];");
10598   verifyFormat("@[ [foo enum] ];");
10599 
10600   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10601 
10602   // Make sure we do not parse attributes as lambda introducers.
10603   FormatStyle MultiLineFunctions = getLLVMStyle();
10604   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10605   verifyFormat("[[unused]] int b() {\n"
10606                "  return 42;\n"
10607                "}\n",
10608                MultiLineFunctions);
10609 }
10610 
10611 TEST_F(FormatTest, AttributeClass) {
10612   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10613   verifyFormat("class S {\n"
10614                "  S(S&&) = default;\n"
10615                "};",
10616                Style);
10617   verifyFormat("class [[nodiscard]] S {\n"
10618                "  S(S&&) = default;\n"
10619                "};",
10620                Style);
10621   verifyFormat("class __attribute((maybeunused)) S {\n"
10622                "  S(S&&) = default;\n"
10623                "};",
10624                Style);
10625   verifyFormat("struct S {\n"
10626                "  S(S&&) = default;\n"
10627                "};",
10628                Style);
10629   verifyFormat("struct [[nodiscard]] S {\n"
10630                "  S(S&&) = default;\n"
10631                "};",
10632                Style);
10633 }
10634 
10635 TEST_F(FormatTest, AttributesAfterMacro) {
10636   FormatStyle Style = getLLVMStyle();
10637   verifyFormat("MACRO;\n"
10638                "__attribute__((maybe_unused)) int foo() {\n"
10639                "  //...\n"
10640                "}");
10641 
10642   verifyFormat("MACRO;\n"
10643                "[[nodiscard]] int foo() {\n"
10644                "  //...\n"
10645                "}");
10646 
10647   EXPECT_EQ("MACRO\n\n"
10648             "__attribute__((maybe_unused)) int foo() {\n"
10649             "  //...\n"
10650             "}",
10651             format("MACRO\n\n"
10652                    "__attribute__((maybe_unused)) int foo() {\n"
10653                    "  //...\n"
10654                    "}"));
10655 
10656   EXPECT_EQ("MACRO\n\n"
10657             "[[nodiscard]] int foo() {\n"
10658             "  //...\n"
10659             "}",
10660             format("MACRO\n\n"
10661                    "[[nodiscard]] int foo() {\n"
10662                    "  //...\n"
10663                    "}"));
10664 }
10665 
10666 TEST_F(FormatTest, AttributePenaltyBreaking) {
10667   FormatStyle Style = getLLVMStyle();
10668   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10669                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10670                Style);
10671   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10672                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10673                Style);
10674   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10675                "shared_ptr<ALongTypeName> &C d) {\n}",
10676                Style);
10677 }
10678 
10679 TEST_F(FormatTest, UnderstandsEllipsis) {
10680   FormatStyle Style = getLLVMStyle();
10681   verifyFormat("int printf(const char *fmt, ...);");
10682   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10683   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10684 
10685   verifyFormat("template <int *...PP> a;", Style);
10686 
10687   Style.PointerAlignment = FormatStyle::PAS_Left;
10688   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10689 
10690   verifyFormat("template <int*... PP> a;", Style);
10691 
10692   Style.PointerAlignment = FormatStyle::PAS_Middle;
10693   verifyFormat("template <int *... PP> a;", Style);
10694 }
10695 
10696 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10697   EXPECT_EQ("int *a;\n"
10698             "int *a;\n"
10699             "int *a;",
10700             format("int *a;\n"
10701                    "int* a;\n"
10702                    "int *a;",
10703                    getGoogleStyle()));
10704   EXPECT_EQ("int* a;\n"
10705             "int* a;\n"
10706             "int* a;",
10707             format("int* a;\n"
10708                    "int* a;\n"
10709                    "int *a;",
10710                    getGoogleStyle()));
10711   EXPECT_EQ("int *a;\n"
10712             "int *a;\n"
10713             "int *a;",
10714             format("int *a;\n"
10715                    "int * a;\n"
10716                    "int *  a;",
10717                    getGoogleStyle()));
10718   EXPECT_EQ("auto x = [] {\n"
10719             "  int *a;\n"
10720             "  int *a;\n"
10721             "  int *a;\n"
10722             "};",
10723             format("auto x=[]{int *a;\n"
10724                    "int * a;\n"
10725                    "int *  a;};",
10726                    getGoogleStyle()));
10727 }
10728 
10729 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10730   verifyFormat("int f(int &&a) {}");
10731   verifyFormat("int f(int a, char &&b) {}");
10732   verifyFormat("void f() { int &&a = b; }");
10733   verifyGoogleFormat("int f(int a, char&& b) {}");
10734   verifyGoogleFormat("void f() { int&& a = b; }");
10735 
10736   verifyIndependentOfContext("A<int &&> a;");
10737   verifyIndependentOfContext("A<int &&, int &&> a;");
10738   verifyGoogleFormat("A<int&&> a;");
10739   verifyGoogleFormat("A<int&&, int&&> a;");
10740 
10741   // Not rvalue references:
10742   verifyFormat("template <bool B, bool C> class A {\n"
10743                "  static_assert(B && C, \"Something is wrong\");\n"
10744                "};");
10745   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10746   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10747   verifyFormat("#define A(a, b) (a && b)");
10748 }
10749 
10750 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10751   verifyFormat("void f() {\n"
10752                "  x[aaaaaaaaa -\n"
10753                "    b] = 23;\n"
10754                "}",
10755                getLLVMStyleWithColumns(15));
10756 }
10757 
10758 TEST_F(FormatTest, FormatsCasts) {
10759   verifyFormat("Type *A = static_cast<Type *>(P);");
10760   verifyFormat("static_cast<Type *>(P);");
10761   verifyFormat("static_cast<Type &>(Fun)(Args);");
10762   verifyFormat("static_cast<Type &>(*Fun)(Args);");
10763   verifyFormat("if (static_cast<int>(A) + B >= 0)\n  ;");
10764   // Check that static_cast<...>(...) does not require the next token to be on
10765   // the same line.
10766   verifyFormat("some_loooong_output << something_something__ << "
10767                "static_cast<const void *>(R)\n"
10768                "                    << something;");
10769   verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
10770   verifyFormat("const_cast<Type &>(*Fun)(Args);");
10771   verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
10772   verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
10773   verifyFormat("Type *A = (Type *)P;");
10774   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10775   verifyFormat("int a = (int)(2.0f);");
10776   verifyFormat("int a = (int)2.0f;");
10777   verifyFormat("x[(int32)y];");
10778   verifyFormat("x = (int32)y;");
10779   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10780   verifyFormat("int a = (int)*b;");
10781   verifyFormat("int a = (int)2.0f;");
10782   verifyFormat("int a = (int)~0;");
10783   verifyFormat("int a = (int)++a;");
10784   verifyFormat("int a = (int)sizeof(int);");
10785   verifyFormat("int a = (int)+2;");
10786   verifyFormat("my_int a = (my_int)2.0f;");
10787   verifyFormat("my_int a = (my_int)sizeof(int);");
10788   verifyFormat("return (my_int)aaa;");
10789   verifyFormat("#define x ((int)-1)");
10790   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10791   verifyFormat("#define p(q) ((int *)&q)");
10792   verifyFormat("fn(a)(b) + 1;");
10793 
10794   verifyFormat("void f() { my_int a = (my_int)*b; }");
10795   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10796   verifyFormat("my_int a = (my_int)~0;");
10797   verifyFormat("my_int a = (my_int)++a;");
10798   verifyFormat("my_int a = (my_int)-2;");
10799   verifyFormat("my_int a = (my_int)1;");
10800   verifyFormat("my_int a = (my_int *)1;");
10801   verifyFormat("my_int a = (const my_int)-1;");
10802   verifyFormat("my_int a = (const my_int *)-1;");
10803   verifyFormat("my_int a = (my_int)(my_int)-1;");
10804   verifyFormat("my_int a = (ns::my_int)-2;");
10805   verifyFormat("case (my_int)ONE:");
10806   verifyFormat("auto x = (X)this;");
10807   // Casts in Obj-C style calls used to not be recognized as such.
10808   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10809 
10810   // FIXME: single value wrapped with paren will be treated as cast.
10811   verifyFormat("void f(int i = (kValue)*kMask) {}");
10812 
10813   verifyFormat("{ (void)F; }");
10814 
10815   // Don't break after a cast's
10816   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10817                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10818                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10819 
10820   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10821   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10822   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10823   verifyFormat("bool *y = (bool *)(void *)(x);");
10824   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10825   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10826   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10827   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10828 
10829   // These are not casts.
10830   verifyFormat("void f(int *) {}");
10831   verifyFormat("f(foo)->b;");
10832   verifyFormat("f(foo).b;");
10833   verifyFormat("f(foo)(b);");
10834   verifyFormat("f(foo)[b];");
10835   verifyFormat("[](foo) { return 4; }(bar);");
10836   verifyFormat("(*funptr)(foo)[4];");
10837   verifyFormat("funptrs[4](foo)[4];");
10838   verifyFormat("void f(int *);");
10839   verifyFormat("void f(int *) = 0;");
10840   verifyFormat("void f(SmallVector<int>) {}");
10841   verifyFormat("void f(SmallVector<int>);");
10842   verifyFormat("void f(SmallVector<int>) = 0;");
10843   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10844   verifyFormat("int a = sizeof(int) * b;");
10845   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10846   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10847   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10848   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10849 
10850   // These are not casts, but at some point were confused with casts.
10851   verifyFormat("virtual void foo(int *) override;");
10852   verifyFormat("virtual void foo(char &) const;");
10853   verifyFormat("virtual void foo(int *a, char *) const;");
10854   verifyFormat("int a = sizeof(int *) + b;");
10855   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10856   verifyFormat("bool b = f(g<int>) && c;");
10857   verifyFormat("typedef void (*f)(int i) func;");
10858   verifyFormat("void operator++(int) noexcept;");
10859   verifyFormat("void operator++(int &) noexcept;");
10860   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10861                "&) noexcept;");
10862   verifyFormat(
10863       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10864   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10865   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10866   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10867   verifyFormat("void operator delete(foo &) noexcept;");
10868   verifyFormat("void operator delete(foo) noexcept;");
10869   verifyFormat("void operator delete(int) noexcept;");
10870   verifyFormat("void operator delete(int &) noexcept;");
10871   verifyFormat("void operator delete(int &) volatile noexcept;");
10872   verifyFormat("void operator delete(int &) const");
10873   verifyFormat("void operator delete(int &) = default");
10874   verifyFormat("void operator delete(int &) = delete");
10875   verifyFormat("void operator delete(int &) [[noreturn]]");
10876   verifyFormat("void operator delete(int &) throw();");
10877   verifyFormat("void operator delete(int &) throw(int);");
10878   verifyFormat("auto operator delete(int &) -> int;");
10879   verifyFormat("auto operator delete(int &) override");
10880   verifyFormat("auto operator delete(int &) final");
10881 
10882   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10883                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10884   // FIXME: The indentation here is not ideal.
10885   verifyFormat(
10886       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10887       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10888       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10889 }
10890 
10891 TEST_F(FormatTest, FormatsFunctionTypes) {
10892   verifyFormat("A<bool()> a;");
10893   verifyFormat("A<SomeType()> a;");
10894   verifyFormat("A<void (*)(int, std::string)> a;");
10895   verifyFormat("A<void *(int)>;");
10896   verifyFormat("void *(*a)(int *, SomeType *);");
10897   verifyFormat("int (*func)(void *);");
10898   verifyFormat("void f() { int (*func)(void *); }");
10899   verifyFormat("template <class CallbackClass>\n"
10900                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10901 
10902   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10903   verifyGoogleFormat("void* (*a)(int);");
10904   verifyGoogleFormat(
10905       "template <class CallbackClass>\n"
10906       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10907 
10908   // Other constructs can look somewhat like function types:
10909   verifyFormat("A<sizeof(*x)> a;");
10910   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10911   verifyFormat("some_var = function(*some_pointer_var)[0];");
10912   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10913   verifyFormat("int x = f(&h)();");
10914   verifyFormat("returnsFunction(&param1, &param2)(param);");
10915   verifyFormat("std::function<\n"
10916                "    LooooooooooongTemplatedType<\n"
10917                "        SomeType>*(\n"
10918                "        LooooooooooooooooongType type)>\n"
10919                "    function;",
10920                getGoogleStyleWithColumns(40));
10921 }
10922 
10923 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10924   verifyFormat("A (*foo_)[6];");
10925   verifyFormat("vector<int> (*foo_)[6];");
10926 }
10927 
10928 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10929   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10930                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10931   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10932                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10933   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10934                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10935 
10936   // Different ways of ()-initializiation.
10937   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10938                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10939   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10940                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10941   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10942                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10943   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10944                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10945 
10946   // Lambdas should not confuse the variable declaration heuristic.
10947   verifyFormat("LooooooooooooooooongType\n"
10948                "    variable(nullptr, [](A *a) {});",
10949                getLLVMStyleWithColumns(40));
10950 }
10951 
10952 TEST_F(FormatTest, BreaksLongDeclarations) {
10953   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10954                "    AnotherNameForTheLongType;");
10955   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10956                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10957   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10958                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10959   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10960                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10961   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10962                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10963   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10964                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10965   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10966                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10967   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10968                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10969   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10970                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10971   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10972                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10973   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10974                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10975   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10976                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10977   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10978                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10979   FormatStyle Indented = getLLVMStyle();
10980   Indented.IndentWrappedFunctionNames = true;
10981   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10982                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10983                Indented);
10984   verifyFormat(
10985       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10986       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10987       Indented);
10988   verifyFormat(
10989       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10990       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10991       Indented);
10992   verifyFormat(
10993       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10994       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10995       Indented);
10996 
10997   // FIXME: Without the comment, this breaks after "(".
10998   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10999                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
11000                getGoogleStyle());
11001 
11002   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
11003                "                  int LoooooooooooooooooooongParam2) {}");
11004   verifyFormat(
11005       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
11006       "                                   SourceLocation L, IdentifierIn *II,\n"
11007       "                                   Type *T) {}");
11008   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
11009                "ReallyReaaallyLongFunctionName(\n"
11010                "    const std::string &SomeParameter,\n"
11011                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11012                "        &ReallyReallyLongParameterName,\n"
11013                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11014                "        &AnotherLongParameterName) {}");
11015   verifyFormat("template <typename A>\n"
11016                "SomeLoooooooooooooooooooooongType<\n"
11017                "    typename some_namespace::SomeOtherType<A>::Type>\n"
11018                "Function() {}");
11019 
11020   verifyGoogleFormat(
11021       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
11022       "    aaaaaaaaaaaaaaaaaaaaaaa;");
11023   verifyGoogleFormat(
11024       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
11025       "                                   SourceLocation L) {}");
11026   verifyGoogleFormat(
11027       "some_namespace::LongReturnType\n"
11028       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
11029       "    int first_long_parameter, int second_parameter) {}");
11030 
11031   verifyGoogleFormat("template <typename T>\n"
11032                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11033                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
11034   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11035                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
11036 
11037   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
11038                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11039                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11040   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11041                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11042                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
11043   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11044                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
11045                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
11046                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11047 
11048   verifyFormat("template <typename T> // Templates on own line.\n"
11049                "static int            // Some comment.\n"
11050                "MyFunction(int a);",
11051                getLLVMStyle());
11052 }
11053 
11054 TEST_F(FormatTest, FormatsAccessModifiers) {
11055   FormatStyle Style = getLLVMStyle();
11056   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
11057             FormatStyle::ELBAMS_LogicalBlock);
11058   verifyFormat("struct foo {\n"
11059                "private:\n"
11060                "  void f() {}\n"
11061                "\n"
11062                "private:\n"
11063                "  int i;\n"
11064                "\n"
11065                "protected:\n"
11066                "  int j;\n"
11067                "};\n",
11068                Style);
11069   verifyFormat("struct foo {\n"
11070                "private:\n"
11071                "  void f() {}\n"
11072                "\n"
11073                "private:\n"
11074                "  int i;\n"
11075                "\n"
11076                "protected:\n"
11077                "  int j;\n"
11078                "};\n",
11079                "struct foo {\n"
11080                "private:\n"
11081                "  void f() {}\n"
11082                "private:\n"
11083                "  int i;\n"
11084                "protected:\n"
11085                "  int j;\n"
11086                "};\n",
11087                Style);
11088   verifyFormat("struct foo { /* comment */\n"
11089                "private:\n"
11090                "  int i;\n"
11091                "  // comment\n"
11092                "private:\n"
11093                "  int j;\n"
11094                "};\n",
11095                Style);
11096   verifyFormat("struct foo {\n"
11097                "#ifdef FOO\n"
11098                "#endif\n"
11099                "private:\n"
11100                "  int i;\n"
11101                "#ifdef FOO\n"
11102                "private:\n"
11103                "#endif\n"
11104                "  int j;\n"
11105                "};\n",
11106                Style);
11107   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11108   verifyFormat("struct foo {\n"
11109                "private:\n"
11110                "  void f() {}\n"
11111                "private:\n"
11112                "  int i;\n"
11113                "protected:\n"
11114                "  int j;\n"
11115                "};\n",
11116                Style);
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                "struct foo {\n"
11126                "\n"
11127                "private:\n"
11128                "  void f() {}\n"
11129                "\n"
11130                "private:\n"
11131                "  int i;\n"
11132                "\n"
11133                "protected:\n"
11134                "  int j;\n"
11135                "};\n",
11136                Style);
11137   verifyFormat("struct foo { /* comment */\n"
11138                "private:\n"
11139                "  int i;\n"
11140                "  // comment\n"
11141                "private:\n"
11142                "  int j;\n"
11143                "};\n",
11144                "struct foo { /* comment */\n"
11145                "\n"
11146                "private:\n"
11147                "  int i;\n"
11148                "  // comment\n"
11149                "\n"
11150                "private:\n"
11151                "  int j;\n"
11152                "};\n",
11153                Style);
11154   verifyFormat("struct foo {\n"
11155                "#ifdef FOO\n"
11156                "#endif\n"
11157                "private:\n"
11158                "  int i;\n"
11159                "#ifdef FOO\n"
11160                "private:\n"
11161                "#endif\n"
11162                "  int j;\n"
11163                "};\n",
11164                "struct foo {\n"
11165                "#ifdef FOO\n"
11166                "#endif\n"
11167                "\n"
11168                "private:\n"
11169                "  int i;\n"
11170                "#ifdef FOO\n"
11171                "\n"
11172                "private:\n"
11173                "#endif\n"
11174                "  int j;\n"
11175                "};\n",
11176                Style);
11177   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11178   verifyFormat("struct foo {\n"
11179                "private:\n"
11180                "  void f() {}\n"
11181                "\n"
11182                "private:\n"
11183                "  int i;\n"
11184                "\n"
11185                "protected:\n"
11186                "  int j;\n"
11187                "};\n",
11188                Style);
11189   verifyFormat("struct foo {\n"
11190                "private:\n"
11191                "  void f() {}\n"
11192                "\n"
11193                "private:\n"
11194                "  int i;\n"
11195                "\n"
11196                "protected:\n"
11197                "  int j;\n"
11198                "};\n",
11199                "struct foo {\n"
11200                "private:\n"
11201                "  void f() {}\n"
11202                "private:\n"
11203                "  int i;\n"
11204                "protected:\n"
11205                "  int j;\n"
11206                "};\n",
11207                Style);
11208   verifyFormat("struct foo { /* comment */\n"
11209                "private:\n"
11210                "  int i;\n"
11211                "  // comment\n"
11212                "\n"
11213                "private:\n"
11214                "  int j;\n"
11215                "};\n",
11216                "struct foo { /* comment */\n"
11217                "private:\n"
11218                "  int i;\n"
11219                "  // comment\n"
11220                "\n"
11221                "private:\n"
11222                "  int j;\n"
11223                "};\n",
11224                Style);
11225   verifyFormat("struct foo {\n"
11226                "#ifdef FOO\n"
11227                "#endif\n"
11228                "\n"
11229                "private:\n"
11230                "  int i;\n"
11231                "#ifdef FOO\n"
11232                "\n"
11233                "private:\n"
11234                "#endif\n"
11235                "  int j;\n"
11236                "};\n",
11237                "struct foo {\n"
11238                "#ifdef FOO\n"
11239                "#endif\n"
11240                "private:\n"
11241                "  int i;\n"
11242                "#ifdef FOO\n"
11243                "private:\n"
11244                "#endif\n"
11245                "  int j;\n"
11246                "};\n",
11247                Style);
11248   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11249   EXPECT_EQ("struct foo {\n"
11250             "\n"
11251             "private:\n"
11252             "  void f() {}\n"
11253             "\n"
11254             "private:\n"
11255             "  int i;\n"
11256             "\n"
11257             "protected:\n"
11258             "  int j;\n"
11259             "};\n",
11260             format("struct foo {\n"
11261                    "\n"
11262                    "private:\n"
11263                    "  void f() {}\n"
11264                    "\n"
11265                    "private:\n"
11266                    "  int i;\n"
11267                    "\n"
11268                    "protected:\n"
11269                    "  int j;\n"
11270                    "};\n",
11271                    Style));
11272   verifyFormat("struct foo {\n"
11273                "private:\n"
11274                "  void f() {}\n"
11275                "private:\n"
11276                "  int i;\n"
11277                "protected:\n"
11278                "  int j;\n"
11279                "};\n",
11280                Style);
11281   EXPECT_EQ("struct foo { /* comment */\n"
11282             "\n"
11283             "private:\n"
11284             "  int i;\n"
11285             "  // comment\n"
11286             "\n"
11287             "private:\n"
11288             "  int j;\n"
11289             "};\n",
11290             format("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                    Style));
11300   verifyFormat("struct foo { /* comment */\n"
11301                "private:\n"
11302                "  int i;\n"
11303                "  // comment\n"
11304                "private:\n"
11305                "  int j;\n"
11306                "};\n",
11307                Style);
11308   EXPECT_EQ("struct foo {\n"
11309             "#ifdef FOO\n"
11310             "#endif\n"
11311             "\n"
11312             "private:\n"
11313             "  int i;\n"
11314             "#ifdef FOO\n"
11315             "\n"
11316             "private:\n"
11317             "#endif\n"
11318             "  int j;\n"
11319             "};\n",
11320             format("struct foo {\n"
11321                    "#ifdef FOO\n"
11322                    "#endif\n"
11323                    "\n"
11324                    "private:\n"
11325                    "  int i;\n"
11326                    "#ifdef FOO\n"
11327                    "\n"
11328                    "private:\n"
11329                    "#endif\n"
11330                    "  int j;\n"
11331                    "};\n",
11332                    Style));
11333   verifyFormat("struct foo {\n"
11334                "#ifdef FOO\n"
11335                "#endif\n"
11336                "private:\n"
11337                "  int i;\n"
11338                "#ifdef FOO\n"
11339                "private:\n"
11340                "#endif\n"
11341                "  int j;\n"
11342                "};\n",
11343                Style);
11344 
11345   FormatStyle NoEmptyLines = getLLVMStyle();
11346   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11347   verifyFormat("struct foo {\n"
11348                "private:\n"
11349                "  void f() {}\n"
11350                "\n"
11351                "private:\n"
11352                "  int i;\n"
11353                "\n"
11354                "public:\n"
11355                "protected:\n"
11356                "  int j;\n"
11357                "};\n",
11358                NoEmptyLines);
11359 
11360   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11361   verifyFormat("struct foo {\n"
11362                "private:\n"
11363                "  void f() {}\n"
11364                "private:\n"
11365                "  int i;\n"
11366                "public:\n"
11367                "protected:\n"
11368                "  int j;\n"
11369                "};\n",
11370                NoEmptyLines);
11371 
11372   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11373   verifyFormat("struct foo {\n"
11374                "private:\n"
11375                "  void f() {}\n"
11376                "\n"
11377                "private:\n"
11378                "  int i;\n"
11379                "\n"
11380                "public:\n"
11381                "\n"
11382                "protected:\n"
11383                "  int j;\n"
11384                "};\n",
11385                NoEmptyLines);
11386 }
11387 
11388 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
11389 
11390   FormatStyle Style = getLLVMStyle();
11391   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
11392   verifyFormat("struct foo {\n"
11393                "private:\n"
11394                "  void f() {}\n"
11395                "\n"
11396                "private:\n"
11397                "  int i;\n"
11398                "\n"
11399                "protected:\n"
11400                "  int j;\n"
11401                "};\n",
11402                Style);
11403 
11404   // Check if lines are removed.
11405   verifyFormat("struct foo {\n"
11406                "private:\n"
11407                "  void f() {}\n"
11408                "\n"
11409                "private:\n"
11410                "  int i;\n"
11411                "\n"
11412                "protected:\n"
11413                "  int j;\n"
11414                "};\n",
11415                "struct foo {\n"
11416                "private:\n"
11417                "\n"
11418                "  void f() {}\n"
11419                "\n"
11420                "private:\n"
11421                "\n"
11422                "  int i;\n"
11423                "\n"
11424                "protected:\n"
11425                "\n"
11426                "  int j;\n"
11427                "};\n",
11428                Style);
11429 
11430   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11431   verifyFormat("struct foo {\n"
11432                "private:\n"
11433                "\n"
11434                "  void f() {}\n"
11435                "\n"
11436                "private:\n"
11437                "\n"
11438                "  int i;\n"
11439                "\n"
11440                "protected:\n"
11441                "\n"
11442                "  int j;\n"
11443                "};\n",
11444                Style);
11445 
11446   // Check if lines are added.
11447   verifyFormat("struct foo {\n"
11448                "private:\n"
11449                "\n"
11450                "  void f() {}\n"
11451                "\n"
11452                "private:\n"
11453                "\n"
11454                "  int i;\n"
11455                "\n"
11456                "protected:\n"
11457                "\n"
11458                "  int j;\n"
11459                "};\n",
11460                "struct foo {\n"
11461                "private:\n"
11462                "  void f() {}\n"
11463                "\n"
11464                "private:\n"
11465                "  int i;\n"
11466                "\n"
11467                "protected:\n"
11468                "  int j;\n"
11469                "};\n",
11470                Style);
11471 
11472   // Leave tests rely on the code layout, test::messUp can not be used.
11473   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11474   Style.MaxEmptyLinesToKeep = 0u;
11475   verifyFormat("struct foo {\n"
11476                "private:\n"
11477                "  void f() {}\n"
11478                "\n"
11479                "private:\n"
11480                "  int i;\n"
11481                "\n"
11482                "protected:\n"
11483                "  int j;\n"
11484                "};\n",
11485                Style);
11486 
11487   // Check if MaxEmptyLinesToKeep is respected.
11488   EXPECT_EQ("struct foo {\n"
11489             "private:\n"
11490             "  void f() {}\n"
11491             "\n"
11492             "private:\n"
11493             "  int i;\n"
11494             "\n"
11495             "protected:\n"
11496             "  int j;\n"
11497             "};\n",
11498             format("struct foo {\n"
11499                    "private:\n"
11500                    "\n\n\n"
11501                    "  void f() {}\n"
11502                    "\n"
11503                    "private:\n"
11504                    "\n\n\n"
11505                    "  int i;\n"
11506                    "\n"
11507                    "protected:\n"
11508                    "\n\n\n"
11509                    "  int j;\n"
11510                    "};\n",
11511                    Style));
11512 
11513   Style.MaxEmptyLinesToKeep = 1u;
11514   EXPECT_EQ("struct foo {\n"
11515             "private:\n"
11516             "\n"
11517             "  void f() {}\n"
11518             "\n"
11519             "private:\n"
11520             "\n"
11521             "  int i;\n"
11522             "\n"
11523             "protected:\n"
11524             "\n"
11525             "  int j;\n"
11526             "};\n",
11527             format("struct foo {\n"
11528                    "private:\n"
11529                    "\n"
11530                    "  void f() {}\n"
11531                    "\n"
11532                    "private:\n"
11533                    "\n"
11534                    "  int i;\n"
11535                    "\n"
11536                    "protected:\n"
11537                    "\n"
11538                    "  int j;\n"
11539                    "};\n",
11540                    Style));
11541   // Check if no lines are kept.
11542   EXPECT_EQ("struct foo {\n"
11543             "private:\n"
11544             "  void f() {}\n"
11545             "\n"
11546             "private:\n"
11547             "  int i;\n"
11548             "\n"
11549             "protected:\n"
11550             "  int j;\n"
11551             "};\n",
11552             format("struct foo {\n"
11553                    "private:\n"
11554                    "  void f() {}\n"
11555                    "\n"
11556                    "private:\n"
11557                    "  int i;\n"
11558                    "\n"
11559                    "protected:\n"
11560                    "  int j;\n"
11561                    "};\n",
11562                    Style));
11563   // Check if MaxEmptyLinesToKeep is respected.
11564   EXPECT_EQ("struct foo {\n"
11565             "private:\n"
11566             "\n"
11567             "  void f() {}\n"
11568             "\n"
11569             "private:\n"
11570             "\n"
11571             "  int i;\n"
11572             "\n"
11573             "protected:\n"
11574             "\n"
11575             "  int j;\n"
11576             "};\n",
11577             format("struct foo {\n"
11578                    "private:\n"
11579                    "\n\n\n"
11580                    "  void f() {}\n"
11581                    "\n"
11582                    "private:\n"
11583                    "\n\n\n"
11584                    "  int i;\n"
11585                    "\n"
11586                    "protected:\n"
11587                    "\n\n\n"
11588                    "  int j;\n"
11589                    "};\n",
11590                    Style));
11591 
11592   Style.MaxEmptyLinesToKeep = 10u;
11593   EXPECT_EQ("struct foo {\n"
11594             "private:\n"
11595             "\n\n\n"
11596             "  void f() {}\n"
11597             "\n"
11598             "private:\n"
11599             "\n\n\n"
11600             "  int i;\n"
11601             "\n"
11602             "protected:\n"
11603             "\n\n\n"
11604             "  int j;\n"
11605             "};\n",
11606             format("struct foo {\n"
11607                    "private:\n"
11608                    "\n\n\n"
11609                    "  void f() {}\n"
11610                    "\n"
11611                    "private:\n"
11612                    "\n\n\n"
11613                    "  int i;\n"
11614                    "\n"
11615                    "protected:\n"
11616                    "\n\n\n"
11617                    "  int j;\n"
11618                    "};\n",
11619                    Style));
11620 
11621   // Test with comments.
11622   Style = getLLVMStyle();
11623   verifyFormat("struct foo {\n"
11624                "private:\n"
11625                "  // comment\n"
11626                "  void f() {}\n"
11627                "\n"
11628                "private: /* comment */\n"
11629                "  int i;\n"
11630                "};\n",
11631                Style);
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                "struct foo {\n"
11641                "private:\n"
11642                "\n"
11643                "  // comment\n"
11644                "  void f() {}\n"
11645                "\n"
11646                "private: /* comment */\n"
11647                "\n"
11648                "  int i;\n"
11649                "};\n",
11650                Style);
11651 
11652   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11653   verifyFormat("struct foo {\n"
11654                "private:\n"
11655                "\n"
11656                "  // comment\n"
11657                "  void f() {}\n"
11658                "\n"
11659                "private: /* comment */\n"
11660                "\n"
11661                "  int i;\n"
11662                "};\n",
11663                "struct foo {\n"
11664                "private:\n"
11665                "  // comment\n"
11666                "  void f() {}\n"
11667                "\n"
11668                "private: /* comment */\n"
11669                "  int i;\n"
11670                "};\n",
11671                Style);
11672   verifyFormat("struct foo {\n"
11673                "private:\n"
11674                "\n"
11675                "  // comment\n"
11676                "  void f() {}\n"
11677                "\n"
11678                "private: /* comment */\n"
11679                "\n"
11680                "  int i;\n"
11681                "};\n",
11682                Style);
11683 
11684   // Test with preprocessor defines.
11685   Style = getLLVMStyle();
11686   verifyFormat("struct foo {\n"
11687                "private:\n"
11688                "#ifdef FOO\n"
11689                "#endif\n"
11690                "  void f() {}\n"
11691                "};\n",
11692                Style);
11693   verifyFormat("struct foo {\n"
11694                "private:\n"
11695                "#ifdef FOO\n"
11696                "#endif\n"
11697                "  void f() {}\n"
11698                "};\n",
11699                "struct foo {\n"
11700                "private:\n"
11701                "\n"
11702                "#ifdef FOO\n"
11703                "#endif\n"
11704                "  void f() {}\n"
11705                "};\n",
11706                Style);
11707 
11708   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11709   verifyFormat("struct foo {\n"
11710                "private:\n"
11711                "\n"
11712                "#ifdef FOO\n"
11713                "#endif\n"
11714                "  void f() {}\n"
11715                "};\n",
11716                "struct foo {\n"
11717                "private:\n"
11718                "#ifdef FOO\n"
11719                "#endif\n"
11720                "  void f() {}\n"
11721                "};\n",
11722                Style);
11723   verifyFormat("struct foo {\n"
11724                "private:\n"
11725                "\n"
11726                "#ifdef FOO\n"
11727                "#endif\n"
11728                "  void f() {}\n"
11729                "};\n",
11730                Style);
11731 }
11732 
11733 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11734   // Combined tests of EmptyLineAfterAccessModifier and
11735   // EmptyLineBeforeAccessModifier.
11736   FormatStyle Style = getLLVMStyle();
11737   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11738   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11739   verifyFormat("struct foo {\n"
11740                "private:\n"
11741                "\n"
11742                "protected:\n"
11743                "};\n",
11744                Style);
11745 
11746   Style.MaxEmptyLinesToKeep = 10u;
11747   // Both remove all new lines.
11748   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11749   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11750   verifyFormat("struct foo {\n"
11751                "private:\n"
11752                "protected:\n"
11753                "};\n",
11754                "struct foo {\n"
11755                "private:\n"
11756                "\n\n\n"
11757                "protected:\n"
11758                "};\n",
11759                Style);
11760 
11761   // Leave tests rely on the code layout, test::messUp can not be used.
11762   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11763   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11764   Style.MaxEmptyLinesToKeep = 10u;
11765   EXPECT_EQ("struct foo {\n"
11766             "private:\n"
11767             "\n\n\n"
11768             "protected:\n"
11769             "};\n",
11770             format("struct foo {\n"
11771                    "private:\n"
11772                    "\n\n\n"
11773                    "protected:\n"
11774                    "};\n",
11775                    Style));
11776   Style.MaxEmptyLinesToKeep = 3u;
11777   EXPECT_EQ("struct foo {\n"
11778             "private:\n"
11779             "\n\n\n"
11780             "protected:\n"
11781             "};\n",
11782             format("struct foo {\n"
11783                    "private:\n"
11784                    "\n\n\n"
11785                    "protected:\n"
11786                    "};\n",
11787                    Style));
11788   Style.MaxEmptyLinesToKeep = 1u;
11789   EXPECT_EQ("struct foo {\n"
11790             "private:\n"
11791             "\n\n\n"
11792             "protected:\n"
11793             "};\n",
11794             format("struct foo {\n"
11795                    "private:\n"
11796                    "\n\n\n"
11797                    "protected:\n"
11798                    "};\n",
11799                    Style)); // Based on new lines in original document and not
11800                             // on the setting.
11801 
11802   Style.MaxEmptyLinesToKeep = 10u;
11803   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11804   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11805   // Newlines are kept if they are greater than zero,
11806   // test::messUp removes all new lines which changes the logic
11807   EXPECT_EQ("struct foo {\n"
11808             "private:\n"
11809             "\n\n\n"
11810             "protected:\n"
11811             "};\n",
11812             format("struct foo {\n"
11813                    "private:\n"
11814                    "\n\n\n"
11815                    "protected:\n"
11816                    "};\n",
11817                    Style));
11818 
11819   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11820   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11821   // test::messUp removes all new lines which changes the logic
11822   EXPECT_EQ("struct foo {\n"
11823             "private:\n"
11824             "\n\n\n"
11825             "protected:\n"
11826             "};\n",
11827             format("struct foo {\n"
11828                    "private:\n"
11829                    "\n\n\n"
11830                    "protected:\n"
11831                    "};\n",
11832                    Style));
11833 
11834   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11835   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11836   EXPECT_EQ("struct foo {\n"
11837             "private:\n"
11838             "\n\n\n"
11839             "protected:\n"
11840             "};\n",
11841             format("struct foo {\n"
11842                    "private:\n"
11843                    "\n\n\n"
11844                    "protected:\n"
11845                    "};\n",
11846                    Style)); // test::messUp removes all new lines which changes
11847                             // the logic.
11848 
11849   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11850   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11851   verifyFormat("struct foo {\n"
11852                "private:\n"
11853                "protected:\n"
11854                "};\n",
11855                "struct foo {\n"
11856                "private:\n"
11857                "\n\n\n"
11858                "protected:\n"
11859                "};\n",
11860                Style);
11861 
11862   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11863   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11864   EXPECT_EQ("struct foo {\n"
11865             "private:\n"
11866             "\n\n\n"
11867             "protected:\n"
11868             "};\n",
11869             format("struct foo {\n"
11870                    "private:\n"
11871                    "\n\n\n"
11872                    "protected:\n"
11873                    "};\n",
11874                    Style)); // test::messUp removes all new lines which changes
11875                             // the logic.
11876 
11877   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11878   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11879   verifyFormat("struct foo {\n"
11880                "private:\n"
11881                "protected:\n"
11882                "};\n",
11883                "struct foo {\n"
11884                "private:\n"
11885                "\n\n\n"
11886                "protected:\n"
11887                "};\n",
11888                Style);
11889 
11890   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11891   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11892   verifyFormat("struct foo {\n"
11893                "private:\n"
11894                "protected:\n"
11895                "};\n",
11896                "struct foo {\n"
11897                "private:\n"
11898                "\n\n\n"
11899                "protected:\n"
11900                "};\n",
11901                Style);
11902 
11903   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11904   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11905   verifyFormat("struct foo {\n"
11906                "private:\n"
11907                "protected:\n"
11908                "};\n",
11909                "struct foo {\n"
11910                "private:\n"
11911                "\n\n\n"
11912                "protected:\n"
11913                "};\n",
11914                Style);
11915 
11916   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11917   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11918   verifyFormat("struct foo {\n"
11919                "private:\n"
11920                "protected:\n"
11921                "};\n",
11922                "struct foo {\n"
11923                "private:\n"
11924                "\n\n\n"
11925                "protected:\n"
11926                "};\n",
11927                Style);
11928 }
11929 
11930 TEST_F(FormatTest, FormatsArrays) {
11931   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11932                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11933   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11934                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11935   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11936                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11937   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11938                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11939   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11940                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11941   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11942                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11943                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11944   verifyFormat(
11945       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11946       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11947       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11948   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11949                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11950 
11951   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11952                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11953   verifyFormat(
11954       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11955       "                                  .aaaaaaa[0]\n"
11956       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11957   verifyFormat("a[::b::c];");
11958 
11959   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11960 
11961   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11962   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11963 }
11964 
11965 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11966   verifyFormat("(a)->b();");
11967   verifyFormat("--a;");
11968 }
11969 
11970 TEST_F(FormatTest, HandlesIncludeDirectives) {
11971   verifyFormat("#include <string>\n"
11972                "#include <a/b/c.h>\n"
11973                "#include \"a/b/string\"\n"
11974                "#include \"string.h\"\n"
11975                "#include \"string.h\"\n"
11976                "#include <a-a>\n"
11977                "#include < path with space >\n"
11978                "#include_next <test.h>"
11979                "#include \"abc.h\" // this is included for ABC\n"
11980                "#include \"some long include\" // with a comment\n"
11981                "#include \"some very long include path\"\n"
11982                "#include <some/very/long/include/path>\n",
11983                getLLVMStyleWithColumns(35));
11984   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11985   EXPECT_EQ("#include <a>", format("#include<a>"));
11986 
11987   verifyFormat("#import <string>");
11988   verifyFormat("#import <a/b/c.h>");
11989   verifyFormat("#import \"a/b/string\"");
11990   verifyFormat("#import \"string.h\"");
11991   verifyFormat("#import \"string.h\"");
11992   verifyFormat("#if __has_include(<strstream>)\n"
11993                "#include <strstream>\n"
11994                "#endif");
11995 
11996   verifyFormat("#define MY_IMPORT <a/b>");
11997 
11998   verifyFormat("#if __has_include(<a/b>)");
11999   verifyFormat("#if __has_include_next(<a/b>)");
12000   verifyFormat("#define F __has_include(<a/b>)");
12001   verifyFormat("#define F __has_include_next(<a/b>)");
12002 
12003   // Protocol buffer definition or missing "#".
12004   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
12005                getLLVMStyleWithColumns(30));
12006 
12007   FormatStyle Style = getLLVMStyle();
12008   Style.AlwaysBreakBeforeMultilineStrings = true;
12009   Style.ColumnLimit = 0;
12010   verifyFormat("#import \"abc.h\"", Style);
12011 
12012   // But 'import' might also be a regular C++ namespace.
12013   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12014                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
12015 }
12016 
12017 //===----------------------------------------------------------------------===//
12018 // Error recovery tests.
12019 //===----------------------------------------------------------------------===//
12020 
12021 TEST_F(FormatTest, IncompleteParameterLists) {
12022   FormatStyle NoBinPacking = getLLVMStyle();
12023   NoBinPacking.BinPackParameters = false;
12024   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
12025                "                        double *min_x,\n"
12026                "                        double *max_x,\n"
12027                "                        double *min_y,\n"
12028                "                        double *max_y,\n"
12029                "                        double *min_z,\n"
12030                "                        double *max_z, ) {}",
12031                NoBinPacking);
12032 }
12033 
12034 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
12035   verifyFormat("void f() { return; }\n42");
12036   verifyFormat("void f() {\n"
12037                "  if (0)\n"
12038                "    return;\n"
12039                "}\n"
12040                "42");
12041   verifyFormat("void f() { return }\n42");
12042   verifyFormat("void f() {\n"
12043                "  if (0)\n"
12044                "    return\n"
12045                "}\n"
12046                "42");
12047 }
12048 
12049 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
12050   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
12051   EXPECT_EQ("void f() {\n"
12052             "  if (a)\n"
12053             "    return\n"
12054             "}",
12055             format("void  f  (  )  {  if  ( a )  return  }"));
12056   EXPECT_EQ("namespace N {\n"
12057             "void f()\n"
12058             "}",
12059             format("namespace  N  {  void f()  }"));
12060   EXPECT_EQ("namespace N {\n"
12061             "void f() {}\n"
12062             "void g()\n"
12063             "} // namespace N",
12064             format("namespace N  { void f( ) { } void g( ) }"));
12065 }
12066 
12067 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
12068   verifyFormat("int aaaaaaaa =\n"
12069                "    // Overlylongcomment\n"
12070                "    b;",
12071                getLLVMStyleWithColumns(20));
12072   verifyFormat("function(\n"
12073                "    ShortArgument,\n"
12074                "    LoooooooooooongArgument);\n",
12075                getLLVMStyleWithColumns(20));
12076 }
12077 
12078 TEST_F(FormatTest, IncorrectAccessSpecifier) {
12079   verifyFormat("public:");
12080   verifyFormat("class A {\n"
12081                "public\n"
12082                "  void f() {}\n"
12083                "};");
12084   verifyFormat("public\n"
12085                "int qwerty;");
12086   verifyFormat("public\n"
12087                "B {}");
12088   verifyFormat("public\n"
12089                "{}");
12090   verifyFormat("public\n"
12091                "B { int x; }");
12092 }
12093 
12094 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
12095   verifyFormat("{");
12096   verifyFormat("#})");
12097   verifyNoCrash("(/**/[:!] ?[).");
12098 }
12099 
12100 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
12101   // Found by oss-fuzz:
12102   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
12103   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
12104   Style.ColumnLimit = 60;
12105   verifyNoCrash(
12106       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
12107       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
12108       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
12109       Style);
12110 }
12111 
12112 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
12113   verifyFormat("do {\n}");
12114   verifyFormat("do {\n}\n"
12115                "f();");
12116   verifyFormat("do {\n}\n"
12117                "wheeee(fun);");
12118   verifyFormat("do {\n"
12119                "  f();\n"
12120                "}");
12121 }
12122 
12123 TEST_F(FormatTest, IncorrectCodeMissingParens) {
12124   verifyFormat("if {\n  foo;\n  foo();\n}");
12125   verifyFormat("switch {\n  foo;\n  foo();\n}");
12126   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
12127   verifyIncompleteFormat("ERROR: for target;");
12128   verifyFormat("while {\n  foo;\n  foo();\n}");
12129   verifyFormat("do {\n  foo;\n  foo();\n} while;");
12130 }
12131 
12132 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
12133   verifyIncompleteFormat("namespace {\n"
12134                          "class Foo { Foo (\n"
12135                          "};\n"
12136                          "} // namespace");
12137 }
12138 
12139 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
12140   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
12141   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
12142   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
12143   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
12144 
12145   EXPECT_EQ("{\n"
12146             "  {\n"
12147             "    breakme(\n"
12148             "        qwe);\n"
12149             "  }\n",
12150             format("{\n"
12151                    "    {\n"
12152                    " breakme(qwe);\n"
12153                    "}\n",
12154                    getLLVMStyleWithColumns(10)));
12155 }
12156 
12157 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
12158   verifyFormat("int x = {\n"
12159                "    avariable,\n"
12160                "    b(alongervariable)};",
12161                getLLVMStyleWithColumns(25));
12162 }
12163 
12164 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
12165   verifyFormat("return (a)(b){1, 2, 3};");
12166 }
12167 
12168 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
12169   verifyFormat("vector<int> x{1, 2, 3, 4};");
12170   verifyFormat("vector<int> x{\n"
12171                "    1,\n"
12172                "    2,\n"
12173                "    3,\n"
12174                "    4,\n"
12175                "};");
12176   verifyFormat("vector<T> x{{}, {}, {}, {}};");
12177   verifyFormat("f({1, 2});");
12178   verifyFormat("auto v = Foo{-1};");
12179   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
12180   verifyFormat("Class::Class : member{1, 2, 3} {}");
12181   verifyFormat("new vector<int>{1, 2, 3};");
12182   verifyFormat("new int[3]{1, 2, 3};");
12183   verifyFormat("new int{1};");
12184   verifyFormat("return {arg1, arg2};");
12185   verifyFormat("return {arg1, SomeType{parameter}};");
12186   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
12187   verifyFormat("new T{arg1, arg2};");
12188   verifyFormat("f(MyMap[{composite, key}]);");
12189   verifyFormat("class Class {\n"
12190                "  T member = {arg1, arg2};\n"
12191                "};");
12192   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
12193   verifyFormat("const struct A a = {.a = 1, .b = 2};");
12194   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
12195   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
12196   verifyFormat("int a = std::is_integral<int>{} + 0;");
12197 
12198   verifyFormat("int foo(int i) { return fo1{}(i); }");
12199   verifyFormat("int foo(int i) { return fo1{}(i); }");
12200   verifyFormat("auto i = decltype(x){};");
12201   verifyFormat("auto i = typeof(x){};");
12202   verifyFormat("auto i = _Atomic(x){};");
12203   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
12204   verifyFormat("Node n{1, Node{1000}, //\n"
12205                "       2};");
12206   verifyFormat("Aaaa aaaaaaa{\n"
12207                "    {\n"
12208                "        aaaa,\n"
12209                "    },\n"
12210                "};");
12211   verifyFormat("class C : public D {\n"
12212                "  SomeClass SC{2};\n"
12213                "};");
12214   verifyFormat("class C : public A {\n"
12215                "  class D : public B {\n"
12216                "    void f() { int i{2}; }\n"
12217                "  };\n"
12218                "};");
12219   verifyFormat("#define A {a, a},");
12220   // Don't confuse braced list initializers with compound statements.
12221   verifyFormat(
12222       "class A {\n"
12223       "  A() : a{} {}\n"
12224       "  A(int b) : b(b) {}\n"
12225       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
12226       "  int a, b;\n"
12227       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
12228       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
12229       "{}\n"
12230       "};");
12231 
12232   // Avoid breaking between equal sign and opening brace
12233   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
12234   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
12235   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
12236                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
12237                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
12238                "     {\"ccccccccccccccccccccc\", 2}};",
12239                AvoidBreakingFirstArgument);
12240 
12241   // Binpacking only if there is no trailing comma
12242   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
12243                "                      cccccccccc, dddddddddd};",
12244                getLLVMStyleWithColumns(50));
12245   verifyFormat("const Aaaaaa aaaaa = {\n"
12246                "    aaaaaaaaaaa,\n"
12247                "    bbbbbbbbbbb,\n"
12248                "    ccccccccccc,\n"
12249                "    ddddddddddd,\n"
12250                "};",
12251                getLLVMStyleWithColumns(50));
12252 
12253   // Cases where distinguising braced lists and blocks is hard.
12254   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
12255   verifyFormat("void f() {\n"
12256                "  return; // comment\n"
12257                "}\n"
12258                "SomeType t;");
12259   verifyFormat("void f() {\n"
12260                "  if (a) {\n"
12261                "    f();\n"
12262                "  }\n"
12263                "}\n"
12264                "SomeType t;");
12265 
12266   // In combination with BinPackArguments = false.
12267   FormatStyle NoBinPacking = getLLVMStyle();
12268   NoBinPacking.BinPackArguments = false;
12269   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
12270                "                      bbbbb,\n"
12271                "                      ccccc,\n"
12272                "                      ddddd,\n"
12273                "                      eeeee,\n"
12274                "                      ffffff,\n"
12275                "                      ggggg,\n"
12276                "                      hhhhhh,\n"
12277                "                      iiiiii,\n"
12278                "                      jjjjjj,\n"
12279                "                      kkkkkk};",
12280                NoBinPacking);
12281   verifyFormat("const Aaaaaa aaaaa = {\n"
12282                "    aaaaa,\n"
12283                "    bbbbb,\n"
12284                "    ccccc,\n"
12285                "    ddddd,\n"
12286                "    eeeee,\n"
12287                "    ffffff,\n"
12288                "    ggggg,\n"
12289                "    hhhhhh,\n"
12290                "    iiiiii,\n"
12291                "    jjjjjj,\n"
12292                "    kkkkkk,\n"
12293                "};",
12294                NoBinPacking);
12295   verifyFormat(
12296       "const Aaaaaa aaaaa = {\n"
12297       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
12298       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
12299       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
12300       "};",
12301       NoBinPacking);
12302 
12303   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12304   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
12305             "    CDDDP83848_BMCR_REGISTER,\n"
12306             "    CDDDP83848_BMSR_REGISTER,\n"
12307             "    CDDDP83848_RBR_REGISTER};",
12308             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
12309                    "                                CDDDP83848_BMSR_REGISTER,\n"
12310                    "                                CDDDP83848_RBR_REGISTER};",
12311                    NoBinPacking));
12312 
12313   // FIXME: The alignment of these trailing comments might be bad. Then again,
12314   // this might be utterly useless in real code.
12315   verifyFormat("Constructor::Constructor()\n"
12316                "    : some_value{         //\n"
12317                "                 aaaaaaa, //\n"
12318                "                 bbbbbbb} {}");
12319 
12320   // In braced lists, the first comment is always assumed to belong to the
12321   // first element. Thus, it can be moved to the next or previous line as
12322   // appropriate.
12323   EXPECT_EQ("function({// First element:\n"
12324             "          1,\n"
12325             "          // Second element:\n"
12326             "          2});",
12327             format("function({\n"
12328                    "    // First element:\n"
12329                    "    1,\n"
12330                    "    // Second element:\n"
12331                    "    2});"));
12332   EXPECT_EQ("std::vector<int> MyNumbers{\n"
12333             "    // First element:\n"
12334             "    1,\n"
12335             "    // Second element:\n"
12336             "    2};",
12337             format("std::vector<int> MyNumbers{// First element:\n"
12338                    "                           1,\n"
12339                    "                           // Second element:\n"
12340                    "                           2};",
12341                    getLLVMStyleWithColumns(30)));
12342   // A trailing comma should still lead to an enforced line break and no
12343   // binpacking.
12344   EXPECT_EQ("vector<int> SomeVector = {\n"
12345             "    // aaa\n"
12346             "    1,\n"
12347             "    2,\n"
12348             "};",
12349             format("vector<int> SomeVector = { // aaa\n"
12350                    "    1, 2, };"));
12351 
12352   // C++11 brace initializer list l-braces should not be treated any differently
12353   // when breaking before lambda bodies is enabled
12354   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
12355   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
12356   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
12357   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
12358   verifyFormat(
12359       "std::runtime_error{\n"
12360       "    \"Long string which will force a break onto the next line...\"};",
12361       BreakBeforeLambdaBody);
12362 
12363   FormatStyle ExtraSpaces = getLLVMStyle();
12364   ExtraSpaces.Cpp11BracedListStyle = false;
12365   ExtraSpaces.ColumnLimit = 75;
12366   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
12367   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
12368   verifyFormat("f({ 1, 2 });", ExtraSpaces);
12369   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
12370   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
12371   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
12372   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
12373   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
12374   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
12375   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
12376   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
12377   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
12378   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
12379   verifyFormat("class Class {\n"
12380                "  T member = { arg1, arg2 };\n"
12381                "};",
12382                ExtraSpaces);
12383   verifyFormat(
12384       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12385       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
12386       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
12387       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
12388       ExtraSpaces);
12389   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
12390   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
12391                ExtraSpaces);
12392   verifyFormat(
12393       "someFunction(OtherParam,\n"
12394       "             BracedList{ // comment 1 (Forcing interesting break)\n"
12395       "                         param1, param2,\n"
12396       "                         // comment 2\n"
12397       "                         param3, param4 });",
12398       ExtraSpaces);
12399   verifyFormat(
12400       "std::this_thread::sleep_for(\n"
12401       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
12402       ExtraSpaces);
12403   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
12404                "    aaaaaaa,\n"
12405                "    aaaaaaaaaa,\n"
12406                "    aaaaa,\n"
12407                "    aaaaaaaaaaaaaaa,\n"
12408                "    aaa,\n"
12409                "    aaaaaaaaaa,\n"
12410                "    a,\n"
12411                "    aaaaaaaaaaaaaaaaaaaaa,\n"
12412                "    aaaaaaaaaaaa,\n"
12413                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
12414                "    aaaaaaa,\n"
12415                "    a};");
12416   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
12417   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
12418   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
12419 
12420   // Avoid breaking between initializer/equal sign and opening brace
12421   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
12422   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
12423                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12424                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12425                "  { \"ccccccccccccccccccccc\", 2 }\n"
12426                "};",
12427                ExtraSpaces);
12428   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
12429                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12430                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12431                "  { \"ccccccccccccccccccccc\", 2 }\n"
12432                "};",
12433                ExtraSpaces);
12434 
12435   FormatStyle SpaceBeforeBrace = getLLVMStyle();
12436   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
12437   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
12438   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
12439 
12440   FormatStyle SpaceBetweenBraces = getLLVMStyle();
12441   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
12442   SpaceBetweenBraces.SpacesInParentheses = true;
12443   SpaceBetweenBraces.SpacesInSquareBrackets = true;
12444   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
12445   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
12446   verifyFormat("vector< int > x{ // comment 1\n"
12447                "                 1, 2, 3, 4 };",
12448                SpaceBetweenBraces);
12449   SpaceBetweenBraces.ColumnLimit = 20;
12450   EXPECT_EQ("vector< int > x{\n"
12451             "    1, 2, 3, 4 };",
12452             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12453   SpaceBetweenBraces.ColumnLimit = 24;
12454   EXPECT_EQ("vector< int > x{ 1, 2,\n"
12455             "                 3, 4 };",
12456             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12457   EXPECT_EQ("vector< int > x{\n"
12458             "    1,\n"
12459             "    2,\n"
12460             "    3,\n"
12461             "    4,\n"
12462             "};",
12463             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12464   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12465   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12466   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12467 }
12468 
12469 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12470   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12471                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12472                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12473                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12474                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12475                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12476   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12477                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12478                "                 1, 22, 333, 4444, 55555, //\n"
12479                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12480                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12481   verifyFormat(
12482       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12483       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12484       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12485       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12486       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12487       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12488       "                 7777777};");
12489   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12490                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12491                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12492   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12493                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12494                "    // Separating comment.\n"
12495                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12496   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12497                "    // Leading comment\n"
12498                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12499                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12500   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12501                "                 1, 1, 1, 1};",
12502                getLLVMStyleWithColumns(39));
12503   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12504                "                 1, 1, 1, 1};",
12505                getLLVMStyleWithColumns(38));
12506   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12507                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12508                getLLVMStyleWithColumns(43));
12509   verifyFormat(
12510       "static unsigned SomeValues[10][3] = {\n"
12511       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12512       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12513   verifyFormat("static auto fields = new vector<string>{\n"
12514                "    \"aaaaaaaaaaaaa\",\n"
12515                "    \"aaaaaaaaaaaaa\",\n"
12516                "    \"aaaaaaaaaaaa\",\n"
12517                "    \"aaaaaaaaaaaaaa\",\n"
12518                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12519                "    \"aaaaaaaaaaaa\",\n"
12520                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12521                "};");
12522   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12523   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12524                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12525                "                 3, cccccccccccccccccccccc};",
12526                getLLVMStyleWithColumns(60));
12527 
12528   // Trailing commas.
12529   verifyFormat("vector<int> x = {\n"
12530                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12531                "};",
12532                getLLVMStyleWithColumns(39));
12533   verifyFormat("vector<int> x = {\n"
12534                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12535                "};",
12536                getLLVMStyleWithColumns(39));
12537   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12538                "                 1, 1, 1, 1,\n"
12539                "                 /**/ /**/};",
12540                getLLVMStyleWithColumns(39));
12541 
12542   // Trailing comment in the first line.
12543   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12544                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12545                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12546                "    11111111,   22222222,   333333333,   44444444};");
12547   // Trailing comment in the last line.
12548   verifyFormat("int aaaaa[] = {\n"
12549                "    1, 2, 3, // comment\n"
12550                "    4, 5, 6  // comment\n"
12551                "};");
12552 
12553   // With nested lists, we should either format one item per line or all nested
12554   // lists one on line.
12555   // FIXME: For some nested lists, we can do better.
12556   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12557                "        {aaaaaaaaaaaaaaaaaaa},\n"
12558                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12559                "        {aaaaaaaaaaaaaaaaa}};",
12560                getLLVMStyleWithColumns(60));
12561   verifyFormat(
12562       "SomeStruct my_struct_array = {\n"
12563       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12564       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12565       "    {aaa, aaa},\n"
12566       "    {aaa, aaa},\n"
12567       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12568       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12569       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12570 
12571   // No column layout should be used here.
12572   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12573                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12574 
12575   verifyNoCrash("a<,");
12576 
12577   // No braced initializer here.
12578   verifyFormat("void f() {\n"
12579                "  struct Dummy {};\n"
12580                "  f(v);\n"
12581                "}");
12582 
12583   // Long lists should be formatted in columns even if they are nested.
12584   verifyFormat(
12585       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12586       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12587       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12588       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12589       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12590       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12591 
12592   // Allow "single-column" layout even if that violates the column limit. There
12593   // isn't going to be a better way.
12594   verifyFormat("std::vector<int> a = {\n"
12595                "    aaaaaaaa,\n"
12596                "    aaaaaaaa,\n"
12597                "    aaaaaaaa,\n"
12598                "    aaaaaaaa,\n"
12599                "    aaaaaaaaaa,\n"
12600                "    aaaaaaaa,\n"
12601                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12602                getLLVMStyleWithColumns(30));
12603   verifyFormat("vector<int> aaaa = {\n"
12604                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12605                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12606                "    aaaaaa.aaaaaaa,\n"
12607                "    aaaaaa.aaaaaaa,\n"
12608                "    aaaaaa.aaaaaaa,\n"
12609                "    aaaaaa.aaaaaaa,\n"
12610                "};");
12611 
12612   // Don't create hanging lists.
12613   verifyFormat("someFunction(Param, {List1, List2,\n"
12614                "                     List3});",
12615                getLLVMStyleWithColumns(35));
12616   verifyFormat("someFunction(Param, Param,\n"
12617                "             {List1, List2,\n"
12618                "              List3});",
12619                getLLVMStyleWithColumns(35));
12620   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12621                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12622 }
12623 
12624 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12625   FormatStyle DoNotMerge = getLLVMStyle();
12626   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12627 
12628   verifyFormat("void f() { return 42; }");
12629   verifyFormat("void f() {\n"
12630                "  return 42;\n"
12631                "}",
12632                DoNotMerge);
12633   verifyFormat("void f() {\n"
12634                "  // Comment\n"
12635                "}");
12636   verifyFormat("{\n"
12637                "#error {\n"
12638                "  int a;\n"
12639                "}");
12640   verifyFormat("{\n"
12641                "  int a;\n"
12642                "#error {\n"
12643                "}");
12644   verifyFormat("void f() {} // comment");
12645   verifyFormat("void f() { int a; } // comment");
12646   verifyFormat("void f() {\n"
12647                "} // comment",
12648                DoNotMerge);
12649   verifyFormat("void f() {\n"
12650                "  int a;\n"
12651                "} // comment",
12652                DoNotMerge);
12653   verifyFormat("void f() {\n"
12654                "} // comment",
12655                getLLVMStyleWithColumns(15));
12656 
12657   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12658   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12659 
12660   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12661   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12662   verifyFormat("class C {\n"
12663                "  C()\n"
12664                "      : iiiiiiii(nullptr),\n"
12665                "        kkkkkkk(nullptr),\n"
12666                "        mmmmmmm(nullptr),\n"
12667                "        nnnnnnn(nullptr) {}\n"
12668                "};",
12669                getGoogleStyle());
12670 
12671   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12672   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12673   EXPECT_EQ("class C {\n"
12674             "  A() : b(0) {}\n"
12675             "};",
12676             format("class C{A():b(0){}};", NoColumnLimit));
12677   EXPECT_EQ("A()\n"
12678             "    : b(0) {\n"
12679             "}",
12680             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12681 
12682   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12683   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12684       FormatStyle::SFS_None;
12685   EXPECT_EQ("A()\n"
12686             "    : b(0) {\n"
12687             "}",
12688             format("A():b(0){}", DoNotMergeNoColumnLimit));
12689   EXPECT_EQ("A()\n"
12690             "    : b(0) {\n"
12691             "}",
12692             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12693 
12694   verifyFormat("#define A          \\\n"
12695                "  void f() {       \\\n"
12696                "    int i;         \\\n"
12697                "  }",
12698                getLLVMStyleWithColumns(20));
12699   verifyFormat("#define A           \\\n"
12700                "  void f() { int i; }",
12701                getLLVMStyleWithColumns(21));
12702   verifyFormat("#define A            \\\n"
12703                "  void f() {         \\\n"
12704                "    int i;           \\\n"
12705                "  }                  \\\n"
12706                "  int j;",
12707                getLLVMStyleWithColumns(22));
12708   verifyFormat("#define A             \\\n"
12709                "  void f() { int i; } \\\n"
12710                "  int j;",
12711                getLLVMStyleWithColumns(23));
12712 }
12713 
12714 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12715   FormatStyle MergeEmptyOnly = getLLVMStyle();
12716   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12717   verifyFormat("class C {\n"
12718                "  int f() {}\n"
12719                "};",
12720                MergeEmptyOnly);
12721   verifyFormat("class C {\n"
12722                "  int f() {\n"
12723                "    return 42;\n"
12724                "  }\n"
12725                "};",
12726                MergeEmptyOnly);
12727   verifyFormat("int f() {}", MergeEmptyOnly);
12728   verifyFormat("int f() {\n"
12729                "  return 42;\n"
12730                "}",
12731                MergeEmptyOnly);
12732 
12733   // Also verify behavior when BraceWrapping.AfterFunction = true
12734   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12735   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12736   verifyFormat("int f() {}", MergeEmptyOnly);
12737   verifyFormat("class C {\n"
12738                "  int f() {}\n"
12739                "};",
12740                MergeEmptyOnly);
12741 }
12742 
12743 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12744   FormatStyle MergeInlineOnly = getLLVMStyle();
12745   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12746   verifyFormat("class C {\n"
12747                "  int f() { return 42; }\n"
12748                "};",
12749                MergeInlineOnly);
12750   verifyFormat("int f() {\n"
12751                "  return 42;\n"
12752                "}",
12753                MergeInlineOnly);
12754 
12755   // SFS_Inline implies SFS_Empty
12756   verifyFormat("class C {\n"
12757                "  int f() {}\n"
12758                "};",
12759                MergeInlineOnly);
12760   verifyFormat("int f() {}", MergeInlineOnly);
12761   // https://llvm.org/PR54147
12762   verifyFormat("auto lambda = []() {\n"
12763                "  // comment\n"
12764                "  f();\n"
12765                "  g();\n"
12766                "};",
12767                MergeInlineOnly);
12768 
12769   verifyFormat("class C {\n"
12770                "#ifdef A\n"
12771                "  int f() { return 42; }\n"
12772                "#endif\n"
12773                "};",
12774                MergeInlineOnly);
12775 
12776   // Also verify behavior when BraceWrapping.AfterFunction = true
12777   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12778   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12779   verifyFormat("class C {\n"
12780                "  int f() { return 42; }\n"
12781                "};",
12782                MergeInlineOnly);
12783   verifyFormat("int f()\n"
12784                "{\n"
12785                "  return 42;\n"
12786                "}",
12787                MergeInlineOnly);
12788 
12789   // SFS_Inline implies SFS_Empty
12790   verifyFormat("int f() {}", MergeInlineOnly);
12791   verifyFormat("class C {\n"
12792                "  int f() {}\n"
12793                "};",
12794                MergeInlineOnly);
12795 
12796   MergeInlineOnly.BraceWrapping.AfterClass = true;
12797   MergeInlineOnly.BraceWrapping.AfterStruct = true;
12798   verifyFormat("class C\n"
12799                "{\n"
12800                "  int f() { return 42; }\n"
12801                "};",
12802                MergeInlineOnly);
12803   verifyFormat("struct C\n"
12804                "{\n"
12805                "  int f() { return 42; }\n"
12806                "};",
12807                MergeInlineOnly);
12808   verifyFormat("int f()\n"
12809                "{\n"
12810                "  return 42;\n"
12811                "}",
12812                MergeInlineOnly);
12813   verifyFormat("int f() {}", MergeInlineOnly);
12814   verifyFormat("class C\n"
12815                "{\n"
12816                "  int f() { return 42; }\n"
12817                "};",
12818                MergeInlineOnly);
12819   verifyFormat("struct C\n"
12820                "{\n"
12821                "  int f() { return 42; }\n"
12822                "};",
12823                MergeInlineOnly);
12824   verifyFormat("struct C\n"
12825                "// comment\n"
12826                "/* comment */\n"
12827                "// comment\n"
12828                "{\n"
12829                "  int f() { return 42; }\n"
12830                "};",
12831                MergeInlineOnly);
12832   verifyFormat("/* comment */ struct C\n"
12833                "{\n"
12834                "  int f() { return 42; }\n"
12835                "};",
12836                MergeInlineOnly);
12837 }
12838 
12839 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12840   FormatStyle MergeInlineOnly = getLLVMStyle();
12841   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12842       FormatStyle::SFS_InlineOnly;
12843   verifyFormat("class C {\n"
12844                "  int f() { return 42; }\n"
12845                "};",
12846                MergeInlineOnly);
12847   verifyFormat("int f() {\n"
12848                "  return 42;\n"
12849                "}",
12850                MergeInlineOnly);
12851 
12852   // SFS_InlineOnly does not imply SFS_Empty
12853   verifyFormat("class C {\n"
12854                "  int f() {}\n"
12855                "};",
12856                MergeInlineOnly);
12857   verifyFormat("int f() {\n"
12858                "}",
12859                MergeInlineOnly);
12860 
12861   // Also verify behavior when BraceWrapping.AfterFunction = true
12862   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12863   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12864   verifyFormat("class C {\n"
12865                "  int f() { return 42; }\n"
12866                "};",
12867                MergeInlineOnly);
12868   verifyFormat("int f()\n"
12869                "{\n"
12870                "  return 42;\n"
12871                "}",
12872                MergeInlineOnly);
12873 
12874   // SFS_InlineOnly does not imply SFS_Empty
12875   verifyFormat("int f()\n"
12876                "{\n"
12877                "}",
12878                MergeInlineOnly);
12879   verifyFormat("class C {\n"
12880                "  int f() {}\n"
12881                "};",
12882                MergeInlineOnly);
12883 }
12884 
12885 TEST_F(FormatTest, SplitEmptyFunction) {
12886   FormatStyle Style = getLLVMStyleWithColumns(40);
12887   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12888   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12889   Style.BraceWrapping.AfterFunction = true;
12890   Style.BraceWrapping.SplitEmptyFunction = false;
12891 
12892   verifyFormat("int f()\n"
12893                "{}",
12894                Style);
12895   verifyFormat("int f()\n"
12896                "{\n"
12897                "  return 42;\n"
12898                "}",
12899                Style);
12900   verifyFormat("int f()\n"
12901                "{\n"
12902                "  // some comment\n"
12903                "}",
12904                Style);
12905 
12906   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12907   verifyFormat("int f() {}", Style);
12908   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12909                "{}",
12910                Style);
12911   verifyFormat("int f()\n"
12912                "{\n"
12913                "  return 0;\n"
12914                "}",
12915                Style);
12916 
12917   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12918   verifyFormat("class Foo {\n"
12919                "  int f() {}\n"
12920                "};\n",
12921                Style);
12922   verifyFormat("class Foo {\n"
12923                "  int f() { return 0; }\n"
12924                "};\n",
12925                Style);
12926   verifyFormat("class Foo {\n"
12927                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12928                "  {}\n"
12929                "};\n",
12930                Style);
12931   verifyFormat("class Foo {\n"
12932                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12933                "  {\n"
12934                "    return 0;\n"
12935                "  }\n"
12936                "};\n",
12937                Style);
12938 
12939   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12940   verifyFormat("int f() {}", Style);
12941   verifyFormat("int f() { return 0; }", Style);
12942   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12943                "{}",
12944                Style);
12945   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12946                "{\n"
12947                "  return 0;\n"
12948                "}",
12949                Style);
12950 }
12951 
12952 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12953   FormatStyle Style = getLLVMStyleWithColumns(40);
12954   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12955   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12956   Style.BraceWrapping.AfterFunction = true;
12957   Style.BraceWrapping.SplitEmptyFunction = true;
12958   Style.BraceWrapping.SplitEmptyRecord = false;
12959 
12960   verifyFormat("class C {};", Style);
12961   verifyFormat("struct C {};", Style);
12962   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12963                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12964                "{\n"
12965                "}",
12966                Style);
12967   verifyFormat("class C {\n"
12968                "  C()\n"
12969                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12970                "        bbbbbbbbbbbbbbbbbbb()\n"
12971                "  {\n"
12972                "  }\n"
12973                "  void\n"
12974                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12975                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12976                "  {\n"
12977                "  }\n"
12978                "};",
12979                Style);
12980 }
12981 
12982 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12983   FormatStyle Style = getLLVMStyle();
12984   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12985   verifyFormat("#ifdef A\n"
12986                "int f() {}\n"
12987                "#else\n"
12988                "int g() {}\n"
12989                "#endif",
12990                Style);
12991 }
12992 
12993 TEST_F(FormatTest, SplitEmptyClass) {
12994   FormatStyle Style = getLLVMStyle();
12995   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12996   Style.BraceWrapping.AfterClass = true;
12997   Style.BraceWrapping.SplitEmptyRecord = false;
12998 
12999   verifyFormat("class Foo\n"
13000                "{};",
13001                Style);
13002   verifyFormat("/* something */ class Foo\n"
13003                "{};",
13004                Style);
13005   verifyFormat("template <typename X> class Foo\n"
13006                "{};",
13007                Style);
13008   verifyFormat("class Foo\n"
13009                "{\n"
13010                "  Foo();\n"
13011                "};",
13012                Style);
13013   verifyFormat("typedef class Foo\n"
13014                "{\n"
13015                "} Foo_t;",
13016                Style);
13017 
13018   Style.BraceWrapping.SplitEmptyRecord = true;
13019   Style.BraceWrapping.AfterStruct = true;
13020   verifyFormat("class rep\n"
13021                "{\n"
13022                "};",
13023                Style);
13024   verifyFormat("struct rep\n"
13025                "{\n"
13026                "};",
13027                Style);
13028   verifyFormat("template <typename T> class rep\n"
13029                "{\n"
13030                "};",
13031                Style);
13032   verifyFormat("template <typename T> struct rep\n"
13033                "{\n"
13034                "};",
13035                Style);
13036   verifyFormat("class rep\n"
13037                "{\n"
13038                "  int x;\n"
13039                "};",
13040                Style);
13041   verifyFormat("struct rep\n"
13042                "{\n"
13043                "  int x;\n"
13044                "};",
13045                Style);
13046   verifyFormat("template <typename T> class rep\n"
13047                "{\n"
13048                "  int x;\n"
13049                "};",
13050                Style);
13051   verifyFormat("template <typename T> struct rep\n"
13052                "{\n"
13053                "  int x;\n"
13054                "};",
13055                Style);
13056   verifyFormat("template <typename T> class rep // Foo\n"
13057                "{\n"
13058                "  int x;\n"
13059                "};",
13060                Style);
13061   verifyFormat("template <typename T> struct rep // Bar\n"
13062                "{\n"
13063                "  int x;\n"
13064                "};",
13065                Style);
13066 
13067   verifyFormat("template <typename T> class rep<T>\n"
13068                "{\n"
13069                "  int x;\n"
13070                "};",
13071                Style);
13072 
13073   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13074                "{\n"
13075                "  int x;\n"
13076                "};",
13077                Style);
13078   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13079                "{\n"
13080                "};",
13081                Style);
13082 
13083   verifyFormat("#include \"stdint.h\"\n"
13084                "namespace rep {}",
13085                Style);
13086   verifyFormat("#include <stdint.h>\n"
13087                "namespace rep {}",
13088                Style);
13089   verifyFormat("#include <stdint.h>\n"
13090                "namespace rep {}",
13091                "#include <stdint.h>\n"
13092                "namespace rep {\n"
13093                "\n"
13094                "\n"
13095                "}",
13096                Style);
13097 }
13098 
13099 TEST_F(FormatTest, SplitEmptyStruct) {
13100   FormatStyle Style = getLLVMStyle();
13101   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13102   Style.BraceWrapping.AfterStruct = true;
13103   Style.BraceWrapping.SplitEmptyRecord = false;
13104 
13105   verifyFormat("struct Foo\n"
13106                "{};",
13107                Style);
13108   verifyFormat("/* something */ struct Foo\n"
13109                "{};",
13110                Style);
13111   verifyFormat("template <typename X> struct Foo\n"
13112                "{};",
13113                Style);
13114   verifyFormat("struct Foo\n"
13115                "{\n"
13116                "  Foo();\n"
13117                "};",
13118                Style);
13119   verifyFormat("typedef struct Foo\n"
13120                "{\n"
13121                "} Foo_t;",
13122                Style);
13123   // typedef struct Bar {} Bar_t;
13124 }
13125 
13126 TEST_F(FormatTest, SplitEmptyUnion) {
13127   FormatStyle Style = getLLVMStyle();
13128   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13129   Style.BraceWrapping.AfterUnion = true;
13130   Style.BraceWrapping.SplitEmptyRecord = false;
13131 
13132   verifyFormat("union Foo\n"
13133                "{};",
13134                Style);
13135   verifyFormat("/* something */ union Foo\n"
13136                "{};",
13137                Style);
13138   verifyFormat("union Foo\n"
13139                "{\n"
13140                "  A,\n"
13141                "};",
13142                Style);
13143   verifyFormat("typedef union Foo\n"
13144                "{\n"
13145                "} Foo_t;",
13146                Style);
13147 }
13148 
13149 TEST_F(FormatTest, SplitEmptyNamespace) {
13150   FormatStyle Style = getLLVMStyle();
13151   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13152   Style.BraceWrapping.AfterNamespace = true;
13153   Style.BraceWrapping.SplitEmptyNamespace = false;
13154 
13155   verifyFormat("namespace Foo\n"
13156                "{};",
13157                Style);
13158   verifyFormat("/* something */ namespace Foo\n"
13159                "{};",
13160                Style);
13161   verifyFormat("inline namespace Foo\n"
13162                "{};",
13163                Style);
13164   verifyFormat("/* something */ inline namespace Foo\n"
13165                "{};",
13166                Style);
13167   verifyFormat("export namespace Foo\n"
13168                "{};",
13169                Style);
13170   verifyFormat("namespace Foo\n"
13171                "{\n"
13172                "void Bar();\n"
13173                "};",
13174                Style);
13175 }
13176 
13177 TEST_F(FormatTest, NeverMergeShortRecords) {
13178   FormatStyle Style = getLLVMStyle();
13179 
13180   verifyFormat("class Foo {\n"
13181                "  Foo();\n"
13182                "};",
13183                Style);
13184   verifyFormat("typedef class Foo {\n"
13185                "  Foo();\n"
13186                "} Foo_t;",
13187                Style);
13188   verifyFormat("struct Foo {\n"
13189                "  Foo();\n"
13190                "};",
13191                Style);
13192   verifyFormat("typedef struct Foo {\n"
13193                "  Foo();\n"
13194                "} Foo_t;",
13195                Style);
13196   verifyFormat("union Foo {\n"
13197                "  A,\n"
13198                "};",
13199                Style);
13200   verifyFormat("typedef union Foo {\n"
13201                "  A,\n"
13202                "} Foo_t;",
13203                Style);
13204   verifyFormat("namespace Foo {\n"
13205                "void Bar();\n"
13206                "};",
13207                Style);
13208 
13209   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13210   Style.BraceWrapping.AfterClass = true;
13211   Style.BraceWrapping.AfterStruct = true;
13212   Style.BraceWrapping.AfterUnion = true;
13213   Style.BraceWrapping.AfterNamespace = true;
13214   verifyFormat("class Foo\n"
13215                "{\n"
13216                "  Foo();\n"
13217                "};",
13218                Style);
13219   verifyFormat("typedef class Foo\n"
13220                "{\n"
13221                "  Foo();\n"
13222                "} Foo_t;",
13223                Style);
13224   verifyFormat("struct Foo\n"
13225                "{\n"
13226                "  Foo();\n"
13227                "};",
13228                Style);
13229   verifyFormat("typedef struct Foo\n"
13230                "{\n"
13231                "  Foo();\n"
13232                "} Foo_t;",
13233                Style);
13234   verifyFormat("union Foo\n"
13235                "{\n"
13236                "  A,\n"
13237                "};",
13238                Style);
13239   verifyFormat("typedef union Foo\n"
13240                "{\n"
13241                "  A,\n"
13242                "} Foo_t;",
13243                Style);
13244   verifyFormat("namespace Foo\n"
13245                "{\n"
13246                "void Bar();\n"
13247                "};",
13248                Style);
13249 }
13250 
13251 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
13252   // Elaborate type variable declarations.
13253   verifyFormat("struct foo a = {bar};\nint n;");
13254   verifyFormat("class foo a = {bar};\nint n;");
13255   verifyFormat("union foo a = {bar};\nint n;");
13256 
13257   // Elaborate types inside function definitions.
13258   verifyFormat("struct foo f() {}\nint n;");
13259   verifyFormat("class foo f() {}\nint n;");
13260   verifyFormat("union foo f() {}\nint n;");
13261 
13262   // Templates.
13263   verifyFormat("template <class X> void f() {}\nint n;");
13264   verifyFormat("template <struct X> void f() {}\nint n;");
13265   verifyFormat("template <union X> void f() {}\nint n;");
13266 
13267   // Actual definitions...
13268   verifyFormat("struct {\n} n;");
13269   verifyFormat(
13270       "template <template <class T, class Y>, class Z> class X {\n} n;");
13271   verifyFormat("union Z {\n  int n;\n} x;");
13272   verifyFormat("class MACRO Z {\n} n;");
13273   verifyFormat("class MACRO(X) Z {\n} n;");
13274   verifyFormat("class __attribute__(X) Z {\n} n;");
13275   verifyFormat("class __declspec(X) Z {\n} n;");
13276   verifyFormat("class A##B##C {\n} n;");
13277   verifyFormat("class alignas(16) Z {\n} n;");
13278   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
13279   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
13280 
13281   // Redefinition from nested context:
13282   verifyFormat("class A::B::C {\n} n;");
13283 
13284   // Template definitions.
13285   verifyFormat(
13286       "template <typename F>\n"
13287       "Matcher(const Matcher<F> &Other,\n"
13288       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
13289       "                             !is_same<F, T>::value>::type * = 0)\n"
13290       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
13291 
13292   // FIXME: This is still incorrectly handled at the formatter side.
13293   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
13294   verifyFormat("int i = SomeFunction(a<b, a> b);");
13295 
13296   // FIXME:
13297   // This now gets parsed incorrectly as class definition.
13298   // verifyFormat("class A<int> f() {\n}\nint n;");
13299 
13300   // Elaborate types where incorrectly parsing the structural element would
13301   // break the indent.
13302   verifyFormat("if (true)\n"
13303                "  class X x;\n"
13304                "else\n"
13305                "  f();\n");
13306 
13307   // This is simply incomplete. Formatting is not important, but must not crash.
13308   verifyFormat("class A:");
13309 }
13310 
13311 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
13312   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
13313             format("#error Leave     all         white!!!!! space* alone!\n"));
13314   EXPECT_EQ(
13315       "#warning Leave     all         white!!!!! space* alone!\n",
13316       format("#warning Leave     all         white!!!!! space* alone!\n"));
13317   EXPECT_EQ("#error 1", format("  #  error   1"));
13318   EXPECT_EQ("#warning 1", format("  #  warning 1"));
13319 }
13320 
13321 TEST_F(FormatTest, FormatHashIfExpressions) {
13322   verifyFormat("#if AAAA && BBBB");
13323   verifyFormat("#if (AAAA && BBBB)");
13324   verifyFormat("#elif (AAAA && BBBB)");
13325   // FIXME: Come up with a better indentation for #elif.
13326   verifyFormat(
13327       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
13328       "    defined(BBBBBBBB)\n"
13329       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
13330       "    defined(BBBBBBBB)\n"
13331       "#endif",
13332       getLLVMStyleWithColumns(65));
13333 }
13334 
13335 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
13336   FormatStyle AllowsMergedIf = getGoogleStyle();
13337   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
13338       FormatStyle::SIS_WithoutElse;
13339   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
13340   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
13341   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
13342   EXPECT_EQ("if (true) return 42;",
13343             format("if (true)\nreturn 42;", AllowsMergedIf));
13344   FormatStyle ShortMergedIf = AllowsMergedIf;
13345   ShortMergedIf.ColumnLimit = 25;
13346   verifyFormat("#define A \\\n"
13347                "  if (true) return 42;",
13348                ShortMergedIf);
13349   verifyFormat("#define A \\\n"
13350                "  f();    \\\n"
13351                "  if (true)\n"
13352                "#define B",
13353                ShortMergedIf);
13354   verifyFormat("#define A \\\n"
13355                "  f();    \\\n"
13356                "  if (true)\n"
13357                "g();",
13358                ShortMergedIf);
13359   verifyFormat("{\n"
13360                "#ifdef A\n"
13361                "  // Comment\n"
13362                "  if (true) continue;\n"
13363                "#endif\n"
13364                "  // Comment\n"
13365                "  if (true) continue;\n"
13366                "}",
13367                ShortMergedIf);
13368   ShortMergedIf.ColumnLimit = 33;
13369   verifyFormat("#define A \\\n"
13370                "  if constexpr (true) return 42;",
13371                ShortMergedIf);
13372   verifyFormat("#define A \\\n"
13373                "  if CONSTEXPR (true) return 42;",
13374                ShortMergedIf);
13375   ShortMergedIf.ColumnLimit = 29;
13376   verifyFormat("#define A                   \\\n"
13377                "  if (aaaaaaaaaa) return 1; \\\n"
13378                "  return 2;",
13379                ShortMergedIf);
13380   ShortMergedIf.ColumnLimit = 28;
13381   verifyFormat("#define A         \\\n"
13382                "  if (aaaaaaaaaa) \\\n"
13383                "    return 1;     \\\n"
13384                "  return 2;",
13385                ShortMergedIf);
13386   verifyFormat("#define A                \\\n"
13387                "  if constexpr (aaaaaaa) \\\n"
13388                "    return 1;            \\\n"
13389                "  return 2;",
13390                ShortMergedIf);
13391   verifyFormat("#define A                \\\n"
13392                "  if CONSTEXPR (aaaaaaa) \\\n"
13393                "    return 1;            \\\n"
13394                "  return 2;",
13395                ShortMergedIf);
13396 
13397   verifyFormat("//\n"
13398                "#define a \\\n"
13399                "  if      \\\n"
13400                "  0",
13401                getChromiumStyle(FormatStyle::LK_Cpp));
13402 }
13403 
13404 TEST_F(FormatTest, FormatStarDependingOnContext) {
13405   verifyFormat("void f(int *a);");
13406   verifyFormat("void f() { f(fint * b); }");
13407   verifyFormat("class A {\n  void f(int *a);\n};");
13408   verifyFormat("class A {\n  int *a;\n};");
13409   verifyFormat("namespace a {\n"
13410                "namespace b {\n"
13411                "class A {\n"
13412                "  void f() {}\n"
13413                "  int *a;\n"
13414                "};\n"
13415                "} // namespace b\n"
13416                "} // namespace a");
13417 }
13418 
13419 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13420   verifyFormat("while");
13421   verifyFormat("operator");
13422 }
13423 
13424 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13425   // This code would be painfully slow to format if we didn't skip it.
13426   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
13427                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13428                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13429                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13430                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13431                    "A(1, 1)\n"
13432                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
13433                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13434                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13435                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13436                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13437                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13438                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13439                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13440                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13441                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
13442   // Deeply nested part is untouched, rest is formatted.
13443   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13444             format(std::string("int    i;\n") + Code + "int    j;\n",
13445                    getLLVMStyle(), SC_ExpectIncomplete));
13446 }
13447 
13448 //===----------------------------------------------------------------------===//
13449 // Objective-C tests.
13450 //===----------------------------------------------------------------------===//
13451 
13452 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13453   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13454   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13455             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13456   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13457   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13458   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13459             format("-(NSInteger)Method3:(id)anObject;"));
13460   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13461             format("-(NSInteger)Method4:(id)anObject;"));
13462   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13463             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13464   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13465             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13466   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13467             "forAllCells:(BOOL)flag;",
13468             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13469                    "forAllCells:(BOOL)flag;"));
13470 
13471   // Very long objectiveC method declaration.
13472   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13473                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13474   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13475                "                    inRange:(NSRange)range\n"
13476                "                   outRange:(NSRange)out_range\n"
13477                "                  outRange1:(NSRange)out_range1\n"
13478                "                  outRange2:(NSRange)out_range2\n"
13479                "                  outRange3:(NSRange)out_range3\n"
13480                "                  outRange4:(NSRange)out_range4\n"
13481                "                  outRange5:(NSRange)out_range5\n"
13482                "                  outRange6:(NSRange)out_range6\n"
13483                "                  outRange7:(NSRange)out_range7\n"
13484                "                  outRange8:(NSRange)out_range8\n"
13485                "                  outRange9:(NSRange)out_range9;");
13486 
13487   // When the function name has to be wrapped.
13488   FormatStyle Style = getLLVMStyle();
13489   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13490   // and always indents instead.
13491   Style.IndentWrappedFunctionNames = false;
13492   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13493                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13494                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13495                "}",
13496                Style);
13497   Style.IndentWrappedFunctionNames = true;
13498   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13499                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13500                "               anotherName:(NSString)dddddddddddddd {\n"
13501                "}",
13502                Style);
13503 
13504   verifyFormat("- (int)sum:(vector<int>)numbers;");
13505   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13506   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13507   // protocol lists (but not for template classes):
13508   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13509 
13510   verifyFormat("- (int (*)())foo:(int (*)())f;");
13511   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13512 
13513   // If there's no return type (very rare in practice!), LLVM and Google style
13514   // agree.
13515   verifyFormat("- foo;");
13516   verifyFormat("- foo:(int)f;");
13517   verifyGoogleFormat("- foo:(int)foo;");
13518 }
13519 
13520 TEST_F(FormatTest, BreaksStringLiterals) {
13521   EXPECT_EQ("\"some text \"\n"
13522             "\"other\";",
13523             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13524   EXPECT_EQ("\"some text \"\n"
13525             "\"other\";",
13526             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13527   EXPECT_EQ(
13528       "#define A  \\\n"
13529       "  \"some \"  \\\n"
13530       "  \"text \"  \\\n"
13531       "  \"other\";",
13532       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13533   EXPECT_EQ(
13534       "#define A  \\\n"
13535       "  \"so \"    \\\n"
13536       "  \"text \"  \\\n"
13537       "  \"other\";",
13538       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13539 
13540   EXPECT_EQ("\"some text\"",
13541             format("\"some text\"", getLLVMStyleWithColumns(1)));
13542   EXPECT_EQ("\"some text\"",
13543             format("\"some text\"", getLLVMStyleWithColumns(11)));
13544   EXPECT_EQ("\"some \"\n"
13545             "\"text\"",
13546             format("\"some text\"", getLLVMStyleWithColumns(10)));
13547   EXPECT_EQ("\"some \"\n"
13548             "\"text\"",
13549             format("\"some text\"", getLLVMStyleWithColumns(7)));
13550   EXPECT_EQ("\"some\"\n"
13551             "\" tex\"\n"
13552             "\"t\"",
13553             format("\"some text\"", getLLVMStyleWithColumns(6)));
13554   EXPECT_EQ("\"some\"\n"
13555             "\" tex\"\n"
13556             "\" and\"",
13557             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13558   EXPECT_EQ("\"some\"\n"
13559             "\"/tex\"\n"
13560             "\"/and\"",
13561             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13562 
13563   EXPECT_EQ("variable =\n"
13564             "    \"long string \"\n"
13565             "    \"literal\";",
13566             format("variable = \"long string literal\";",
13567                    getLLVMStyleWithColumns(20)));
13568 
13569   EXPECT_EQ("variable = f(\n"
13570             "    \"long string \"\n"
13571             "    \"literal\",\n"
13572             "    short,\n"
13573             "    loooooooooooooooooooong);",
13574             format("variable = f(\"long string literal\", short, "
13575                    "loooooooooooooooooooong);",
13576                    getLLVMStyleWithColumns(20)));
13577 
13578   EXPECT_EQ(
13579       "f(g(\"long string \"\n"
13580       "    \"literal\"),\n"
13581       "  b);",
13582       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13583   EXPECT_EQ("f(g(\"long string \"\n"
13584             "    \"literal\",\n"
13585             "    a),\n"
13586             "  b);",
13587             format("f(g(\"long string literal\", a), b);",
13588                    getLLVMStyleWithColumns(20)));
13589   EXPECT_EQ(
13590       "f(\"one two\".split(\n"
13591       "    variable));",
13592       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13593   EXPECT_EQ("f(\"one two three four five six \"\n"
13594             "  \"seven\".split(\n"
13595             "      really_looooong_variable));",
13596             format("f(\"one two three four five six seven\"."
13597                    "split(really_looooong_variable));",
13598                    getLLVMStyleWithColumns(33)));
13599 
13600   EXPECT_EQ("f(\"some \"\n"
13601             "  \"text\",\n"
13602             "  other);",
13603             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13604 
13605   // Only break as a last resort.
13606   verifyFormat(
13607       "aaaaaaaaaaaaaaaaaaaa(\n"
13608       "    aaaaaaaaaaaaaaaaaaaa,\n"
13609       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13610 
13611   EXPECT_EQ("\"splitmea\"\n"
13612             "\"trandomp\"\n"
13613             "\"oint\"",
13614             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13615 
13616   EXPECT_EQ("\"split/\"\n"
13617             "\"pathat/\"\n"
13618             "\"slashes\"",
13619             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13620 
13621   EXPECT_EQ("\"split/\"\n"
13622             "\"pathat/\"\n"
13623             "\"slashes\"",
13624             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13625   EXPECT_EQ("\"split at \"\n"
13626             "\"spaces/at/\"\n"
13627             "\"slashes.at.any$\"\n"
13628             "\"non-alphanumeric%\"\n"
13629             "\"1111111111characte\"\n"
13630             "\"rs\"",
13631             format("\"split at "
13632                    "spaces/at/"
13633                    "slashes.at."
13634                    "any$non-"
13635                    "alphanumeric%"
13636                    "1111111111characte"
13637                    "rs\"",
13638                    getLLVMStyleWithColumns(20)));
13639 
13640   // Verify that splitting the strings understands
13641   // Style::AlwaysBreakBeforeMultilineStrings.
13642   EXPECT_EQ("aaaaaaaaaaaa(\n"
13643             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13644             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13645             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13646                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13647                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13648                    getGoogleStyle()));
13649   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13650             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13651             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13652                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13653                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13654                    getGoogleStyle()));
13655   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13656             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13657             format("llvm::outs() << "
13658                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13659                    "aaaaaaaaaaaaaaaaaaa\";"));
13660   EXPECT_EQ("ffff(\n"
13661             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13662             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13663             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13664                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13665                    getGoogleStyle()));
13666 
13667   FormatStyle Style = getLLVMStyleWithColumns(12);
13668   Style.BreakStringLiterals = false;
13669   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13670 
13671   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13672   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13673   EXPECT_EQ("#define A \\\n"
13674             "  \"some \" \\\n"
13675             "  \"text \" \\\n"
13676             "  \"other\";",
13677             format("#define A \"some text other\";", AlignLeft));
13678 }
13679 
13680 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13681   EXPECT_EQ("C a = \"some more \"\n"
13682             "      \"text\";",
13683             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13684 }
13685 
13686 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13687   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13688   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13689   EXPECT_EQ("int i = a(b());",
13690             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13691 }
13692 
13693 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13694   EXPECT_EQ(
13695       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13696       "(\n"
13697       "    \"x\t\");",
13698       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13699              "aaaaaaa("
13700              "\"x\t\");"));
13701 }
13702 
13703 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13704   EXPECT_EQ(
13705       "u8\"utf8 string \"\n"
13706       "u8\"literal\";",
13707       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13708   EXPECT_EQ(
13709       "u\"utf16 string \"\n"
13710       "u\"literal\";",
13711       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13712   EXPECT_EQ(
13713       "U\"utf32 string \"\n"
13714       "U\"literal\";",
13715       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13716   EXPECT_EQ("L\"wide string \"\n"
13717             "L\"literal\";",
13718             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13719   EXPECT_EQ("@\"NSString \"\n"
13720             "@\"literal\";",
13721             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13722   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13723 
13724   // This input makes clang-format try to split the incomplete unicode escape
13725   // sequence, which used to lead to a crasher.
13726   verifyNoCrash(
13727       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13728       getLLVMStyleWithColumns(60));
13729 }
13730 
13731 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13732   FormatStyle Style = getGoogleStyleWithColumns(15);
13733   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13734   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13735   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13736   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13737   EXPECT_EQ("u8R\"x(raw literal)x\";",
13738             format("u8R\"x(raw literal)x\";", Style));
13739 }
13740 
13741 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13742   FormatStyle Style = getLLVMStyleWithColumns(20);
13743   EXPECT_EQ(
13744       "_T(\"aaaaaaaaaaaaaa\")\n"
13745       "_T(\"aaaaaaaaaaaaaa\")\n"
13746       "_T(\"aaaaaaaaaaaa\")",
13747       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13748   EXPECT_EQ("f(x,\n"
13749             "  _T(\"aaaaaaaaaaaa\")\n"
13750             "  _T(\"aaa\"),\n"
13751             "  z);",
13752             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13753 
13754   // FIXME: Handle embedded spaces in one iteration.
13755   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13756   //            "_T(\"aaaaaaaaaaaaa\")\n"
13757   //            "_T(\"aaaaaaaaaaaaa\")\n"
13758   //            "_T(\"a\")",
13759   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13760   //                   getLLVMStyleWithColumns(20)));
13761   EXPECT_EQ(
13762       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13763       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13764   EXPECT_EQ("f(\n"
13765             "#if !TEST\n"
13766             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13767             "#endif\n"
13768             ");",
13769             format("f(\n"
13770                    "#if !TEST\n"
13771                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13772                    "#endif\n"
13773                    ");"));
13774   EXPECT_EQ("f(\n"
13775             "\n"
13776             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13777             format("f(\n"
13778                    "\n"
13779                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13780   // Regression test for accessing tokens past the end of a vector in the
13781   // TokenLexer.
13782   verifyNoCrash(R"(_T(
13783 "
13784 )
13785 )");
13786 }
13787 
13788 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13789   // In a function call with two operands, the second can be broken with no line
13790   // break before it.
13791   EXPECT_EQ(
13792       "func(a, \"long long \"\n"
13793       "        \"long long\");",
13794       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13795   // In a function call with three operands, the second must be broken with a
13796   // line break before it.
13797   EXPECT_EQ("func(a,\n"
13798             "     \"long long long \"\n"
13799             "     \"long\",\n"
13800             "     c);",
13801             format("func(a, \"long long long long\", c);",
13802                    getLLVMStyleWithColumns(24)));
13803   // In a function call with three operands, the third must be broken with a
13804   // line break before it.
13805   EXPECT_EQ("func(a, b,\n"
13806             "     \"long long long \"\n"
13807             "     \"long\");",
13808             format("func(a, b, \"long long long long\");",
13809                    getLLVMStyleWithColumns(24)));
13810   // In a function call with three operands, both the second and the third must
13811   // be broken with a line break before them.
13812   EXPECT_EQ("func(a,\n"
13813             "     \"long long long \"\n"
13814             "     \"long\",\n"
13815             "     \"long long long \"\n"
13816             "     \"long\");",
13817             format("func(a, \"long long long long\", \"long long long long\");",
13818                    getLLVMStyleWithColumns(24)));
13819   // In a chain of << with two operands, the second can be broken with no line
13820   // break before it.
13821   EXPECT_EQ("a << \"line line \"\n"
13822             "     \"line\";",
13823             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13824   // In a chain of << with three operands, the second can be broken with no line
13825   // break before it.
13826   EXPECT_EQ(
13827       "abcde << \"line \"\n"
13828       "         \"line line\"\n"
13829       "      << c;",
13830       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13831   // In a chain of << with three operands, the third must be broken with a line
13832   // break before it.
13833   EXPECT_EQ(
13834       "a << b\n"
13835       "  << \"line line \"\n"
13836       "     \"line\";",
13837       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13838   // In a chain of << with three operands, the second can be broken with no line
13839   // break before it and the third must be broken with a line break before it.
13840   EXPECT_EQ("abcd << \"line line \"\n"
13841             "        \"line\"\n"
13842             "     << \"line line \"\n"
13843             "        \"line\";",
13844             format("abcd << \"line line line\" << \"line line line\";",
13845                    getLLVMStyleWithColumns(20)));
13846   // In a chain of binary operators with two operands, the second can be broken
13847   // with no line break before it.
13848   EXPECT_EQ(
13849       "abcd + \"line line \"\n"
13850       "       \"line line\";",
13851       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13852   // In a chain of binary operators with three operands, the second must be
13853   // broken with a line break before it.
13854   EXPECT_EQ("abcd +\n"
13855             "    \"line line \"\n"
13856             "    \"line line\" +\n"
13857             "    e;",
13858             format("abcd + \"line line line line\" + e;",
13859                    getLLVMStyleWithColumns(20)));
13860   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13861   // the first must be broken with a line break before it.
13862   FormatStyle Style = getLLVMStyleWithColumns(25);
13863   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13864   EXPECT_EQ("someFunction(\n"
13865             "    \"long long long \"\n"
13866             "    \"long\",\n"
13867             "    a);",
13868             format("someFunction(\"long long long long\", a);", Style));
13869 }
13870 
13871 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13872   EXPECT_EQ(
13873       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13874       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13875       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13876       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13877              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13878              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13879 }
13880 
13881 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13882   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13883             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13884   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13885             "multiline raw string literal xxxxxxxxxxxxxx\n"
13886             ")x\",\n"
13887             "              a),\n"
13888             "            b);",
13889             format("fffffffffff(g(R\"x(\n"
13890                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13891                    ")x\", a), b);",
13892                    getGoogleStyleWithColumns(20)));
13893   EXPECT_EQ("fffffffffff(\n"
13894             "    g(R\"x(qqq\n"
13895             "multiline raw string literal xxxxxxxxxxxxxx\n"
13896             ")x\",\n"
13897             "      a),\n"
13898             "    b);",
13899             format("fffffffffff(g(R\"x(qqq\n"
13900                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13901                    ")x\", a), b);",
13902                    getGoogleStyleWithColumns(20)));
13903 
13904   EXPECT_EQ("fffffffffff(R\"x(\n"
13905             "multiline raw string literal xxxxxxxxxxxxxx\n"
13906             ")x\");",
13907             format("fffffffffff(R\"x(\n"
13908                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13909                    ")x\");",
13910                    getGoogleStyleWithColumns(20)));
13911   EXPECT_EQ("fffffffffff(R\"x(\n"
13912             "multiline raw string literal xxxxxxxxxxxxxx\n"
13913             ")x\" + bbbbbb);",
13914             format("fffffffffff(R\"x(\n"
13915                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13916                    ")x\" +   bbbbbb);",
13917                    getGoogleStyleWithColumns(20)));
13918   EXPECT_EQ("fffffffffff(\n"
13919             "    R\"x(\n"
13920             "multiline raw string literal xxxxxxxxxxxxxx\n"
13921             ")x\" +\n"
13922             "    bbbbbb);",
13923             format("fffffffffff(\n"
13924                    " R\"x(\n"
13925                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13926                    ")x\" + bbbbbb);",
13927                    getGoogleStyleWithColumns(20)));
13928   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13929             format("fffffffffff(\n"
13930                    " R\"(single line raw string)\" + bbbbbb);"));
13931 }
13932 
13933 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13934   verifyFormat("string a = \"unterminated;");
13935   EXPECT_EQ("function(\"unterminated,\n"
13936             "         OtherParameter);",
13937             format("function(  \"unterminated,\n"
13938                    "    OtherParameter);"));
13939 }
13940 
13941 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13942   FormatStyle Style = getLLVMStyle();
13943   Style.Standard = FormatStyle::LS_Cpp03;
13944   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13945             format("#define x(_a) printf(\"foo\"_a);", Style));
13946 }
13947 
13948 TEST_F(FormatTest, CppLexVersion) {
13949   FormatStyle Style = getLLVMStyle();
13950   // Formatting of x * y differs if x is a type.
13951   verifyFormat("void foo() { MACRO(a * b); }", Style);
13952   verifyFormat("void foo() { MACRO(int *b); }", Style);
13953 
13954   // LLVM style uses latest lexer.
13955   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13956   Style.Standard = FormatStyle::LS_Cpp17;
13957   // But in c++17, char8_t isn't a keyword.
13958   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13959 }
13960 
13961 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13962 
13963 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13964   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13965             "             \"ddeeefff\");",
13966             format("someFunction(\"aaabbbcccdddeeefff\");",
13967                    getLLVMStyleWithColumns(25)));
13968   EXPECT_EQ("someFunction1234567890(\n"
13969             "    \"aaabbbcccdddeeefff\");",
13970             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13971                    getLLVMStyleWithColumns(26)));
13972   EXPECT_EQ("someFunction1234567890(\n"
13973             "    \"aaabbbcccdddeeeff\"\n"
13974             "    \"f\");",
13975             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13976                    getLLVMStyleWithColumns(25)));
13977   EXPECT_EQ("someFunction1234567890(\n"
13978             "    \"aaabbbcccdddeeeff\"\n"
13979             "    \"f\");",
13980             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13981                    getLLVMStyleWithColumns(24)));
13982   EXPECT_EQ("someFunction(\n"
13983             "    \"aaabbbcc ddde \"\n"
13984             "    \"efff\");",
13985             format("someFunction(\"aaabbbcc ddde efff\");",
13986                    getLLVMStyleWithColumns(25)));
13987   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13988             "             \"ddeeefff\");",
13989             format("someFunction(\"aaabbbccc ddeeefff\");",
13990                    getLLVMStyleWithColumns(25)));
13991   EXPECT_EQ("someFunction1234567890(\n"
13992             "    \"aaabb \"\n"
13993             "    \"cccdddeeefff\");",
13994             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13995                    getLLVMStyleWithColumns(25)));
13996   EXPECT_EQ("#define A          \\\n"
13997             "  string s =       \\\n"
13998             "      \"123456789\"  \\\n"
13999             "      \"0\";         \\\n"
14000             "  int i;",
14001             format("#define A string s = \"1234567890\"; int i;",
14002                    getLLVMStyleWithColumns(20)));
14003   EXPECT_EQ("someFunction(\n"
14004             "    \"aaabbbcc \"\n"
14005             "    \"dddeeefff\");",
14006             format("someFunction(\"aaabbbcc dddeeefff\");",
14007                    getLLVMStyleWithColumns(25)));
14008 }
14009 
14010 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
14011   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
14012   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
14013   EXPECT_EQ("\"test\"\n"
14014             "\"\\n\"",
14015             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
14016   EXPECT_EQ("\"tes\\\\\"\n"
14017             "\"n\"",
14018             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
14019   EXPECT_EQ("\"\\\\\\\\\"\n"
14020             "\"\\n\"",
14021             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
14022   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
14023   EXPECT_EQ("\"\\uff01\"\n"
14024             "\"test\"",
14025             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
14026   EXPECT_EQ("\"\\Uff01ff02\"",
14027             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
14028   EXPECT_EQ("\"\\x000000000001\"\n"
14029             "\"next\"",
14030             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
14031   EXPECT_EQ("\"\\x000000000001next\"",
14032             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
14033   EXPECT_EQ("\"\\x000000000001\"",
14034             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
14035   EXPECT_EQ("\"test\"\n"
14036             "\"\\000000\"\n"
14037             "\"000001\"",
14038             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
14039   EXPECT_EQ("\"test\\000\"\n"
14040             "\"00000000\"\n"
14041             "\"1\"",
14042             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
14043 }
14044 
14045 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
14046   verifyFormat("void f() {\n"
14047                "  return g() {}\n"
14048                "  void h() {}");
14049   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
14050                "g();\n"
14051                "}");
14052 }
14053 
14054 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
14055   verifyFormat(
14056       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
14057 }
14058 
14059 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
14060   verifyFormat("class X {\n"
14061                "  void f() {\n"
14062                "  }\n"
14063                "};",
14064                getLLVMStyleWithColumns(12));
14065 }
14066 
14067 TEST_F(FormatTest, ConfigurableIndentWidth) {
14068   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
14069   EightIndent.IndentWidth = 8;
14070   EightIndent.ContinuationIndentWidth = 8;
14071   verifyFormat("void f() {\n"
14072                "        someFunction();\n"
14073                "        if (true) {\n"
14074                "                f();\n"
14075                "        }\n"
14076                "}",
14077                EightIndent);
14078   verifyFormat("class X {\n"
14079                "        void f() {\n"
14080                "        }\n"
14081                "};",
14082                EightIndent);
14083   verifyFormat("int x[] = {\n"
14084                "        call(),\n"
14085                "        call()};",
14086                EightIndent);
14087 }
14088 
14089 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
14090   verifyFormat("double\n"
14091                "f();",
14092                getLLVMStyleWithColumns(8));
14093 }
14094 
14095 TEST_F(FormatTest, ConfigurableUseOfTab) {
14096   FormatStyle Tab = getLLVMStyleWithColumns(42);
14097   Tab.IndentWidth = 8;
14098   Tab.UseTab = FormatStyle::UT_Always;
14099   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14100 
14101   EXPECT_EQ("if (aaaaaaaa && // q\n"
14102             "    bb)\t\t// w\n"
14103             "\t;",
14104             format("if (aaaaaaaa &&// q\n"
14105                    "bb)// w\n"
14106                    ";",
14107                    Tab));
14108   EXPECT_EQ("if (aaa && bbb) // w\n"
14109             "\t;",
14110             format("if(aaa&&bbb)// w\n"
14111                    ";",
14112                    Tab));
14113 
14114   verifyFormat("class X {\n"
14115                "\tvoid f() {\n"
14116                "\t\tsomeFunction(parameter1,\n"
14117                "\t\t\t     parameter2);\n"
14118                "\t}\n"
14119                "};",
14120                Tab);
14121   verifyFormat("#define A                        \\\n"
14122                "\tvoid f() {               \\\n"
14123                "\t\tsomeFunction(    \\\n"
14124                "\t\t    parameter1,  \\\n"
14125                "\t\t    parameter2); \\\n"
14126                "\t}",
14127                Tab);
14128   verifyFormat("int a;\t      // x\n"
14129                "int bbbbbbbb; // x\n",
14130                Tab);
14131 
14132   Tab.TabWidth = 4;
14133   Tab.IndentWidth = 8;
14134   verifyFormat("class TabWidth4Indent8 {\n"
14135                "\t\tvoid f() {\n"
14136                "\t\t\t\tsomeFunction(parameter1,\n"
14137                "\t\t\t\t\t\t\t parameter2);\n"
14138                "\t\t}\n"
14139                "};",
14140                Tab);
14141 
14142   Tab.TabWidth = 4;
14143   Tab.IndentWidth = 4;
14144   verifyFormat("class TabWidth4Indent4 {\n"
14145                "\tvoid f() {\n"
14146                "\t\tsomeFunction(parameter1,\n"
14147                "\t\t\t\t\t parameter2);\n"
14148                "\t}\n"
14149                "};",
14150                Tab);
14151 
14152   Tab.TabWidth = 8;
14153   Tab.IndentWidth = 4;
14154   verifyFormat("class TabWidth8Indent4 {\n"
14155                "    void f() {\n"
14156                "\tsomeFunction(parameter1,\n"
14157                "\t\t     parameter2);\n"
14158                "    }\n"
14159                "};",
14160                Tab);
14161 
14162   Tab.TabWidth = 8;
14163   Tab.IndentWidth = 8;
14164   EXPECT_EQ("/*\n"
14165             "\t      a\t\tcomment\n"
14166             "\t      in multiple lines\n"
14167             "       */",
14168             format("   /*\t \t \n"
14169                    " \t \t a\t\tcomment\t \t\n"
14170                    " \t \t in multiple lines\t\n"
14171                    " \t  */",
14172                    Tab));
14173 
14174   Tab.UseTab = FormatStyle::UT_ForIndentation;
14175   verifyFormat("{\n"
14176                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14177                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14178                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14179                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14180                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14181                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14182                "};",
14183                Tab);
14184   verifyFormat("enum AA {\n"
14185                "\ta1, // Force multiple lines\n"
14186                "\ta2,\n"
14187                "\ta3\n"
14188                "};",
14189                Tab);
14190   EXPECT_EQ("if (aaaaaaaa && // q\n"
14191             "    bb)         // w\n"
14192             "\t;",
14193             format("if (aaaaaaaa &&// q\n"
14194                    "bb)// w\n"
14195                    ";",
14196                    Tab));
14197   verifyFormat("class X {\n"
14198                "\tvoid f() {\n"
14199                "\t\tsomeFunction(parameter1,\n"
14200                "\t\t             parameter2);\n"
14201                "\t}\n"
14202                "};",
14203                Tab);
14204   verifyFormat("{\n"
14205                "\tQ(\n"
14206                "\t    {\n"
14207                "\t\t    int a;\n"
14208                "\t\t    someFunction(aaaaaaaa,\n"
14209                "\t\t                 bbbbbbb);\n"
14210                "\t    },\n"
14211                "\t    p);\n"
14212                "}",
14213                Tab);
14214   EXPECT_EQ("{\n"
14215             "\t/* aaaa\n"
14216             "\t   bbbb */\n"
14217             "}",
14218             format("{\n"
14219                    "/* aaaa\n"
14220                    "   bbbb */\n"
14221                    "}",
14222                    Tab));
14223   EXPECT_EQ("{\n"
14224             "\t/*\n"
14225             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14226             "\t  bbbbbbbbbbbbb\n"
14227             "\t*/\n"
14228             "}",
14229             format("{\n"
14230                    "/*\n"
14231                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14232                    "*/\n"
14233                    "}",
14234                    Tab));
14235   EXPECT_EQ("{\n"
14236             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14237             "\t// bbbbbbbbbbbbb\n"
14238             "}",
14239             format("{\n"
14240                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14241                    "}",
14242                    Tab));
14243   EXPECT_EQ("{\n"
14244             "\t/*\n"
14245             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14246             "\t  bbbbbbbbbbbbb\n"
14247             "\t*/\n"
14248             "}",
14249             format("{\n"
14250                    "\t/*\n"
14251                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14252                    "\t*/\n"
14253                    "}",
14254                    Tab));
14255   EXPECT_EQ("{\n"
14256             "\t/*\n"
14257             "\n"
14258             "\t*/\n"
14259             "}",
14260             format("{\n"
14261                    "\t/*\n"
14262                    "\n"
14263                    "\t*/\n"
14264                    "}",
14265                    Tab));
14266   EXPECT_EQ("{\n"
14267             "\t/*\n"
14268             " asdf\n"
14269             "\t*/\n"
14270             "}",
14271             format("{\n"
14272                    "\t/*\n"
14273                    " asdf\n"
14274                    "\t*/\n"
14275                    "}",
14276                    Tab));
14277 
14278   verifyFormat("void f() {\n"
14279                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14280                "\t            : bbbbbbbbbbbbbbbbbb\n"
14281                "}",
14282                Tab);
14283   FormatStyle TabNoBreak = Tab;
14284   TabNoBreak.BreakBeforeTernaryOperators = false;
14285   verifyFormat("void f() {\n"
14286                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14287                "\t              bbbbbbbbbbbbbbbbbb\n"
14288                "}",
14289                TabNoBreak);
14290   verifyFormat("void f() {\n"
14291                "\treturn true ?\n"
14292                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14293                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14294                "}",
14295                TabNoBreak);
14296 
14297   Tab.UseTab = FormatStyle::UT_Never;
14298   EXPECT_EQ("/*\n"
14299             "              a\t\tcomment\n"
14300             "              in multiple lines\n"
14301             "       */",
14302             format("   /*\t \t \n"
14303                    " \t \t a\t\tcomment\t \t\n"
14304                    " \t \t in multiple lines\t\n"
14305                    " \t  */",
14306                    Tab));
14307   EXPECT_EQ("/* some\n"
14308             "   comment */",
14309             format(" \t \t /* some\n"
14310                    " \t \t    comment */",
14311                    Tab));
14312   EXPECT_EQ("int a; /* some\n"
14313             "   comment */",
14314             format(" \t \t int a; /* some\n"
14315                    " \t \t    comment */",
14316                    Tab));
14317 
14318   EXPECT_EQ("int a; /* some\n"
14319             "comment */",
14320             format(" \t \t int\ta; /* some\n"
14321                    " \t \t    comment */",
14322                    Tab));
14323   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14324             "    comment */",
14325             format(" \t \t f(\"\t\t\"); /* some\n"
14326                    " \t \t    comment */",
14327                    Tab));
14328   EXPECT_EQ("{\n"
14329             "        /*\n"
14330             "         * Comment\n"
14331             "         */\n"
14332             "        int i;\n"
14333             "}",
14334             format("{\n"
14335                    "\t/*\n"
14336                    "\t * Comment\n"
14337                    "\t */\n"
14338                    "\t int i;\n"
14339                    "}",
14340                    Tab));
14341 
14342   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14343   Tab.TabWidth = 8;
14344   Tab.IndentWidth = 8;
14345   EXPECT_EQ("if (aaaaaaaa && // q\n"
14346             "    bb)         // w\n"
14347             "\t;",
14348             format("if (aaaaaaaa &&// q\n"
14349                    "bb)// w\n"
14350                    ";",
14351                    Tab));
14352   EXPECT_EQ("if (aaa && bbb) // w\n"
14353             "\t;",
14354             format("if(aaa&&bbb)// w\n"
14355                    ";",
14356                    Tab));
14357   verifyFormat("class X {\n"
14358                "\tvoid f() {\n"
14359                "\t\tsomeFunction(parameter1,\n"
14360                "\t\t\t     parameter2);\n"
14361                "\t}\n"
14362                "};",
14363                Tab);
14364   verifyFormat("#define A                        \\\n"
14365                "\tvoid f() {               \\\n"
14366                "\t\tsomeFunction(    \\\n"
14367                "\t\t    parameter1,  \\\n"
14368                "\t\t    parameter2); \\\n"
14369                "\t}",
14370                Tab);
14371   Tab.TabWidth = 4;
14372   Tab.IndentWidth = 8;
14373   verifyFormat("class TabWidth4Indent8 {\n"
14374                "\t\tvoid f() {\n"
14375                "\t\t\t\tsomeFunction(parameter1,\n"
14376                "\t\t\t\t\t\t\t parameter2);\n"
14377                "\t\t}\n"
14378                "};",
14379                Tab);
14380   Tab.TabWidth = 4;
14381   Tab.IndentWidth = 4;
14382   verifyFormat("class TabWidth4Indent4 {\n"
14383                "\tvoid f() {\n"
14384                "\t\tsomeFunction(parameter1,\n"
14385                "\t\t\t\t\t parameter2);\n"
14386                "\t}\n"
14387                "};",
14388                Tab);
14389   Tab.TabWidth = 8;
14390   Tab.IndentWidth = 4;
14391   verifyFormat("class TabWidth8Indent4 {\n"
14392                "    void f() {\n"
14393                "\tsomeFunction(parameter1,\n"
14394                "\t\t     parameter2);\n"
14395                "    }\n"
14396                "};",
14397                Tab);
14398   Tab.TabWidth = 8;
14399   Tab.IndentWidth = 8;
14400   EXPECT_EQ("/*\n"
14401             "\t      a\t\tcomment\n"
14402             "\t      in multiple lines\n"
14403             "       */",
14404             format("   /*\t \t \n"
14405                    " \t \t a\t\tcomment\t \t\n"
14406                    " \t \t in multiple lines\t\n"
14407                    " \t  */",
14408                    Tab));
14409   verifyFormat("{\n"
14410                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14411                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14412                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14413                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14414                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14415                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14416                "};",
14417                Tab);
14418   verifyFormat("enum AA {\n"
14419                "\ta1, // Force multiple lines\n"
14420                "\ta2,\n"
14421                "\ta3\n"
14422                "};",
14423                Tab);
14424   EXPECT_EQ("if (aaaaaaaa && // q\n"
14425             "    bb)         // w\n"
14426             "\t;",
14427             format("if (aaaaaaaa &&// q\n"
14428                    "bb)// w\n"
14429                    ";",
14430                    Tab));
14431   verifyFormat("class X {\n"
14432                "\tvoid f() {\n"
14433                "\t\tsomeFunction(parameter1,\n"
14434                "\t\t\t     parameter2);\n"
14435                "\t}\n"
14436                "};",
14437                Tab);
14438   verifyFormat("{\n"
14439                "\tQ(\n"
14440                "\t    {\n"
14441                "\t\t    int a;\n"
14442                "\t\t    someFunction(aaaaaaaa,\n"
14443                "\t\t\t\t bbbbbbb);\n"
14444                "\t    },\n"
14445                "\t    p);\n"
14446                "}",
14447                Tab);
14448   EXPECT_EQ("{\n"
14449             "\t/* aaaa\n"
14450             "\t   bbbb */\n"
14451             "}",
14452             format("{\n"
14453                    "/* aaaa\n"
14454                    "   bbbb */\n"
14455                    "}",
14456                    Tab));
14457   EXPECT_EQ("{\n"
14458             "\t/*\n"
14459             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14460             "\t  bbbbbbbbbbbbb\n"
14461             "\t*/\n"
14462             "}",
14463             format("{\n"
14464                    "/*\n"
14465                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14466                    "*/\n"
14467                    "}",
14468                    Tab));
14469   EXPECT_EQ("{\n"
14470             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14471             "\t// bbbbbbbbbbbbb\n"
14472             "}",
14473             format("{\n"
14474                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14475                    "}",
14476                    Tab));
14477   EXPECT_EQ("{\n"
14478             "\t/*\n"
14479             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14480             "\t  bbbbbbbbbbbbb\n"
14481             "\t*/\n"
14482             "}",
14483             format("{\n"
14484                    "\t/*\n"
14485                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14486                    "\t*/\n"
14487                    "}",
14488                    Tab));
14489   EXPECT_EQ("{\n"
14490             "\t/*\n"
14491             "\n"
14492             "\t*/\n"
14493             "}",
14494             format("{\n"
14495                    "\t/*\n"
14496                    "\n"
14497                    "\t*/\n"
14498                    "}",
14499                    Tab));
14500   EXPECT_EQ("{\n"
14501             "\t/*\n"
14502             " asdf\n"
14503             "\t*/\n"
14504             "}",
14505             format("{\n"
14506                    "\t/*\n"
14507                    " asdf\n"
14508                    "\t*/\n"
14509                    "}",
14510                    Tab));
14511   EXPECT_EQ("/* some\n"
14512             "   comment */",
14513             format(" \t \t /* some\n"
14514                    " \t \t    comment */",
14515                    Tab));
14516   EXPECT_EQ("int a; /* some\n"
14517             "   comment */",
14518             format(" \t \t int a; /* some\n"
14519                    " \t \t    comment */",
14520                    Tab));
14521   EXPECT_EQ("int a; /* some\n"
14522             "comment */",
14523             format(" \t \t int\ta; /* some\n"
14524                    " \t \t    comment */",
14525                    Tab));
14526   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14527             "    comment */",
14528             format(" \t \t f(\"\t\t\"); /* some\n"
14529                    " \t \t    comment */",
14530                    Tab));
14531   EXPECT_EQ("{\n"
14532             "\t/*\n"
14533             "\t * Comment\n"
14534             "\t */\n"
14535             "\tint i;\n"
14536             "}",
14537             format("{\n"
14538                    "\t/*\n"
14539                    "\t * Comment\n"
14540                    "\t */\n"
14541                    "\t int i;\n"
14542                    "}",
14543                    Tab));
14544   Tab.TabWidth = 2;
14545   Tab.IndentWidth = 2;
14546   EXPECT_EQ("{\n"
14547             "\t/* aaaa\n"
14548             "\t\t bbbb */\n"
14549             "}",
14550             format("{\n"
14551                    "/* aaaa\n"
14552                    "\t bbbb */\n"
14553                    "}",
14554                    Tab));
14555   EXPECT_EQ("{\n"
14556             "\t/*\n"
14557             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14558             "\t\tbbbbbbbbbbbbb\n"
14559             "\t*/\n"
14560             "}",
14561             format("{\n"
14562                    "/*\n"
14563                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14564                    "*/\n"
14565                    "}",
14566                    Tab));
14567   Tab.AlignConsecutiveAssignments.Enabled = true;
14568   Tab.AlignConsecutiveDeclarations.Enabled = true;
14569   Tab.TabWidth = 4;
14570   Tab.IndentWidth = 4;
14571   verifyFormat("class Assign {\n"
14572                "\tvoid f() {\n"
14573                "\t\tint         x      = 123;\n"
14574                "\t\tint         random = 4;\n"
14575                "\t\tstd::string alphabet =\n"
14576                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14577                "\t}\n"
14578                "};",
14579                Tab);
14580 
14581   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14582   Tab.TabWidth = 8;
14583   Tab.IndentWidth = 8;
14584   EXPECT_EQ("if (aaaaaaaa && // q\n"
14585             "    bb)         // w\n"
14586             "\t;",
14587             format("if (aaaaaaaa &&// q\n"
14588                    "bb)// w\n"
14589                    ";",
14590                    Tab));
14591   EXPECT_EQ("if (aaa && bbb) // w\n"
14592             "\t;",
14593             format("if(aaa&&bbb)// w\n"
14594                    ";",
14595                    Tab));
14596   verifyFormat("class X {\n"
14597                "\tvoid f() {\n"
14598                "\t\tsomeFunction(parameter1,\n"
14599                "\t\t             parameter2);\n"
14600                "\t}\n"
14601                "};",
14602                Tab);
14603   verifyFormat("#define A                        \\\n"
14604                "\tvoid f() {               \\\n"
14605                "\t\tsomeFunction(    \\\n"
14606                "\t\t    parameter1,  \\\n"
14607                "\t\t    parameter2); \\\n"
14608                "\t}",
14609                Tab);
14610   Tab.TabWidth = 4;
14611   Tab.IndentWidth = 8;
14612   verifyFormat("class TabWidth4Indent8 {\n"
14613                "\t\tvoid f() {\n"
14614                "\t\t\t\tsomeFunction(parameter1,\n"
14615                "\t\t\t\t             parameter2);\n"
14616                "\t\t}\n"
14617                "};",
14618                Tab);
14619   Tab.TabWidth = 4;
14620   Tab.IndentWidth = 4;
14621   verifyFormat("class TabWidth4Indent4 {\n"
14622                "\tvoid f() {\n"
14623                "\t\tsomeFunction(parameter1,\n"
14624                "\t\t             parameter2);\n"
14625                "\t}\n"
14626                "};",
14627                Tab);
14628   Tab.TabWidth = 8;
14629   Tab.IndentWidth = 4;
14630   verifyFormat("class TabWidth8Indent4 {\n"
14631                "    void f() {\n"
14632                "\tsomeFunction(parameter1,\n"
14633                "\t             parameter2);\n"
14634                "    }\n"
14635                "};",
14636                Tab);
14637   Tab.TabWidth = 8;
14638   Tab.IndentWidth = 8;
14639   EXPECT_EQ("/*\n"
14640             "              a\t\tcomment\n"
14641             "              in multiple lines\n"
14642             "       */",
14643             format("   /*\t \t \n"
14644                    " \t \t a\t\tcomment\t \t\n"
14645                    " \t \t in multiple lines\t\n"
14646                    " \t  */",
14647                    Tab));
14648   verifyFormat("{\n"
14649                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14650                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14651                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14652                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14653                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14654                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14655                "};",
14656                Tab);
14657   verifyFormat("enum AA {\n"
14658                "\ta1, // Force multiple lines\n"
14659                "\ta2,\n"
14660                "\ta3\n"
14661                "};",
14662                Tab);
14663   EXPECT_EQ("if (aaaaaaaa && // q\n"
14664             "    bb)         // w\n"
14665             "\t;",
14666             format("if (aaaaaaaa &&// q\n"
14667                    "bb)// w\n"
14668                    ";",
14669                    Tab));
14670   verifyFormat("class X {\n"
14671                "\tvoid f() {\n"
14672                "\t\tsomeFunction(parameter1,\n"
14673                "\t\t             parameter2);\n"
14674                "\t}\n"
14675                "};",
14676                Tab);
14677   verifyFormat("{\n"
14678                "\tQ(\n"
14679                "\t    {\n"
14680                "\t\t    int a;\n"
14681                "\t\t    someFunction(aaaaaaaa,\n"
14682                "\t\t                 bbbbbbb);\n"
14683                "\t    },\n"
14684                "\t    p);\n"
14685                "}",
14686                Tab);
14687   EXPECT_EQ("{\n"
14688             "\t/* aaaa\n"
14689             "\t   bbbb */\n"
14690             "}",
14691             format("{\n"
14692                    "/* aaaa\n"
14693                    "   bbbb */\n"
14694                    "}",
14695                    Tab));
14696   EXPECT_EQ("{\n"
14697             "\t/*\n"
14698             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14699             "\t  bbbbbbbbbbbbb\n"
14700             "\t*/\n"
14701             "}",
14702             format("{\n"
14703                    "/*\n"
14704                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14705                    "*/\n"
14706                    "}",
14707                    Tab));
14708   EXPECT_EQ("{\n"
14709             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14710             "\t// bbbbbbbbbbbbb\n"
14711             "}",
14712             format("{\n"
14713                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14714                    "}",
14715                    Tab));
14716   EXPECT_EQ("{\n"
14717             "\t/*\n"
14718             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14719             "\t  bbbbbbbbbbbbb\n"
14720             "\t*/\n"
14721             "}",
14722             format("{\n"
14723                    "\t/*\n"
14724                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14725                    "\t*/\n"
14726                    "}",
14727                    Tab));
14728   EXPECT_EQ("{\n"
14729             "\t/*\n"
14730             "\n"
14731             "\t*/\n"
14732             "}",
14733             format("{\n"
14734                    "\t/*\n"
14735                    "\n"
14736                    "\t*/\n"
14737                    "}",
14738                    Tab));
14739   EXPECT_EQ("{\n"
14740             "\t/*\n"
14741             " asdf\n"
14742             "\t*/\n"
14743             "}",
14744             format("{\n"
14745                    "\t/*\n"
14746                    " asdf\n"
14747                    "\t*/\n"
14748                    "}",
14749                    Tab));
14750   EXPECT_EQ("/* some\n"
14751             "   comment */",
14752             format(" \t \t /* some\n"
14753                    " \t \t    comment */",
14754                    Tab));
14755   EXPECT_EQ("int a; /* some\n"
14756             "   comment */",
14757             format(" \t \t int a; /* some\n"
14758                    " \t \t    comment */",
14759                    Tab));
14760   EXPECT_EQ("int a; /* some\n"
14761             "comment */",
14762             format(" \t \t int\ta; /* some\n"
14763                    " \t \t    comment */",
14764                    Tab));
14765   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14766             "    comment */",
14767             format(" \t \t f(\"\t\t\"); /* some\n"
14768                    " \t \t    comment */",
14769                    Tab));
14770   EXPECT_EQ("{\n"
14771             "\t/*\n"
14772             "\t * Comment\n"
14773             "\t */\n"
14774             "\tint i;\n"
14775             "}",
14776             format("{\n"
14777                    "\t/*\n"
14778                    "\t * Comment\n"
14779                    "\t */\n"
14780                    "\t int i;\n"
14781                    "}",
14782                    Tab));
14783   Tab.TabWidth = 2;
14784   Tab.IndentWidth = 2;
14785   EXPECT_EQ("{\n"
14786             "\t/* aaaa\n"
14787             "\t   bbbb */\n"
14788             "}",
14789             format("{\n"
14790                    "/* aaaa\n"
14791                    "   bbbb */\n"
14792                    "}",
14793                    Tab));
14794   EXPECT_EQ("{\n"
14795             "\t/*\n"
14796             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14797             "\t  bbbbbbbbbbbbb\n"
14798             "\t*/\n"
14799             "}",
14800             format("{\n"
14801                    "/*\n"
14802                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14803                    "*/\n"
14804                    "}",
14805                    Tab));
14806   Tab.AlignConsecutiveAssignments.Enabled = true;
14807   Tab.AlignConsecutiveDeclarations.Enabled = true;
14808   Tab.TabWidth = 4;
14809   Tab.IndentWidth = 4;
14810   verifyFormat("class Assign {\n"
14811                "\tvoid f() {\n"
14812                "\t\tint         x      = 123;\n"
14813                "\t\tint         random = 4;\n"
14814                "\t\tstd::string alphabet =\n"
14815                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14816                "\t}\n"
14817                "};",
14818                Tab);
14819   Tab.AlignOperands = FormatStyle::OAS_Align;
14820   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14821                "                 cccccccccccccccccccc;",
14822                Tab);
14823   // no alignment
14824   verifyFormat("int aaaaaaaaaa =\n"
14825                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14826                Tab);
14827   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14828                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14829                "                        : 333333333333333;",
14830                Tab);
14831   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14832   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14833   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14834                "               + cccccccccccccccccccc;",
14835                Tab);
14836 }
14837 
14838 TEST_F(FormatTest, ZeroTabWidth) {
14839   FormatStyle Tab = getLLVMStyleWithColumns(42);
14840   Tab.IndentWidth = 8;
14841   Tab.UseTab = FormatStyle::UT_Never;
14842   Tab.TabWidth = 0;
14843   EXPECT_EQ("void a(){\n"
14844             "    // line starts with '\t'\n"
14845             "};",
14846             format("void a(){\n"
14847                    "\t// line starts with '\t'\n"
14848                    "};",
14849                    Tab));
14850 
14851   EXPECT_EQ("void a(){\n"
14852             "    // line starts with '\t'\n"
14853             "};",
14854             format("void a(){\n"
14855                    "\t\t// line starts with '\t'\n"
14856                    "};",
14857                    Tab));
14858 
14859   Tab.UseTab = FormatStyle::UT_ForIndentation;
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_ForContinuationAndIndentation;
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_AlignWithSpaces;
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_Always;
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 
14928 TEST_F(FormatTest, CalculatesOriginalColumn) {
14929   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14930             "q\"; /* some\n"
14931             "       comment */",
14932             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14933                    "q\"; /* some\n"
14934                    "       comment */",
14935                    getLLVMStyle()));
14936   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14937             "/* some\n"
14938             "   comment */",
14939             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14940                    " /* some\n"
14941                    "    comment */",
14942                    getLLVMStyle()));
14943   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14944             "qqq\n"
14945             "/* some\n"
14946             "   comment */",
14947             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14948                    "qqq\n"
14949                    " /* some\n"
14950                    "    comment */",
14951                    getLLVMStyle()));
14952   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14953             "wwww; /* some\n"
14954             "         comment */",
14955             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14956                    "wwww; /* some\n"
14957                    "         comment */",
14958                    getLLVMStyle()));
14959 }
14960 
14961 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14962   FormatStyle NoSpace = getLLVMStyle();
14963   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14964 
14965   verifyFormat("while(true)\n"
14966                "  continue;",
14967                NoSpace);
14968   verifyFormat("for(;;)\n"
14969                "  continue;",
14970                NoSpace);
14971   verifyFormat("if(true)\n"
14972                "  f();\n"
14973                "else if(true)\n"
14974                "  f();",
14975                NoSpace);
14976   verifyFormat("do {\n"
14977                "  do_something();\n"
14978                "} while(something());",
14979                NoSpace);
14980   verifyFormat("switch(x) {\n"
14981                "default:\n"
14982                "  break;\n"
14983                "}",
14984                NoSpace);
14985   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14986   verifyFormat("size_t x = sizeof(x);", NoSpace);
14987   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14988   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14989   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14990   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14991   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14992   verifyFormat("alignas(128) char a[128];", NoSpace);
14993   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14994   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14995   verifyFormat("int f() throw(Deprecated);", NoSpace);
14996   verifyFormat("typedef void (*cb)(int);", NoSpace);
14997   verifyFormat("T A::operator()();", NoSpace);
14998   verifyFormat("X A::operator++(T);", NoSpace);
14999   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
15000 
15001   FormatStyle Space = getLLVMStyle();
15002   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
15003 
15004   verifyFormat("int f ();", Space);
15005   verifyFormat("void f (int a, T b) {\n"
15006                "  while (true)\n"
15007                "    continue;\n"
15008                "}",
15009                Space);
15010   verifyFormat("if (true)\n"
15011                "  f ();\n"
15012                "else if (true)\n"
15013                "  f ();",
15014                Space);
15015   verifyFormat("do {\n"
15016                "  do_something ();\n"
15017                "} while (something ());",
15018                Space);
15019   verifyFormat("switch (x) {\n"
15020                "default:\n"
15021                "  break;\n"
15022                "}",
15023                Space);
15024   verifyFormat("A::A () : a (1) {}", Space);
15025   verifyFormat("void f () __attribute__ ((asdf));", Space);
15026   verifyFormat("*(&a + 1);\n"
15027                "&((&a)[1]);\n"
15028                "a[(b + c) * d];\n"
15029                "(((a + 1) * 2) + 3) * 4;",
15030                Space);
15031   verifyFormat("#define A(x) x", Space);
15032   verifyFormat("#define A (x) x", Space);
15033   verifyFormat("#if defined(x)\n"
15034                "#endif",
15035                Space);
15036   verifyFormat("auto i = std::make_unique<int> (5);", Space);
15037   verifyFormat("size_t x = sizeof (x);", Space);
15038   verifyFormat("auto f (int x) -> decltype (x);", Space);
15039   verifyFormat("auto f (int x) -> typeof (x);", Space);
15040   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
15041   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
15042   verifyFormat("int f (T x) noexcept (x.create ());", Space);
15043   verifyFormat("alignas (128) char a[128];", Space);
15044   verifyFormat("size_t x = alignof (MyType);", Space);
15045   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
15046   verifyFormat("int f () throw (Deprecated);", Space);
15047   verifyFormat("typedef void (*cb) (int);", Space);
15048   // FIXME these tests regressed behaviour.
15049   // verifyFormat("T A::operator() ();", Space);
15050   // verifyFormat("X A::operator++ (T);", Space);
15051   verifyFormat("auto lambda = [] () { return 0; };", Space);
15052   verifyFormat("int x = int (y);", Space);
15053 
15054   FormatStyle SomeSpace = getLLVMStyle();
15055   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
15056 
15057   verifyFormat("[]() -> float {}", SomeSpace);
15058   verifyFormat("[] (auto foo) {}", SomeSpace);
15059   verifyFormat("[foo]() -> int {}", SomeSpace);
15060   verifyFormat("int f();", SomeSpace);
15061   verifyFormat("void f (int a, T b) {\n"
15062                "  while (true)\n"
15063                "    continue;\n"
15064                "}",
15065                SomeSpace);
15066   verifyFormat("if (true)\n"
15067                "  f();\n"
15068                "else if (true)\n"
15069                "  f();",
15070                SomeSpace);
15071   verifyFormat("do {\n"
15072                "  do_something();\n"
15073                "} while (something());",
15074                SomeSpace);
15075   verifyFormat("switch (x) {\n"
15076                "default:\n"
15077                "  break;\n"
15078                "}",
15079                SomeSpace);
15080   verifyFormat("A::A() : a (1) {}", SomeSpace);
15081   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
15082   verifyFormat("*(&a + 1);\n"
15083                "&((&a)[1]);\n"
15084                "a[(b + c) * d];\n"
15085                "(((a + 1) * 2) + 3) * 4;",
15086                SomeSpace);
15087   verifyFormat("#define A(x) x", SomeSpace);
15088   verifyFormat("#define A (x) x", SomeSpace);
15089   verifyFormat("#if defined(x)\n"
15090                "#endif",
15091                SomeSpace);
15092   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
15093   verifyFormat("size_t x = sizeof (x);", SomeSpace);
15094   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
15095   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
15096   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
15097   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
15098   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
15099   verifyFormat("alignas (128) char a[128];", SomeSpace);
15100   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
15101   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15102                SomeSpace);
15103   verifyFormat("int f() throw (Deprecated);", SomeSpace);
15104   verifyFormat("typedef void (*cb) (int);", SomeSpace);
15105   verifyFormat("T A::operator()();", SomeSpace);
15106   // FIXME these tests regressed behaviour.
15107   // verifyFormat("X A::operator++ (T);", SomeSpace);
15108   verifyFormat("int x = int (y);", SomeSpace);
15109   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
15110 
15111   FormatStyle SpaceControlStatements = getLLVMStyle();
15112   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15113   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
15114 
15115   verifyFormat("while (true)\n"
15116                "  continue;",
15117                SpaceControlStatements);
15118   verifyFormat("if (true)\n"
15119                "  f();\n"
15120                "else if (true)\n"
15121                "  f();",
15122                SpaceControlStatements);
15123   verifyFormat("for (;;) {\n"
15124                "  do_something();\n"
15125                "}",
15126                SpaceControlStatements);
15127   verifyFormat("do {\n"
15128                "  do_something();\n"
15129                "} while (something());",
15130                SpaceControlStatements);
15131   verifyFormat("switch (x) {\n"
15132                "default:\n"
15133                "  break;\n"
15134                "}",
15135                SpaceControlStatements);
15136 
15137   FormatStyle SpaceFuncDecl = getLLVMStyle();
15138   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15139   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
15140 
15141   verifyFormat("int f ();", SpaceFuncDecl);
15142   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
15143   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
15144   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
15145   verifyFormat("#define A(x) x", SpaceFuncDecl);
15146   verifyFormat("#define A (x) x", SpaceFuncDecl);
15147   verifyFormat("#if defined(x)\n"
15148                "#endif",
15149                SpaceFuncDecl);
15150   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
15151   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
15152   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
15153   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
15154   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
15155   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
15156   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
15157   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
15158   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
15159   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15160                SpaceFuncDecl);
15161   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
15162   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
15163   // FIXME these tests regressed behaviour.
15164   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
15165   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
15166   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
15167   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
15168   verifyFormat("int x = int(y);", SpaceFuncDecl);
15169   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15170                SpaceFuncDecl);
15171 
15172   FormatStyle SpaceFuncDef = getLLVMStyle();
15173   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15174   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
15175 
15176   verifyFormat("int f();", SpaceFuncDef);
15177   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
15178   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
15179   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
15180   verifyFormat("#define A(x) x", SpaceFuncDef);
15181   verifyFormat("#define A (x) x", SpaceFuncDef);
15182   verifyFormat("#if defined(x)\n"
15183                "#endif",
15184                SpaceFuncDef);
15185   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
15186   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
15187   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
15188   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
15189   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
15190   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
15191   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
15192   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
15193   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
15194   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15195                SpaceFuncDef);
15196   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
15197   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
15198   verifyFormat("T A::operator()();", SpaceFuncDef);
15199   verifyFormat("X A::operator++(T);", SpaceFuncDef);
15200   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
15201   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
15202   verifyFormat("int x = int(y);", SpaceFuncDef);
15203   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15204                SpaceFuncDef);
15205 
15206   FormatStyle SpaceIfMacros = getLLVMStyle();
15207   SpaceIfMacros.IfMacros.clear();
15208   SpaceIfMacros.IfMacros.push_back("MYIF");
15209   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15210   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
15211   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
15212   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
15213   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
15214 
15215   FormatStyle SpaceForeachMacros = getLLVMStyle();
15216   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
15217             FormatStyle::SBS_Never);
15218   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
15219   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15220   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
15221   verifyFormat("for (;;) {\n"
15222                "}",
15223                SpaceForeachMacros);
15224   verifyFormat("foreach (Item *item, itemlist) {\n"
15225                "}",
15226                SpaceForeachMacros);
15227   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15228                "}",
15229                SpaceForeachMacros);
15230   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15231                "}",
15232                SpaceForeachMacros);
15233   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15234 
15235   FormatStyle SomeSpace2 = getLLVMStyle();
15236   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15237   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15238   verifyFormat("[]() -> float {}", SomeSpace2);
15239   verifyFormat("[] (auto foo) {}", SomeSpace2);
15240   verifyFormat("[foo]() -> int {}", SomeSpace2);
15241   verifyFormat("int f();", SomeSpace2);
15242   verifyFormat("void f (int a, T b) {\n"
15243                "  while (true)\n"
15244                "    continue;\n"
15245                "}",
15246                SomeSpace2);
15247   verifyFormat("if (true)\n"
15248                "  f();\n"
15249                "else if (true)\n"
15250                "  f();",
15251                SomeSpace2);
15252   verifyFormat("do {\n"
15253                "  do_something();\n"
15254                "} while (something());",
15255                SomeSpace2);
15256   verifyFormat("switch (x) {\n"
15257                "default:\n"
15258                "  break;\n"
15259                "}",
15260                SomeSpace2);
15261   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15262   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15263   verifyFormat("*(&a + 1);\n"
15264                "&((&a)[1]);\n"
15265                "a[(b + c) * d];\n"
15266                "(((a + 1) * 2) + 3) * 4;",
15267                SomeSpace2);
15268   verifyFormat("#define A(x) x", SomeSpace2);
15269   verifyFormat("#define A (x) x", SomeSpace2);
15270   verifyFormat("#if defined(x)\n"
15271                "#endif",
15272                SomeSpace2);
15273   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15274   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15275   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15276   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15277   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15278   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15279   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15280   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15281   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15282   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15283                SomeSpace2);
15284   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15285   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15286   verifyFormat("T A::operator()();", SomeSpace2);
15287   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15288   verifyFormat("int x = int (y);", SomeSpace2);
15289   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15290 
15291   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15292   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15293   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15294       .AfterOverloadedOperator = true;
15295 
15296   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15297   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15298   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15299   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15300 
15301   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15302       .AfterOverloadedOperator = false;
15303 
15304   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15305   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15306   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15307   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15308 
15309   auto SpaceAfterRequires = getLLVMStyle();
15310   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15311   EXPECT_FALSE(
15312       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15313   EXPECT_FALSE(
15314       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15315   verifyFormat("void f(auto x)\n"
15316                "  requires requires(int i) { x + i; }\n"
15317                "{}",
15318                SpaceAfterRequires);
15319   verifyFormat("void f(auto x)\n"
15320                "  requires(requires(int i) { x + i; })\n"
15321                "{}",
15322                SpaceAfterRequires);
15323   verifyFormat("if (requires(int i) { x + i; })\n"
15324                "  return;",
15325                SpaceAfterRequires);
15326   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15327   verifyFormat("template <typename T>\n"
15328                "  requires(Foo<T>)\n"
15329                "class Bar;",
15330                SpaceAfterRequires);
15331 
15332   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15333   verifyFormat("void f(auto x)\n"
15334                "  requires requires(int i) { x + i; }\n"
15335                "{}",
15336                SpaceAfterRequires);
15337   verifyFormat("void f(auto x)\n"
15338                "  requires (requires(int i) { x + i; })\n"
15339                "{}",
15340                SpaceAfterRequires);
15341   verifyFormat("if (requires(int i) { x + i; })\n"
15342                "  return;",
15343                SpaceAfterRequires);
15344   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15345   verifyFormat("template <typename T>\n"
15346                "  requires (Foo<T>)\n"
15347                "class Bar;",
15348                SpaceAfterRequires);
15349 
15350   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15351   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15352   verifyFormat("void f(auto x)\n"
15353                "  requires requires (int i) { x + i; }\n"
15354                "{}",
15355                SpaceAfterRequires);
15356   verifyFormat("void f(auto x)\n"
15357                "  requires(requires (int i) { x + i; })\n"
15358                "{}",
15359                SpaceAfterRequires);
15360   verifyFormat("if (requires (int i) { x + i; })\n"
15361                "  return;",
15362                SpaceAfterRequires);
15363   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15364   verifyFormat("template <typename T>\n"
15365                "  requires(Foo<T>)\n"
15366                "class Bar;",
15367                SpaceAfterRequires);
15368 
15369   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15370   verifyFormat("void f(auto x)\n"
15371                "  requires requires (int i) { x + i; }\n"
15372                "{}",
15373                SpaceAfterRequires);
15374   verifyFormat("void f(auto x)\n"
15375                "  requires (requires (int i) { x + i; })\n"
15376                "{}",
15377                SpaceAfterRequires);
15378   verifyFormat("if (requires (int i) { x + i; })\n"
15379                "  return;",
15380                SpaceAfterRequires);
15381   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15382   verifyFormat("template <typename T>\n"
15383                "  requires (Foo<T>)\n"
15384                "class Bar;",
15385                SpaceAfterRequires);
15386 }
15387 
15388 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15389   FormatStyle Spaces = getLLVMStyle();
15390   Spaces.SpaceAfterLogicalNot = true;
15391 
15392   verifyFormat("bool x = ! y", Spaces);
15393   verifyFormat("if (! isFailure())", Spaces);
15394   verifyFormat("if (! (a && b))", Spaces);
15395   verifyFormat("\"Error!\"", Spaces);
15396   verifyFormat("! ! x", Spaces);
15397 }
15398 
15399 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15400   FormatStyle Spaces = getLLVMStyle();
15401 
15402   Spaces.SpacesInParentheses = true;
15403   verifyFormat("do_something( ::globalVar );", Spaces);
15404   verifyFormat("call( x, y, z );", Spaces);
15405   verifyFormat("call();", Spaces);
15406   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15407   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15408                Spaces);
15409   verifyFormat("while ( (bool)1 )\n"
15410                "  continue;",
15411                Spaces);
15412   verifyFormat("for ( ;; )\n"
15413                "  continue;",
15414                Spaces);
15415   verifyFormat("if ( true )\n"
15416                "  f();\n"
15417                "else if ( true )\n"
15418                "  f();",
15419                Spaces);
15420   verifyFormat("do {\n"
15421                "  do_something( (int)i );\n"
15422                "} while ( something() );",
15423                Spaces);
15424   verifyFormat("switch ( x ) {\n"
15425                "default:\n"
15426                "  break;\n"
15427                "}",
15428                Spaces);
15429 
15430   Spaces.SpacesInParentheses = false;
15431   Spaces.SpacesInCStyleCastParentheses = true;
15432   verifyFormat("Type *A = ( Type * )P;", Spaces);
15433   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15434   verifyFormat("x = ( int32 )y;", Spaces);
15435   verifyFormat("int a = ( int )(2.0f);", Spaces);
15436   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15437   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15438   verifyFormat("#define x (( int )-1)", Spaces);
15439 
15440   // Run the first set of tests again with:
15441   Spaces.SpacesInParentheses = false;
15442   Spaces.SpaceInEmptyParentheses = true;
15443   Spaces.SpacesInCStyleCastParentheses = true;
15444   verifyFormat("call(x, y, z);", Spaces);
15445   verifyFormat("call( );", Spaces);
15446   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15447   verifyFormat("while (( bool )1)\n"
15448                "  continue;",
15449                Spaces);
15450   verifyFormat("for (;;)\n"
15451                "  continue;",
15452                Spaces);
15453   verifyFormat("if (true)\n"
15454                "  f( );\n"
15455                "else if (true)\n"
15456                "  f( );",
15457                Spaces);
15458   verifyFormat("do {\n"
15459                "  do_something(( int )i);\n"
15460                "} while (something( ));",
15461                Spaces);
15462   verifyFormat("switch (x) {\n"
15463                "default:\n"
15464                "  break;\n"
15465                "}",
15466                Spaces);
15467 
15468   // Run the first set of tests again with:
15469   Spaces.SpaceAfterCStyleCast = true;
15470   verifyFormat("call(x, y, z);", Spaces);
15471   verifyFormat("call( );", Spaces);
15472   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15473   verifyFormat("while (( bool ) 1)\n"
15474                "  continue;",
15475                Spaces);
15476   verifyFormat("for (;;)\n"
15477                "  continue;",
15478                Spaces);
15479   verifyFormat("if (true)\n"
15480                "  f( );\n"
15481                "else if (true)\n"
15482                "  f( );",
15483                Spaces);
15484   verifyFormat("do {\n"
15485                "  do_something(( int ) i);\n"
15486                "} while (something( ));",
15487                Spaces);
15488   verifyFormat("switch (x) {\n"
15489                "default:\n"
15490                "  break;\n"
15491                "}",
15492                Spaces);
15493   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15494   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15495   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15496   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15497   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15498 
15499   // Run subset of tests again with:
15500   Spaces.SpacesInCStyleCastParentheses = false;
15501   Spaces.SpaceAfterCStyleCast = true;
15502   verifyFormat("while ((bool) 1)\n"
15503                "  continue;",
15504                Spaces);
15505   verifyFormat("do {\n"
15506                "  do_something((int) i);\n"
15507                "} while (something( ));",
15508                Spaces);
15509 
15510   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15511   verifyFormat("size_t idx = (size_t) a;", Spaces);
15512   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15513   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15514   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15515   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15516   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15517   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15518   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15519   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15520   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15521   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15522   Spaces.ColumnLimit = 80;
15523   Spaces.IndentWidth = 4;
15524   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15525   verifyFormat("void foo( ) {\n"
15526                "    size_t foo = (*(function))(\n"
15527                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15528                "BarrrrrrrrrrrrLong,\n"
15529                "        FoooooooooLooooong);\n"
15530                "}",
15531                Spaces);
15532   Spaces.SpaceAfterCStyleCast = false;
15533   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15534   verifyFormat("size_t idx = (size_t)a;", Spaces);
15535   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15536   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15537   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15538   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15539   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15540 
15541   verifyFormat("void foo( ) {\n"
15542                "    size_t foo = (*(function))(\n"
15543                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15544                "BarrrrrrrrrrrrLong,\n"
15545                "        FoooooooooLooooong);\n"
15546                "}",
15547                Spaces);
15548 }
15549 
15550 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15551   verifyFormat("int a[5];");
15552   verifyFormat("a[3] += 42;");
15553 
15554   FormatStyle Spaces = getLLVMStyle();
15555   Spaces.SpacesInSquareBrackets = true;
15556   // Not lambdas.
15557   verifyFormat("int a[ 5 ];", Spaces);
15558   verifyFormat("a[ 3 ] += 42;", Spaces);
15559   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15560   verifyFormat("double &operator[](int i) { return 0; }\n"
15561                "int i;",
15562                Spaces);
15563   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15564   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15565   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15566   // Lambdas.
15567   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15568   verifyFormat("return [ i, args... ] {};", Spaces);
15569   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15570   verifyFormat("int foo = [ = ]() {};", Spaces);
15571   verifyFormat("int foo = [ & ]() {};", Spaces);
15572   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15573   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15574 }
15575 
15576 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15577   FormatStyle NoSpaceStyle = getLLVMStyle();
15578   verifyFormat("int a[5];", NoSpaceStyle);
15579   verifyFormat("a[3] += 42;", NoSpaceStyle);
15580 
15581   verifyFormat("int a[1];", NoSpaceStyle);
15582   verifyFormat("int 1 [a];", NoSpaceStyle);
15583   verifyFormat("int a[1][2];", NoSpaceStyle);
15584   verifyFormat("a[7] = 5;", NoSpaceStyle);
15585   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15586   verifyFormat("f([] {})", NoSpaceStyle);
15587 
15588   FormatStyle Space = getLLVMStyle();
15589   Space.SpaceBeforeSquareBrackets = true;
15590   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15591   verifyFormat("return [i, args...] {};", Space);
15592 
15593   verifyFormat("int a [5];", Space);
15594   verifyFormat("a [3] += 42;", Space);
15595   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15596   verifyFormat("double &operator[](int i) { return 0; }\n"
15597                "int i;",
15598                Space);
15599   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15600   verifyFormat("int i = a [a][a]->f();", Space);
15601   verifyFormat("int i = (*b) [a]->f();", Space);
15602 
15603   verifyFormat("int a [1];", Space);
15604   verifyFormat("int 1 [a];", Space);
15605   verifyFormat("int a [1][2];", Space);
15606   verifyFormat("a [7] = 5;", Space);
15607   verifyFormat("int a = (f()) [23];", Space);
15608   verifyFormat("f([] {})", Space);
15609 }
15610 
15611 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15612   verifyFormat("int a = 5;");
15613   verifyFormat("a += 42;");
15614   verifyFormat("a or_eq 8;");
15615 
15616   FormatStyle Spaces = getLLVMStyle();
15617   Spaces.SpaceBeforeAssignmentOperators = false;
15618   verifyFormat("int a= 5;", Spaces);
15619   verifyFormat("a+= 42;", Spaces);
15620   verifyFormat("a or_eq 8;", Spaces);
15621 }
15622 
15623 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15624   verifyFormat("class Foo : public Bar {};");
15625   verifyFormat("Foo::Foo() : foo(1) {}");
15626   verifyFormat("for (auto a : b) {\n}");
15627   verifyFormat("int x = a ? b : c;");
15628   verifyFormat("{\n"
15629                "label0:\n"
15630                "  int x = 0;\n"
15631                "}");
15632   verifyFormat("switch (x) {\n"
15633                "case 1:\n"
15634                "default:\n"
15635                "}");
15636   verifyFormat("switch (allBraces) {\n"
15637                "case 1: {\n"
15638                "  break;\n"
15639                "}\n"
15640                "case 2: {\n"
15641                "  [[fallthrough]];\n"
15642                "}\n"
15643                "default: {\n"
15644                "  break;\n"
15645                "}\n"
15646                "}");
15647 
15648   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15649   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15650   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15651   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15652   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15653   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15654   verifyFormat("{\n"
15655                "label1:\n"
15656                "  int x = 0;\n"
15657                "}",
15658                CtorInitializerStyle);
15659   verifyFormat("switch (x) {\n"
15660                "case 1:\n"
15661                "default:\n"
15662                "}",
15663                CtorInitializerStyle);
15664   verifyFormat("switch (allBraces) {\n"
15665                "case 1: {\n"
15666                "  break;\n"
15667                "}\n"
15668                "case 2: {\n"
15669                "  [[fallthrough]];\n"
15670                "}\n"
15671                "default: {\n"
15672                "  break;\n"
15673                "}\n"
15674                "}",
15675                CtorInitializerStyle);
15676   CtorInitializerStyle.BreakConstructorInitializers =
15677       FormatStyle::BCIS_AfterColon;
15678   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15679                "    aaaaaaaaaaaaaaaa(1),\n"
15680                "    bbbbbbbbbbbbbbbb(2) {}",
15681                CtorInitializerStyle);
15682   CtorInitializerStyle.BreakConstructorInitializers =
15683       FormatStyle::BCIS_BeforeComma;
15684   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15685                "    : aaaaaaaaaaaaaaaa(1)\n"
15686                "    , bbbbbbbbbbbbbbbb(2) {}",
15687                CtorInitializerStyle);
15688   CtorInitializerStyle.BreakConstructorInitializers =
15689       FormatStyle::BCIS_BeforeColon;
15690   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15691                "    : aaaaaaaaaaaaaaaa(1),\n"
15692                "      bbbbbbbbbbbbbbbb(2) {}",
15693                CtorInitializerStyle);
15694   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15695   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15696                ": aaaaaaaaaaaaaaaa(1),\n"
15697                "  bbbbbbbbbbbbbbbb(2) {}",
15698                CtorInitializerStyle);
15699 
15700   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15701   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15702   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15703   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15704   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15705   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15706   verifyFormat("{\n"
15707                "label2:\n"
15708                "  int x = 0;\n"
15709                "}",
15710                InheritanceStyle);
15711   verifyFormat("switch (x) {\n"
15712                "case 1:\n"
15713                "default:\n"
15714                "}",
15715                InheritanceStyle);
15716   verifyFormat("switch (allBraces) {\n"
15717                "case 1: {\n"
15718                "  break;\n"
15719                "}\n"
15720                "case 2: {\n"
15721                "  [[fallthrough]];\n"
15722                "}\n"
15723                "default: {\n"
15724                "  break;\n"
15725                "}\n"
15726                "}",
15727                InheritanceStyle);
15728   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15729   verifyFormat("class Foooooooooooooooooooooo\n"
15730                "    : public aaaaaaaaaaaaaaaaaa,\n"
15731                "      public bbbbbbbbbbbbbbbbbb {\n"
15732                "}",
15733                InheritanceStyle);
15734   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15735   verifyFormat("class Foooooooooooooooooooooo:\n"
15736                "    public aaaaaaaaaaaaaaaaaa,\n"
15737                "    public bbbbbbbbbbbbbbbbbb {\n"
15738                "}",
15739                InheritanceStyle);
15740   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15741   verifyFormat("class Foooooooooooooooooooooo\n"
15742                "    : public aaaaaaaaaaaaaaaaaa\n"
15743                "    , public bbbbbbbbbbbbbbbbbb {\n"
15744                "}",
15745                InheritanceStyle);
15746   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15747   verifyFormat("class Foooooooooooooooooooooo\n"
15748                "    : public aaaaaaaaaaaaaaaaaa,\n"
15749                "      public bbbbbbbbbbbbbbbbbb {\n"
15750                "}",
15751                InheritanceStyle);
15752   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15753   verifyFormat("class Foooooooooooooooooooooo\n"
15754                ": public aaaaaaaaaaaaaaaaaa,\n"
15755                "  public bbbbbbbbbbbbbbbbbb {}",
15756                InheritanceStyle);
15757 
15758   FormatStyle ForLoopStyle = getLLVMStyle();
15759   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15760   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15761   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15762   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15763   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15764   verifyFormat("{\n"
15765                "label2:\n"
15766                "  int x = 0;\n"
15767                "}",
15768                ForLoopStyle);
15769   verifyFormat("switch (x) {\n"
15770                "case 1:\n"
15771                "default:\n"
15772                "}",
15773                ForLoopStyle);
15774   verifyFormat("switch (allBraces) {\n"
15775                "case 1: {\n"
15776                "  break;\n"
15777                "}\n"
15778                "case 2: {\n"
15779                "  [[fallthrough]];\n"
15780                "}\n"
15781                "default: {\n"
15782                "  break;\n"
15783                "}\n"
15784                "}",
15785                ForLoopStyle);
15786 
15787   FormatStyle CaseStyle = getLLVMStyle();
15788   CaseStyle.SpaceBeforeCaseColon = true;
15789   verifyFormat("class Foo : public Bar {};", CaseStyle);
15790   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15791   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15792   verifyFormat("int x = a ? b : c;", CaseStyle);
15793   verifyFormat("switch (x) {\n"
15794                "case 1 :\n"
15795                "default :\n"
15796                "}",
15797                CaseStyle);
15798   verifyFormat("switch (allBraces) {\n"
15799                "case 1 : {\n"
15800                "  break;\n"
15801                "}\n"
15802                "case 2 : {\n"
15803                "  [[fallthrough]];\n"
15804                "}\n"
15805                "default : {\n"
15806                "  break;\n"
15807                "}\n"
15808                "}",
15809                CaseStyle);
15810 
15811   FormatStyle NoSpaceStyle = getLLVMStyle();
15812   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15813   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15814   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15815   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15816   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15817   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15818   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15819   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15820   verifyFormat("{\n"
15821                "label3:\n"
15822                "  int x = 0;\n"
15823                "}",
15824                NoSpaceStyle);
15825   verifyFormat("switch (x) {\n"
15826                "case 1:\n"
15827                "default:\n"
15828                "}",
15829                NoSpaceStyle);
15830   verifyFormat("switch (allBraces) {\n"
15831                "case 1: {\n"
15832                "  break;\n"
15833                "}\n"
15834                "case 2: {\n"
15835                "  [[fallthrough]];\n"
15836                "}\n"
15837                "default: {\n"
15838                "  break;\n"
15839                "}\n"
15840                "}",
15841                NoSpaceStyle);
15842 
15843   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15844   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15845   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15846   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15847   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15848   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15849   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15850   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15851   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15852   verifyFormat("{\n"
15853                "label3:\n"
15854                "  int x = 0;\n"
15855                "}",
15856                InvertedSpaceStyle);
15857   verifyFormat("switch (x) {\n"
15858                "case 1 :\n"
15859                "case 2 : {\n"
15860                "  break;\n"
15861                "}\n"
15862                "default :\n"
15863                "  break;\n"
15864                "}",
15865                InvertedSpaceStyle);
15866   verifyFormat("switch (allBraces) {\n"
15867                "case 1 : {\n"
15868                "  break;\n"
15869                "}\n"
15870                "case 2 : {\n"
15871                "  [[fallthrough]];\n"
15872                "}\n"
15873                "default : {\n"
15874                "  break;\n"
15875                "}\n"
15876                "}",
15877                InvertedSpaceStyle);
15878 }
15879 
15880 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15881   FormatStyle Style = getLLVMStyle();
15882 
15883   Style.PointerAlignment = FormatStyle::PAS_Left;
15884   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15885   verifyFormat("void* const* x = NULL;", Style);
15886 
15887 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15888   do {                                                                         \
15889     Style.PointerAlignment = FormatStyle::Pointers;                            \
15890     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15891     verifyFormat(Code, Style);                                                 \
15892   } while (false)
15893 
15894   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15895   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15896   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15897 
15898   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15899   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15900   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15901 
15902   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15903   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15904   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15905 
15906   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15907   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15908   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15909 
15910   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15911   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15912                         SAPQ_Default);
15913   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15914                         SAPQ_Default);
15915 
15916   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15917   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15918                         SAPQ_Before);
15919   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15920                         SAPQ_Before);
15921 
15922   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15923   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15924   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15925                         SAPQ_After);
15926 
15927   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15928   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15929   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15930 
15931 #undef verifyQualifierSpaces
15932 
15933   FormatStyle Spaces = getLLVMStyle();
15934   Spaces.AttributeMacros.push_back("qualified");
15935   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15936   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15937   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15938   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15939   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15940   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15941   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15942   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15943   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15944   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15945   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15946   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15947   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15948 
15949   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15950   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15951   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15952   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15953   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15954   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15955   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15956   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15957   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15958   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15959   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15960   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15961   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15962   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15963   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15964 
15965   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15966   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15967   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15968   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15969   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15970   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15971   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15972   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15973 }
15974 
15975 TEST_F(FormatTest, AlignConsecutiveMacros) {
15976   FormatStyle Style = getLLVMStyle();
15977   Style.AlignConsecutiveAssignments.Enabled = true;
15978   Style.AlignConsecutiveDeclarations.Enabled = true;
15979 
15980   verifyFormat("#define a 3\n"
15981                "#define bbbb 4\n"
15982                "#define ccc (5)",
15983                Style);
15984 
15985   verifyFormat("#define f(x) (x * x)\n"
15986                "#define fff(x, y, z) (x * y + z)\n"
15987                "#define ffff(x, y) (x - y)",
15988                Style);
15989 
15990   verifyFormat("#define foo(x, y) (x + y)\n"
15991                "#define bar (5, 6)(2 + 2)",
15992                Style);
15993 
15994   verifyFormat("#define a 3\n"
15995                "#define bbbb 4\n"
15996                "#define ccc (5)\n"
15997                "#define f(x) (x * x)\n"
15998                "#define fff(x, y, z) (x * y + z)\n"
15999                "#define ffff(x, y) (x - y)",
16000                Style);
16001 
16002   Style.AlignConsecutiveMacros.Enabled = true;
16003   verifyFormat("#define a    3\n"
16004                "#define bbbb 4\n"
16005                "#define ccc  (5)",
16006                Style);
16007 
16008   verifyFormat("#define f(x)         (x * x)\n"
16009                "#define fff(x, y, z) (x * y + z)\n"
16010                "#define ffff(x, y)   (x - y)",
16011                Style);
16012 
16013   verifyFormat("#define foo(x, y) (x + y)\n"
16014                "#define bar       (5, 6)(2 + 2)",
16015                Style);
16016 
16017   verifyFormat("#define a            3\n"
16018                "#define bbbb         4\n"
16019                "#define ccc          (5)\n"
16020                "#define f(x)         (x * x)\n"
16021                "#define fff(x, y, z) (x * y + z)\n"
16022                "#define ffff(x, y)   (x - y)",
16023                Style);
16024 
16025   verifyFormat("#define a         5\n"
16026                "#define foo(x, y) (x + y)\n"
16027                "#define CCC       (6)\n"
16028                "auto lambda = []() {\n"
16029                "  auto  ii = 0;\n"
16030                "  float j  = 0;\n"
16031                "  return 0;\n"
16032                "};\n"
16033                "int   i  = 0;\n"
16034                "float i2 = 0;\n"
16035                "auto  v  = type{\n"
16036                "    i = 1,   //\n"
16037                "    (i = 2), //\n"
16038                "    i = 3    //\n"
16039                "};",
16040                Style);
16041 
16042   Style.AlignConsecutiveMacros.Enabled = false;
16043   Style.ColumnLimit = 20;
16044 
16045   verifyFormat("#define a          \\\n"
16046                "  \"aabbbbbbbbbbbb\"\n"
16047                "#define D          \\\n"
16048                "  \"aabbbbbbbbbbbb\" \\\n"
16049                "  \"ccddeeeeeeeee\"\n"
16050                "#define B          \\\n"
16051                "  \"QQQQQQQQQQQQQ\"  \\\n"
16052                "  \"FFFFFFFFFFFFF\"  \\\n"
16053                "  \"LLLLLLLL\"\n",
16054                Style);
16055 
16056   Style.AlignConsecutiveMacros.Enabled = true;
16057   verifyFormat("#define a          \\\n"
16058                "  \"aabbbbbbbbbbbb\"\n"
16059                "#define D          \\\n"
16060                "  \"aabbbbbbbbbbbb\" \\\n"
16061                "  \"ccddeeeeeeeee\"\n"
16062                "#define B          \\\n"
16063                "  \"QQQQQQQQQQQQQ\"  \\\n"
16064                "  \"FFFFFFFFFFFFF\"  \\\n"
16065                "  \"LLLLLLLL\"\n",
16066                Style);
16067 
16068   // Test across comments
16069   Style.MaxEmptyLinesToKeep = 10;
16070   Style.ReflowComments = false;
16071   Style.AlignConsecutiveMacros.AcrossComments = true;
16072   EXPECT_EQ("#define a    3\n"
16073             "// line comment\n"
16074             "#define bbbb 4\n"
16075             "#define ccc  (5)",
16076             format("#define a 3\n"
16077                    "// line comment\n"
16078                    "#define bbbb 4\n"
16079                    "#define ccc (5)",
16080                    Style));
16081 
16082   EXPECT_EQ("#define a    3\n"
16083             "/* block comment */\n"
16084             "#define bbbb 4\n"
16085             "#define ccc  (5)",
16086             format("#define a  3\n"
16087                    "/* block comment */\n"
16088                    "#define bbbb 4\n"
16089                    "#define ccc (5)",
16090                    Style));
16091 
16092   EXPECT_EQ("#define a    3\n"
16093             "/* multi-line *\n"
16094             " * block comment */\n"
16095             "#define bbbb 4\n"
16096             "#define ccc  (5)",
16097             format("#define a 3\n"
16098                    "/* multi-line *\n"
16099                    " * block comment */\n"
16100                    "#define bbbb 4\n"
16101                    "#define ccc (5)",
16102                    Style));
16103 
16104   EXPECT_EQ("#define a    3\n"
16105             "// multi-line line comment\n"
16106             "//\n"
16107             "#define bbbb 4\n"
16108             "#define ccc  (5)",
16109             format("#define a  3\n"
16110                    "// multi-line line comment\n"
16111                    "//\n"
16112                    "#define bbbb 4\n"
16113                    "#define ccc (5)",
16114                    Style));
16115 
16116   EXPECT_EQ("#define a 3\n"
16117             "// empty lines still break.\n"
16118             "\n"
16119             "#define bbbb 4\n"
16120             "#define ccc  (5)",
16121             format("#define a     3\n"
16122                    "// empty lines still break.\n"
16123                    "\n"
16124                    "#define bbbb     4\n"
16125                    "#define ccc  (5)",
16126                    Style));
16127 
16128   // Test across empty lines
16129   Style.AlignConsecutiveMacros.AcrossComments = false;
16130   Style.AlignConsecutiveMacros.AcrossEmptyLines = true;
16131   EXPECT_EQ("#define a    3\n"
16132             "\n"
16133             "#define bbbb 4\n"
16134             "#define ccc  (5)",
16135             format("#define a 3\n"
16136                    "\n"
16137                    "#define bbbb 4\n"
16138                    "#define ccc (5)",
16139                    Style));
16140 
16141   EXPECT_EQ("#define a    3\n"
16142             "\n"
16143             "\n"
16144             "\n"
16145             "#define bbbb 4\n"
16146             "#define ccc  (5)",
16147             format("#define a        3\n"
16148                    "\n"
16149                    "\n"
16150                    "\n"
16151                    "#define bbbb 4\n"
16152                    "#define ccc (5)",
16153                    Style));
16154 
16155   EXPECT_EQ("#define a 3\n"
16156             "// comments should break alignment\n"
16157             "//\n"
16158             "#define bbbb 4\n"
16159             "#define ccc  (5)",
16160             format("#define a        3\n"
16161                    "// comments should break alignment\n"
16162                    "//\n"
16163                    "#define bbbb 4\n"
16164                    "#define ccc (5)",
16165                    Style));
16166 
16167   // Test across empty lines and comments
16168   Style.AlignConsecutiveMacros.AcrossComments = true;
16169   verifyFormat("#define a    3\n"
16170                "\n"
16171                "// line comment\n"
16172                "#define bbbb 4\n"
16173                "#define ccc  (5)",
16174                Style);
16175 
16176   EXPECT_EQ("#define a    3\n"
16177             "\n"
16178             "\n"
16179             "/* multi-line *\n"
16180             " * block comment */\n"
16181             "\n"
16182             "\n"
16183             "#define bbbb 4\n"
16184             "#define ccc  (5)",
16185             format("#define a 3\n"
16186                    "\n"
16187                    "\n"
16188                    "/* multi-line *\n"
16189                    " * block comment */\n"
16190                    "\n"
16191                    "\n"
16192                    "#define bbbb 4\n"
16193                    "#define ccc (5)",
16194                    Style));
16195 
16196   EXPECT_EQ("#define a    3\n"
16197             "\n"
16198             "\n"
16199             "/* multi-line *\n"
16200             " * block comment */\n"
16201             "\n"
16202             "\n"
16203             "#define bbbb 4\n"
16204             "#define ccc  (5)",
16205             format("#define a 3\n"
16206                    "\n"
16207                    "\n"
16208                    "/* multi-line *\n"
16209                    " * block comment */\n"
16210                    "\n"
16211                    "\n"
16212                    "#define bbbb 4\n"
16213                    "#define ccc       (5)",
16214                    Style));
16215 }
16216 
16217 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
16218   FormatStyle Alignment = getLLVMStyle();
16219   Alignment.AlignConsecutiveMacros.Enabled = true;
16220   Alignment.AlignConsecutiveAssignments.Enabled = true;
16221   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16222 
16223   Alignment.MaxEmptyLinesToKeep = 10;
16224   /* Test alignment across empty lines */
16225   EXPECT_EQ("int a           = 5;\n"
16226             "\n"
16227             "int oneTwoThree = 123;",
16228             format("int a       = 5;\n"
16229                    "\n"
16230                    "int oneTwoThree= 123;",
16231                    Alignment));
16232   EXPECT_EQ("int a           = 5;\n"
16233             "int one         = 1;\n"
16234             "\n"
16235             "int oneTwoThree = 123;",
16236             format("int a = 5;\n"
16237                    "int one = 1;\n"
16238                    "\n"
16239                    "int oneTwoThree = 123;",
16240                    Alignment));
16241   EXPECT_EQ("int a           = 5;\n"
16242             "int one         = 1;\n"
16243             "\n"
16244             "int oneTwoThree = 123;\n"
16245             "int oneTwo      = 12;",
16246             format("int a = 5;\n"
16247                    "int one = 1;\n"
16248                    "\n"
16249                    "int oneTwoThree = 123;\n"
16250                    "int oneTwo = 12;",
16251                    Alignment));
16252 
16253   /* Test across comments */
16254   EXPECT_EQ("int a = 5;\n"
16255             "/* block comment */\n"
16256             "int oneTwoThree = 123;",
16257             format("int a = 5;\n"
16258                    "/* block comment */\n"
16259                    "int oneTwoThree=123;",
16260                    Alignment));
16261 
16262   EXPECT_EQ("int a = 5;\n"
16263             "// line comment\n"
16264             "int oneTwoThree = 123;",
16265             format("int a = 5;\n"
16266                    "// line comment\n"
16267                    "int oneTwoThree=123;",
16268                    Alignment));
16269 
16270   /* Test across comments and newlines */
16271   EXPECT_EQ("int a = 5;\n"
16272             "\n"
16273             "/* block comment */\n"
16274             "int oneTwoThree = 123;",
16275             format("int a = 5;\n"
16276                    "\n"
16277                    "/* block comment */\n"
16278                    "int oneTwoThree=123;",
16279                    Alignment));
16280 
16281   EXPECT_EQ("int a = 5;\n"
16282             "\n"
16283             "// line comment\n"
16284             "int oneTwoThree = 123;",
16285             format("int a = 5;\n"
16286                    "\n"
16287                    "// line comment\n"
16288                    "int oneTwoThree=123;",
16289                    Alignment));
16290 }
16291 
16292 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16293   FormatStyle Alignment = getLLVMStyle();
16294   Alignment.AlignConsecutiveDeclarations.Enabled = true;
16295   Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true;
16296   Alignment.AlignConsecutiveDeclarations.AcrossComments = true;
16297 
16298   Alignment.MaxEmptyLinesToKeep = 10;
16299   /* Test alignment across empty lines */
16300   EXPECT_EQ("int         a = 5;\n"
16301             "\n"
16302             "float const oneTwoThree = 123;",
16303             format("int a = 5;\n"
16304                    "\n"
16305                    "float const oneTwoThree = 123;",
16306                    Alignment));
16307   EXPECT_EQ("int         a = 5;\n"
16308             "float const one = 1;\n"
16309             "\n"
16310             "int         oneTwoThree = 123;",
16311             format("int a = 5;\n"
16312                    "float const one = 1;\n"
16313                    "\n"
16314                    "int oneTwoThree = 123;",
16315                    Alignment));
16316 
16317   /* Test across comments */
16318   EXPECT_EQ("float const a = 5;\n"
16319             "/* block comment */\n"
16320             "int         oneTwoThree = 123;",
16321             format("float const a = 5;\n"
16322                    "/* block comment */\n"
16323                    "int oneTwoThree=123;",
16324                    Alignment));
16325 
16326   EXPECT_EQ("float const a = 5;\n"
16327             "// line comment\n"
16328             "int         oneTwoThree = 123;",
16329             format("float const a = 5;\n"
16330                    "// line comment\n"
16331                    "int oneTwoThree=123;",
16332                    Alignment));
16333 
16334   /* Test across comments and newlines */
16335   EXPECT_EQ("float const a = 5;\n"
16336             "\n"
16337             "/* block comment */\n"
16338             "int         oneTwoThree = 123;",
16339             format("float const a = 5;\n"
16340                    "\n"
16341                    "/* block comment */\n"
16342                    "int         oneTwoThree=123;",
16343                    Alignment));
16344 
16345   EXPECT_EQ("float const a = 5;\n"
16346             "\n"
16347             "// line comment\n"
16348             "int         oneTwoThree = 123;",
16349             format("float const a = 5;\n"
16350                    "\n"
16351                    "// line comment\n"
16352                    "int oneTwoThree=123;",
16353                    Alignment));
16354 }
16355 
16356 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16357   FormatStyle Alignment = getLLVMStyle();
16358   Alignment.AlignConsecutiveBitFields.Enabled = true;
16359   Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true;
16360   Alignment.AlignConsecutiveBitFields.AcrossComments = true;
16361 
16362   Alignment.MaxEmptyLinesToKeep = 10;
16363   /* Test alignment across empty lines */
16364   EXPECT_EQ("int a            : 5;\n"
16365             "\n"
16366             "int longbitfield : 6;",
16367             format("int a : 5;\n"
16368                    "\n"
16369                    "int longbitfield : 6;",
16370                    Alignment));
16371   EXPECT_EQ("int a            : 5;\n"
16372             "int one          : 1;\n"
16373             "\n"
16374             "int longbitfield : 6;",
16375             format("int a : 5;\n"
16376                    "int one : 1;\n"
16377                    "\n"
16378                    "int longbitfield : 6;",
16379                    Alignment));
16380 
16381   /* Test across comments */
16382   EXPECT_EQ("int a            : 5;\n"
16383             "/* block comment */\n"
16384             "int longbitfield : 6;",
16385             format("int a : 5;\n"
16386                    "/* block comment */\n"
16387                    "int longbitfield : 6;",
16388                    Alignment));
16389   EXPECT_EQ("int a            : 5;\n"
16390             "int one          : 1;\n"
16391             "// line comment\n"
16392             "int longbitfield : 6;",
16393             format("int a : 5;\n"
16394                    "int one : 1;\n"
16395                    "// line comment\n"
16396                    "int longbitfield : 6;",
16397                    Alignment));
16398 
16399   /* Test across comments and newlines */
16400   EXPECT_EQ("int a            : 5;\n"
16401             "/* block comment */\n"
16402             "\n"
16403             "int longbitfield : 6;",
16404             format("int a : 5;\n"
16405                    "/* block comment */\n"
16406                    "\n"
16407                    "int longbitfield : 6;",
16408                    Alignment));
16409   EXPECT_EQ("int a            : 5;\n"
16410             "int one          : 1;\n"
16411             "\n"
16412             "// line comment\n"
16413             "\n"
16414             "int longbitfield : 6;",
16415             format("int a : 5;\n"
16416                    "int one : 1;\n"
16417                    "\n"
16418                    "// line comment \n"
16419                    "\n"
16420                    "int longbitfield : 6;",
16421                    Alignment));
16422 }
16423 
16424 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16425   FormatStyle Alignment = getLLVMStyle();
16426   Alignment.AlignConsecutiveMacros.Enabled = true;
16427   Alignment.AlignConsecutiveAssignments.Enabled = true;
16428   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16429 
16430   Alignment.MaxEmptyLinesToKeep = 10;
16431   /* Test alignment across empty lines */
16432   EXPECT_EQ("int a = 5;\n"
16433             "\n"
16434             "int oneTwoThree = 123;",
16435             format("int a       = 5;\n"
16436                    "\n"
16437                    "int oneTwoThree= 123;",
16438                    Alignment));
16439   EXPECT_EQ("int a   = 5;\n"
16440             "int one = 1;\n"
16441             "\n"
16442             "int oneTwoThree = 123;",
16443             format("int a = 5;\n"
16444                    "int one = 1;\n"
16445                    "\n"
16446                    "int oneTwoThree = 123;",
16447                    Alignment));
16448 
16449   /* Test across comments */
16450   EXPECT_EQ("int a           = 5;\n"
16451             "/* block comment */\n"
16452             "int oneTwoThree = 123;",
16453             format("int a = 5;\n"
16454                    "/* block comment */\n"
16455                    "int oneTwoThree=123;",
16456                    Alignment));
16457 
16458   EXPECT_EQ("int a           = 5;\n"
16459             "// line comment\n"
16460             "int oneTwoThree = 123;",
16461             format("int a = 5;\n"
16462                    "// line comment\n"
16463                    "int oneTwoThree=123;",
16464                    Alignment));
16465 
16466   EXPECT_EQ("int a           = 5;\n"
16467             "/*\n"
16468             " * multi-line block comment\n"
16469             " */\n"
16470             "int oneTwoThree = 123;",
16471             format("int a = 5;\n"
16472                    "/*\n"
16473                    " * multi-line block comment\n"
16474                    " */\n"
16475                    "int oneTwoThree=123;",
16476                    Alignment));
16477 
16478   EXPECT_EQ("int a           = 5;\n"
16479             "//\n"
16480             "// multi-line line comment\n"
16481             "//\n"
16482             "int oneTwoThree = 123;",
16483             format("int a = 5;\n"
16484                    "//\n"
16485                    "// multi-line line comment\n"
16486                    "//\n"
16487                    "int oneTwoThree=123;",
16488                    Alignment));
16489 
16490   /* Test across comments and newlines */
16491   EXPECT_EQ("int a = 5;\n"
16492             "\n"
16493             "/* block comment */\n"
16494             "int oneTwoThree = 123;",
16495             format("int a = 5;\n"
16496                    "\n"
16497                    "/* block comment */\n"
16498                    "int oneTwoThree=123;",
16499                    Alignment));
16500 
16501   EXPECT_EQ("int a = 5;\n"
16502             "\n"
16503             "// line comment\n"
16504             "int oneTwoThree = 123;",
16505             format("int a = 5;\n"
16506                    "\n"
16507                    "// line comment\n"
16508                    "int oneTwoThree=123;",
16509                    Alignment));
16510 }
16511 
16512 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16513   FormatStyle Alignment = getLLVMStyle();
16514   Alignment.AlignConsecutiveMacros.Enabled = true;
16515   Alignment.AlignConsecutiveAssignments.Enabled = true;
16516   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16517   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16518   verifyFormat("int a           = 5;\n"
16519                "int oneTwoThree = 123;",
16520                Alignment);
16521   verifyFormat("int a           = method();\n"
16522                "int oneTwoThree = 133;",
16523                Alignment);
16524   verifyFormat("a &= 5;\n"
16525                "bcd *= 5;\n"
16526                "ghtyf += 5;\n"
16527                "dvfvdb -= 5;\n"
16528                "a /= 5;\n"
16529                "vdsvsv %= 5;\n"
16530                "sfdbddfbdfbb ^= 5;\n"
16531                "dvsdsv |= 5;\n"
16532                "int dsvvdvsdvvv = 123;",
16533                Alignment);
16534   verifyFormat("int i = 1, j = 10;\n"
16535                "something = 2000;",
16536                Alignment);
16537   verifyFormat("something = 2000;\n"
16538                "int i = 1, j = 10;\n",
16539                Alignment);
16540   verifyFormat("something = 2000;\n"
16541                "another   = 911;\n"
16542                "int i = 1, j = 10;\n"
16543                "oneMore = 1;\n"
16544                "i       = 2;",
16545                Alignment);
16546   verifyFormat("int a   = 5;\n"
16547                "int one = 1;\n"
16548                "method();\n"
16549                "int oneTwoThree = 123;\n"
16550                "int oneTwo      = 12;",
16551                Alignment);
16552   verifyFormat("int oneTwoThree = 123;\n"
16553                "int oneTwo      = 12;\n"
16554                "method();\n",
16555                Alignment);
16556   verifyFormat("int oneTwoThree = 123; // comment\n"
16557                "int oneTwo      = 12;  // comment",
16558                Alignment);
16559 
16560   // Bug 25167
16561   /* Uncomment when fixed
16562     verifyFormat("#if A\n"
16563                  "#else\n"
16564                  "int aaaaaaaa = 12;\n"
16565                  "#endif\n"
16566                  "#if B\n"
16567                  "#else\n"
16568                  "int a = 12;\n"
16569                  "#endif\n",
16570                  Alignment);
16571     verifyFormat("enum foo {\n"
16572                  "#if A\n"
16573                  "#else\n"
16574                  "  aaaaaaaa = 12;\n"
16575                  "#endif\n"
16576                  "#if B\n"
16577                  "#else\n"
16578                  "  a = 12;\n"
16579                  "#endif\n"
16580                  "};\n",
16581                  Alignment);
16582   */
16583 
16584   Alignment.MaxEmptyLinesToKeep = 10;
16585   /* Test alignment across empty lines */
16586   EXPECT_EQ("int a           = 5;\n"
16587             "\n"
16588             "int oneTwoThree = 123;",
16589             format("int a       = 5;\n"
16590                    "\n"
16591                    "int oneTwoThree= 123;",
16592                    Alignment));
16593   EXPECT_EQ("int a           = 5;\n"
16594             "int one         = 1;\n"
16595             "\n"
16596             "int oneTwoThree = 123;",
16597             format("int a = 5;\n"
16598                    "int one = 1;\n"
16599                    "\n"
16600                    "int oneTwoThree = 123;",
16601                    Alignment));
16602   EXPECT_EQ("int a           = 5;\n"
16603             "int one         = 1;\n"
16604             "\n"
16605             "int oneTwoThree = 123;\n"
16606             "int oneTwo      = 12;",
16607             format("int a = 5;\n"
16608                    "int one = 1;\n"
16609                    "\n"
16610                    "int oneTwoThree = 123;\n"
16611                    "int oneTwo = 12;",
16612                    Alignment));
16613 
16614   /* Test across comments */
16615   EXPECT_EQ("int a           = 5;\n"
16616             "/* block comment */\n"
16617             "int oneTwoThree = 123;",
16618             format("int a = 5;\n"
16619                    "/* block comment */\n"
16620                    "int oneTwoThree=123;",
16621                    Alignment));
16622 
16623   EXPECT_EQ("int a           = 5;\n"
16624             "// line comment\n"
16625             "int oneTwoThree = 123;",
16626             format("int a = 5;\n"
16627                    "// line comment\n"
16628                    "int oneTwoThree=123;",
16629                    Alignment));
16630 
16631   /* Test across comments and newlines */
16632   EXPECT_EQ("int a           = 5;\n"
16633             "\n"
16634             "/* block comment */\n"
16635             "int oneTwoThree = 123;",
16636             format("int a = 5;\n"
16637                    "\n"
16638                    "/* block comment */\n"
16639                    "int oneTwoThree=123;",
16640                    Alignment));
16641 
16642   EXPECT_EQ("int a           = 5;\n"
16643             "\n"
16644             "// line comment\n"
16645             "int oneTwoThree = 123;",
16646             format("int a = 5;\n"
16647                    "\n"
16648                    "// line comment\n"
16649                    "int oneTwoThree=123;",
16650                    Alignment));
16651 
16652   EXPECT_EQ("int a           = 5;\n"
16653             "//\n"
16654             "// multi-line line comment\n"
16655             "//\n"
16656             "int oneTwoThree = 123;",
16657             format("int a = 5;\n"
16658                    "//\n"
16659                    "// multi-line line comment\n"
16660                    "//\n"
16661                    "int oneTwoThree=123;",
16662                    Alignment));
16663 
16664   EXPECT_EQ("int a           = 5;\n"
16665             "/*\n"
16666             " *  multi-line block comment\n"
16667             " */\n"
16668             "int oneTwoThree = 123;",
16669             format("int a = 5;\n"
16670                    "/*\n"
16671                    " *  multi-line block comment\n"
16672                    " */\n"
16673                    "int oneTwoThree=123;",
16674                    Alignment));
16675 
16676   EXPECT_EQ("int a           = 5;\n"
16677             "\n"
16678             "/* block comment */\n"
16679             "\n"
16680             "\n"
16681             "\n"
16682             "int oneTwoThree = 123;",
16683             format("int a = 5;\n"
16684                    "\n"
16685                    "/* block comment */\n"
16686                    "\n"
16687                    "\n"
16688                    "\n"
16689                    "int oneTwoThree=123;",
16690                    Alignment));
16691 
16692   EXPECT_EQ("int a           = 5;\n"
16693             "\n"
16694             "// line comment\n"
16695             "\n"
16696             "\n"
16697             "\n"
16698             "int oneTwoThree = 123;",
16699             format("int a = 5;\n"
16700                    "\n"
16701                    "// line comment\n"
16702                    "\n"
16703                    "\n"
16704                    "\n"
16705                    "int oneTwoThree=123;",
16706                    Alignment));
16707 
16708   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16709   verifyFormat("#define A \\\n"
16710                "  int aaaa       = 12; \\\n"
16711                "  int b          = 23; \\\n"
16712                "  int ccc        = 234; \\\n"
16713                "  int dddddddddd = 2345;",
16714                Alignment);
16715   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16716   verifyFormat("#define A               \\\n"
16717                "  int aaaa       = 12;  \\\n"
16718                "  int b          = 23;  \\\n"
16719                "  int ccc        = 234; \\\n"
16720                "  int dddddddddd = 2345;",
16721                Alignment);
16722   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16723   verifyFormat("#define A                                                      "
16724                "                \\\n"
16725                "  int aaaa       = 12;                                         "
16726                "                \\\n"
16727                "  int b          = 23;                                         "
16728                "                \\\n"
16729                "  int ccc        = 234;                                        "
16730                "                \\\n"
16731                "  int dddddddddd = 2345;",
16732                Alignment);
16733   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16734                "k = 4, int l = 5,\n"
16735                "                  int m = 6) {\n"
16736                "  int j      = 10;\n"
16737                "  otherThing = 1;\n"
16738                "}",
16739                Alignment);
16740   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16741                "  int i   = 1;\n"
16742                "  int j   = 2;\n"
16743                "  int big = 10000;\n"
16744                "}",
16745                Alignment);
16746   verifyFormat("class C {\n"
16747                "public:\n"
16748                "  int i            = 1;\n"
16749                "  virtual void f() = 0;\n"
16750                "};",
16751                Alignment);
16752   verifyFormat("int i = 1;\n"
16753                "if (SomeType t = getSomething()) {\n"
16754                "}\n"
16755                "int j   = 2;\n"
16756                "int big = 10000;",
16757                Alignment);
16758   verifyFormat("int j = 7;\n"
16759                "for (int k = 0; k < N; ++k) {\n"
16760                "}\n"
16761                "int j   = 2;\n"
16762                "int big = 10000;\n"
16763                "}",
16764                Alignment);
16765   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16766   verifyFormat("int i = 1;\n"
16767                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16768                "    = someLooooooooooooooooongFunction();\n"
16769                "int j = 2;",
16770                Alignment);
16771   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16772   verifyFormat("int i = 1;\n"
16773                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16774                "    someLooooooooooooooooongFunction();\n"
16775                "int j = 2;",
16776                Alignment);
16777 
16778   verifyFormat("auto lambda = []() {\n"
16779                "  auto i = 0;\n"
16780                "  return 0;\n"
16781                "};\n"
16782                "int i  = 0;\n"
16783                "auto v = type{\n"
16784                "    i = 1,   //\n"
16785                "    (i = 2), //\n"
16786                "    i = 3    //\n"
16787                "};",
16788                Alignment);
16789 
16790   verifyFormat(
16791       "int i      = 1;\n"
16792       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16793       "                          loooooooooooooooooooooongParameterB);\n"
16794       "int j      = 2;",
16795       Alignment);
16796 
16797   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16798                "          typename B   = very_long_type_name_1,\n"
16799                "          typename T_2 = very_long_type_name_2>\n"
16800                "auto foo() {}\n",
16801                Alignment);
16802   verifyFormat("int a, b = 1;\n"
16803                "int c  = 2;\n"
16804                "int dd = 3;\n",
16805                Alignment);
16806   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16807                "float b[1][] = {{3.f}};\n",
16808                Alignment);
16809   verifyFormat("for (int i = 0; i < 1; i++)\n"
16810                "  int x = 1;\n",
16811                Alignment);
16812   verifyFormat("for (i = 0; i < 1; i++)\n"
16813                "  x = 1;\n"
16814                "y = 1;\n",
16815                Alignment);
16816 
16817   Alignment.ReflowComments = true;
16818   Alignment.ColumnLimit = 50;
16819   EXPECT_EQ("int x   = 0;\n"
16820             "int yy  = 1; /// specificlennospace\n"
16821             "int zzz = 2;\n",
16822             format("int x   = 0;\n"
16823                    "int yy  = 1; ///specificlennospace\n"
16824                    "int zzz = 2;\n",
16825                    Alignment));
16826 }
16827 
16828 TEST_F(FormatTest, AlignCompoundAssignments) {
16829   FormatStyle Alignment = getLLVMStyle();
16830   Alignment.AlignConsecutiveAssignments.Enabled = true;
16831   Alignment.AlignConsecutiveAssignments.AlignCompound = true;
16832   Alignment.AlignConsecutiveAssignments.PadOperators = false;
16833   verifyFormat("sfdbddfbdfbb    = 5;\n"
16834                "dvsdsv          = 5;\n"
16835                "int dsvvdvsdvvv = 123;",
16836                Alignment);
16837   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16838                "dvsdsv         |= 5;\n"
16839                "int dsvvdvsdvvv = 123;",
16840                Alignment);
16841   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16842                "dvsdsv        <<= 5;\n"
16843                "int dsvvdvsdvvv = 123;",
16844                Alignment);
16845   // Test that `<=` is not treated as a compound assignment.
16846   verifyFormat("aa &= 5;\n"
16847                "b <= 10;\n"
16848                "c = 15;",
16849                Alignment);
16850   Alignment.AlignConsecutiveAssignments.PadOperators = true;
16851   verifyFormat("sfdbddfbdfbb    = 5;\n"
16852                "dvsdsv          = 5;\n"
16853                "int dsvvdvsdvvv = 123;",
16854                Alignment);
16855   verifyFormat("sfdbddfbdfbb    ^= 5;\n"
16856                "dvsdsv          |= 5;\n"
16857                "int dsvvdvsdvvv  = 123;",
16858                Alignment);
16859   verifyFormat("sfdbddfbdfbb     ^= 5;\n"
16860                "dvsdsv          <<= 5;\n"
16861                "int dsvvdvsdvvv   = 123;",
16862                Alignment);
16863   EXPECT_EQ("a   += 5;\n"
16864             "one  = 1;\n"
16865             "\n"
16866             "oneTwoThree = 123;\n",
16867             format("a += 5;\n"
16868                    "one = 1;\n"
16869                    "\n"
16870                    "oneTwoThree = 123;\n",
16871                    Alignment));
16872   EXPECT_EQ("a   += 5;\n"
16873             "one  = 1;\n"
16874             "//\n"
16875             "oneTwoThree = 123;\n",
16876             format("a += 5;\n"
16877                    "one = 1;\n"
16878                    "//\n"
16879                    "oneTwoThree = 123;\n",
16880                    Alignment));
16881   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16882   EXPECT_EQ("a           += 5;\n"
16883             "one          = 1;\n"
16884             "\n"
16885             "oneTwoThree  = 123;\n",
16886             format("a += 5;\n"
16887                    "one = 1;\n"
16888                    "\n"
16889                    "oneTwoThree = 123;\n",
16890                    Alignment));
16891   EXPECT_EQ("a   += 5;\n"
16892             "one  = 1;\n"
16893             "//\n"
16894             "oneTwoThree = 123;\n",
16895             format("a += 5;\n"
16896                    "one = 1;\n"
16897                    "//\n"
16898                    "oneTwoThree = 123;\n",
16899                    Alignment));
16900   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false;
16901   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16902   EXPECT_EQ("a   += 5;\n"
16903             "one  = 1;\n"
16904             "\n"
16905             "oneTwoThree = 123;\n",
16906             format("a += 5;\n"
16907                    "one = 1;\n"
16908                    "\n"
16909                    "oneTwoThree = 123;\n",
16910                    Alignment));
16911   EXPECT_EQ("a           += 5;\n"
16912             "one          = 1;\n"
16913             "//\n"
16914             "oneTwoThree  = 123;\n",
16915             format("a += 5;\n"
16916                    "one = 1;\n"
16917                    "//\n"
16918                    "oneTwoThree = 123;\n",
16919                    Alignment));
16920   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16921   EXPECT_EQ("a            += 5;\n"
16922             "one         >>= 1;\n"
16923             "\n"
16924             "oneTwoThree   = 123;\n",
16925             format("a += 5;\n"
16926                    "one >>= 1;\n"
16927                    "\n"
16928                    "oneTwoThree = 123;\n",
16929                    Alignment));
16930   EXPECT_EQ("a            += 5;\n"
16931             "one           = 1;\n"
16932             "//\n"
16933             "oneTwoThree <<= 123;\n",
16934             format("a += 5;\n"
16935                    "one = 1;\n"
16936                    "//\n"
16937                    "oneTwoThree <<= 123;\n",
16938                    Alignment));
16939 }
16940 
16941 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16942   FormatStyle Alignment = getLLVMStyle();
16943   Alignment.AlignConsecutiveMacros.Enabled = true;
16944   verifyFormat("int a = 5;\n"
16945                "int oneTwoThree = 123;",
16946                Alignment);
16947   verifyFormat("int a = 5;\n"
16948                "int oneTwoThree = 123;",
16949                Alignment);
16950 
16951   Alignment.AlignConsecutiveAssignments.Enabled = true;
16952   verifyFormat("int a           = 5;\n"
16953                "int oneTwoThree = 123;",
16954                Alignment);
16955   verifyFormat("int a           = method();\n"
16956                "int oneTwoThree = 133;",
16957                Alignment);
16958   verifyFormat("aa <= 5;\n"
16959                "a &= 5;\n"
16960                "bcd *= 5;\n"
16961                "ghtyf += 5;\n"
16962                "dvfvdb -= 5;\n"
16963                "a /= 5;\n"
16964                "vdsvsv %= 5;\n"
16965                "sfdbddfbdfbb ^= 5;\n"
16966                "dvsdsv |= 5;\n"
16967                "int dsvvdvsdvvv = 123;",
16968                Alignment);
16969   verifyFormat("int i = 1, j = 10;\n"
16970                "something = 2000;",
16971                Alignment);
16972   verifyFormat("something = 2000;\n"
16973                "int i = 1, j = 10;\n",
16974                Alignment);
16975   verifyFormat("something = 2000;\n"
16976                "another   = 911;\n"
16977                "int i = 1, j = 10;\n"
16978                "oneMore = 1;\n"
16979                "i       = 2;",
16980                Alignment);
16981   verifyFormat("int a   = 5;\n"
16982                "int one = 1;\n"
16983                "method();\n"
16984                "int oneTwoThree = 123;\n"
16985                "int oneTwo      = 12;",
16986                Alignment);
16987   verifyFormat("int oneTwoThree = 123;\n"
16988                "int oneTwo      = 12;\n"
16989                "method();\n",
16990                Alignment);
16991   verifyFormat("int oneTwoThree = 123; // comment\n"
16992                "int oneTwo      = 12;  // comment",
16993                Alignment);
16994   verifyFormat("int f()         = default;\n"
16995                "int &operator() = default;\n"
16996                "int &operator=() {",
16997                Alignment);
16998   verifyFormat("int f()         = delete;\n"
16999                "int &operator() = delete;\n"
17000                "int &operator=() {",
17001                Alignment);
17002   verifyFormat("int f()         = default; // comment\n"
17003                "int &operator() = default; // comment\n"
17004                "int &operator=() {",
17005                Alignment);
17006   verifyFormat("int f()         = default;\n"
17007                "int &operator() = default;\n"
17008                "int &operator==() {",
17009                Alignment);
17010   verifyFormat("int f()         = default;\n"
17011                "int &operator() = default;\n"
17012                "int &operator<=() {",
17013                Alignment);
17014   verifyFormat("int f()         = default;\n"
17015                "int &operator() = default;\n"
17016                "int &operator!=() {",
17017                Alignment);
17018   verifyFormat("int f()         = default;\n"
17019                "int &operator() = default;\n"
17020                "int &operator=();",
17021                Alignment);
17022   verifyFormat("int f()         = delete;\n"
17023                "int &operator() = delete;\n"
17024                "int &operator=();",
17025                Alignment);
17026   verifyFormat("/* long long padding */ int f() = default;\n"
17027                "int &operator()                 = default;\n"
17028                "int &operator/**/ =();",
17029                Alignment);
17030   // https://llvm.org/PR33697
17031   FormatStyle AlignmentWithPenalty = getLLVMStyle();
17032   AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true;
17033   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
17034   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
17035                "  void f() = delete;\n"
17036                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
17037                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
17038                "};\n",
17039                AlignmentWithPenalty);
17040 
17041   // Bug 25167
17042   /* Uncomment when fixed
17043     verifyFormat("#if A\n"
17044                  "#else\n"
17045                  "int aaaaaaaa = 12;\n"
17046                  "#endif\n"
17047                  "#if B\n"
17048                  "#else\n"
17049                  "int a = 12;\n"
17050                  "#endif\n",
17051                  Alignment);
17052     verifyFormat("enum foo {\n"
17053                  "#if A\n"
17054                  "#else\n"
17055                  "  aaaaaaaa = 12;\n"
17056                  "#endif\n"
17057                  "#if B\n"
17058                  "#else\n"
17059                  "  a = 12;\n"
17060                  "#endif\n"
17061                  "};\n",
17062                  Alignment);
17063   */
17064 
17065   EXPECT_EQ("int a = 5;\n"
17066             "\n"
17067             "int oneTwoThree = 123;",
17068             format("int a       = 5;\n"
17069                    "\n"
17070                    "int oneTwoThree= 123;",
17071                    Alignment));
17072   EXPECT_EQ("int a   = 5;\n"
17073             "int one = 1;\n"
17074             "\n"
17075             "int oneTwoThree = 123;",
17076             format("int a = 5;\n"
17077                    "int one = 1;\n"
17078                    "\n"
17079                    "int oneTwoThree = 123;",
17080                    Alignment));
17081   EXPECT_EQ("int a   = 5;\n"
17082             "int one = 1;\n"
17083             "\n"
17084             "int oneTwoThree = 123;\n"
17085             "int oneTwo      = 12;",
17086             format("int a = 5;\n"
17087                    "int one = 1;\n"
17088                    "\n"
17089                    "int oneTwoThree = 123;\n"
17090                    "int oneTwo = 12;",
17091                    Alignment));
17092   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17093   verifyFormat("#define A \\\n"
17094                "  int aaaa       = 12; \\\n"
17095                "  int b          = 23; \\\n"
17096                "  int ccc        = 234; \\\n"
17097                "  int dddddddddd = 2345;",
17098                Alignment);
17099   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17100   verifyFormat("#define A               \\\n"
17101                "  int aaaa       = 12;  \\\n"
17102                "  int b          = 23;  \\\n"
17103                "  int ccc        = 234; \\\n"
17104                "  int dddddddddd = 2345;",
17105                Alignment);
17106   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17107   verifyFormat("#define A                                                      "
17108                "                \\\n"
17109                "  int aaaa       = 12;                                         "
17110                "                \\\n"
17111                "  int b          = 23;                                         "
17112                "                \\\n"
17113                "  int ccc        = 234;                                        "
17114                "                \\\n"
17115                "  int dddddddddd = 2345;",
17116                Alignment);
17117   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17118                "k = 4, int l = 5,\n"
17119                "                  int m = 6) {\n"
17120                "  int j      = 10;\n"
17121                "  otherThing = 1;\n"
17122                "}",
17123                Alignment);
17124   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17125                "  int i   = 1;\n"
17126                "  int j   = 2;\n"
17127                "  int big = 10000;\n"
17128                "}",
17129                Alignment);
17130   verifyFormat("class C {\n"
17131                "public:\n"
17132                "  int i            = 1;\n"
17133                "  virtual void f() = 0;\n"
17134                "};",
17135                Alignment);
17136   verifyFormat("int i = 1;\n"
17137                "if (SomeType t = getSomething()) {\n"
17138                "}\n"
17139                "int j   = 2;\n"
17140                "int big = 10000;",
17141                Alignment);
17142   verifyFormat("int j = 7;\n"
17143                "for (int k = 0; k < N; ++k) {\n"
17144                "}\n"
17145                "int j   = 2;\n"
17146                "int big = 10000;\n"
17147                "}",
17148                Alignment);
17149   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17150   verifyFormat("int i = 1;\n"
17151                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17152                "    = someLooooooooooooooooongFunction();\n"
17153                "int j = 2;",
17154                Alignment);
17155   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17156   verifyFormat("int i = 1;\n"
17157                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17158                "    someLooooooooooooooooongFunction();\n"
17159                "int j = 2;",
17160                Alignment);
17161 
17162   verifyFormat("auto lambda = []() {\n"
17163                "  auto i = 0;\n"
17164                "  return 0;\n"
17165                "};\n"
17166                "int i  = 0;\n"
17167                "auto v = type{\n"
17168                "    i = 1,   //\n"
17169                "    (i = 2), //\n"
17170                "    i = 3    //\n"
17171                "};",
17172                Alignment);
17173 
17174   verifyFormat(
17175       "int i      = 1;\n"
17176       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17177       "                          loooooooooooooooooooooongParameterB);\n"
17178       "int j      = 2;",
17179       Alignment);
17180 
17181   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17182                "          typename B   = very_long_type_name_1,\n"
17183                "          typename T_2 = very_long_type_name_2>\n"
17184                "auto foo() {}\n",
17185                Alignment);
17186   verifyFormat("int a, b = 1;\n"
17187                "int c  = 2;\n"
17188                "int dd = 3;\n",
17189                Alignment);
17190   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17191                "float b[1][] = {{3.f}};\n",
17192                Alignment);
17193   verifyFormat("for (int i = 0; i < 1; i++)\n"
17194                "  int x = 1;\n",
17195                Alignment);
17196   verifyFormat("for (i = 0; i < 1; i++)\n"
17197                "  x = 1;\n"
17198                "y = 1;\n",
17199                Alignment);
17200 
17201   EXPECT_EQ(Alignment.ReflowComments, true);
17202   Alignment.ColumnLimit = 50;
17203   EXPECT_EQ("int x   = 0;\n"
17204             "int yy  = 1; /// specificlennospace\n"
17205             "int zzz = 2;\n",
17206             format("int x   = 0;\n"
17207                    "int yy  = 1; ///specificlennospace\n"
17208                    "int zzz = 2;\n",
17209                    Alignment));
17210 
17211   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17212                "auto b                     = [] {\n"
17213                "  f();\n"
17214                "  return;\n"
17215                "};",
17216                Alignment);
17217   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17218                "auto b                     = g([] {\n"
17219                "  f();\n"
17220                "  return;\n"
17221                "});",
17222                Alignment);
17223   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17224                "auto b                     = g(param, [] {\n"
17225                "  f();\n"
17226                "  return;\n"
17227                "});",
17228                Alignment);
17229   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17230                "auto b                     = [] {\n"
17231                "  if (condition) {\n"
17232                "    return;\n"
17233                "  }\n"
17234                "};",
17235                Alignment);
17236 
17237   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17238                "           ccc ? aaaaa : bbbbb,\n"
17239                "           dddddddddddddddddddddddddd);",
17240                Alignment);
17241   // FIXME: https://llvm.org/PR53497
17242   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
17243   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17244   //              "    ccc ? aaaaa : bbbbb,\n"
17245   //              "    dddddddddddddddddddddddddd);",
17246   //              Alignment);
17247 }
17248 
17249 TEST_F(FormatTest, AlignConsecutiveBitFields) {
17250   FormatStyle Alignment = getLLVMStyle();
17251   Alignment.AlignConsecutiveBitFields.Enabled = true;
17252   verifyFormat("int const a     : 5;\n"
17253                "int oneTwoThree : 23;",
17254                Alignment);
17255 
17256   // Initializers are allowed starting with c++2a
17257   verifyFormat("int const a     : 5 = 1;\n"
17258                "int oneTwoThree : 23 = 0;",
17259                Alignment);
17260 
17261   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17262   verifyFormat("int const a           : 5;\n"
17263                "int       oneTwoThree : 23;",
17264                Alignment);
17265 
17266   verifyFormat("int const a           : 5;  // comment\n"
17267                "int       oneTwoThree : 23; // comment",
17268                Alignment);
17269 
17270   verifyFormat("int const a           : 5 = 1;\n"
17271                "int       oneTwoThree : 23 = 0;",
17272                Alignment);
17273 
17274   Alignment.AlignConsecutiveAssignments.Enabled = true;
17275   verifyFormat("int const a           : 5  = 1;\n"
17276                "int       oneTwoThree : 23 = 0;",
17277                Alignment);
17278   verifyFormat("int const a           : 5  = {1};\n"
17279                "int       oneTwoThree : 23 = 0;",
17280                Alignment);
17281 
17282   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
17283   verifyFormat("int const a          :5;\n"
17284                "int       oneTwoThree:23;",
17285                Alignment);
17286 
17287   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
17288   verifyFormat("int const a           :5;\n"
17289                "int       oneTwoThree :23;",
17290                Alignment);
17291 
17292   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
17293   verifyFormat("int const a          : 5;\n"
17294                "int       oneTwoThree: 23;",
17295                Alignment);
17296 
17297   // Known limitations: ':' is only recognized as a bitfield colon when
17298   // followed by a number.
17299   /*
17300   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
17301                "int a           : 5;",
17302                Alignment);
17303   */
17304 }
17305 
17306 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
17307   FormatStyle Alignment = getLLVMStyle();
17308   Alignment.AlignConsecutiveMacros.Enabled = true;
17309   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17310   verifyFormat("float const a = 5;\n"
17311                "int oneTwoThree = 123;",
17312                Alignment);
17313   verifyFormat("int a = 5;\n"
17314                "float const oneTwoThree = 123;",
17315                Alignment);
17316 
17317   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17318   verifyFormat("float const a = 5;\n"
17319                "int         oneTwoThree = 123;",
17320                Alignment);
17321   verifyFormat("int         a = method();\n"
17322                "float const oneTwoThree = 133;",
17323                Alignment);
17324   verifyFormat("int i = 1, j = 10;\n"
17325                "something = 2000;",
17326                Alignment);
17327   verifyFormat("something = 2000;\n"
17328                "int i = 1, j = 10;\n",
17329                Alignment);
17330   verifyFormat("float      something = 2000;\n"
17331                "double     another = 911;\n"
17332                "int        i = 1, j = 10;\n"
17333                "const int *oneMore = 1;\n"
17334                "unsigned   i = 2;",
17335                Alignment);
17336   verifyFormat("float a = 5;\n"
17337                "int   one = 1;\n"
17338                "method();\n"
17339                "const double       oneTwoThree = 123;\n"
17340                "const unsigned int oneTwo = 12;",
17341                Alignment);
17342   verifyFormat("int      oneTwoThree{0}; // comment\n"
17343                "unsigned oneTwo;         // comment",
17344                Alignment);
17345   verifyFormat("unsigned int       *a;\n"
17346                "int                *b;\n"
17347                "unsigned int Const *c;\n"
17348                "unsigned int const *d;\n"
17349                "unsigned int Const &e;\n"
17350                "unsigned int const &f;",
17351                Alignment);
17352   verifyFormat("Const unsigned int *c;\n"
17353                "const unsigned int *d;\n"
17354                "Const unsigned int &e;\n"
17355                "const unsigned int &f;\n"
17356                "const unsigned      g;\n"
17357                "Const unsigned      h;",
17358                Alignment);
17359   EXPECT_EQ("float const a = 5;\n"
17360             "\n"
17361             "int oneTwoThree = 123;",
17362             format("float const   a = 5;\n"
17363                    "\n"
17364                    "int           oneTwoThree= 123;",
17365                    Alignment));
17366   EXPECT_EQ("float a = 5;\n"
17367             "int   one = 1;\n"
17368             "\n"
17369             "unsigned oneTwoThree = 123;",
17370             format("float    a = 5;\n"
17371                    "int      one = 1;\n"
17372                    "\n"
17373                    "unsigned oneTwoThree = 123;",
17374                    Alignment));
17375   EXPECT_EQ("float a = 5;\n"
17376             "int   one = 1;\n"
17377             "\n"
17378             "unsigned oneTwoThree = 123;\n"
17379             "int      oneTwo = 12;",
17380             format("float    a = 5;\n"
17381                    "int one = 1;\n"
17382                    "\n"
17383                    "unsigned oneTwoThree = 123;\n"
17384                    "int oneTwo = 12;",
17385                    Alignment));
17386   // Function prototype alignment
17387   verifyFormat("int    a();\n"
17388                "double b();",
17389                Alignment);
17390   verifyFormat("int    a(int x);\n"
17391                "double b();",
17392                Alignment);
17393   unsigned OldColumnLimit = Alignment.ColumnLimit;
17394   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17395   // otherwise the function parameters will be re-flowed onto a single line.
17396   Alignment.ColumnLimit = 0;
17397   EXPECT_EQ("int    a(int   x,\n"
17398             "         float y);\n"
17399             "double b(int    x,\n"
17400             "         double y);",
17401             format("int a(int x,\n"
17402                    " float y);\n"
17403                    "double b(int x,\n"
17404                    " double y);",
17405                    Alignment));
17406   // This ensures that function parameters of function declarations are
17407   // correctly indented when their owning functions are indented.
17408   // The failure case here is for 'double y' to not be indented enough.
17409   EXPECT_EQ("double a(int x);\n"
17410             "int    b(int    y,\n"
17411             "         double z);",
17412             format("double a(int x);\n"
17413                    "int b(int y,\n"
17414                    " double z);",
17415                    Alignment));
17416   // Set ColumnLimit low so that we induce wrapping immediately after
17417   // the function name and opening paren.
17418   Alignment.ColumnLimit = 13;
17419   verifyFormat("int function(\n"
17420                "    int  x,\n"
17421                "    bool y);",
17422                Alignment);
17423   Alignment.ColumnLimit = OldColumnLimit;
17424   // Ensure function pointers don't screw up recursive alignment
17425   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17426                "double b();",
17427                Alignment);
17428   Alignment.AlignConsecutiveAssignments.Enabled = true;
17429   // Ensure recursive alignment is broken by function braces, so that the
17430   // "a = 1" does not align with subsequent assignments inside the function
17431   // body.
17432   verifyFormat("int func(int a = 1) {\n"
17433                "  int b  = 2;\n"
17434                "  int cc = 3;\n"
17435                "}",
17436                Alignment);
17437   verifyFormat("float      something = 2000;\n"
17438                "double     another   = 911;\n"
17439                "int        i = 1, j = 10;\n"
17440                "const int *oneMore = 1;\n"
17441                "unsigned   i       = 2;",
17442                Alignment);
17443   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17444                "unsigned oneTwo      = 0;   // comment",
17445                Alignment);
17446   // Make sure that scope is correctly tracked, in the absence of braces
17447   verifyFormat("for (int i = 0; i < n; i++)\n"
17448                "  j = i;\n"
17449                "double x = 1;\n",
17450                Alignment);
17451   verifyFormat("if (int i = 0)\n"
17452                "  j = i;\n"
17453                "double x = 1;\n",
17454                Alignment);
17455   // Ensure operator[] and operator() are comprehended
17456   verifyFormat("struct test {\n"
17457                "  long long int foo();\n"
17458                "  int           operator[](int a);\n"
17459                "  double        bar();\n"
17460                "};\n",
17461                Alignment);
17462   verifyFormat("struct test {\n"
17463                "  long long int foo();\n"
17464                "  int           operator()(int a);\n"
17465                "  double        bar();\n"
17466                "};\n",
17467                Alignment);
17468   // http://llvm.org/PR52914
17469   verifyFormat("char *a[]     = {\"a\", // comment\n"
17470                "                 \"bb\"};\n"
17471                "int   bbbbbbb = 0;",
17472                Alignment);
17473 
17474   // PAS_Right
17475   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17476             "  int const i   = 1;\n"
17477             "  int      *j   = 2;\n"
17478             "  int       big = 10000;\n"
17479             "\n"
17480             "  unsigned oneTwoThree = 123;\n"
17481             "  int      oneTwo      = 12;\n"
17482             "  method();\n"
17483             "  float k  = 2;\n"
17484             "  int   ll = 10000;\n"
17485             "}",
17486             format("void SomeFunction(int parameter= 0) {\n"
17487                    " int const  i= 1;\n"
17488                    "  int *j=2;\n"
17489                    " int big  =  10000;\n"
17490                    "\n"
17491                    "unsigned oneTwoThree  =123;\n"
17492                    "int oneTwo = 12;\n"
17493                    "  method();\n"
17494                    "float k= 2;\n"
17495                    "int ll=10000;\n"
17496                    "}",
17497                    Alignment));
17498   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17499             "  int const i   = 1;\n"
17500             "  int     **j   = 2, ***k;\n"
17501             "  int      &k   = i;\n"
17502             "  int     &&l   = i + j;\n"
17503             "  int       big = 10000;\n"
17504             "\n"
17505             "  unsigned oneTwoThree = 123;\n"
17506             "  int      oneTwo      = 12;\n"
17507             "  method();\n"
17508             "  float k  = 2;\n"
17509             "  int   ll = 10000;\n"
17510             "}",
17511             format("void SomeFunction(int parameter= 0) {\n"
17512                    " int const  i= 1;\n"
17513                    "  int **j=2,***k;\n"
17514                    "int &k=i;\n"
17515                    "int &&l=i+j;\n"
17516                    " int big  =  10000;\n"
17517                    "\n"
17518                    "unsigned oneTwoThree  =123;\n"
17519                    "int oneTwo = 12;\n"
17520                    "  method();\n"
17521                    "float k= 2;\n"
17522                    "int ll=10000;\n"
17523                    "}",
17524                    Alignment));
17525   // variables are aligned at their name, pointers are at the right most
17526   // position
17527   verifyFormat("int   *a;\n"
17528                "int  **b;\n"
17529                "int ***c;\n"
17530                "int    foobar;\n",
17531                Alignment);
17532 
17533   // PAS_Left
17534   FormatStyle AlignmentLeft = Alignment;
17535   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17536   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17537             "  int const i   = 1;\n"
17538             "  int*      j   = 2;\n"
17539             "  int       big = 10000;\n"
17540             "\n"
17541             "  unsigned oneTwoThree = 123;\n"
17542             "  int      oneTwo      = 12;\n"
17543             "  method();\n"
17544             "  float k  = 2;\n"
17545             "  int   ll = 10000;\n"
17546             "}",
17547             format("void SomeFunction(int parameter= 0) {\n"
17548                    " int const  i= 1;\n"
17549                    "  int *j=2;\n"
17550                    " int big  =  10000;\n"
17551                    "\n"
17552                    "unsigned oneTwoThree  =123;\n"
17553                    "int oneTwo = 12;\n"
17554                    "  method();\n"
17555                    "float k= 2;\n"
17556                    "int ll=10000;\n"
17557                    "}",
17558                    AlignmentLeft));
17559   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17560             "  int const i   = 1;\n"
17561             "  int**     j   = 2;\n"
17562             "  int&      k   = i;\n"
17563             "  int&&     l   = i + j;\n"
17564             "  int       big = 10000;\n"
17565             "\n"
17566             "  unsigned oneTwoThree = 123;\n"
17567             "  int      oneTwo      = 12;\n"
17568             "  method();\n"
17569             "  float k  = 2;\n"
17570             "  int   ll = 10000;\n"
17571             "}",
17572             format("void SomeFunction(int parameter= 0) {\n"
17573                    " int const  i= 1;\n"
17574                    "  int **j=2;\n"
17575                    "int &k=i;\n"
17576                    "int &&l=i+j;\n"
17577                    " int big  =  10000;\n"
17578                    "\n"
17579                    "unsigned oneTwoThree  =123;\n"
17580                    "int oneTwo = 12;\n"
17581                    "  method();\n"
17582                    "float k= 2;\n"
17583                    "int ll=10000;\n"
17584                    "}",
17585                    AlignmentLeft));
17586   // variables are aligned at their name, pointers are at the left most position
17587   verifyFormat("int*   a;\n"
17588                "int**  b;\n"
17589                "int*** c;\n"
17590                "int    foobar;\n",
17591                AlignmentLeft);
17592 
17593   // PAS_Middle
17594   FormatStyle AlignmentMiddle = Alignment;
17595   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17596   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17597             "  int const i   = 1;\n"
17598             "  int *     j   = 2;\n"
17599             "  int       big = 10000;\n"
17600             "\n"
17601             "  unsigned oneTwoThree = 123;\n"
17602             "  int      oneTwo      = 12;\n"
17603             "  method();\n"
17604             "  float k  = 2;\n"
17605             "  int   ll = 10000;\n"
17606             "}",
17607             format("void SomeFunction(int parameter= 0) {\n"
17608                    " int const  i= 1;\n"
17609                    "  int *j=2;\n"
17610                    " int big  =  10000;\n"
17611                    "\n"
17612                    "unsigned oneTwoThree  =123;\n"
17613                    "int oneTwo = 12;\n"
17614                    "  method();\n"
17615                    "float k= 2;\n"
17616                    "int ll=10000;\n"
17617                    "}",
17618                    AlignmentMiddle));
17619   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17620             "  int const i   = 1;\n"
17621             "  int **    j   = 2, ***k;\n"
17622             "  int &     k   = i;\n"
17623             "  int &&    l   = i + j;\n"
17624             "  int       big = 10000;\n"
17625             "\n"
17626             "  unsigned oneTwoThree = 123;\n"
17627             "  int      oneTwo      = 12;\n"
17628             "  method();\n"
17629             "  float k  = 2;\n"
17630             "  int   ll = 10000;\n"
17631             "}",
17632             format("void SomeFunction(int parameter= 0) {\n"
17633                    " int const  i= 1;\n"
17634                    "  int **j=2,***k;\n"
17635                    "int &k=i;\n"
17636                    "int &&l=i+j;\n"
17637                    " int big  =  10000;\n"
17638                    "\n"
17639                    "unsigned oneTwoThree  =123;\n"
17640                    "int oneTwo = 12;\n"
17641                    "  method();\n"
17642                    "float k= 2;\n"
17643                    "int ll=10000;\n"
17644                    "}",
17645                    AlignmentMiddle));
17646   // variables are aligned at their name, pointers are in the middle
17647   verifyFormat("int *   a;\n"
17648                "int *   b;\n"
17649                "int *** c;\n"
17650                "int     foobar;\n",
17651                AlignmentMiddle);
17652 
17653   Alignment.AlignConsecutiveAssignments.Enabled = false;
17654   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17655   verifyFormat("#define A \\\n"
17656                "  int       aaaa = 12; \\\n"
17657                "  float     b = 23; \\\n"
17658                "  const int ccc = 234; \\\n"
17659                "  unsigned  dddddddddd = 2345;",
17660                Alignment);
17661   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17662   verifyFormat("#define A              \\\n"
17663                "  int       aaaa = 12; \\\n"
17664                "  float     b = 23;    \\\n"
17665                "  const int ccc = 234; \\\n"
17666                "  unsigned  dddddddddd = 2345;",
17667                Alignment);
17668   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17669   Alignment.ColumnLimit = 30;
17670   verifyFormat("#define A                    \\\n"
17671                "  int       aaaa = 12;       \\\n"
17672                "  float     b = 23;          \\\n"
17673                "  const int ccc = 234;       \\\n"
17674                "  int       dddddddddd = 2345;",
17675                Alignment);
17676   Alignment.ColumnLimit = 80;
17677   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17678                "k = 4, int l = 5,\n"
17679                "                  int m = 6) {\n"
17680                "  const int j = 10;\n"
17681                "  otherThing = 1;\n"
17682                "}",
17683                Alignment);
17684   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17685                "  int const i = 1;\n"
17686                "  int      *j = 2;\n"
17687                "  int       big = 10000;\n"
17688                "}",
17689                Alignment);
17690   verifyFormat("class C {\n"
17691                "public:\n"
17692                "  int          i = 1;\n"
17693                "  virtual void f() = 0;\n"
17694                "};",
17695                Alignment);
17696   verifyFormat("float i = 1;\n"
17697                "if (SomeType t = getSomething()) {\n"
17698                "}\n"
17699                "const unsigned j = 2;\n"
17700                "int            big = 10000;",
17701                Alignment);
17702   verifyFormat("float j = 7;\n"
17703                "for (int k = 0; k < N; ++k) {\n"
17704                "}\n"
17705                "unsigned j = 2;\n"
17706                "int      big = 10000;\n"
17707                "}",
17708                Alignment);
17709   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17710   verifyFormat("float              i = 1;\n"
17711                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17712                "    = someLooooooooooooooooongFunction();\n"
17713                "int j = 2;",
17714                Alignment);
17715   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17716   verifyFormat("int                i = 1;\n"
17717                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17718                "    someLooooooooooooooooongFunction();\n"
17719                "int j = 2;",
17720                Alignment);
17721 
17722   Alignment.AlignConsecutiveAssignments.Enabled = true;
17723   verifyFormat("auto lambda = []() {\n"
17724                "  auto  ii = 0;\n"
17725                "  float j  = 0;\n"
17726                "  return 0;\n"
17727                "};\n"
17728                "int   i  = 0;\n"
17729                "float i2 = 0;\n"
17730                "auto  v  = type{\n"
17731                "    i = 1,   //\n"
17732                "    (i = 2), //\n"
17733                "    i = 3    //\n"
17734                "};",
17735                Alignment);
17736   Alignment.AlignConsecutiveAssignments.Enabled = false;
17737 
17738   verifyFormat(
17739       "int      i = 1;\n"
17740       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17741       "                          loooooooooooooooooooooongParameterB);\n"
17742       "int      j = 2;",
17743       Alignment);
17744 
17745   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17746   // We expect declarations and assignments to align, as long as it doesn't
17747   // exceed the column limit, starting a new alignment sequence whenever it
17748   // happens.
17749   Alignment.AlignConsecutiveAssignments.Enabled = true;
17750   Alignment.ColumnLimit = 30;
17751   verifyFormat("float    ii              = 1;\n"
17752                "unsigned j               = 2;\n"
17753                "int someVerylongVariable = 1;\n"
17754                "AnotherLongType  ll = 123456;\n"
17755                "VeryVeryLongType k  = 2;\n"
17756                "int              myvar = 1;",
17757                Alignment);
17758   Alignment.ColumnLimit = 80;
17759   Alignment.AlignConsecutiveAssignments.Enabled = false;
17760 
17761   verifyFormat(
17762       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17763       "          typename LongType, typename B>\n"
17764       "auto foo() {}\n",
17765       Alignment);
17766   verifyFormat("float a, b = 1;\n"
17767                "int   c = 2;\n"
17768                "int   dd = 3;\n",
17769                Alignment);
17770   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17771                "float b[1][] = {{3.f}};\n",
17772                Alignment);
17773   Alignment.AlignConsecutiveAssignments.Enabled = true;
17774   verifyFormat("float a, b = 1;\n"
17775                "int   c  = 2;\n"
17776                "int   dd = 3;\n",
17777                Alignment);
17778   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17779                "float b[1][] = {{3.f}};\n",
17780                Alignment);
17781   Alignment.AlignConsecutiveAssignments.Enabled = false;
17782 
17783   Alignment.ColumnLimit = 30;
17784   Alignment.BinPackParameters = false;
17785   verifyFormat("void foo(float     a,\n"
17786                "         float     b,\n"
17787                "         int       c,\n"
17788                "         uint32_t *d) {\n"
17789                "  int   *e = 0;\n"
17790                "  float  f = 0;\n"
17791                "  double g = 0;\n"
17792                "}\n"
17793                "void bar(ino_t     a,\n"
17794                "         int       b,\n"
17795                "         uint32_t *c,\n"
17796                "         bool      d) {}\n",
17797                Alignment);
17798   Alignment.BinPackParameters = true;
17799   Alignment.ColumnLimit = 80;
17800 
17801   // Bug 33507
17802   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17803   verifyFormat(
17804       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
17805       "  static const Version verVs2017;\n"
17806       "  return true;\n"
17807       "});\n",
17808       Alignment);
17809   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17810 
17811   // See llvm.org/PR35641
17812   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17813   verifyFormat("int func() { //\n"
17814                "  int      b;\n"
17815                "  unsigned c;\n"
17816                "}",
17817                Alignment);
17818 
17819   // See PR37175
17820   FormatStyle Style = getMozillaStyle();
17821   Style.AlignConsecutiveDeclarations.Enabled = true;
17822   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
17823             "foo(int a);",
17824             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
17825 
17826   Alignment.PointerAlignment = FormatStyle::PAS_Left;
17827   verifyFormat("unsigned int*       a;\n"
17828                "int*                b;\n"
17829                "unsigned int Const* c;\n"
17830                "unsigned int const* d;\n"
17831                "unsigned int Const& e;\n"
17832                "unsigned int const& f;",
17833                Alignment);
17834   verifyFormat("Const unsigned int* c;\n"
17835                "const unsigned int* d;\n"
17836                "Const unsigned int& e;\n"
17837                "const unsigned int& f;\n"
17838                "const unsigned      g;\n"
17839                "Const unsigned      h;",
17840                Alignment);
17841 
17842   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17843   verifyFormat("unsigned int *       a;\n"
17844                "int *                b;\n"
17845                "unsigned int Const * c;\n"
17846                "unsigned int const * d;\n"
17847                "unsigned int Const & e;\n"
17848                "unsigned int const & f;",
17849                Alignment);
17850   verifyFormat("Const unsigned int * c;\n"
17851                "const unsigned int * d;\n"
17852                "Const unsigned int & e;\n"
17853                "const unsigned int & f;\n"
17854                "const unsigned       g;\n"
17855                "Const unsigned       h;",
17856                Alignment);
17857 
17858   // See PR46529
17859   FormatStyle BracedAlign = getLLVMStyle();
17860   BracedAlign.AlignConsecutiveDeclarations.Enabled = true;
17861   verifyFormat("const auto result{[]() {\n"
17862                "  const auto something = 1;\n"
17863                "  return 2;\n"
17864                "}};",
17865                BracedAlign);
17866   verifyFormat("int foo{[]() {\n"
17867                "  int bar{0};\n"
17868                "  return 0;\n"
17869                "}()};",
17870                BracedAlign);
17871   BracedAlign.Cpp11BracedListStyle = false;
17872   verifyFormat("const auto result{ []() {\n"
17873                "  const auto something = 1;\n"
17874                "  return 2;\n"
17875                "} };",
17876                BracedAlign);
17877   verifyFormat("int foo{ []() {\n"
17878                "  int bar{ 0 };\n"
17879                "  return 0;\n"
17880                "}() };",
17881                BracedAlign);
17882 }
17883 
17884 TEST_F(FormatTest, AlignWithLineBreaks) {
17885   auto Style = getLLVMStyleWithColumns(120);
17886 
17887   EXPECT_EQ(Style.AlignConsecutiveAssignments,
17888             FormatStyle::AlignConsecutiveStyle(
17889                 {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
17890                  /*AcrossComments=*/false, /*AlignCompound=*/false,
17891                  /*PadOperators=*/true}));
17892   EXPECT_EQ(Style.AlignConsecutiveDeclarations,
17893             FormatStyle::AlignConsecutiveStyle({}));
17894   verifyFormat("void foo() {\n"
17895                "  int myVar = 5;\n"
17896                "  double x = 3.14;\n"
17897                "  auto str = \"Hello \"\n"
17898                "             \"World\";\n"
17899                "  auto s = \"Hello \"\n"
17900                "           \"Again\";\n"
17901                "}",
17902                Style);
17903 
17904   // clang-format off
17905   verifyFormat("void foo() {\n"
17906                "  const int capacityBefore = Entries.capacity();\n"
17907                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17908                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17909                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17910                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17911                "}",
17912                Style);
17913   // clang-format on
17914 
17915   Style.AlignConsecutiveAssignments.Enabled = true;
17916   verifyFormat("void foo() {\n"
17917                "  int myVar = 5;\n"
17918                "  double x  = 3.14;\n"
17919                "  auto str  = \"Hello \"\n"
17920                "              \"World\";\n"
17921                "  auto s    = \"Hello \"\n"
17922                "              \"Again\";\n"
17923                "}",
17924                Style);
17925 
17926   // clang-format off
17927   verifyFormat("void foo() {\n"
17928                "  const int capacityBefore = Entries.capacity();\n"
17929                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17930                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17931                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17932                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17933                "}",
17934                Style);
17935   // clang-format on
17936 
17937   Style.AlignConsecutiveAssignments.Enabled = false;
17938   Style.AlignConsecutiveDeclarations.Enabled = true;
17939   verifyFormat("void foo() {\n"
17940                "  int    myVar = 5;\n"
17941                "  double x = 3.14;\n"
17942                "  auto   str = \"Hello \"\n"
17943                "               \"World\";\n"
17944                "  auto   s = \"Hello \"\n"
17945                "             \"Again\";\n"
17946                "}",
17947                Style);
17948 
17949   // clang-format off
17950   verifyFormat("void foo() {\n"
17951                "  const int  capacityBefore = Entries.capacity();\n"
17952                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17953                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17954                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17955                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17956                "}",
17957                Style);
17958   // clang-format on
17959 
17960   Style.AlignConsecutiveAssignments.Enabled = true;
17961   Style.AlignConsecutiveDeclarations.Enabled = true;
17962 
17963   verifyFormat("void foo() {\n"
17964                "  int    myVar = 5;\n"
17965                "  double x     = 3.14;\n"
17966                "  auto   str   = \"Hello \"\n"
17967                "                 \"World\";\n"
17968                "  auto   s     = \"Hello \"\n"
17969                "                 \"Again\";\n"
17970                "}",
17971                Style);
17972 
17973   // clang-format off
17974   verifyFormat("void foo() {\n"
17975                "  const int  capacityBefore = Entries.capacity();\n"
17976                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17977                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17978                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17979                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17980                "}",
17981                Style);
17982   // clang-format on
17983 
17984   Style = getLLVMStyleWithColumns(120);
17985   Style.AlignConsecutiveAssignments.Enabled = true;
17986   Style.ContinuationIndentWidth = 4;
17987   Style.IndentWidth = 4;
17988 
17989   // clang-format off
17990   verifyFormat("void SomeFunc() {\n"
17991                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17992                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17993                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17994                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17995                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17996                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17997                "}",
17998                Style);
17999   // clang-format on
18000 
18001   Style.BinPackArguments = false;
18002 
18003   // clang-format off
18004   verifyFormat("void SomeFunc() {\n"
18005                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
18006                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18007                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
18008                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18009                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
18010                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18011                "}",
18012                Style);
18013   // clang-format on
18014 }
18015 
18016 TEST_F(FormatTest, AlignWithInitializerPeriods) {
18017   auto Style = getLLVMStyleWithColumns(60);
18018 
18019   verifyFormat("void foo1(void) {\n"
18020                "  BYTE p[1] = 1;\n"
18021                "  A B = {.one_foooooooooooooooo = 2,\n"
18022                "         .two_fooooooooooooo = 3,\n"
18023                "         .three_fooooooooooooo = 4};\n"
18024                "  BYTE payload = 2;\n"
18025                "}",
18026                Style);
18027 
18028   Style.AlignConsecutiveAssignments.Enabled = true;
18029   Style.AlignConsecutiveDeclarations.Enabled = false;
18030   verifyFormat("void foo2(void) {\n"
18031                "  BYTE p[1]    = 1;\n"
18032                "  A B          = {.one_foooooooooooooooo = 2,\n"
18033                "                  .two_fooooooooooooo    = 3,\n"
18034                "                  .three_fooooooooooooo  = 4};\n"
18035                "  BYTE payload = 2;\n"
18036                "}",
18037                Style);
18038 
18039   Style.AlignConsecutiveAssignments.Enabled = false;
18040   Style.AlignConsecutiveDeclarations.Enabled = true;
18041   verifyFormat("void foo3(void) {\n"
18042                "  BYTE p[1] = 1;\n"
18043                "  A    B = {.one_foooooooooooooooo = 2,\n"
18044                "            .two_fooooooooooooo = 3,\n"
18045                "            .three_fooooooooooooo = 4};\n"
18046                "  BYTE payload = 2;\n"
18047                "}",
18048                Style);
18049 
18050   Style.AlignConsecutiveAssignments.Enabled = true;
18051   Style.AlignConsecutiveDeclarations.Enabled = true;
18052   verifyFormat("void foo4(void) {\n"
18053                "  BYTE p[1]    = 1;\n"
18054                "  A    B       = {.one_foooooooooooooooo = 2,\n"
18055                "                  .two_fooooooooooooo    = 3,\n"
18056                "                  .three_fooooooooooooo  = 4};\n"
18057                "  BYTE payload = 2;\n"
18058                "}",
18059                Style);
18060 }
18061 
18062 TEST_F(FormatTest, LinuxBraceBreaking) {
18063   FormatStyle LinuxBraceStyle = getLLVMStyle();
18064   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
18065   verifyFormat("namespace a\n"
18066                "{\n"
18067                "class A\n"
18068                "{\n"
18069                "  void f()\n"
18070                "  {\n"
18071                "    if (true) {\n"
18072                "      a();\n"
18073                "      b();\n"
18074                "    } else {\n"
18075                "      a();\n"
18076                "    }\n"
18077                "  }\n"
18078                "  void g() { return; }\n"
18079                "};\n"
18080                "struct B {\n"
18081                "  int x;\n"
18082                "};\n"
18083                "} // namespace a\n",
18084                LinuxBraceStyle);
18085   verifyFormat("enum X {\n"
18086                "  Y = 0,\n"
18087                "}\n",
18088                LinuxBraceStyle);
18089   verifyFormat("struct S {\n"
18090                "  int Type;\n"
18091                "  union {\n"
18092                "    int x;\n"
18093                "    double y;\n"
18094                "  } Value;\n"
18095                "  class C\n"
18096                "  {\n"
18097                "    MyFavoriteType Value;\n"
18098                "  } Class;\n"
18099                "}\n",
18100                LinuxBraceStyle);
18101 }
18102 
18103 TEST_F(FormatTest, MozillaBraceBreaking) {
18104   FormatStyle MozillaBraceStyle = getLLVMStyle();
18105   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
18106   MozillaBraceStyle.FixNamespaceComments = false;
18107   verifyFormat("namespace a {\n"
18108                "class A\n"
18109                "{\n"
18110                "  void f()\n"
18111                "  {\n"
18112                "    if (true) {\n"
18113                "      a();\n"
18114                "      b();\n"
18115                "    }\n"
18116                "  }\n"
18117                "  void g() { return; }\n"
18118                "};\n"
18119                "enum E\n"
18120                "{\n"
18121                "  A,\n"
18122                "  // foo\n"
18123                "  B,\n"
18124                "  C\n"
18125                "};\n"
18126                "struct B\n"
18127                "{\n"
18128                "  int x;\n"
18129                "};\n"
18130                "}\n",
18131                MozillaBraceStyle);
18132   verifyFormat("struct S\n"
18133                "{\n"
18134                "  int Type;\n"
18135                "  union\n"
18136                "  {\n"
18137                "    int x;\n"
18138                "    double y;\n"
18139                "  } Value;\n"
18140                "  class C\n"
18141                "  {\n"
18142                "    MyFavoriteType Value;\n"
18143                "  } Class;\n"
18144                "}\n",
18145                MozillaBraceStyle);
18146 }
18147 
18148 TEST_F(FormatTest, StroustrupBraceBreaking) {
18149   FormatStyle StroustrupBraceStyle = getLLVMStyle();
18150   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18151   verifyFormat("namespace a {\n"
18152                "class A {\n"
18153                "  void f()\n"
18154                "  {\n"
18155                "    if (true) {\n"
18156                "      a();\n"
18157                "      b();\n"
18158                "    }\n"
18159                "  }\n"
18160                "  void g() { return; }\n"
18161                "};\n"
18162                "struct B {\n"
18163                "  int x;\n"
18164                "};\n"
18165                "} // namespace a\n",
18166                StroustrupBraceStyle);
18167 
18168   verifyFormat("void foo()\n"
18169                "{\n"
18170                "  if (a) {\n"
18171                "    a();\n"
18172                "  }\n"
18173                "  else {\n"
18174                "    b();\n"
18175                "  }\n"
18176                "}\n",
18177                StroustrupBraceStyle);
18178 
18179   verifyFormat("#ifdef _DEBUG\n"
18180                "int foo(int i = 0)\n"
18181                "#else\n"
18182                "int foo(int i = 5)\n"
18183                "#endif\n"
18184                "{\n"
18185                "  return i;\n"
18186                "}",
18187                StroustrupBraceStyle);
18188 
18189   verifyFormat("void foo() {}\n"
18190                "void bar()\n"
18191                "#ifdef _DEBUG\n"
18192                "{\n"
18193                "  foo();\n"
18194                "}\n"
18195                "#else\n"
18196                "{\n"
18197                "}\n"
18198                "#endif",
18199                StroustrupBraceStyle);
18200 
18201   verifyFormat("void foobar() { int i = 5; }\n"
18202                "#ifdef _DEBUG\n"
18203                "void bar() {}\n"
18204                "#else\n"
18205                "void bar() { foobar(); }\n"
18206                "#endif",
18207                StroustrupBraceStyle);
18208 }
18209 
18210 TEST_F(FormatTest, AllmanBraceBreaking) {
18211   FormatStyle AllmanBraceStyle = getLLVMStyle();
18212   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
18213 
18214   EXPECT_EQ("namespace a\n"
18215             "{\n"
18216             "void f();\n"
18217             "void g();\n"
18218             "} // namespace a\n",
18219             format("namespace a\n"
18220                    "{\n"
18221                    "void f();\n"
18222                    "void g();\n"
18223                    "}\n",
18224                    AllmanBraceStyle));
18225 
18226   verifyFormat("namespace a\n"
18227                "{\n"
18228                "class A\n"
18229                "{\n"
18230                "  void f()\n"
18231                "  {\n"
18232                "    if (true)\n"
18233                "    {\n"
18234                "      a();\n"
18235                "      b();\n"
18236                "    }\n"
18237                "  }\n"
18238                "  void g() { return; }\n"
18239                "};\n"
18240                "struct B\n"
18241                "{\n"
18242                "  int x;\n"
18243                "};\n"
18244                "union C\n"
18245                "{\n"
18246                "};\n"
18247                "} // namespace a",
18248                AllmanBraceStyle);
18249 
18250   verifyFormat("void f()\n"
18251                "{\n"
18252                "  if (true)\n"
18253                "  {\n"
18254                "    a();\n"
18255                "  }\n"
18256                "  else if (false)\n"
18257                "  {\n"
18258                "    b();\n"
18259                "  }\n"
18260                "  else\n"
18261                "  {\n"
18262                "    c();\n"
18263                "  }\n"
18264                "}\n",
18265                AllmanBraceStyle);
18266 
18267   verifyFormat("void f()\n"
18268                "{\n"
18269                "  for (int i = 0; i < 10; ++i)\n"
18270                "  {\n"
18271                "    a();\n"
18272                "  }\n"
18273                "  while (false)\n"
18274                "  {\n"
18275                "    b();\n"
18276                "  }\n"
18277                "  do\n"
18278                "  {\n"
18279                "    c();\n"
18280                "  } while (false)\n"
18281                "}\n",
18282                AllmanBraceStyle);
18283 
18284   verifyFormat("void f(int a)\n"
18285                "{\n"
18286                "  switch (a)\n"
18287                "  {\n"
18288                "  case 0:\n"
18289                "    break;\n"
18290                "  case 1:\n"
18291                "  {\n"
18292                "    break;\n"
18293                "  }\n"
18294                "  case 2:\n"
18295                "  {\n"
18296                "  }\n"
18297                "  break;\n"
18298                "  default:\n"
18299                "    break;\n"
18300                "  }\n"
18301                "}\n",
18302                AllmanBraceStyle);
18303 
18304   verifyFormat("enum X\n"
18305                "{\n"
18306                "  Y = 0,\n"
18307                "}\n",
18308                AllmanBraceStyle);
18309   verifyFormat("enum X\n"
18310                "{\n"
18311                "  Y = 0\n"
18312                "}\n",
18313                AllmanBraceStyle);
18314 
18315   verifyFormat("@interface BSApplicationController ()\n"
18316                "{\n"
18317                "@private\n"
18318                "  id _extraIvar;\n"
18319                "}\n"
18320                "@end\n",
18321                AllmanBraceStyle);
18322 
18323   verifyFormat("#ifdef _DEBUG\n"
18324                "int foo(int i = 0)\n"
18325                "#else\n"
18326                "int foo(int i = 5)\n"
18327                "#endif\n"
18328                "{\n"
18329                "  return i;\n"
18330                "}",
18331                AllmanBraceStyle);
18332 
18333   verifyFormat("void foo() {}\n"
18334                "void bar()\n"
18335                "#ifdef _DEBUG\n"
18336                "{\n"
18337                "  foo();\n"
18338                "}\n"
18339                "#else\n"
18340                "{\n"
18341                "}\n"
18342                "#endif",
18343                AllmanBraceStyle);
18344 
18345   verifyFormat("void foobar() { int i = 5; }\n"
18346                "#ifdef _DEBUG\n"
18347                "void bar() {}\n"
18348                "#else\n"
18349                "void bar() { foobar(); }\n"
18350                "#endif",
18351                AllmanBraceStyle);
18352 
18353   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18354             FormatStyle::SLS_All);
18355 
18356   verifyFormat("[](int i) { return i + 2; };\n"
18357                "[](int i, int j)\n"
18358                "{\n"
18359                "  auto x = i + j;\n"
18360                "  auto y = i * j;\n"
18361                "  return x ^ y;\n"
18362                "};\n"
18363                "void foo()\n"
18364                "{\n"
18365                "  auto shortLambda = [](int i) { return i + 2; };\n"
18366                "  auto longLambda = [](int i, int j)\n"
18367                "  {\n"
18368                "    auto x = i + j;\n"
18369                "    auto y = i * j;\n"
18370                "    return x ^ y;\n"
18371                "  };\n"
18372                "}",
18373                AllmanBraceStyle);
18374 
18375   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18376 
18377   verifyFormat("[](int i)\n"
18378                "{\n"
18379                "  return i + 2;\n"
18380                "};\n"
18381                "[](int i, int j)\n"
18382                "{\n"
18383                "  auto x = i + j;\n"
18384                "  auto y = i * j;\n"
18385                "  return x ^ y;\n"
18386                "};\n"
18387                "void foo()\n"
18388                "{\n"
18389                "  auto shortLambda = [](int i)\n"
18390                "  {\n"
18391                "    return i + 2;\n"
18392                "  };\n"
18393                "  auto longLambda = [](int i, int j)\n"
18394                "  {\n"
18395                "    auto x = i + j;\n"
18396                "    auto y = i * j;\n"
18397                "    return x ^ y;\n"
18398                "  };\n"
18399                "}",
18400                AllmanBraceStyle);
18401 
18402   // Reset
18403   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18404 
18405   // This shouldn't affect ObjC blocks..
18406   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18407                "  // ...\n"
18408                "  int i;\n"
18409                "}];",
18410                AllmanBraceStyle);
18411   verifyFormat("void (^block)(void) = ^{\n"
18412                "  // ...\n"
18413                "  int i;\n"
18414                "};",
18415                AllmanBraceStyle);
18416   // .. or dict literals.
18417   verifyFormat("void f()\n"
18418                "{\n"
18419                "  // ...\n"
18420                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18421                "}",
18422                AllmanBraceStyle);
18423   verifyFormat("void f()\n"
18424                "{\n"
18425                "  // ...\n"
18426                "  [object someMethod:@{a : @\"b\"}];\n"
18427                "}",
18428                AllmanBraceStyle);
18429   verifyFormat("int f()\n"
18430                "{ // comment\n"
18431                "  return 42;\n"
18432                "}",
18433                AllmanBraceStyle);
18434 
18435   AllmanBraceStyle.ColumnLimit = 19;
18436   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18437   AllmanBraceStyle.ColumnLimit = 18;
18438   verifyFormat("void f()\n"
18439                "{\n"
18440                "  int i;\n"
18441                "}",
18442                AllmanBraceStyle);
18443   AllmanBraceStyle.ColumnLimit = 80;
18444 
18445   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18446   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18447       FormatStyle::SIS_WithoutElse;
18448   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18449   verifyFormat("void f(bool b)\n"
18450                "{\n"
18451                "  if (b)\n"
18452                "  {\n"
18453                "    return;\n"
18454                "  }\n"
18455                "}\n",
18456                BreakBeforeBraceShortIfs);
18457   verifyFormat("void f(bool b)\n"
18458                "{\n"
18459                "  if constexpr (b)\n"
18460                "  {\n"
18461                "    return;\n"
18462                "  }\n"
18463                "}\n",
18464                BreakBeforeBraceShortIfs);
18465   verifyFormat("void f(bool b)\n"
18466                "{\n"
18467                "  if CONSTEXPR (b)\n"
18468                "  {\n"
18469                "    return;\n"
18470                "  }\n"
18471                "}\n",
18472                BreakBeforeBraceShortIfs);
18473   verifyFormat("void f(bool b)\n"
18474                "{\n"
18475                "  if (b) return;\n"
18476                "}\n",
18477                BreakBeforeBraceShortIfs);
18478   verifyFormat("void f(bool b)\n"
18479                "{\n"
18480                "  if constexpr (b) return;\n"
18481                "}\n",
18482                BreakBeforeBraceShortIfs);
18483   verifyFormat("void f(bool b)\n"
18484                "{\n"
18485                "  if CONSTEXPR (b) return;\n"
18486                "}\n",
18487                BreakBeforeBraceShortIfs);
18488   verifyFormat("void f(bool b)\n"
18489                "{\n"
18490                "  while (b)\n"
18491                "  {\n"
18492                "    return;\n"
18493                "  }\n"
18494                "}\n",
18495                BreakBeforeBraceShortIfs);
18496 }
18497 
18498 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18499   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18500   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18501 
18502   // Make a few changes to the style for testing purposes
18503   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18504       FormatStyle::SFS_Empty;
18505   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18506 
18507   // FIXME: this test case can't decide whether there should be a blank line
18508   // after the ~D() line or not. It adds one if one doesn't exist in the test
18509   // and it removes the line if one exists.
18510   /*
18511   verifyFormat("class A;\n"
18512                "namespace B\n"
18513                "  {\n"
18514                "class C;\n"
18515                "// Comment\n"
18516                "class D\n"
18517                "  {\n"
18518                "public:\n"
18519                "  D();\n"
18520                "  ~D() {}\n"
18521                "private:\n"
18522                "  enum E\n"
18523                "    {\n"
18524                "    F\n"
18525                "    }\n"
18526                "  };\n"
18527                "  } // namespace B\n",
18528                WhitesmithsBraceStyle);
18529   */
18530 
18531   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18532   verifyFormat("namespace a\n"
18533                "  {\n"
18534                "class A\n"
18535                "  {\n"
18536                "  void f()\n"
18537                "    {\n"
18538                "    if (true)\n"
18539                "      {\n"
18540                "      a();\n"
18541                "      b();\n"
18542                "      }\n"
18543                "    }\n"
18544                "  void g()\n"
18545                "    {\n"
18546                "    return;\n"
18547                "    }\n"
18548                "  };\n"
18549                "struct B\n"
18550                "  {\n"
18551                "  int x;\n"
18552                "  };\n"
18553                "  } // namespace a",
18554                WhitesmithsBraceStyle);
18555 
18556   verifyFormat("namespace a\n"
18557                "  {\n"
18558                "namespace b\n"
18559                "  {\n"
18560                "class A\n"
18561                "  {\n"
18562                "  void f()\n"
18563                "    {\n"
18564                "    if (true)\n"
18565                "      {\n"
18566                "      a();\n"
18567                "      b();\n"
18568                "      }\n"
18569                "    }\n"
18570                "  void g()\n"
18571                "    {\n"
18572                "    return;\n"
18573                "    }\n"
18574                "  };\n"
18575                "struct B\n"
18576                "  {\n"
18577                "  int x;\n"
18578                "  };\n"
18579                "  } // namespace b\n"
18580                "  } // namespace a",
18581                WhitesmithsBraceStyle);
18582 
18583   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18584   verifyFormat("namespace a\n"
18585                "  {\n"
18586                "namespace b\n"
18587                "  {\n"
18588                "  class A\n"
18589                "    {\n"
18590                "    void f()\n"
18591                "      {\n"
18592                "      if (true)\n"
18593                "        {\n"
18594                "        a();\n"
18595                "        b();\n"
18596                "        }\n"
18597                "      }\n"
18598                "    void g()\n"
18599                "      {\n"
18600                "      return;\n"
18601                "      }\n"
18602                "    };\n"
18603                "  struct B\n"
18604                "    {\n"
18605                "    int x;\n"
18606                "    };\n"
18607                "  } // namespace b\n"
18608                "  } // namespace a",
18609                WhitesmithsBraceStyle);
18610 
18611   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18612   verifyFormat("namespace a\n"
18613                "  {\n"
18614                "  namespace b\n"
18615                "    {\n"
18616                "    class A\n"
18617                "      {\n"
18618                "      void f()\n"
18619                "        {\n"
18620                "        if (true)\n"
18621                "          {\n"
18622                "          a();\n"
18623                "          b();\n"
18624                "          }\n"
18625                "        }\n"
18626                "      void g()\n"
18627                "        {\n"
18628                "        return;\n"
18629                "        }\n"
18630                "      };\n"
18631                "    struct B\n"
18632                "      {\n"
18633                "      int x;\n"
18634                "      };\n"
18635                "    } // namespace b\n"
18636                "  }   // namespace a",
18637                WhitesmithsBraceStyle);
18638 
18639   verifyFormat("void f()\n"
18640                "  {\n"
18641                "  if (true)\n"
18642                "    {\n"
18643                "    a();\n"
18644                "    }\n"
18645                "  else if (false)\n"
18646                "    {\n"
18647                "    b();\n"
18648                "    }\n"
18649                "  else\n"
18650                "    {\n"
18651                "    c();\n"
18652                "    }\n"
18653                "  }\n",
18654                WhitesmithsBraceStyle);
18655 
18656   verifyFormat("void f()\n"
18657                "  {\n"
18658                "  for (int i = 0; i < 10; ++i)\n"
18659                "    {\n"
18660                "    a();\n"
18661                "    }\n"
18662                "  while (false)\n"
18663                "    {\n"
18664                "    b();\n"
18665                "    }\n"
18666                "  do\n"
18667                "    {\n"
18668                "    c();\n"
18669                "    } while (false)\n"
18670                "  }\n",
18671                WhitesmithsBraceStyle);
18672 
18673   WhitesmithsBraceStyle.IndentCaseLabels = true;
18674   verifyFormat("void switchTest1(int a)\n"
18675                "  {\n"
18676                "  switch (a)\n"
18677                "    {\n"
18678                "    case 2:\n"
18679                "      {\n"
18680                "      }\n"
18681                "      break;\n"
18682                "    }\n"
18683                "  }\n",
18684                WhitesmithsBraceStyle);
18685 
18686   verifyFormat("void switchTest2(int a)\n"
18687                "  {\n"
18688                "  switch (a)\n"
18689                "    {\n"
18690                "    case 0:\n"
18691                "      break;\n"
18692                "    case 1:\n"
18693                "      {\n"
18694                "      break;\n"
18695                "      }\n"
18696                "    case 2:\n"
18697                "      {\n"
18698                "      }\n"
18699                "      break;\n"
18700                "    default:\n"
18701                "      break;\n"
18702                "    }\n"
18703                "  }\n",
18704                WhitesmithsBraceStyle);
18705 
18706   verifyFormat("void switchTest3(int a)\n"
18707                "  {\n"
18708                "  switch (a)\n"
18709                "    {\n"
18710                "    case 0:\n"
18711                "      {\n"
18712                "      foo(x);\n"
18713                "      }\n"
18714                "      break;\n"
18715                "    default:\n"
18716                "      {\n"
18717                "      foo(1);\n"
18718                "      }\n"
18719                "      break;\n"
18720                "    }\n"
18721                "  }\n",
18722                WhitesmithsBraceStyle);
18723 
18724   WhitesmithsBraceStyle.IndentCaseLabels = false;
18725 
18726   verifyFormat("void switchTest4(int a)\n"
18727                "  {\n"
18728                "  switch (a)\n"
18729                "    {\n"
18730                "  case 2:\n"
18731                "    {\n"
18732                "    }\n"
18733                "    break;\n"
18734                "    }\n"
18735                "  }\n",
18736                WhitesmithsBraceStyle);
18737 
18738   verifyFormat("void switchTest5(int a)\n"
18739                "  {\n"
18740                "  switch (a)\n"
18741                "    {\n"
18742                "  case 0:\n"
18743                "    break;\n"
18744                "  case 1:\n"
18745                "    {\n"
18746                "    foo();\n"
18747                "    break;\n"
18748                "    }\n"
18749                "  case 2:\n"
18750                "    {\n"
18751                "    }\n"
18752                "    break;\n"
18753                "  default:\n"
18754                "    break;\n"
18755                "    }\n"
18756                "  }\n",
18757                WhitesmithsBraceStyle);
18758 
18759   verifyFormat("void switchTest6(int a)\n"
18760                "  {\n"
18761                "  switch (a)\n"
18762                "    {\n"
18763                "  case 0:\n"
18764                "    {\n"
18765                "    foo(x);\n"
18766                "    }\n"
18767                "    break;\n"
18768                "  default:\n"
18769                "    {\n"
18770                "    foo(1);\n"
18771                "    }\n"
18772                "    break;\n"
18773                "    }\n"
18774                "  }\n",
18775                WhitesmithsBraceStyle);
18776 
18777   verifyFormat("enum X\n"
18778                "  {\n"
18779                "  Y = 0, // testing\n"
18780                "  }\n",
18781                WhitesmithsBraceStyle);
18782 
18783   verifyFormat("enum X\n"
18784                "  {\n"
18785                "  Y = 0\n"
18786                "  }\n",
18787                WhitesmithsBraceStyle);
18788   verifyFormat("enum X\n"
18789                "  {\n"
18790                "  Y = 0,\n"
18791                "  Z = 1\n"
18792                "  };\n",
18793                WhitesmithsBraceStyle);
18794 
18795   verifyFormat("@interface BSApplicationController ()\n"
18796                "  {\n"
18797                "@private\n"
18798                "  id _extraIvar;\n"
18799                "  }\n"
18800                "@end\n",
18801                WhitesmithsBraceStyle);
18802 
18803   verifyFormat("#ifdef _DEBUG\n"
18804                "int foo(int i = 0)\n"
18805                "#else\n"
18806                "int foo(int i = 5)\n"
18807                "#endif\n"
18808                "  {\n"
18809                "  return i;\n"
18810                "  }",
18811                WhitesmithsBraceStyle);
18812 
18813   verifyFormat("void foo() {}\n"
18814                "void bar()\n"
18815                "#ifdef _DEBUG\n"
18816                "  {\n"
18817                "  foo();\n"
18818                "  }\n"
18819                "#else\n"
18820                "  {\n"
18821                "  }\n"
18822                "#endif",
18823                WhitesmithsBraceStyle);
18824 
18825   verifyFormat("void foobar()\n"
18826                "  {\n"
18827                "  int i = 5;\n"
18828                "  }\n"
18829                "#ifdef _DEBUG\n"
18830                "void bar()\n"
18831                "  {\n"
18832                "  }\n"
18833                "#else\n"
18834                "void bar()\n"
18835                "  {\n"
18836                "  foobar();\n"
18837                "  }\n"
18838                "#endif",
18839                WhitesmithsBraceStyle);
18840 
18841   // This shouldn't affect ObjC blocks..
18842   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18843                "  // ...\n"
18844                "  int i;\n"
18845                "}];",
18846                WhitesmithsBraceStyle);
18847   verifyFormat("void (^block)(void) = ^{\n"
18848                "  // ...\n"
18849                "  int i;\n"
18850                "};",
18851                WhitesmithsBraceStyle);
18852   // .. or dict literals.
18853   verifyFormat("void f()\n"
18854                "  {\n"
18855                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18856                "  }",
18857                WhitesmithsBraceStyle);
18858 
18859   verifyFormat("int f()\n"
18860                "  { // comment\n"
18861                "  return 42;\n"
18862                "  }",
18863                WhitesmithsBraceStyle);
18864 
18865   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
18866   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18867       FormatStyle::SIS_OnlyFirstIf;
18868   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18869   verifyFormat("void f(bool b)\n"
18870                "  {\n"
18871                "  if (b)\n"
18872                "    {\n"
18873                "    return;\n"
18874                "    }\n"
18875                "  }\n",
18876                BreakBeforeBraceShortIfs);
18877   verifyFormat("void f(bool b)\n"
18878                "  {\n"
18879                "  if (b) return;\n"
18880                "  }\n",
18881                BreakBeforeBraceShortIfs);
18882   verifyFormat("void f(bool b)\n"
18883                "  {\n"
18884                "  while (b)\n"
18885                "    {\n"
18886                "    return;\n"
18887                "    }\n"
18888                "  }\n",
18889                BreakBeforeBraceShortIfs);
18890 }
18891 
18892 TEST_F(FormatTest, GNUBraceBreaking) {
18893   FormatStyle GNUBraceStyle = getLLVMStyle();
18894   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
18895   verifyFormat("namespace a\n"
18896                "{\n"
18897                "class A\n"
18898                "{\n"
18899                "  void f()\n"
18900                "  {\n"
18901                "    int a;\n"
18902                "    {\n"
18903                "      int b;\n"
18904                "    }\n"
18905                "    if (true)\n"
18906                "      {\n"
18907                "        a();\n"
18908                "        b();\n"
18909                "      }\n"
18910                "  }\n"
18911                "  void g() { return; }\n"
18912                "}\n"
18913                "} // namespace a",
18914                GNUBraceStyle);
18915 
18916   verifyFormat("void f()\n"
18917                "{\n"
18918                "  if (true)\n"
18919                "    {\n"
18920                "      a();\n"
18921                "    }\n"
18922                "  else if (false)\n"
18923                "    {\n"
18924                "      b();\n"
18925                "    }\n"
18926                "  else\n"
18927                "    {\n"
18928                "      c();\n"
18929                "    }\n"
18930                "}\n",
18931                GNUBraceStyle);
18932 
18933   verifyFormat("void f()\n"
18934                "{\n"
18935                "  for (int i = 0; i < 10; ++i)\n"
18936                "    {\n"
18937                "      a();\n"
18938                "    }\n"
18939                "  while (false)\n"
18940                "    {\n"
18941                "      b();\n"
18942                "    }\n"
18943                "  do\n"
18944                "    {\n"
18945                "      c();\n"
18946                "    }\n"
18947                "  while (false);\n"
18948                "}\n",
18949                GNUBraceStyle);
18950 
18951   verifyFormat("void f(int a)\n"
18952                "{\n"
18953                "  switch (a)\n"
18954                "    {\n"
18955                "    case 0:\n"
18956                "      break;\n"
18957                "    case 1:\n"
18958                "      {\n"
18959                "        break;\n"
18960                "      }\n"
18961                "    case 2:\n"
18962                "      {\n"
18963                "      }\n"
18964                "      break;\n"
18965                "    default:\n"
18966                "      break;\n"
18967                "    }\n"
18968                "}\n",
18969                GNUBraceStyle);
18970 
18971   verifyFormat("enum X\n"
18972                "{\n"
18973                "  Y = 0,\n"
18974                "}\n",
18975                GNUBraceStyle);
18976 
18977   verifyFormat("@interface BSApplicationController ()\n"
18978                "{\n"
18979                "@private\n"
18980                "  id _extraIvar;\n"
18981                "}\n"
18982                "@end\n",
18983                GNUBraceStyle);
18984 
18985   verifyFormat("#ifdef _DEBUG\n"
18986                "int foo(int i = 0)\n"
18987                "#else\n"
18988                "int foo(int i = 5)\n"
18989                "#endif\n"
18990                "{\n"
18991                "  return i;\n"
18992                "}",
18993                GNUBraceStyle);
18994 
18995   verifyFormat("void foo() {}\n"
18996                "void bar()\n"
18997                "#ifdef _DEBUG\n"
18998                "{\n"
18999                "  foo();\n"
19000                "}\n"
19001                "#else\n"
19002                "{\n"
19003                "}\n"
19004                "#endif",
19005                GNUBraceStyle);
19006 
19007   verifyFormat("void foobar() { int i = 5; }\n"
19008                "#ifdef _DEBUG\n"
19009                "void bar() {}\n"
19010                "#else\n"
19011                "void bar() { foobar(); }\n"
19012                "#endif",
19013                GNUBraceStyle);
19014 }
19015 
19016 TEST_F(FormatTest, WebKitBraceBreaking) {
19017   FormatStyle WebKitBraceStyle = getLLVMStyle();
19018   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
19019   WebKitBraceStyle.FixNamespaceComments = false;
19020   verifyFormat("namespace a {\n"
19021                "class A {\n"
19022                "  void f()\n"
19023                "  {\n"
19024                "    if (true) {\n"
19025                "      a();\n"
19026                "      b();\n"
19027                "    }\n"
19028                "  }\n"
19029                "  void g() { return; }\n"
19030                "};\n"
19031                "enum E {\n"
19032                "  A,\n"
19033                "  // foo\n"
19034                "  B,\n"
19035                "  C\n"
19036                "};\n"
19037                "struct B {\n"
19038                "  int x;\n"
19039                "};\n"
19040                "}\n",
19041                WebKitBraceStyle);
19042   verifyFormat("struct S {\n"
19043                "  int Type;\n"
19044                "  union {\n"
19045                "    int x;\n"
19046                "    double y;\n"
19047                "  } Value;\n"
19048                "  class C {\n"
19049                "    MyFavoriteType Value;\n"
19050                "  } Class;\n"
19051                "};\n",
19052                WebKitBraceStyle);
19053 }
19054 
19055 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
19056   verifyFormat("void f() {\n"
19057                "  try {\n"
19058                "  } catch (const Exception &e) {\n"
19059                "  }\n"
19060                "}\n",
19061                getLLVMStyle());
19062 }
19063 
19064 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
19065   auto Style = getLLVMStyle();
19066   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19067   Style.AlignConsecutiveAssignments.Enabled = true;
19068   Style.AlignConsecutiveDeclarations.Enabled = true;
19069   verifyFormat("struct test demo[] = {\n"
19070                "    {56,    23, \"hello\"},\n"
19071                "    {-1, 93463, \"world\"},\n"
19072                "    { 7,     5,    \"!!\"}\n"
19073                "};\n",
19074                Style);
19075 
19076   verifyFormat("struct test demo[] = {\n"
19077                "    {56,    23, \"hello\"}, // first line\n"
19078                "    {-1, 93463, \"world\"}, // second line\n"
19079                "    { 7,     5,    \"!!\"}  // third line\n"
19080                "};\n",
19081                Style);
19082 
19083   verifyFormat("struct test demo[4] = {\n"
19084                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19085                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19086                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19087                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19088                "};\n",
19089                Style);
19090 
19091   verifyFormat("struct test demo[3] = {\n"
19092                "    {56,    23, \"hello\"},\n"
19093                "    {-1, 93463, \"world\"},\n"
19094                "    { 7,     5,    \"!!\"}\n"
19095                "};\n",
19096                Style);
19097 
19098   verifyFormat("struct test demo[3] = {\n"
19099                "    {int{56},    23, \"hello\"},\n"
19100                "    {int{-1}, 93463, \"world\"},\n"
19101                "    { int{7},     5,    \"!!\"}\n"
19102                "};\n",
19103                Style);
19104 
19105   verifyFormat("struct test demo[] = {\n"
19106                "    {56,    23, \"hello\"},\n"
19107                "    {-1, 93463, \"world\"},\n"
19108                "    { 7,     5,    \"!!\"},\n"
19109                "};\n",
19110                Style);
19111 
19112   verifyFormat("test demo[] = {\n"
19113                "    {56,    23, \"hello\"},\n"
19114                "    {-1, 93463, \"world\"},\n"
19115                "    { 7,     5,    \"!!\"},\n"
19116                "};\n",
19117                Style);
19118 
19119   verifyFormat("demo = std::array<struct test, 3>{\n"
19120                "    test{56,    23, \"hello\"},\n"
19121                "    test{-1, 93463, \"world\"},\n"
19122                "    test{ 7,     5,    \"!!\"},\n"
19123                "};\n",
19124                Style);
19125 
19126   verifyFormat("test demo[] = {\n"
19127                "    {56,    23, \"hello\"},\n"
19128                "#if X\n"
19129                "    {-1, 93463, \"world\"},\n"
19130                "#endif\n"
19131                "    { 7,     5,    \"!!\"}\n"
19132                "};\n",
19133                Style);
19134 
19135   verifyFormat(
19136       "test demo[] = {\n"
19137       "    { 7,    23,\n"
19138       "     \"hello world i am a very long line that really, in any\"\n"
19139       "     \"just world, ought to be split over multiple lines\"},\n"
19140       "    {-1, 93463,                                  \"world\"},\n"
19141       "    {56,     5,                                     \"!!\"}\n"
19142       "};\n",
19143       Style);
19144 
19145   verifyFormat("return GradForUnaryCwise(g, {\n"
19146                "                                {{\"sign\"}, \"Sign\",  "
19147                "  {\"x\", \"dy\"}},\n"
19148                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
19149                ", \"sign\"}},\n"
19150                "});\n",
19151                Style);
19152 
19153   Style.ColumnLimit = 0;
19154   EXPECT_EQ(
19155       "test demo[] = {\n"
19156       "    {56,    23, \"hello world i am a very long line that really, "
19157       "in any just world, ought to be split over multiple lines\"},\n"
19158       "    {-1, 93463,                                                  "
19159       "                                                 \"world\"},\n"
19160       "    { 7,     5,                                                  "
19161       "                                                    \"!!\"},\n"
19162       "};",
19163       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19164              "that really, in any just world, ought to be split over multiple "
19165              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19166              Style));
19167 
19168   Style.ColumnLimit = 80;
19169   verifyFormat("test demo[] = {\n"
19170                "    {56,    23, /* a comment */ \"hello\"},\n"
19171                "    {-1, 93463,                 \"world\"},\n"
19172                "    { 7,     5,                    \"!!\"}\n"
19173                "};\n",
19174                Style);
19175 
19176   verifyFormat("test demo[] = {\n"
19177                "    {56,    23,                    \"hello\"},\n"
19178                "    {-1, 93463, \"world\" /* comment here */},\n"
19179                "    { 7,     5,                       \"!!\"}\n"
19180                "};\n",
19181                Style);
19182 
19183   verifyFormat("test demo[] = {\n"
19184                "    {56, /* a comment */ 23, \"hello\"},\n"
19185                "    {-1,              93463, \"world\"},\n"
19186                "    { 7,                  5,    \"!!\"}\n"
19187                "};\n",
19188                Style);
19189 
19190   Style.ColumnLimit = 20;
19191   EXPECT_EQ(
19192       "demo = std::array<\n"
19193       "    struct test, 3>{\n"
19194       "    test{\n"
19195       "         56,    23,\n"
19196       "         \"hello \"\n"
19197       "         \"world i \"\n"
19198       "         \"am a very \"\n"
19199       "         \"long line \"\n"
19200       "         \"that \"\n"
19201       "         \"really, \"\n"
19202       "         \"in any \"\n"
19203       "         \"just \"\n"
19204       "         \"world, \"\n"
19205       "         \"ought to \"\n"
19206       "         \"be split \"\n"
19207       "         \"over \"\n"
19208       "         \"multiple \"\n"
19209       "         \"lines\"},\n"
19210       "    test{-1, 93463,\n"
19211       "         \"world\"},\n"
19212       "    test{ 7,     5,\n"
19213       "         \"!!\"   },\n"
19214       "};",
19215       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19216              "i am a very long line that really, in any just world, ought "
19217              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19218              "test{7, 5, \"!!\"},};",
19219              Style));
19220   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19221   Style = getLLVMStyleWithColumns(50);
19222   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19223   verifyFormat("static A x = {\n"
19224                "    {{init1, init2, init3, init4},\n"
19225                "     {init1, init2, init3, init4}}\n"
19226                "};",
19227                Style);
19228   // TODO: Fix the indentations below when this option is fully functional.
19229   verifyFormat("int a[][] = {\n"
19230                "    {\n"
19231                "     {0, 2}, //\n"
19232                " {1, 2}  //\n"
19233                "    }\n"
19234                "};",
19235                Style);
19236   Style.ColumnLimit = 100;
19237   EXPECT_EQ(
19238       "test demo[] = {\n"
19239       "    {56,    23,\n"
19240       "     \"hello world i am a very long line that really, in any just world"
19241       ", ought to be split over \"\n"
19242       "     \"multiple lines\"  },\n"
19243       "    {-1, 93463, \"world\"},\n"
19244       "    { 7,     5,    \"!!\"},\n"
19245       "};",
19246       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19247              "that really, in any just world, ought to be split over multiple "
19248              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19249              Style));
19250 
19251   Style = getLLVMStyleWithColumns(50);
19252   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19253   verifyFormat("struct test demo[] = {\n"
19254                "    {56,    23, \"hello\"},\n"
19255                "    {-1, 93463, \"world\"},\n"
19256                "    { 7,     5,    \"!!\"}\n"
19257                "};\n"
19258                "static A x = {\n"
19259                "    {{init1, init2, init3, init4},\n"
19260                "     {init1, init2, init3, init4}}\n"
19261                "};",
19262                Style);
19263   Style.ColumnLimit = 100;
19264   Style.AlignConsecutiveAssignments.AcrossComments = true;
19265   Style.AlignConsecutiveDeclarations.AcrossComments = true;
19266   verifyFormat("struct test demo[] = {\n"
19267                "    {56,    23, \"hello\"},\n"
19268                "    {-1, 93463, \"world\"},\n"
19269                "    { 7,     5,    \"!!\"}\n"
19270                "};\n"
19271                "struct test demo[4] = {\n"
19272                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19273                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19274                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19275                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19276                "};\n",
19277                Style);
19278   EXPECT_EQ(
19279       "test demo[] = {\n"
19280       "    {56,\n"
19281       "     \"hello world i am a very long line that really, in any just world"
19282       ", ought to be split over \"\n"
19283       "     \"multiple lines\",    23},\n"
19284       "    {-1,      \"world\", 93463},\n"
19285       "    { 7,         \"!!\",     5},\n"
19286       "};",
19287       format("test demo[] = {{56, \"hello world i am a very long line "
19288              "that really, in any just world, ought to be split over multiple "
19289              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
19290              Style));
19291 }
19292 
19293 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
19294   auto Style = getLLVMStyle();
19295   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19296   /* FIXME: This case gets misformatted.
19297   verifyFormat("auto foo = Items{\n"
19298                "    Section{0, bar(), },\n"
19299                "    Section{1, boo()  }\n"
19300                "};\n",
19301                Style);
19302   */
19303   verifyFormat("auto foo = Items{\n"
19304                "    Section{\n"
19305                "            0, bar(),\n"
19306                "            }\n"
19307                "};\n",
19308                Style);
19309   verifyFormat("struct test demo[] = {\n"
19310                "    {56, 23,    \"hello\"},\n"
19311                "    {-1, 93463, \"world\"},\n"
19312                "    {7,  5,     \"!!\"   }\n"
19313                "};\n",
19314                Style);
19315   verifyFormat("struct test demo[] = {\n"
19316                "    {56, 23,    \"hello\"}, // first line\n"
19317                "    {-1, 93463, \"world\"}, // second line\n"
19318                "    {7,  5,     \"!!\"   }  // third line\n"
19319                "};\n",
19320                Style);
19321   verifyFormat("struct test demo[4] = {\n"
19322                "    {56,  23,    21, \"oh\"      }, // first line\n"
19323                "    {-1,  93463, 22, \"my\"      }, // second line\n"
19324                "    {7,   5,     1,  \"goodness\"}  // third line\n"
19325                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
19326                "};\n",
19327                Style);
19328   verifyFormat("struct test demo[3] = {\n"
19329                "    {56, 23,    \"hello\"},\n"
19330                "    {-1, 93463, \"world\"},\n"
19331                "    {7,  5,     \"!!\"   }\n"
19332                "};\n",
19333                Style);
19334 
19335   verifyFormat("struct test demo[3] = {\n"
19336                "    {int{56}, 23,    \"hello\"},\n"
19337                "    {int{-1}, 93463, \"world\"},\n"
19338                "    {int{7},  5,     \"!!\"   }\n"
19339                "};\n",
19340                Style);
19341   verifyFormat("struct test demo[] = {\n"
19342                "    {56, 23,    \"hello\"},\n"
19343                "    {-1, 93463, \"world\"},\n"
19344                "    {7,  5,     \"!!\"   },\n"
19345                "};\n",
19346                Style);
19347   verifyFormat("test demo[] = {\n"
19348                "    {56, 23,    \"hello\"},\n"
19349                "    {-1, 93463, \"world\"},\n"
19350                "    {7,  5,     \"!!\"   },\n"
19351                "};\n",
19352                Style);
19353   verifyFormat("demo = std::array<struct test, 3>{\n"
19354                "    test{56, 23,    \"hello\"},\n"
19355                "    test{-1, 93463, \"world\"},\n"
19356                "    test{7,  5,     \"!!\"   },\n"
19357                "};\n",
19358                Style);
19359   verifyFormat("test demo[] = {\n"
19360                "    {56, 23,    \"hello\"},\n"
19361                "#if X\n"
19362                "    {-1, 93463, \"world\"},\n"
19363                "#endif\n"
19364                "    {7,  5,     \"!!\"   }\n"
19365                "};\n",
19366                Style);
19367   verifyFormat(
19368       "test demo[] = {\n"
19369       "    {7,  23,\n"
19370       "     \"hello world i am a very long line that really, in any\"\n"
19371       "     \"just world, ought to be split over multiple lines\"},\n"
19372       "    {-1, 93463, \"world\"                                 },\n"
19373       "    {56, 5,     \"!!\"                                    }\n"
19374       "};\n",
19375       Style);
19376 
19377   verifyFormat("return GradForUnaryCwise(g, {\n"
19378                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19379                "\"dy\"}   },\n"
19380                "                                {{\"dx\"},   \"Mul\",  "
19381                "{\"dy\", \"sign\"}},\n"
19382                "});\n",
19383                Style);
19384 
19385   Style.ColumnLimit = 0;
19386   EXPECT_EQ(
19387       "test demo[] = {\n"
19388       "    {56, 23,    \"hello world i am a very long line that really, in any "
19389       "just world, ought to be split over multiple lines\"},\n"
19390       "    {-1, 93463, \"world\"                                               "
19391       "                                                   },\n"
19392       "    {7,  5,     \"!!\"                                                  "
19393       "                                                   },\n"
19394       "};",
19395       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19396              "that really, in any just world, ought to be split over multiple "
19397              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19398              Style));
19399 
19400   Style.ColumnLimit = 80;
19401   verifyFormat("test demo[] = {\n"
19402                "    {56, 23,    /* a comment */ \"hello\"},\n"
19403                "    {-1, 93463, \"world\"                },\n"
19404                "    {7,  5,     \"!!\"                   }\n"
19405                "};\n",
19406                Style);
19407 
19408   verifyFormat("test demo[] = {\n"
19409                "    {56, 23,    \"hello\"                   },\n"
19410                "    {-1, 93463, \"world\" /* comment here */},\n"
19411                "    {7,  5,     \"!!\"                      }\n"
19412                "};\n",
19413                Style);
19414 
19415   verifyFormat("test demo[] = {\n"
19416                "    {56, /* a comment */ 23, \"hello\"},\n"
19417                "    {-1, 93463,              \"world\"},\n"
19418                "    {7,  5,                  \"!!\"   }\n"
19419                "};\n",
19420                Style);
19421 
19422   Style.ColumnLimit = 20;
19423   EXPECT_EQ(
19424       "demo = std::array<\n"
19425       "    struct test, 3>{\n"
19426       "    test{\n"
19427       "         56, 23,\n"
19428       "         \"hello \"\n"
19429       "         \"world i \"\n"
19430       "         \"am a very \"\n"
19431       "         \"long line \"\n"
19432       "         \"that \"\n"
19433       "         \"really, \"\n"
19434       "         \"in any \"\n"
19435       "         \"just \"\n"
19436       "         \"world, \"\n"
19437       "         \"ought to \"\n"
19438       "         \"be split \"\n"
19439       "         \"over \"\n"
19440       "         \"multiple \"\n"
19441       "         \"lines\"},\n"
19442       "    test{-1, 93463,\n"
19443       "         \"world\"},\n"
19444       "    test{7,  5,\n"
19445       "         \"!!\"   },\n"
19446       "};",
19447       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19448              "i am a very long line that really, in any just world, ought "
19449              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19450              "test{7, 5, \"!!\"},};",
19451              Style));
19452 
19453   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19454   Style = getLLVMStyleWithColumns(50);
19455   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19456   verifyFormat("static A x = {\n"
19457                "    {{init1, init2, init3, init4},\n"
19458                "     {init1, init2, init3, init4}}\n"
19459                "};",
19460                Style);
19461   Style.ColumnLimit = 100;
19462   EXPECT_EQ(
19463       "test demo[] = {\n"
19464       "    {56, 23,\n"
19465       "     \"hello world i am a very long line that really, in any just world"
19466       ", ought to be split over \"\n"
19467       "     \"multiple lines\"  },\n"
19468       "    {-1, 93463, \"world\"},\n"
19469       "    {7,  5,     \"!!\"   },\n"
19470       "};",
19471       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19472              "that really, in any just world, ought to be split over multiple "
19473              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19474              Style));
19475 }
19476 
19477 TEST_F(FormatTest, UnderstandsPragmas) {
19478   verifyFormat("#pragma omp reduction(| : var)");
19479   verifyFormat("#pragma omp reduction(+ : var)");
19480 
19481   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19482             "(including parentheses).",
19483             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19484                    "(including parentheses)."));
19485 }
19486 
19487 TEST_F(FormatTest, UnderstandPragmaOption) {
19488   verifyFormat("#pragma option -C -A");
19489 
19490   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19491 }
19492 
19493 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19494   FormatStyle Style = getLLVMStyleWithColumns(20);
19495 
19496   // See PR41213
19497   EXPECT_EQ("/*\n"
19498             " *\t9012345\n"
19499             " * /8901\n"
19500             " */",
19501             format("/*\n"
19502                    " *\t9012345 /8901\n"
19503                    " */",
19504                    Style));
19505   EXPECT_EQ("/*\n"
19506             " *345678\n"
19507             " *\t/8901\n"
19508             " */",
19509             format("/*\n"
19510                    " *345678\t/8901\n"
19511                    " */",
19512                    Style));
19513 
19514   verifyFormat("int a; // the\n"
19515                "       // comment",
19516                Style);
19517   EXPECT_EQ("int a; /* first line\n"
19518             "        * second\n"
19519             "        * line third\n"
19520             "        * line\n"
19521             "        */",
19522             format("int a; /* first line\n"
19523                    "        * second\n"
19524                    "        * line third\n"
19525                    "        * line\n"
19526                    "        */",
19527                    Style));
19528   EXPECT_EQ("int a; // first line\n"
19529             "       // second\n"
19530             "       // line third\n"
19531             "       // line",
19532             format("int a; // first line\n"
19533                    "       // second line\n"
19534                    "       // third line",
19535                    Style));
19536 
19537   Style.PenaltyExcessCharacter = 90;
19538   verifyFormat("int a; // the comment", Style);
19539   EXPECT_EQ("int a; // the comment\n"
19540             "       // aaa",
19541             format("int a; // the comment aaa", Style));
19542   EXPECT_EQ("int a; /* first line\n"
19543             "        * second line\n"
19544             "        * third line\n"
19545             "        */",
19546             format("int a; /* first line\n"
19547                    "        * second line\n"
19548                    "        * third line\n"
19549                    "        */",
19550                    Style));
19551   EXPECT_EQ("int a; // first line\n"
19552             "       // second line\n"
19553             "       // third line",
19554             format("int a; // first line\n"
19555                    "       // second line\n"
19556                    "       // third line",
19557                    Style));
19558   // FIXME: Investigate why this is not getting the same layout as the test
19559   // above.
19560   EXPECT_EQ("int a; /* first line\n"
19561             "        * second line\n"
19562             "        * third line\n"
19563             "        */",
19564             format("int a; /* first line second line third line"
19565                    "\n*/",
19566                    Style));
19567 
19568   EXPECT_EQ("// foo bar baz bazfoo\n"
19569             "// foo bar foo bar\n",
19570             format("// foo bar baz bazfoo\n"
19571                    "// foo bar foo           bar\n",
19572                    Style));
19573   EXPECT_EQ("// foo bar baz bazfoo\n"
19574             "// foo bar foo bar\n",
19575             format("// foo bar baz      bazfoo\n"
19576                    "// foo            bar foo bar\n",
19577                    Style));
19578 
19579   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19580   // next one.
19581   EXPECT_EQ("// foo bar baz bazfoo\n"
19582             "// bar foo bar\n",
19583             format("// foo bar baz      bazfoo bar\n"
19584                    "// foo            bar\n",
19585                    Style));
19586 
19587   EXPECT_EQ("// foo bar baz bazfoo\n"
19588             "// foo bar baz bazfoo\n"
19589             "// bar foo bar\n",
19590             format("// foo bar baz      bazfoo\n"
19591                    "// foo bar baz      bazfoo bar\n"
19592                    "// foo bar\n",
19593                    Style));
19594 
19595   EXPECT_EQ("// foo bar baz bazfoo\n"
19596             "// foo bar baz bazfoo\n"
19597             "// bar foo bar\n",
19598             format("// foo bar baz      bazfoo\n"
19599                    "// foo bar baz      bazfoo bar\n"
19600                    "// foo           bar\n",
19601                    Style));
19602 
19603   // Make sure we do not keep protruding characters if strict mode reflow is
19604   // cheaper than keeping protruding characters.
19605   Style.ColumnLimit = 21;
19606   EXPECT_EQ(
19607       "// foo foo foo foo\n"
19608       "// foo foo foo foo\n"
19609       "// foo foo foo foo\n",
19610       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19611 
19612   EXPECT_EQ("int a = /* long block\n"
19613             "           comment */\n"
19614             "    42;",
19615             format("int a = /* long block comment */ 42;", Style));
19616 }
19617 
19618 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19619   FormatStyle Style = getLLVMStyle();
19620   Style.ColumnLimit = 8;
19621   Style.PenaltyExcessCharacter = 15;
19622   verifyFormat("int foo(\n"
19623                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19624                Style);
19625   Style.PenaltyBreakOpenParenthesis = 200;
19626   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19627             format("int foo(\n"
19628                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19629                    Style));
19630 }
19631 
19632 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19633   FormatStyle Style = getLLVMStyle();
19634   Style.ColumnLimit = 5;
19635   Style.PenaltyExcessCharacter = 150;
19636   verifyFormat("foo((\n"
19637                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19638 
19639                Style);
19640   Style.PenaltyBreakOpenParenthesis = 100000;
19641   EXPECT_EQ("foo((int)\n"
19642             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19643             format("foo((\n"
19644                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19645                    Style));
19646 }
19647 
19648 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19649   FormatStyle Style = getLLVMStyle();
19650   Style.ColumnLimit = 4;
19651   Style.PenaltyExcessCharacter = 100;
19652   verifyFormat("for (\n"
19653                "    int iiiiiiiiiiiiiiiii =\n"
19654                "        0;\n"
19655                "    iiiiiiiiiiiiiiiii <\n"
19656                "    2;\n"
19657                "    iiiiiiiiiiiiiiiii++) {\n"
19658                "}",
19659 
19660                Style);
19661   Style.PenaltyBreakOpenParenthesis = 1250;
19662   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19663             "         0;\n"
19664             "     iiiiiiiiiiiiiiiii <\n"
19665             "     2;\n"
19666             "     iiiiiiiiiiiiiiiii++) {\n"
19667             "}",
19668             format("for (\n"
19669                    "    int iiiiiiiiiiiiiiiii =\n"
19670                    "        0;\n"
19671                    "    iiiiiiiiiiiiiiiii <\n"
19672                    "    2;\n"
19673                    "    iiiiiiiiiiiiiiiii++) {\n"
19674                    "}",
19675                    Style));
19676 }
19677 
19678 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19679   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19680   EXPECT_EQ(Styles[0], Styles[i])                                              \
19681       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19682 
19683 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19684   SmallVector<FormatStyle, 3> Styles;
19685   Styles.resize(3);
19686 
19687   Styles[0] = getLLVMStyle();
19688   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19689   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19690   EXPECT_ALL_STYLES_EQUAL(Styles);
19691 
19692   Styles[0] = getGoogleStyle();
19693   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19694   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19695   EXPECT_ALL_STYLES_EQUAL(Styles);
19696 
19697   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19698   EXPECT_TRUE(
19699       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19700   EXPECT_TRUE(
19701       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19702   EXPECT_ALL_STYLES_EQUAL(Styles);
19703 
19704   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19705   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19706   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19707   EXPECT_ALL_STYLES_EQUAL(Styles);
19708 
19709   Styles[0] = getMozillaStyle();
19710   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19711   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19712   EXPECT_ALL_STYLES_EQUAL(Styles);
19713 
19714   Styles[0] = getWebKitStyle();
19715   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19716   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19717   EXPECT_ALL_STYLES_EQUAL(Styles);
19718 
19719   Styles[0] = getGNUStyle();
19720   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19721   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19722   EXPECT_ALL_STYLES_EQUAL(Styles);
19723 
19724   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19725 }
19726 
19727 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19728   SmallVector<FormatStyle, 8> Styles;
19729   Styles.resize(2);
19730 
19731   Styles[0] = getGoogleStyle();
19732   Styles[1] = getLLVMStyle();
19733   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19734   EXPECT_ALL_STYLES_EQUAL(Styles);
19735 
19736   Styles.resize(5);
19737   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19738   Styles[1] = getLLVMStyle();
19739   Styles[1].Language = FormatStyle::LK_JavaScript;
19740   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19741 
19742   Styles[2] = getLLVMStyle();
19743   Styles[2].Language = FormatStyle::LK_JavaScript;
19744   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19745                                   "BasedOnStyle: Google",
19746                                   &Styles[2])
19747                    .value());
19748 
19749   Styles[3] = getLLVMStyle();
19750   Styles[3].Language = FormatStyle::LK_JavaScript;
19751   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19752                                   "Language: JavaScript",
19753                                   &Styles[3])
19754                    .value());
19755 
19756   Styles[4] = getLLVMStyle();
19757   Styles[4].Language = FormatStyle::LK_JavaScript;
19758   EXPECT_EQ(0, parseConfiguration("---\n"
19759                                   "BasedOnStyle: LLVM\n"
19760                                   "IndentWidth: 123\n"
19761                                   "---\n"
19762                                   "BasedOnStyle: Google\n"
19763                                   "Language: JavaScript",
19764                                   &Styles[4])
19765                    .value());
19766   EXPECT_ALL_STYLES_EQUAL(Styles);
19767 }
19768 
19769 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
19770   Style.FIELD = false;                                                         \
19771   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
19772   EXPECT_TRUE(Style.FIELD);                                                    \
19773   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
19774   EXPECT_FALSE(Style.FIELD);
19775 
19776 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
19777 
19778 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
19779   Style.STRUCT.FIELD = false;                                                  \
19780   EXPECT_EQ(0,                                                                 \
19781             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
19782                 .value());                                                     \
19783   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
19784   EXPECT_EQ(0,                                                                 \
19785             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
19786                 .value());                                                     \
19787   EXPECT_FALSE(Style.STRUCT.FIELD);
19788 
19789 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
19790   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
19791 
19792 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
19793   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
19794   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
19795   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
19796 
19797 TEST_F(FormatTest, ParsesConfigurationBools) {
19798   FormatStyle Style = {};
19799   Style.Language = FormatStyle::LK_Cpp;
19800   CHECK_PARSE_BOOL(AlignTrailingComments);
19801   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
19802   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
19803   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
19804   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
19805   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
19806   CHECK_PARSE_BOOL(BinPackArguments);
19807   CHECK_PARSE_BOOL(BinPackParameters);
19808   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
19809   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
19810   CHECK_PARSE_BOOL(BreakStringLiterals);
19811   CHECK_PARSE_BOOL(CompactNamespaces);
19812   CHECK_PARSE_BOOL(DeriveLineEnding);
19813   CHECK_PARSE_BOOL(DerivePointerAlignment);
19814   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
19815   CHECK_PARSE_BOOL(DisableFormat);
19816   CHECK_PARSE_BOOL(IndentAccessModifiers);
19817   CHECK_PARSE_BOOL(IndentCaseLabels);
19818   CHECK_PARSE_BOOL(IndentCaseBlocks);
19819   CHECK_PARSE_BOOL(IndentGotoLabels);
19820   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
19821   CHECK_PARSE_BOOL(IndentRequiresClause);
19822   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
19823   CHECK_PARSE_BOOL(InsertBraces);
19824   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
19825   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
19826   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
19827   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
19828   CHECK_PARSE_BOOL(ReflowComments);
19829   CHECK_PARSE_BOOL(RemoveBracesLLVM);
19830   CHECK_PARSE_BOOL(SortUsingDeclarations);
19831   CHECK_PARSE_BOOL(SpacesInParentheses);
19832   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
19833   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
19834   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
19835   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
19836   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
19837   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
19838   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
19839   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
19840   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
19841   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
19842   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
19843   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
19844   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
19845   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
19846   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
19847   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
19848   CHECK_PARSE_BOOL(UseCRLF);
19849 
19850   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
19851   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
19852   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
19853   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
19854   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
19855   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
19856   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
19857   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
19858   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
19859   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
19860   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
19861   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
19862   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
19863   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
19864   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
19865   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
19866   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
19867   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
19868   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
19869   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19870                           AfterFunctionDeclarationName);
19871   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19872                           AfterFunctionDefinitionName);
19873   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
19874   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
19875   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
19876 }
19877 
19878 #undef CHECK_PARSE_BOOL
19879 
19880 TEST_F(FormatTest, ParsesConfiguration) {
19881   FormatStyle Style = {};
19882   Style.Language = FormatStyle::LK_Cpp;
19883   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
19884   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
19885               ConstructorInitializerIndentWidth, 1234u);
19886   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
19887   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
19888   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
19889   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
19890   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
19891               PenaltyBreakBeforeFirstCallParameter, 1234u);
19892   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
19893               PenaltyBreakTemplateDeclaration, 1234u);
19894   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
19895               1234u);
19896   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
19897   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
19898               PenaltyReturnTypeOnItsOwnLine, 1234u);
19899   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
19900               SpacesBeforeTrailingComments, 1234u);
19901   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
19902   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
19903   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
19904 
19905   Style.QualifierAlignment = FormatStyle::QAS_Right;
19906   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
19907               FormatStyle::QAS_Leave);
19908   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
19909               FormatStyle::QAS_Right);
19910   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
19911               FormatStyle::QAS_Left);
19912   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
19913               FormatStyle::QAS_Custom);
19914 
19915   Style.QualifierOrder.clear();
19916   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
19917               std::vector<std::string>({"const", "volatile", "type"}));
19918   Style.QualifierOrder.clear();
19919   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
19920               std::vector<std::string>({"const", "type"}));
19921   Style.QualifierOrder.clear();
19922   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
19923               std::vector<std::string>({"volatile", "type"}));
19924 
19925 #define CHECK_ALIGN_CONSECUTIVE(FIELD)                                         \
19926   do {                                                                         \
19927     Style.FIELD.Enabled = true;                                                \
19928     CHECK_PARSE(#FIELD ": None", FIELD,                                        \
19929                 FormatStyle::AlignConsecutiveStyle(                            \
19930                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19931                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19932                      /*PadOperators=*/true}));                                 \
19933     CHECK_PARSE(#FIELD ": Consecutive", FIELD,                                 \
19934                 FormatStyle::AlignConsecutiveStyle(                            \
19935                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19936                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19937                      /*PadOperators=*/true}));                                 \
19938     CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD,                            \
19939                 FormatStyle::AlignConsecutiveStyle(                            \
19940                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19941                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19942                      /*PadOperators=*/true}));                                 \
19943     CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD,                 \
19944                 FormatStyle::AlignConsecutiveStyle(                            \
19945                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19946                      /*AcrossComments=*/true, /*AlignCompound=*/false,         \
19947                      /*PadOperators=*/true}));                                 \
19948     /* For backwards compability, false / true should still parse */           \
19949     CHECK_PARSE(#FIELD ": false", FIELD,                                       \
19950                 FormatStyle::AlignConsecutiveStyle(                            \
19951                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19952                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19953                      /*PadOperators=*/true}));                                 \
19954     CHECK_PARSE(#FIELD ": true", FIELD,                                        \
19955                 FormatStyle::AlignConsecutiveStyle(                            \
19956                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19957                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19958                      /*PadOperators=*/true}));                                 \
19959                                                                                \
19960     CHECK_PARSE_NESTED_BOOL(FIELD, Enabled);                                   \
19961     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines);                          \
19962     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments);                            \
19963     CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound);                             \
19964     CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators);                              \
19965   } while (false)
19966 
19967   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments);
19968   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields);
19969   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros);
19970   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations);
19971 
19972 #undef CHECK_ALIGN_CONSECUTIVE
19973 
19974   Style.PointerAlignment = FormatStyle::PAS_Middle;
19975   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
19976               FormatStyle::PAS_Left);
19977   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
19978               FormatStyle::PAS_Right);
19979   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
19980               FormatStyle::PAS_Middle);
19981   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
19982   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
19983               FormatStyle::RAS_Pointer);
19984   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
19985               FormatStyle::RAS_Left);
19986   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
19987               FormatStyle::RAS_Right);
19988   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
19989               FormatStyle::RAS_Middle);
19990   // For backward compatibility:
19991   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
19992               FormatStyle::PAS_Left);
19993   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
19994               FormatStyle::PAS_Right);
19995   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
19996               FormatStyle::PAS_Middle);
19997 
19998   Style.Standard = FormatStyle::LS_Auto;
19999   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
20000   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
20001   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
20002   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
20003   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
20004   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
20005   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
20006   // Legacy aliases:
20007   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
20008   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
20009   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
20010   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
20011 
20012   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
20013   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
20014               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
20015   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
20016               FormatStyle::BOS_None);
20017   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
20018               FormatStyle::BOS_All);
20019   // For backward compatibility:
20020   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
20021               FormatStyle::BOS_None);
20022   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
20023               FormatStyle::BOS_All);
20024 
20025   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
20026   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
20027               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20028   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
20029               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
20030   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
20031               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
20032   // For backward compatibility:
20033   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
20034               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20035 
20036   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
20037   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
20038               FormatStyle::BILS_AfterComma);
20039   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
20040               FormatStyle::BILS_BeforeComma);
20041   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
20042               FormatStyle::BILS_AfterColon);
20043   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
20044               FormatStyle::BILS_BeforeColon);
20045   // For backward compatibility:
20046   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
20047               FormatStyle::BILS_BeforeComma);
20048 
20049   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20050   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
20051               FormatStyle::PCIS_Never);
20052   CHECK_PARSE("PackConstructorInitializers: BinPack",
20053               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20054   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
20055               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20056   CHECK_PARSE("PackConstructorInitializers: NextLine",
20057               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20058   // For backward compatibility:
20059   CHECK_PARSE("BasedOnStyle: Google\n"
20060               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20061               "AllowAllConstructorInitializersOnNextLine: false",
20062               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20063   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20064   CHECK_PARSE("BasedOnStyle: Google\n"
20065               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
20066               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20067   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20068               "AllowAllConstructorInitializersOnNextLine: true",
20069               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20070   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20071   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20072               "AllowAllConstructorInitializersOnNextLine: false",
20073               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20074 
20075   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
20076   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
20077               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
20078   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
20079               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
20080   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
20081               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
20082   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
20083               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
20084 
20085   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20086   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
20087               FormatStyle::BAS_Align);
20088   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
20089               FormatStyle::BAS_DontAlign);
20090   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
20091               FormatStyle::BAS_AlwaysBreak);
20092   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
20093               FormatStyle::BAS_BlockIndent);
20094   // For backward compatibility:
20095   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
20096               FormatStyle::BAS_DontAlign);
20097   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
20098               FormatStyle::BAS_Align);
20099 
20100   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
20101   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
20102               FormatStyle::ENAS_DontAlign);
20103   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
20104               FormatStyle::ENAS_Left);
20105   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
20106               FormatStyle::ENAS_Right);
20107   // For backward compatibility:
20108   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
20109               FormatStyle::ENAS_Left);
20110   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
20111               FormatStyle::ENAS_Right);
20112 
20113   Style.AlignOperands = FormatStyle::OAS_Align;
20114   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
20115               FormatStyle::OAS_DontAlign);
20116   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
20117   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
20118               FormatStyle::OAS_AlignAfterOperator);
20119   // For backward compatibility:
20120   CHECK_PARSE("AlignOperands: false", AlignOperands,
20121               FormatStyle::OAS_DontAlign);
20122   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
20123 
20124   Style.UseTab = FormatStyle::UT_ForIndentation;
20125   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
20126   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
20127   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
20128   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
20129               FormatStyle::UT_ForContinuationAndIndentation);
20130   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
20131               FormatStyle::UT_AlignWithSpaces);
20132   // For backward compatibility:
20133   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
20134   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
20135 
20136   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
20137   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
20138               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20139   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
20140               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
20141   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
20142               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20143   // For backward compatibility:
20144   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
20145               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20146   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
20147               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20148 
20149   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
20150   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
20151               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20152   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
20153               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
20154   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
20155               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
20156   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
20157               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20158   // For backward compatibility:
20159   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
20160               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20161   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
20162               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20163 
20164   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
20165   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
20166               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
20167   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
20168               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
20169   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
20170               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
20171   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
20172               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
20173 
20174   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
20175   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
20176               FormatStyle::SBPO_Never);
20177   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
20178               FormatStyle::SBPO_Always);
20179   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
20180               FormatStyle::SBPO_ControlStatements);
20181   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
20182               SpaceBeforeParens,
20183               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20184   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
20185               FormatStyle::SBPO_NonEmptyParentheses);
20186   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
20187               FormatStyle::SBPO_Custom);
20188   // For backward compatibility:
20189   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
20190               FormatStyle::SBPO_Never);
20191   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
20192               FormatStyle::SBPO_ControlStatements);
20193   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
20194               SpaceBeforeParens,
20195               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20196 
20197   Style.ColumnLimit = 123;
20198   FormatStyle BaseStyle = getLLVMStyle();
20199   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
20200   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
20201 
20202   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
20203   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
20204               FormatStyle::BS_Attach);
20205   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
20206               FormatStyle::BS_Linux);
20207   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
20208               FormatStyle::BS_Mozilla);
20209   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
20210               FormatStyle::BS_Stroustrup);
20211   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
20212               FormatStyle::BS_Allman);
20213   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
20214               FormatStyle::BS_Whitesmiths);
20215   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
20216   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
20217               FormatStyle::BS_WebKit);
20218   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
20219               FormatStyle::BS_Custom);
20220 
20221   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
20222   CHECK_PARSE("BraceWrapping:\n"
20223               "  AfterControlStatement: MultiLine",
20224               BraceWrapping.AfterControlStatement,
20225               FormatStyle::BWACS_MultiLine);
20226   CHECK_PARSE("BraceWrapping:\n"
20227               "  AfterControlStatement: Always",
20228               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20229   CHECK_PARSE("BraceWrapping:\n"
20230               "  AfterControlStatement: Never",
20231               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20232   // For backward compatibility:
20233   CHECK_PARSE("BraceWrapping:\n"
20234               "  AfterControlStatement: true",
20235               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20236   CHECK_PARSE("BraceWrapping:\n"
20237               "  AfterControlStatement: false",
20238               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20239 
20240   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
20241   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
20242               FormatStyle::RTBS_None);
20243   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
20244               FormatStyle::RTBS_All);
20245   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
20246               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
20247   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
20248               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
20249   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
20250               AlwaysBreakAfterReturnType,
20251               FormatStyle::RTBS_TopLevelDefinitions);
20252 
20253   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
20254   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
20255               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
20256   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
20257               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20258   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
20259               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20260   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
20261               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20262   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
20263               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20264 
20265   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
20266   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
20267               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
20268   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
20269               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
20270   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
20271               AlwaysBreakAfterDefinitionReturnType,
20272               FormatStyle::DRTBS_TopLevel);
20273 
20274   Style.NamespaceIndentation = FormatStyle::NI_All;
20275   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
20276               FormatStyle::NI_None);
20277   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
20278               FormatStyle::NI_Inner);
20279   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
20280               FormatStyle::NI_All);
20281 
20282   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
20283   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
20284               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20285   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
20286               AllowShortIfStatementsOnASingleLine,
20287               FormatStyle::SIS_WithoutElse);
20288   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
20289               AllowShortIfStatementsOnASingleLine,
20290               FormatStyle::SIS_OnlyFirstIf);
20291   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
20292               AllowShortIfStatementsOnASingleLine,
20293               FormatStyle::SIS_AllIfsAndElse);
20294   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
20295               AllowShortIfStatementsOnASingleLine,
20296               FormatStyle::SIS_OnlyFirstIf);
20297   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
20298               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20299   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
20300               AllowShortIfStatementsOnASingleLine,
20301               FormatStyle::SIS_WithoutElse);
20302 
20303   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
20304   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
20305               FormatStyle::IEBS_AfterExternBlock);
20306   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
20307               FormatStyle::IEBS_Indent);
20308   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
20309               FormatStyle::IEBS_NoIndent);
20310   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
20311               FormatStyle::IEBS_Indent);
20312   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
20313               FormatStyle::IEBS_NoIndent);
20314 
20315   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
20316   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
20317               FormatStyle::BFCS_Both);
20318   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
20319               FormatStyle::BFCS_None);
20320   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
20321               FormatStyle::BFCS_Before);
20322   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
20323               FormatStyle::BFCS_After);
20324 
20325   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
20326   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
20327               FormatStyle::SJSIO_After);
20328   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
20329               FormatStyle::SJSIO_Before);
20330 
20331   // FIXME: This is required because parsing a configuration simply overwrites
20332   // the first N elements of the list instead of resetting it.
20333   Style.ForEachMacros.clear();
20334   std::vector<std::string> BoostForeach;
20335   BoostForeach.push_back("BOOST_FOREACH");
20336   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20337   std::vector<std::string> BoostAndQForeach;
20338   BoostAndQForeach.push_back("BOOST_FOREACH");
20339   BoostAndQForeach.push_back("Q_FOREACH");
20340   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20341               BoostAndQForeach);
20342 
20343   Style.IfMacros.clear();
20344   std::vector<std::string> CustomIfs;
20345   CustomIfs.push_back("MYIF");
20346   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20347 
20348   Style.AttributeMacros.clear();
20349   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20350               std::vector<std::string>{"__capability"});
20351   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20352               std::vector<std::string>({"attr1", "attr2"}));
20353 
20354   Style.StatementAttributeLikeMacros.clear();
20355   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20356               StatementAttributeLikeMacros,
20357               std::vector<std::string>({"emit", "Q_EMIT"}));
20358 
20359   Style.StatementMacros.clear();
20360   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20361               std::vector<std::string>{"QUNUSED"});
20362   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20363               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20364 
20365   Style.NamespaceMacros.clear();
20366   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20367               std::vector<std::string>{"TESTSUITE"});
20368   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20369               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20370 
20371   Style.WhitespaceSensitiveMacros.clear();
20372   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20373               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20374   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20375               WhitespaceSensitiveMacros,
20376               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20377   Style.WhitespaceSensitiveMacros.clear();
20378   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
20379               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20380   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
20381               WhitespaceSensitiveMacros,
20382               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20383 
20384   Style.IncludeStyle.IncludeCategories.clear();
20385   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20386       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20387   CHECK_PARSE("IncludeCategories:\n"
20388               "  - Regex: abc/.*\n"
20389               "    Priority: 2\n"
20390               "  - Regex: .*\n"
20391               "    Priority: 1\n"
20392               "    CaseSensitive: true\n",
20393               IncludeStyle.IncludeCategories, ExpectedCategories);
20394   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20395               "abc$");
20396   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20397               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20398 
20399   Style.SortIncludes = FormatStyle::SI_Never;
20400   CHECK_PARSE("SortIncludes: true", SortIncludes,
20401               FormatStyle::SI_CaseSensitive);
20402   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20403   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20404               FormatStyle::SI_CaseInsensitive);
20405   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20406               FormatStyle::SI_CaseSensitive);
20407   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20408 
20409   Style.RawStringFormats.clear();
20410   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20411       {
20412           FormatStyle::LK_TextProto,
20413           {"pb", "proto"},
20414           {"PARSE_TEXT_PROTO"},
20415           /*CanonicalDelimiter=*/"",
20416           "llvm",
20417       },
20418       {
20419           FormatStyle::LK_Cpp,
20420           {"cc", "cpp"},
20421           {"C_CODEBLOCK", "CPPEVAL"},
20422           /*CanonicalDelimiter=*/"cc",
20423           /*BasedOnStyle=*/"",
20424       },
20425   };
20426 
20427   CHECK_PARSE("RawStringFormats:\n"
20428               "  - Language: TextProto\n"
20429               "    Delimiters:\n"
20430               "      - 'pb'\n"
20431               "      - 'proto'\n"
20432               "    EnclosingFunctions:\n"
20433               "      - 'PARSE_TEXT_PROTO'\n"
20434               "    BasedOnStyle: llvm\n"
20435               "  - Language: Cpp\n"
20436               "    Delimiters:\n"
20437               "      - 'cc'\n"
20438               "      - 'cpp'\n"
20439               "    EnclosingFunctions:\n"
20440               "      - 'C_CODEBLOCK'\n"
20441               "      - 'CPPEVAL'\n"
20442               "    CanonicalDelimiter: 'cc'",
20443               RawStringFormats, ExpectedRawStringFormats);
20444 
20445   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20446               "  Minimum: 0\n"
20447               "  Maximum: 0",
20448               SpacesInLineCommentPrefix.Minimum, 0u);
20449   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20450   Style.SpacesInLineCommentPrefix.Minimum = 1;
20451   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20452               "  Minimum: 2",
20453               SpacesInLineCommentPrefix.Minimum, 0u);
20454   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20455               "  Maximum: -1",
20456               SpacesInLineCommentPrefix.Maximum, -1u);
20457   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20458               "  Minimum: 2",
20459               SpacesInLineCommentPrefix.Minimum, 2u);
20460   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20461               "  Maximum: 1",
20462               SpacesInLineCommentPrefix.Maximum, 1u);
20463   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20464 
20465   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20466   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20467   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20468               FormatStyle::SIAS_Always);
20469   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20470   // For backward compatibility:
20471   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20472   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20473 
20474   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20475               FormatStyle::RCPS_WithPreceding);
20476   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20477               FormatStyle::RCPS_WithFollowing);
20478   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20479               FormatStyle::RCPS_SingleLine);
20480   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20481               FormatStyle::RCPS_OwnLine);
20482 
20483   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20484               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20485   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20486               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20487   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20488               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20489   // For backward compatibility:
20490   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20491               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20492   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20493               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20494 }
20495 
20496 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20497   FormatStyle Style = {};
20498   Style.Language = FormatStyle::LK_Cpp;
20499   CHECK_PARSE("Language: Cpp\n"
20500               "IndentWidth: 12",
20501               IndentWidth, 12u);
20502   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20503                                "IndentWidth: 34",
20504                                &Style),
20505             ParseError::Unsuitable);
20506   FormatStyle BinPackedTCS = {};
20507   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20508   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20509                                "InsertTrailingCommas: Wrapped",
20510                                &BinPackedTCS),
20511             ParseError::BinPackTrailingCommaConflict);
20512   EXPECT_EQ(12u, Style.IndentWidth);
20513   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20514   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20515 
20516   Style.Language = FormatStyle::LK_JavaScript;
20517   CHECK_PARSE("Language: JavaScript\n"
20518               "IndentWidth: 12",
20519               IndentWidth, 12u);
20520   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20521   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20522                                "IndentWidth: 34",
20523                                &Style),
20524             ParseError::Unsuitable);
20525   EXPECT_EQ(23u, Style.IndentWidth);
20526   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20527   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20528 
20529   CHECK_PARSE("BasedOnStyle: LLVM\n"
20530               "IndentWidth: 67",
20531               IndentWidth, 67u);
20532 
20533   CHECK_PARSE("---\n"
20534               "Language: JavaScript\n"
20535               "IndentWidth: 12\n"
20536               "---\n"
20537               "Language: Cpp\n"
20538               "IndentWidth: 34\n"
20539               "...\n",
20540               IndentWidth, 12u);
20541 
20542   Style.Language = FormatStyle::LK_Cpp;
20543   CHECK_PARSE("---\n"
20544               "Language: JavaScript\n"
20545               "IndentWidth: 12\n"
20546               "---\n"
20547               "Language: Cpp\n"
20548               "IndentWidth: 34\n"
20549               "...\n",
20550               IndentWidth, 34u);
20551   CHECK_PARSE("---\n"
20552               "IndentWidth: 78\n"
20553               "---\n"
20554               "Language: JavaScript\n"
20555               "IndentWidth: 56\n"
20556               "...\n",
20557               IndentWidth, 78u);
20558 
20559   Style.ColumnLimit = 123;
20560   Style.IndentWidth = 234;
20561   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20562   Style.TabWidth = 345;
20563   EXPECT_FALSE(parseConfiguration("---\n"
20564                                   "IndentWidth: 456\n"
20565                                   "BreakBeforeBraces: Allman\n"
20566                                   "---\n"
20567                                   "Language: JavaScript\n"
20568                                   "IndentWidth: 111\n"
20569                                   "TabWidth: 111\n"
20570                                   "---\n"
20571                                   "Language: Cpp\n"
20572                                   "BreakBeforeBraces: Stroustrup\n"
20573                                   "TabWidth: 789\n"
20574                                   "...\n",
20575                                   &Style));
20576   EXPECT_EQ(123u, Style.ColumnLimit);
20577   EXPECT_EQ(456u, Style.IndentWidth);
20578   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20579   EXPECT_EQ(789u, Style.TabWidth);
20580 
20581   EXPECT_EQ(parseConfiguration("---\n"
20582                                "Language: JavaScript\n"
20583                                "IndentWidth: 56\n"
20584                                "---\n"
20585                                "IndentWidth: 78\n"
20586                                "...\n",
20587                                &Style),
20588             ParseError::Error);
20589   EXPECT_EQ(parseConfiguration("---\n"
20590                                "Language: JavaScript\n"
20591                                "IndentWidth: 56\n"
20592                                "---\n"
20593                                "Language: JavaScript\n"
20594                                "IndentWidth: 78\n"
20595                                "...\n",
20596                                &Style),
20597             ParseError::Error);
20598 
20599   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20600 }
20601 
20602 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20603   FormatStyle Style = {};
20604   Style.Language = FormatStyle::LK_JavaScript;
20605   Style.BreakBeforeTernaryOperators = true;
20606   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20607   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20608 
20609   Style.BreakBeforeTernaryOperators = true;
20610   EXPECT_EQ(0, parseConfiguration("---\n"
20611                                   "BasedOnStyle: Google\n"
20612                                   "---\n"
20613                                   "Language: JavaScript\n"
20614                                   "IndentWidth: 76\n"
20615                                   "...\n",
20616                                   &Style)
20617                    .value());
20618   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20619   EXPECT_EQ(76u, Style.IndentWidth);
20620   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20621 }
20622 
20623 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20624   FormatStyle Style = getLLVMStyle();
20625   std::string YAML = configurationAsText(Style);
20626   FormatStyle ParsedStyle = {};
20627   ParsedStyle.Language = FormatStyle::LK_Cpp;
20628   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20629   EXPECT_EQ(Style, ParsedStyle);
20630 }
20631 
20632 TEST_F(FormatTest, WorksFor8bitEncodings) {
20633   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20634             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20635             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20636             "\"\xef\xee\xf0\xf3...\"",
20637             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20638                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20639                    "\xef\xee\xf0\xf3...\"",
20640                    getLLVMStyleWithColumns(12)));
20641 }
20642 
20643 TEST_F(FormatTest, HandlesUTF8BOM) {
20644   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20645   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20646             format("\xef\xbb\xbf#include <iostream>"));
20647   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20648             format("\xef\xbb\xbf\n#include <iostream>"));
20649 }
20650 
20651 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20652 #if !defined(_MSC_VER)
20653 
20654 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20655   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20656                getLLVMStyleWithColumns(35));
20657   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20658                getLLVMStyleWithColumns(31));
20659   verifyFormat("// Однажды в студёную зимнюю пору...",
20660                getLLVMStyleWithColumns(36));
20661   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20662   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20663                getLLVMStyleWithColumns(39));
20664   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20665                getLLVMStyleWithColumns(35));
20666 }
20667 
20668 TEST_F(FormatTest, SplitsUTF8Strings) {
20669   // Non-printable characters' width is currently considered to be the length in
20670   // bytes in UTF8. The characters can be displayed in very different manner
20671   // (zero-width, single width with a substitution glyph, expanded to their code
20672   // (e.g. "<8d>"), so there's no single correct way to handle them.
20673   EXPECT_EQ("\"aaaaÄ\"\n"
20674             "\"\xc2\x8d\";",
20675             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20676   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20677             "\"\xc2\x8d\";",
20678             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20679   EXPECT_EQ("\"Однажды, в \"\n"
20680             "\"студёную \"\n"
20681             "\"зимнюю \"\n"
20682             "\"пору,\"",
20683             format("\"Однажды, в студёную зимнюю пору,\"",
20684                    getLLVMStyleWithColumns(13)));
20685   EXPECT_EQ(
20686       "\"一 二 三 \"\n"
20687       "\"四 五六 \"\n"
20688       "\"七 八 九 \"\n"
20689       "\"十\"",
20690       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20691   EXPECT_EQ("\"一\t\"\n"
20692             "\"二 \t\"\n"
20693             "\"三 四 \"\n"
20694             "\"五\t\"\n"
20695             "\"六 \t\"\n"
20696             "\"七 \"\n"
20697             "\"八九十\tqq\"",
20698             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20699                    getLLVMStyleWithColumns(11)));
20700 
20701   // UTF8 character in an escape sequence.
20702   EXPECT_EQ("\"aaaaaa\"\n"
20703             "\"\\\xC2\x8D\"",
20704             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20705 }
20706 
20707 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20708   EXPECT_EQ("const char *sssss =\n"
20709             "    \"一二三四五六七八\\\n"
20710             " 九 十\";",
20711             format("const char *sssss = \"一二三四五六七八\\\n"
20712                    " 九 十\";",
20713                    getLLVMStyleWithColumns(30)));
20714 }
20715 
20716 TEST_F(FormatTest, SplitsUTF8LineComments) {
20717   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20718             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20719   EXPECT_EQ("// Я из лесу\n"
20720             "// вышел; был\n"
20721             "// сильный\n"
20722             "// мороз.",
20723             format("// Я из лесу вышел; был сильный мороз.",
20724                    getLLVMStyleWithColumns(13)));
20725   EXPECT_EQ("// 一二三\n"
20726             "// 四五六七\n"
20727             "// 八  九\n"
20728             "// 十",
20729             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20730 }
20731 
20732 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20733   EXPECT_EQ("/* Гляжу,\n"
20734             " * поднимается\n"
20735             " * медленно в\n"
20736             " * гору\n"
20737             " * Лошадка,\n"
20738             " * везущая\n"
20739             " * хворосту\n"
20740             " * воз. */",
20741             format("/* Гляжу, поднимается медленно в гору\n"
20742                    " * Лошадка, везущая хворосту воз. */",
20743                    getLLVMStyleWithColumns(13)));
20744   EXPECT_EQ(
20745       "/* 一二三\n"
20746       " * 四五六七\n"
20747       " * 八  九\n"
20748       " * 十  */",
20749       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20750   EXPECT_EQ("/* �������� ��������\n"
20751             " * ��������\n"
20752             " * ������-�� */",
20753             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20754 }
20755 
20756 #endif // _MSC_VER
20757 
20758 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
20759   FormatStyle Style = getLLVMStyle();
20760 
20761   Style.ConstructorInitializerIndentWidth = 4;
20762   verifyFormat(
20763       "SomeClass::Constructor()\n"
20764       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20765       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20766       Style);
20767 
20768   Style.ConstructorInitializerIndentWidth = 2;
20769   verifyFormat(
20770       "SomeClass::Constructor()\n"
20771       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20772       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20773       Style);
20774 
20775   Style.ConstructorInitializerIndentWidth = 0;
20776   verifyFormat(
20777       "SomeClass::Constructor()\n"
20778       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20779       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20780       Style);
20781   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20782   verifyFormat(
20783       "SomeLongTemplateVariableName<\n"
20784       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
20785       Style);
20786   verifyFormat("bool smaller = 1 < "
20787                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
20788                "                       "
20789                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
20790                Style);
20791 
20792   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
20793   verifyFormat("SomeClass::Constructor() :\n"
20794                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
20795                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
20796                Style);
20797 }
20798 
20799 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
20800   FormatStyle Style = getLLVMStyle();
20801   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20802   Style.ConstructorInitializerIndentWidth = 4;
20803   verifyFormat("SomeClass::Constructor()\n"
20804                "    : a(a)\n"
20805                "    , b(b)\n"
20806                "    , c(c) {}",
20807                Style);
20808   verifyFormat("SomeClass::Constructor()\n"
20809                "    : a(a) {}",
20810                Style);
20811 
20812   Style.ColumnLimit = 0;
20813   verifyFormat("SomeClass::Constructor()\n"
20814                "    : a(a) {}",
20815                Style);
20816   verifyFormat("SomeClass::Constructor() noexcept\n"
20817                "    : a(a) {}",
20818                Style);
20819   verifyFormat("SomeClass::Constructor()\n"
20820                "    : a(a)\n"
20821                "    , b(b)\n"
20822                "    , c(c) {}",
20823                Style);
20824   verifyFormat("SomeClass::Constructor()\n"
20825                "    : a(a) {\n"
20826                "  foo();\n"
20827                "  bar();\n"
20828                "}",
20829                Style);
20830 
20831   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
20832   verifyFormat("SomeClass::Constructor()\n"
20833                "    : a(a)\n"
20834                "    , b(b)\n"
20835                "    , c(c) {\n}",
20836                Style);
20837   verifyFormat("SomeClass::Constructor()\n"
20838                "    : a(a) {\n}",
20839                Style);
20840 
20841   Style.ColumnLimit = 80;
20842   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
20843   Style.ConstructorInitializerIndentWidth = 2;
20844   verifyFormat("SomeClass::Constructor()\n"
20845                "  : a(a)\n"
20846                "  , b(b)\n"
20847                "  , c(c) {}",
20848                Style);
20849 
20850   Style.ConstructorInitializerIndentWidth = 0;
20851   verifyFormat("SomeClass::Constructor()\n"
20852                ": a(a)\n"
20853                ", b(b)\n"
20854                ", c(c) {}",
20855                Style);
20856 
20857   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20858   Style.ConstructorInitializerIndentWidth = 4;
20859   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
20860   verifyFormat(
20861       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
20862       Style);
20863   verifyFormat(
20864       "SomeClass::Constructor()\n"
20865       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
20866       Style);
20867   Style.ConstructorInitializerIndentWidth = 4;
20868   Style.ColumnLimit = 60;
20869   verifyFormat("SomeClass::Constructor()\n"
20870                "    : aaaaaaaa(aaaaaaaa)\n"
20871                "    , aaaaaaaa(aaaaaaaa)\n"
20872                "    , aaaaaaaa(aaaaaaaa) {}",
20873                Style);
20874 }
20875 
20876 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
20877   FormatStyle Style = getLLVMStyle();
20878   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20879   Style.ConstructorInitializerIndentWidth = 4;
20880   verifyFormat("SomeClass::Constructor()\n"
20881                "    : a{a}\n"
20882                "    , b{b} {}",
20883                Style);
20884   verifyFormat("SomeClass::Constructor()\n"
20885                "    : a{a}\n"
20886                "#if CONDITION\n"
20887                "    , b{b}\n"
20888                "#endif\n"
20889                "{\n}",
20890                Style);
20891   Style.ConstructorInitializerIndentWidth = 2;
20892   verifyFormat("SomeClass::Constructor()\n"
20893                "#if CONDITION\n"
20894                "  : a{a}\n"
20895                "#endif\n"
20896                "  , b{b}\n"
20897                "  , c{c} {\n}",
20898                Style);
20899   Style.ConstructorInitializerIndentWidth = 0;
20900   verifyFormat("SomeClass::Constructor()\n"
20901                ": a{a}\n"
20902                "#ifdef CONDITION\n"
20903                ", b{b}\n"
20904                "#else\n"
20905                ", c{c}\n"
20906                "#endif\n"
20907                ", d{d} {\n}",
20908                Style);
20909   Style.ConstructorInitializerIndentWidth = 4;
20910   verifyFormat("SomeClass::Constructor()\n"
20911                "    : a{a}\n"
20912                "#if WINDOWS\n"
20913                "#if DEBUG\n"
20914                "    , b{0}\n"
20915                "#else\n"
20916                "    , b{1}\n"
20917                "#endif\n"
20918                "#else\n"
20919                "#if DEBUG\n"
20920                "    , b{2}\n"
20921                "#else\n"
20922                "    , b{3}\n"
20923                "#endif\n"
20924                "#endif\n"
20925                "{\n}",
20926                Style);
20927   verifyFormat("SomeClass::Constructor()\n"
20928                "    : a{a}\n"
20929                "#if WINDOWS\n"
20930                "    , b{0}\n"
20931                "#if DEBUG\n"
20932                "    , c{0}\n"
20933                "#else\n"
20934                "    , c{1}\n"
20935                "#endif\n"
20936                "#else\n"
20937                "#if DEBUG\n"
20938                "    , c{2}\n"
20939                "#else\n"
20940                "    , c{3}\n"
20941                "#endif\n"
20942                "    , b{1}\n"
20943                "#endif\n"
20944                "{\n}",
20945                Style);
20946 }
20947 
20948 TEST_F(FormatTest, Destructors) {
20949   verifyFormat("void F(int &i) { i.~int(); }");
20950   verifyFormat("void F(int &i) { i->~int(); }");
20951 }
20952 
20953 TEST_F(FormatTest, FormatsWithWebKitStyle) {
20954   FormatStyle Style = getWebKitStyle();
20955 
20956   // Don't indent in outer namespaces.
20957   verifyFormat("namespace outer {\n"
20958                "int i;\n"
20959                "namespace inner {\n"
20960                "    int i;\n"
20961                "} // namespace inner\n"
20962                "} // namespace outer\n"
20963                "namespace other_outer {\n"
20964                "int i;\n"
20965                "}",
20966                Style);
20967 
20968   // Don't indent case labels.
20969   verifyFormat("switch (variable) {\n"
20970                "case 1:\n"
20971                "case 2:\n"
20972                "    doSomething();\n"
20973                "    break;\n"
20974                "default:\n"
20975                "    ++variable;\n"
20976                "}",
20977                Style);
20978 
20979   // Wrap before binary operators.
20980   EXPECT_EQ("void f()\n"
20981             "{\n"
20982             "    if (aaaaaaaaaaaaaaaa\n"
20983             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
20984             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20985             "        return;\n"
20986             "}",
20987             format("void f() {\n"
20988                    "if (aaaaaaaaaaaaaaaa\n"
20989                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
20990                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20991                    "return;\n"
20992                    "}",
20993                    Style));
20994 
20995   // Allow functions on a single line.
20996   verifyFormat("void f() { return; }", Style);
20997 
20998   // Allow empty blocks on a single line and insert a space in empty blocks.
20999   EXPECT_EQ("void f() { }", format("void f() {}", Style));
21000   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
21001   // However, don't merge non-empty short loops.
21002   EXPECT_EQ("while (true) {\n"
21003             "    continue;\n"
21004             "}",
21005             format("while (true) { continue; }", Style));
21006 
21007   // Constructor initializers are formatted one per line with the "," on the
21008   // new line.
21009   verifyFormat("Constructor()\n"
21010                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
21011                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
21012                "          aaaaaaaaaaaaaa)\n"
21013                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
21014                "{\n"
21015                "}",
21016                Style);
21017   verifyFormat("SomeClass::Constructor()\n"
21018                "    : a(a)\n"
21019                "{\n"
21020                "}",
21021                Style);
21022   EXPECT_EQ("SomeClass::Constructor()\n"
21023             "    : a(a)\n"
21024             "{\n"
21025             "}",
21026             format("SomeClass::Constructor():a(a){}", Style));
21027   verifyFormat("SomeClass::Constructor()\n"
21028                "    : a(a)\n"
21029                "    , b(b)\n"
21030                "    , c(c)\n"
21031                "{\n"
21032                "}",
21033                Style);
21034   verifyFormat("SomeClass::Constructor()\n"
21035                "    : a(a)\n"
21036                "{\n"
21037                "    foo();\n"
21038                "    bar();\n"
21039                "}",
21040                Style);
21041 
21042   // Access specifiers should be aligned left.
21043   verifyFormat("class C {\n"
21044                "public:\n"
21045                "    int i;\n"
21046                "};",
21047                Style);
21048 
21049   // Do not align comments.
21050   verifyFormat("int a; // Do not\n"
21051                "double b; // align comments.",
21052                Style);
21053 
21054   // Do not align operands.
21055   EXPECT_EQ("ASSERT(aaaa\n"
21056             "    || bbbb);",
21057             format("ASSERT ( aaaa\n||bbbb);", Style));
21058 
21059   // Accept input's line breaks.
21060   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
21061             "    || bbbbbbbbbbbbbbb) {\n"
21062             "    i++;\n"
21063             "}",
21064             format("if (aaaaaaaaaaaaaaa\n"
21065                    "|| bbbbbbbbbbbbbbb) { i++; }",
21066                    Style));
21067   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
21068             "    i++;\n"
21069             "}",
21070             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
21071 
21072   // Don't automatically break all macro definitions (llvm.org/PR17842).
21073   verifyFormat("#define aNumber 10", Style);
21074   // However, generally keep the line breaks that the user authored.
21075   EXPECT_EQ("#define aNumber \\\n"
21076             "    10",
21077             format("#define aNumber \\\n"
21078                    " 10",
21079                    Style));
21080 
21081   // Keep empty and one-element array literals on a single line.
21082   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
21083             "                                  copyItems:YES];",
21084             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
21085                    "copyItems:YES];",
21086                    Style));
21087   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
21088             "                                  copyItems:YES];",
21089             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
21090                    "             copyItems:YES];",
21091                    Style));
21092   // FIXME: This does not seem right, there should be more indentation before
21093   // the array literal's entries. Nested blocks have the same problem.
21094   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21095             "    @\"a\",\n"
21096             "    @\"a\"\n"
21097             "]\n"
21098             "                                  copyItems:YES];",
21099             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21100                    "     @\"a\",\n"
21101                    "     @\"a\"\n"
21102                    "     ]\n"
21103                    "       copyItems:YES];",
21104                    Style));
21105   EXPECT_EQ(
21106       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21107       "                                  copyItems:YES];",
21108       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21109              "   copyItems:YES];",
21110              Style));
21111 
21112   verifyFormat("[self.a b:c c:d];", Style);
21113   EXPECT_EQ("[self.a b:c\n"
21114             "        c:d];",
21115             format("[self.a b:c\n"
21116                    "c:d];",
21117                    Style));
21118 }
21119 
21120 TEST_F(FormatTest, FormatsLambdas) {
21121   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
21122   verifyFormat(
21123       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
21124   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
21125   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
21126   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
21127   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
21128   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
21129   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
21130   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
21131   verifyFormat("int x = f(*+[] {});");
21132   verifyFormat("void f() {\n"
21133                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
21134                "}\n");
21135   verifyFormat("void f() {\n"
21136                "  other(x.begin(), //\n"
21137                "        x.end(),   //\n"
21138                "        [&](int, int) { return 1; });\n"
21139                "}\n");
21140   verifyFormat("void f() {\n"
21141                "  other.other.other.other.other(\n"
21142                "      x.begin(), x.end(),\n"
21143                "      [something, rather](int, int, int, int, int, int, int) { "
21144                "return 1; });\n"
21145                "}\n");
21146   verifyFormat(
21147       "void f() {\n"
21148       "  other.other.other.other.other(\n"
21149       "      x.begin(), x.end(),\n"
21150       "      [something, rather](int, int, int, int, int, int, int) {\n"
21151       "        //\n"
21152       "      });\n"
21153       "}\n");
21154   verifyFormat("SomeFunction([]() { // A cool function...\n"
21155                "  return 43;\n"
21156                "});");
21157   EXPECT_EQ("SomeFunction([]() {\n"
21158             "#define A a\n"
21159             "  return 43;\n"
21160             "});",
21161             format("SomeFunction([](){\n"
21162                    "#define A a\n"
21163                    "return 43;\n"
21164                    "});"));
21165   verifyFormat("void f() {\n"
21166                "  SomeFunction([](decltype(x), A *a) {});\n"
21167                "  SomeFunction([](typeof(x), A *a) {});\n"
21168                "  SomeFunction([](_Atomic(x), A *a) {});\n"
21169                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
21170                "}");
21171   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21172                "    [](const aaaaaaaaaa &a) { return a; });");
21173   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
21174                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
21175                "});");
21176   verifyFormat("Constructor()\n"
21177                "    : Field([] { // comment\n"
21178                "        int i;\n"
21179                "      }) {}");
21180   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
21181                "  return some_parameter.size();\n"
21182                "};");
21183   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
21184                "    [](const string &s) { return s; };");
21185   verifyFormat("int i = aaaaaa ? 1 //\n"
21186                "               : [] {\n"
21187                "                   return 2; //\n"
21188                "                 }();");
21189   verifyFormat("llvm::errs() << \"number of twos is \"\n"
21190                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
21191                "                  return x == 2; // force break\n"
21192                "                });");
21193   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21194                "    [=](int iiiiiiiiiiii) {\n"
21195                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
21196                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
21197                "    });",
21198                getLLVMStyleWithColumns(60));
21199 
21200   verifyFormat("SomeFunction({[&] {\n"
21201                "                // comment\n"
21202                "              },\n"
21203                "              [&] {\n"
21204                "                // comment\n"
21205                "              }});");
21206   verifyFormat("SomeFunction({[&] {\n"
21207                "  // comment\n"
21208                "}});");
21209   verifyFormat(
21210       "virtual aaaaaaaaaaaaaaaa(\n"
21211       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
21212       "    aaaaa aaaaaaaaa);");
21213 
21214   // Lambdas with return types.
21215   verifyFormat("int c = []() -> int { return 2; }();\n");
21216   verifyFormat("int c = []() -> int * { return 2; }();\n");
21217   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
21218   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
21219   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
21220   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
21221   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
21222   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
21223   verifyFormat("[a, a]() -> a<1> {};");
21224   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
21225   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
21226   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
21227   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
21228   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
21229   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
21230   verifyFormat("[]() -> foo<!5> { return {}; };");
21231   verifyFormat("[]() -> foo<~5> { return {}; };");
21232   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
21233   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
21234   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
21235   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
21236   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
21237   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
21238   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
21239   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
21240   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
21241   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
21242   verifyFormat("namespace bar {\n"
21243                "// broken:\n"
21244                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
21245                "} // namespace bar");
21246   verifyFormat("namespace bar {\n"
21247                "// broken:\n"
21248                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
21249                "} // namespace bar");
21250   verifyFormat("namespace bar {\n"
21251                "// broken:\n"
21252                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
21253                "} // namespace bar");
21254   verifyFormat("namespace bar {\n"
21255                "// broken:\n"
21256                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
21257                "} // namespace bar");
21258   verifyFormat("namespace bar {\n"
21259                "// broken:\n"
21260                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
21261                "} // namespace bar");
21262   verifyFormat("namespace bar {\n"
21263                "// broken:\n"
21264                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
21265                "} // namespace bar");
21266   verifyFormat("namespace bar {\n"
21267                "// broken:\n"
21268                "auto foo{[]() -> foo<!5> { return {}; }};\n"
21269                "} // namespace bar");
21270   verifyFormat("namespace bar {\n"
21271                "// broken:\n"
21272                "auto foo{[]() -> foo<~5> { return {}; }};\n"
21273                "} // namespace bar");
21274   verifyFormat("namespace bar {\n"
21275                "// broken:\n"
21276                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
21277                "} // namespace bar");
21278   verifyFormat("namespace bar {\n"
21279                "// broken:\n"
21280                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
21281                "} // namespace bar");
21282   verifyFormat("namespace bar {\n"
21283                "// broken:\n"
21284                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
21285                "} // namespace bar");
21286   verifyFormat("namespace bar {\n"
21287                "// broken:\n"
21288                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
21289                "} // namespace bar");
21290   verifyFormat("namespace bar {\n"
21291                "// broken:\n"
21292                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
21293                "} // namespace bar");
21294   verifyFormat("namespace bar {\n"
21295                "// broken:\n"
21296                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
21297                "} // namespace bar");
21298   verifyFormat("namespace bar {\n"
21299                "// broken:\n"
21300                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
21301                "} // namespace bar");
21302   verifyFormat("namespace bar {\n"
21303                "// broken:\n"
21304                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
21305                "} // namespace bar");
21306   verifyFormat("namespace bar {\n"
21307                "// broken:\n"
21308                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
21309                "} // namespace bar");
21310   verifyFormat("namespace bar {\n"
21311                "// broken:\n"
21312                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
21313                "} // namespace bar");
21314   verifyFormat("[]() -> a<1> {};");
21315   verifyFormat("[]() -> a<1> { ; };");
21316   verifyFormat("[]() -> a<1> { ; }();");
21317   verifyFormat("[a, a]() -> a<true> {};");
21318   verifyFormat("[]() -> a<true> {};");
21319   verifyFormat("[]() -> a<true> { ; };");
21320   verifyFormat("[]() -> a<true> { ; }();");
21321   verifyFormat("[a, a]() -> a<false> {};");
21322   verifyFormat("[]() -> a<false> {};");
21323   verifyFormat("[]() -> a<false> { ; };");
21324   verifyFormat("[]() -> a<false> { ; }();");
21325   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
21326   verifyFormat("namespace bar {\n"
21327                "auto foo{[]() -> foo<false> { ; }};\n"
21328                "} // namespace bar");
21329   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
21330                "                   int j) -> int {\n"
21331                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21332                "};");
21333   verifyFormat(
21334       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21335       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21336       "      return aaaaaaaaaaaaaaaaa;\n"
21337       "    });",
21338       getLLVMStyleWithColumns(70));
21339   verifyFormat("[]() //\n"
21340                "    -> int {\n"
21341                "  return 1; //\n"
21342                "};");
21343   verifyFormat("[]() -> Void<T...> {};");
21344   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21345   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21346   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21347   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21348   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21349   verifyFormat("return int{[x = x]() { return x; }()};");
21350 
21351   // Lambdas with explicit template argument lists.
21352   verifyFormat(
21353       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21354   verifyFormat("auto L = []<class T>(T) {\n"
21355                "  {\n"
21356                "    f();\n"
21357                "    g();\n"
21358                "  }\n"
21359                "};\n");
21360   verifyFormat("auto L = []<class... T>(T...) {\n"
21361                "  {\n"
21362                "    f();\n"
21363                "    g();\n"
21364                "  }\n"
21365                "};\n");
21366   verifyFormat("auto L = []<typename... T>(T...) {\n"
21367                "  {\n"
21368                "    f();\n"
21369                "    g();\n"
21370                "  }\n"
21371                "};\n");
21372   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21373                "  {\n"
21374                "    f();\n"
21375                "    g();\n"
21376                "  }\n"
21377                "};\n");
21378   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21379                "  {\n"
21380                "    f();\n"
21381                "    g();\n"
21382                "  }\n"
21383                "};\n");
21384 
21385   // Multiple lambdas in the same parentheses change indentation rules. These
21386   // lambdas are forced to start on new lines.
21387   verifyFormat("SomeFunction(\n"
21388                "    []() {\n"
21389                "      //\n"
21390                "    },\n"
21391                "    []() {\n"
21392                "      //\n"
21393                "    });");
21394 
21395   // A lambda passed as arg0 is always pushed to the next line.
21396   verifyFormat("SomeFunction(\n"
21397                "    [this] {\n"
21398                "      //\n"
21399                "    },\n"
21400                "    1);\n");
21401 
21402   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21403   // the arg0 case above.
21404   auto Style = getGoogleStyle();
21405   Style.BinPackArguments = false;
21406   verifyFormat("SomeFunction(\n"
21407                "    a,\n"
21408                "    [this] {\n"
21409                "      //\n"
21410                "    },\n"
21411                "    b);\n",
21412                Style);
21413   verifyFormat("SomeFunction(\n"
21414                "    a,\n"
21415                "    [this] {\n"
21416                "      //\n"
21417                "    },\n"
21418                "    b);\n");
21419 
21420   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21421   // the BinPackArguments value (as long as the code is wide enough).
21422   verifyFormat(
21423       "something->SomeFunction(\n"
21424       "    a,\n"
21425       "    [this] {\n"
21426       "      "
21427       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21428       "    },\n"
21429       "    b);\n");
21430 
21431   // A multi-line lambda is pulled up as long as the introducer fits on the
21432   // previous line and there are no further args.
21433   verifyFormat("function(1, [this, that] {\n"
21434                "  //\n"
21435                "});\n");
21436   verifyFormat("function([this, that] {\n"
21437                "  //\n"
21438                "});\n");
21439   // FIXME: this format is not ideal and we should consider forcing the first
21440   // arg onto its own line.
21441   verifyFormat("function(a, b, c, //\n"
21442                "         d, [this, that] {\n"
21443                "           //\n"
21444                "         });\n");
21445 
21446   // Multiple lambdas are treated correctly even when there is a short arg0.
21447   verifyFormat("SomeFunction(\n"
21448                "    1,\n"
21449                "    [this] {\n"
21450                "      //\n"
21451                "    },\n"
21452                "    [this] {\n"
21453                "      //\n"
21454                "    },\n"
21455                "    1);\n");
21456 
21457   // More complex introducers.
21458   verifyFormat("return [i, args...] {};");
21459 
21460   // Not lambdas.
21461   verifyFormat("constexpr char hello[]{\"hello\"};");
21462   verifyFormat("double &operator[](int i) { return 0; }\n"
21463                "int i;");
21464   verifyFormat("std::unique_ptr<int[]> foo() {}");
21465   verifyFormat("int i = a[a][a]->f();");
21466   verifyFormat("int i = (*b)[a]->f();");
21467 
21468   // Other corner cases.
21469   verifyFormat("void f() {\n"
21470                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21471                "  );\n"
21472                "}");
21473 
21474   // Lambdas created through weird macros.
21475   verifyFormat("void f() {\n"
21476                "  MACRO((const AA &a) { return 1; });\n"
21477                "  MACRO((AA &a) { return 1; });\n"
21478                "}");
21479 
21480   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21481                "      doo_dah();\n"
21482                "      doo_dah();\n"
21483                "    })) {\n"
21484                "}");
21485   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21486                "                doo_dah();\n"
21487                "                doo_dah();\n"
21488                "              })) {\n"
21489                "}");
21490   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21491                "                doo_dah();\n"
21492                "                doo_dah();\n"
21493                "              })) {\n"
21494                "}");
21495   verifyFormat("auto lambda = []() {\n"
21496                "  int a = 2\n"
21497                "#if A\n"
21498                "          + 2\n"
21499                "#endif\n"
21500                "      ;\n"
21501                "};");
21502 
21503   // Lambdas with complex multiline introducers.
21504   verifyFormat(
21505       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21506       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21507       "        -> ::std::unordered_set<\n"
21508       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21509       "      //\n"
21510       "    });");
21511 
21512   FormatStyle DoNotMerge = getLLVMStyle();
21513   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21514   verifyFormat("auto c = []() {\n"
21515                "  return b;\n"
21516                "};",
21517                "auto c = []() { return b; };", DoNotMerge);
21518   verifyFormat("auto c = []() {\n"
21519                "};",
21520                " auto c = []() {};", DoNotMerge);
21521 
21522   FormatStyle MergeEmptyOnly = getLLVMStyle();
21523   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21524   verifyFormat("auto c = []() {\n"
21525                "  return b;\n"
21526                "};",
21527                "auto c = []() {\n"
21528                "  return b;\n"
21529                " };",
21530                MergeEmptyOnly);
21531   verifyFormat("auto c = []() {};",
21532                "auto c = []() {\n"
21533                "};",
21534                MergeEmptyOnly);
21535 
21536   FormatStyle MergeInline = getLLVMStyle();
21537   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21538   verifyFormat("auto c = []() {\n"
21539                "  return b;\n"
21540                "};",
21541                "auto c = []() { return b; };", MergeInline);
21542   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21543                MergeInline);
21544   verifyFormat("function([]() { return b; }, a)",
21545                "function([]() { return b; }, a)", MergeInline);
21546   verifyFormat("function(a, []() { return b; })",
21547                "function(a, []() { return b; })", MergeInline);
21548 
21549   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21550   // AllowShortLambdasOnASingleLine
21551   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21552   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21553   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21554   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21555       FormatStyle::ShortLambdaStyle::SLS_None;
21556   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21557                "    []()\n"
21558                "    {\n"
21559                "      return 17;\n"
21560                "    });",
21561                LLVMWithBeforeLambdaBody);
21562   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21563                "    []()\n"
21564                "    {\n"
21565                "    });",
21566                LLVMWithBeforeLambdaBody);
21567   verifyFormat("auto fct_SLS_None = []()\n"
21568                "{\n"
21569                "  return 17;\n"
21570                "};",
21571                LLVMWithBeforeLambdaBody);
21572   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21573                "    []()\n"
21574                "    {\n"
21575                "      return Call(\n"
21576                "          []()\n"
21577                "          {\n"
21578                "            return 17;\n"
21579                "          });\n"
21580                "    });",
21581                LLVMWithBeforeLambdaBody);
21582   verifyFormat("void Fct() {\n"
21583                "  return {[]()\n"
21584                "          {\n"
21585                "            return 17;\n"
21586                "          }};\n"
21587                "}",
21588                LLVMWithBeforeLambdaBody);
21589 
21590   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21591       FormatStyle::ShortLambdaStyle::SLS_Empty;
21592   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21593                "    []()\n"
21594                "    {\n"
21595                "      return 17;\n"
21596                "    });",
21597                LLVMWithBeforeLambdaBody);
21598   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21599                LLVMWithBeforeLambdaBody);
21600   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21601                "ongFunctionName_SLS_Empty(\n"
21602                "    []() {});",
21603                LLVMWithBeforeLambdaBody);
21604   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21605                "                                []()\n"
21606                "                                {\n"
21607                "                                  return 17;\n"
21608                "                                });",
21609                LLVMWithBeforeLambdaBody);
21610   verifyFormat("auto fct_SLS_Empty = []()\n"
21611                "{\n"
21612                "  return 17;\n"
21613                "};",
21614                LLVMWithBeforeLambdaBody);
21615   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21616                "    []()\n"
21617                "    {\n"
21618                "      return Call([]() {});\n"
21619                "    });",
21620                LLVMWithBeforeLambdaBody);
21621   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21622                "                           []()\n"
21623                "                           {\n"
21624                "                             return Call([]() {});\n"
21625                "                           });",
21626                LLVMWithBeforeLambdaBody);
21627   verifyFormat(
21628       "FctWithLongLineInLambda_SLS_Empty(\n"
21629       "    []()\n"
21630       "    {\n"
21631       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21632       "                               AndShouldNotBeConsiderAsInline,\n"
21633       "                               LambdaBodyMustBeBreak);\n"
21634       "    });",
21635       LLVMWithBeforeLambdaBody);
21636 
21637   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21638       FormatStyle::ShortLambdaStyle::SLS_Inline;
21639   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21640                LLVMWithBeforeLambdaBody);
21641   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21642                LLVMWithBeforeLambdaBody);
21643   verifyFormat("auto fct_SLS_Inline = []()\n"
21644                "{\n"
21645                "  return 17;\n"
21646                "};",
21647                LLVMWithBeforeLambdaBody);
21648   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21649                "17; }); });",
21650                LLVMWithBeforeLambdaBody);
21651   verifyFormat(
21652       "FctWithLongLineInLambda_SLS_Inline(\n"
21653       "    []()\n"
21654       "    {\n"
21655       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21656       "                               AndShouldNotBeConsiderAsInline,\n"
21657       "                               LambdaBodyMustBeBreak);\n"
21658       "    });",
21659       LLVMWithBeforeLambdaBody);
21660   verifyFormat("FctWithMultipleParams_SLS_Inline("
21661                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21662                "                                 []() { return 17; });",
21663                LLVMWithBeforeLambdaBody);
21664   verifyFormat(
21665       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21666       LLVMWithBeforeLambdaBody);
21667 
21668   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21669       FormatStyle::ShortLambdaStyle::SLS_All;
21670   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21671                LLVMWithBeforeLambdaBody);
21672   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21673                LLVMWithBeforeLambdaBody);
21674   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21675                LLVMWithBeforeLambdaBody);
21676   verifyFormat("FctWithOneParam_SLS_All(\n"
21677                "    []()\n"
21678                "    {\n"
21679                "      // A cool function...\n"
21680                "      return 43;\n"
21681                "    });",
21682                LLVMWithBeforeLambdaBody);
21683   verifyFormat("FctWithMultipleParams_SLS_All("
21684                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21685                "                              []() { return 17; });",
21686                LLVMWithBeforeLambdaBody);
21687   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21688                LLVMWithBeforeLambdaBody);
21689   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21690                LLVMWithBeforeLambdaBody);
21691   verifyFormat(
21692       "FctWithLongLineInLambda_SLS_All(\n"
21693       "    []()\n"
21694       "    {\n"
21695       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21696       "                               AndShouldNotBeConsiderAsInline,\n"
21697       "                               LambdaBodyMustBeBreak);\n"
21698       "    });",
21699       LLVMWithBeforeLambdaBody);
21700   verifyFormat(
21701       "auto fct_SLS_All = []()\n"
21702       "{\n"
21703       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21704       "                           AndShouldNotBeConsiderAsInline,\n"
21705       "                           LambdaBodyMustBeBreak);\n"
21706       "};",
21707       LLVMWithBeforeLambdaBody);
21708   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21709   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21710                LLVMWithBeforeLambdaBody);
21711   verifyFormat(
21712       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21713       "                                FirstParam,\n"
21714       "                                SecondParam,\n"
21715       "                                ThirdParam,\n"
21716       "                                FourthParam);",
21717       LLVMWithBeforeLambdaBody);
21718   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21719                "    []() { return "
21720                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21721                "    FirstParam,\n"
21722                "    SecondParam,\n"
21723                "    ThirdParam,\n"
21724                "    FourthParam);",
21725                LLVMWithBeforeLambdaBody);
21726   verifyFormat(
21727       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21728       "                                SecondParam,\n"
21729       "                                ThirdParam,\n"
21730       "                                FourthParam,\n"
21731       "                                []() { return SomeValueNotSoLong; });",
21732       LLVMWithBeforeLambdaBody);
21733   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21734                "    []()\n"
21735                "    {\n"
21736                "      return "
21737                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21738                "eConsiderAsInline;\n"
21739                "    });",
21740                LLVMWithBeforeLambdaBody);
21741   verifyFormat(
21742       "FctWithLongLineInLambda_SLS_All(\n"
21743       "    []()\n"
21744       "    {\n"
21745       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21746       "                               AndShouldNotBeConsiderAsInline,\n"
21747       "                               LambdaBodyMustBeBreak);\n"
21748       "    });",
21749       LLVMWithBeforeLambdaBody);
21750   verifyFormat("FctWithTwoParams_SLS_All(\n"
21751                "    []()\n"
21752                "    {\n"
21753                "      // A cool function...\n"
21754                "      return 43;\n"
21755                "    },\n"
21756                "    87);",
21757                LLVMWithBeforeLambdaBody);
21758   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
21759                LLVMWithBeforeLambdaBody);
21760   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
21761                LLVMWithBeforeLambdaBody);
21762   verifyFormat(
21763       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
21764       LLVMWithBeforeLambdaBody);
21765   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
21766                "}); }, x);",
21767                LLVMWithBeforeLambdaBody);
21768   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21769                "    []()\n"
21770                "    {\n"
21771                "      // A cool function...\n"
21772                "      return Call([]() { return 17; });\n"
21773                "    });",
21774                LLVMWithBeforeLambdaBody);
21775   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21776                "    []()\n"
21777                "    {\n"
21778                "      return Call(\n"
21779                "          []()\n"
21780                "          {\n"
21781                "            // A cool function...\n"
21782                "            return 17;\n"
21783                "          });\n"
21784                "    });",
21785                LLVMWithBeforeLambdaBody);
21786 
21787   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21788       FormatStyle::ShortLambdaStyle::SLS_None;
21789 
21790   verifyFormat("auto select = [this]() -> const Library::Object *\n"
21791                "{\n"
21792                "  return MyAssignment::SelectFromList(this);\n"
21793                "};\n",
21794                LLVMWithBeforeLambdaBody);
21795 
21796   verifyFormat("auto select = [this]() -> const Library::Object &\n"
21797                "{\n"
21798                "  return MyAssignment::SelectFromList(this);\n"
21799                "};\n",
21800                LLVMWithBeforeLambdaBody);
21801 
21802   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
21803                "{\n"
21804                "  return MyAssignment::SelectFromList(this);\n"
21805                "};\n",
21806                LLVMWithBeforeLambdaBody);
21807 
21808   verifyFormat("namespace test {\n"
21809                "class Test {\n"
21810                "public:\n"
21811                "  Test() = default;\n"
21812                "};\n"
21813                "} // namespace test",
21814                LLVMWithBeforeLambdaBody);
21815 
21816   // Lambdas with different indentation styles.
21817   Style = getLLVMStyleWithColumns(100);
21818   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21819             "  return promise.then(\n"
21820             "      [this, &someVariable, someObject = "
21821             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21822             "        return someObject.startAsyncAction().then(\n"
21823             "            [this, &someVariable](AsyncActionResult result) "
21824             "mutable { result.processMore(); });\n"
21825             "      });\n"
21826             "}\n",
21827             format("SomeResult doSomething(SomeObject promise) {\n"
21828                    "  return promise.then([this, &someVariable, someObject = "
21829                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21830                    "    return someObject.startAsyncAction().then([this, "
21831                    "&someVariable](AsyncActionResult result) mutable {\n"
21832                    "      result.processMore();\n"
21833                    "    });\n"
21834                    "  });\n"
21835                    "}\n",
21836                    Style));
21837   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21838   verifyFormat("test() {\n"
21839                "  ([]() -> {\n"
21840                "    int b = 32;\n"
21841                "    return 3;\n"
21842                "  }).foo();\n"
21843                "}",
21844                Style);
21845   verifyFormat("test() {\n"
21846                "  []() -> {\n"
21847                "    int b = 32;\n"
21848                "    return 3;\n"
21849                "  }\n"
21850                "}",
21851                Style);
21852   verifyFormat("std::sort(v.begin(), v.end(),\n"
21853                "          [](const auto &someLongArgumentName, const auto "
21854                "&someOtherLongArgumentName) {\n"
21855                "  return someLongArgumentName.someMemberVariable < "
21856                "someOtherLongArgumentName.someMemberVariable;\n"
21857                "});",
21858                Style);
21859   verifyFormat("test() {\n"
21860                "  (\n"
21861                "      []() -> {\n"
21862                "        int b = 32;\n"
21863                "        return 3;\n"
21864                "      },\n"
21865                "      foo, bar)\n"
21866                "      .foo();\n"
21867                "}",
21868                Style);
21869   verifyFormat("test() {\n"
21870                "  ([]() -> {\n"
21871                "    int b = 32;\n"
21872                "    return 3;\n"
21873                "  })\n"
21874                "      .foo()\n"
21875                "      .bar();\n"
21876                "}",
21877                Style);
21878   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21879             "  return promise.then(\n"
21880             "      [this, &someVariable, someObject = "
21881             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21882             "    return someObject.startAsyncAction().then(\n"
21883             "        [this, &someVariable](AsyncActionResult result) mutable { "
21884             "result.processMore(); });\n"
21885             "  });\n"
21886             "}\n",
21887             format("SomeResult doSomething(SomeObject promise) {\n"
21888                    "  return promise.then([this, &someVariable, someObject = "
21889                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21890                    "    return someObject.startAsyncAction().then([this, "
21891                    "&someVariable](AsyncActionResult result) mutable {\n"
21892                    "      result.processMore();\n"
21893                    "    });\n"
21894                    "  });\n"
21895                    "}\n",
21896                    Style));
21897   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21898             "  return promise.then([this, &someVariable] {\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] {\n"
21906                    "    return someObject.startAsyncAction().then([this, "
21907                    "&someVariable](AsyncActionResult result) mutable {\n"
21908                    "      result.processMore();\n"
21909                    "    });\n"
21910                    "  });\n"
21911                    "}\n",
21912                    Style));
21913   Style = getGoogleStyle();
21914   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21915   EXPECT_EQ("#define A                                       \\\n"
21916             "  [] {                                          \\\n"
21917             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
21918             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
21919             "      }",
21920             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
21921                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
21922                    Style));
21923   // TODO: The current formatting has a minor issue that's not worth fixing
21924   // right now whereby the closing brace is indented relative to the signature
21925   // instead of being aligned. This only happens with macros.
21926 }
21927 
21928 TEST_F(FormatTest, LambdaWithLineComments) {
21929   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21930   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21931   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21932   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21933       FormatStyle::ShortLambdaStyle::SLS_All;
21934 
21935   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
21936   verifyFormat("auto k = []() // comment\n"
21937                "{ return; }",
21938                LLVMWithBeforeLambdaBody);
21939   verifyFormat("auto k = []() /* comment */ { return; }",
21940                LLVMWithBeforeLambdaBody);
21941   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
21942                LLVMWithBeforeLambdaBody);
21943   verifyFormat("auto k = []() // X\n"
21944                "{ return; }",
21945                LLVMWithBeforeLambdaBody);
21946   verifyFormat(
21947       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
21948       "{ return; }",
21949       LLVMWithBeforeLambdaBody);
21950 
21951   LLVMWithBeforeLambdaBody.ColumnLimit = 0;
21952 
21953   verifyFormat("foo([]()\n"
21954                "    {\n"
21955                "      bar();    //\n"
21956                "      return 1; // comment\n"
21957                "    }());",
21958                "foo([]() {\n"
21959                "  bar(); //\n"
21960                "  return 1; // comment\n"
21961                "}());",
21962                LLVMWithBeforeLambdaBody);
21963   verifyFormat("foo(\n"
21964                "    1, MACRO {\n"
21965                "      baz();\n"
21966                "      bar(); // comment\n"
21967                "    },\n"
21968                "    []() {});",
21969                "foo(\n"
21970                "  1, MACRO { baz(); bar(); // comment\n"
21971                "  }, []() {}\n"
21972                ");",
21973                LLVMWithBeforeLambdaBody);
21974 }
21975 
21976 TEST_F(FormatTest, EmptyLinesInLambdas) {
21977   verifyFormat("auto lambda = []() {\n"
21978                "  x(); //\n"
21979                "};",
21980                "auto lambda = []() {\n"
21981                "\n"
21982                "  x(); //\n"
21983                "\n"
21984                "};");
21985 }
21986 
21987 TEST_F(FormatTest, FormatsBlocks) {
21988   FormatStyle ShortBlocks = getLLVMStyle();
21989   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21990   verifyFormat("int (^Block)(int, int);", ShortBlocks);
21991   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
21992   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
21993   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
21994   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
21995   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
21996 
21997   verifyFormat("foo(^{ bar(); });", ShortBlocks);
21998   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
21999   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
22000 
22001   verifyFormat("[operation setCompletionBlock:^{\n"
22002                "  [self onOperationDone];\n"
22003                "}];");
22004   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
22005                "  [self onOperationDone];\n"
22006                "}]};");
22007   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
22008                "  f();\n"
22009                "}];");
22010   verifyFormat("int a = [operation block:^int(int *i) {\n"
22011                "  return 1;\n"
22012                "}];");
22013   verifyFormat("[myObject doSomethingWith:arg1\n"
22014                "                      aaa:^int(int *a) {\n"
22015                "                        return 1;\n"
22016                "                      }\n"
22017                "                      bbb:f(a * bbbbbbbb)];");
22018 
22019   verifyFormat("[operation setCompletionBlock:^{\n"
22020                "  [self.delegate newDataAvailable];\n"
22021                "}];",
22022                getLLVMStyleWithColumns(60));
22023   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
22024                "  NSString *path = [self sessionFilePath];\n"
22025                "  if (path) {\n"
22026                "    // ...\n"
22027                "  }\n"
22028                "});");
22029   verifyFormat("[[SessionService sharedService]\n"
22030                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22031                "      if (window) {\n"
22032                "        [self windowDidLoad:window];\n"
22033                "      } else {\n"
22034                "        [self errorLoadingWindow];\n"
22035                "      }\n"
22036                "    }];");
22037   verifyFormat("void (^largeBlock)(void) = ^{\n"
22038                "  // ...\n"
22039                "};\n",
22040                getLLVMStyleWithColumns(40));
22041   verifyFormat("[[SessionService sharedService]\n"
22042                "    loadWindowWithCompletionBlock: //\n"
22043                "        ^(SessionWindow *window) {\n"
22044                "          if (window) {\n"
22045                "            [self windowDidLoad:window];\n"
22046                "          } else {\n"
22047                "            [self errorLoadingWindow];\n"
22048                "          }\n"
22049                "        }];",
22050                getLLVMStyleWithColumns(60));
22051   verifyFormat("[myObject doSomethingWith:arg1\n"
22052                "    firstBlock:^(Foo *a) {\n"
22053                "      // ...\n"
22054                "      int i;\n"
22055                "    }\n"
22056                "    secondBlock:^(Bar *b) {\n"
22057                "      // ...\n"
22058                "      int i;\n"
22059                "    }\n"
22060                "    thirdBlock:^Foo(Bar *b) {\n"
22061                "      // ...\n"
22062                "      int i;\n"
22063                "    }];");
22064   verifyFormat("[myObject doSomethingWith:arg1\n"
22065                "               firstBlock:-1\n"
22066                "              secondBlock:^(Bar *b) {\n"
22067                "                // ...\n"
22068                "                int i;\n"
22069                "              }];");
22070 
22071   verifyFormat("f(^{\n"
22072                "  @autoreleasepool {\n"
22073                "    if (a) {\n"
22074                "      g();\n"
22075                "    }\n"
22076                "  }\n"
22077                "});");
22078   verifyFormat("Block b = ^int *(A *a, B *b) {}");
22079   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
22080                "};");
22081 
22082   FormatStyle FourIndent = getLLVMStyle();
22083   FourIndent.ObjCBlockIndentWidth = 4;
22084   verifyFormat("[operation setCompletionBlock:^{\n"
22085                "    [self onOperationDone];\n"
22086                "}];",
22087                FourIndent);
22088 }
22089 
22090 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
22091   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
22092 
22093   verifyFormat("[[SessionService sharedService] "
22094                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22095                "  if (window) {\n"
22096                "    [self windowDidLoad:window];\n"
22097                "  } else {\n"
22098                "    [self errorLoadingWindow];\n"
22099                "  }\n"
22100                "}];",
22101                ZeroColumn);
22102   EXPECT_EQ("[[SessionService sharedService]\n"
22103             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22104             "      if (window) {\n"
22105             "        [self windowDidLoad:window];\n"
22106             "      } else {\n"
22107             "        [self errorLoadingWindow];\n"
22108             "      }\n"
22109             "    }];",
22110             format("[[SessionService sharedService]\n"
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   verifyFormat("[myObject doSomethingWith:arg1\n"
22120                "    firstBlock:^(Foo *a) {\n"
22121                "      // ...\n"
22122                "      int i;\n"
22123                "    }\n"
22124                "    secondBlock:^(Bar *b) {\n"
22125                "      // ...\n"
22126                "      int i;\n"
22127                "    }\n"
22128                "    thirdBlock:^Foo(Bar *b) {\n"
22129                "      // ...\n"
22130                "      int i;\n"
22131                "    }];",
22132                ZeroColumn);
22133   verifyFormat("f(^{\n"
22134                "  @autoreleasepool {\n"
22135                "    if (a) {\n"
22136                "      g();\n"
22137                "    }\n"
22138                "  }\n"
22139                "});",
22140                ZeroColumn);
22141   verifyFormat("void (^largeBlock)(void) = ^{\n"
22142                "  // ...\n"
22143                "};",
22144                ZeroColumn);
22145 
22146   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22147   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
22148             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22149   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
22150   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
22151             "  int i;\n"
22152             "};",
22153             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22154 }
22155 
22156 TEST_F(FormatTest, SupportsCRLF) {
22157   EXPECT_EQ("int a;\r\n"
22158             "int b;\r\n"
22159             "int c;\r\n",
22160             format("int a;\r\n"
22161                    "  int b;\r\n"
22162                    "    int c;\r\n",
22163                    getLLVMStyle()));
22164   EXPECT_EQ("int a;\r\n"
22165             "int b;\r\n"
22166             "int c;\r\n",
22167             format("int a;\r\n"
22168                    "  int b;\n"
22169                    "    int c;\r\n",
22170                    getLLVMStyle()));
22171   EXPECT_EQ("int a;\n"
22172             "int b;\n"
22173             "int c;\n",
22174             format("int a;\r\n"
22175                    "  int b;\n"
22176                    "    int c;\n",
22177                    getLLVMStyle()));
22178   EXPECT_EQ("\"aaaaaaa \"\r\n"
22179             "\"bbbbbbb\";\r\n",
22180             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
22181   EXPECT_EQ("#define A \\\r\n"
22182             "  b;      \\\r\n"
22183             "  c;      \\\r\n"
22184             "  d;\r\n",
22185             format("#define A \\\r\n"
22186                    "  b; \\\r\n"
22187                    "  c; d; \r\n",
22188                    getGoogleStyle()));
22189 
22190   EXPECT_EQ("/*\r\n"
22191             "multi line block comments\r\n"
22192             "should not introduce\r\n"
22193             "an extra carriage return\r\n"
22194             "*/\r\n",
22195             format("/*\r\n"
22196                    "multi line block comments\r\n"
22197                    "should not introduce\r\n"
22198                    "an extra carriage return\r\n"
22199                    "*/\r\n"));
22200   EXPECT_EQ("/*\r\n"
22201             "\r\n"
22202             "*/",
22203             format("/*\r\n"
22204                    "    \r\r\r\n"
22205                    "*/"));
22206 
22207   FormatStyle style = getLLVMStyle();
22208 
22209   style.DeriveLineEnding = true;
22210   style.UseCRLF = false;
22211   EXPECT_EQ("union FooBarBazQux {\n"
22212             "  int foo;\n"
22213             "  int bar;\n"
22214             "  int baz;\n"
22215             "};",
22216             format("union FooBarBazQux {\r\n"
22217                    "  int foo;\n"
22218                    "  int bar;\r\n"
22219                    "  int baz;\n"
22220                    "};",
22221                    style));
22222   style.UseCRLF = true;
22223   EXPECT_EQ("union FooBarBazQux {\r\n"
22224             "  int foo;\r\n"
22225             "  int bar;\r\n"
22226             "  int baz;\r\n"
22227             "};",
22228             format("union FooBarBazQux {\r\n"
22229                    "  int foo;\n"
22230                    "  int bar;\r\n"
22231                    "  int baz;\n"
22232                    "};",
22233                    style));
22234 
22235   style.DeriveLineEnding = false;
22236   style.UseCRLF = false;
22237   EXPECT_EQ("union FooBarBazQux {\n"
22238             "  int foo;\n"
22239             "  int bar;\n"
22240             "  int baz;\n"
22241             "  int qux;\n"
22242             "};",
22243             format("union FooBarBazQux {\r\n"
22244                    "  int foo;\n"
22245                    "  int bar;\r\n"
22246                    "  int baz;\n"
22247                    "  int qux;\r\n"
22248                    "};",
22249                    style));
22250   style.UseCRLF = true;
22251   EXPECT_EQ("union FooBarBazQux {\r\n"
22252             "  int foo;\r\n"
22253             "  int bar;\r\n"
22254             "  int baz;\r\n"
22255             "  int qux;\r\n"
22256             "};",
22257             format("union FooBarBazQux {\r\n"
22258                    "  int foo;\n"
22259                    "  int bar;\r\n"
22260                    "  int baz;\n"
22261                    "  int qux;\n"
22262                    "};",
22263                    style));
22264 
22265   style.DeriveLineEnding = true;
22266   style.UseCRLF = false;
22267   EXPECT_EQ("union FooBarBazQux {\r\n"
22268             "  int foo;\r\n"
22269             "  int bar;\r\n"
22270             "  int baz;\r\n"
22271             "  int qux;\r\n"
22272             "};",
22273             format("union FooBarBazQux {\r\n"
22274                    "  int foo;\n"
22275                    "  int bar;\r\n"
22276                    "  int baz;\n"
22277                    "  int qux;\r\n"
22278                    "};",
22279                    style));
22280   style.UseCRLF = true;
22281   EXPECT_EQ("union FooBarBazQux {\n"
22282             "  int foo;\n"
22283             "  int bar;\n"
22284             "  int baz;\n"
22285             "  int qux;\n"
22286             "};",
22287             format("union FooBarBazQux {\r\n"
22288                    "  int foo;\n"
22289                    "  int bar;\r\n"
22290                    "  int baz;\n"
22291                    "  int qux;\n"
22292                    "};",
22293                    style));
22294 }
22295 
22296 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
22297   verifyFormat("MY_CLASS(C) {\n"
22298                "  int i;\n"
22299                "  int j;\n"
22300                "};");
22301 }
22302 
22303 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
22304   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
22305   TwoIndent.ContinuationIndentWidth = 2;
22306 
22307   EXPECT_EQ("int i =\n"
22308             "  longFunction(\n"
22309             "    arg);",
22310             format("int i = longFunction(arg);", TwoIndent));
22311 
22312   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
22313   SixIndent.ContinuationIndentWidth = 6;
22314 
22315   EXPECT_EQ("int i =\n"
22316             "      longFunction(\n"
22317             "            arg);",
22318             format("int i = longFunction(arg);", SixIndent));
22319 }
22320 
22321 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
22322   FormatStyle Style = getLLVMStyle();
22323   verifyFormat("int Foo::getter(\n"
22324                "    //\n"
22325                ") const {\n"
22326                "  return foo;\n"
22327                "}",
22328                Style);
22329   verifyFormat("void Foo::setter(\n"
22330                "    //\n"
22331                ") {\n"
22332                "  foo = 1;\n"
22333                "}",
22334                Style);
22335 }
22336 
22337 TEST_F(FormatTest, SpacesInAngles) {
22338   FormatStyle Spaces = getLLVMStyle();
22339   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22340 
22341   verifyFormat("vector< ::std::string > x1;", Spaces);
22342   verifyFormat("Foo< int, Bar > x2;", Spaces);
22343   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
22344 
22345   verifyFormat("static_cast< int >(arg);", Spaces);
22346   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
22347   verifyFormat("f< int, float >();", Spaces);
22348   verifyFormat("template <> g() {}", Spaces);
22349   verifyFormat("template < std::vector< int > > f() {}", Spaces);
22350   verifyFormat("std::function< void(int, int) > fct;", Spaces);
22351   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
22352                Spaces);
22353 
22354   Spaces.Standard = FormatStyle::LS_Cpp03;
22355   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22356   verifyFormat("A< A< int > >();", Spaces);
22357 
22358   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22359   verifyFormat("A<A<int> >();", Spaces);
22360 
22361   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22362   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22363                Spaces);
22364   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22365                Spaces);
22366 
22367   verifyFormat("A<A<int> >();", Spaces);
22368   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22369   verifyFormat("A< A< int > >();", Spaces);
22370 
22371   Spaces.Standard = FormatStyle::LS_Cpp11;
22372   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22373   verifyFormat("A< A< int > >();", Spaces);
22374 
22375   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22376   verifyFormat("vector<::std::string> x4;", Spaces);
22377   verifyFormat("vector<int> x5;", Spaces);
22378   verifyFormat("Foo<int, Bar> x6;", Spaces);
22379   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22380 
22381   verifyFormat("A<A<int>>();", Spaces);
22382 
22383   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22384   verifyFormat("vector<::std::string> x4;", Spaces);
22385   verifyFormat("vector< ::std::string > x4;", Spaces);
22386   verifyFormat("vector<int> x5;", Spaces);
22387   verifyFormat("vector< int > x5;", Spaces);
22388   verifyFormat("Foo<int, Bar> x6;", Spaces);
22389   verifyFormat("Foo< int, Bar > x6;", Spaces);
22390   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22391   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22392 
22393   verifyFormat("A<A<int>>();", Spaces);
22394   verifyFormat("A< A< int > >();", Spaces);
22395   verifyFormat("A<A<int > >();", Spaces);
22396   verifyFormat("A< A< int>>();", Spaces);
22397 
22398   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22399   verifyFormat("// clang-format off\n"
22400                "foo<<<1, 1>>>();\n"
22401                "// clang-format on\n",
22402                Spaces);
22403   verifyFormat("// clang-format off\n"
22404                "foo< < <1, 1> > >();\n"
22405                "// clang-format on\n",
22406                Spaces);
22407 }
22408 
22409 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22410   FormatStyle Style = getLLVMStyle();
22411   Style.SpaceAfterTemplateKeyword = false;
22412   verifyFormat("template<int> void foo();", Style);
22413 }
22414 
22415 TEST_F(FormatTest, TripleAngleBrackets) {
22416   verifyFormat("f<<<1, 1>>>();");
22417   verifyFormat("f<<<1, 1, 1, s>>>();");
22418   verifyFormat("f<<<a, b, c, d>>>();");
22419   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22420   verifyFormat("f<param><<<1, 1>>>();");
22421   verifyFormat("f<1><<<1, 1>>>();");
22422   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22423   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22424                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22425   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22426                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22427 }
22428 
22429 TEST_F(FormatTest, MergeLessLessAtEnd) {
22430   verifyFormat("<<");
22431   EXPECT_EQ("< < <", format("\\\n<<<"));
22432   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22433                "aaallvm::outs() <<");
22434   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22435                "aaaallvm::outs()\n    <<");
22436 }
22437 
22438 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22439   std::string code = "#if A\n"
22440                      "#if B\n"
22441                      "a.\n"
22442                      "#endif\n"
22443                      "    a = 1;\n"
22444                      "#else\n"
22445                      "#endif\n"
22446                      "#if C\n"
22447                      "#else\n"
22448                      "#endif\n";
22449   EXPECT_EQ(code, format(code));
22450 }
22451 
22452 TEST_F(FormatTest, HandleConflictMarkers) {
22453   // Git/SVN conflict markers.
22454   EXPECT_EQ("int a;\n"
22455             "void f() {\n"
22456             "  callme(some(parameter1,\n"
22457             "<<<<<<< text by the vcs\n"
22458             "              parameter2),\n"
22459             "||||||| text by the vcs\n"
22460             "              parameter2),\n"
22461             "         parameter3,\n"
22462             "======= text by the vcs\n"
22463             "              parameter2, parameter3),\n"
22464             ">>>>>>> text by the vcs\n"
22465             "         otherparameter);\n",
22466             format("int a;\n"
22467                    "void f() {\n"
22468                    "  callme(some(parameter1,\n"
22469                    "<<<<<<< text by the vcs\n"
22470                    "  parameter2),\n"
22471                    "||||||| text by the vcs\n"
22472                    "  parameter2),\n"
22473                    "  parameter3,\n"
22474                    "======= text by the vcs\n"
22475                    "  parameter2,\n"
22476                    "  parameter3),\n"
22477                    ">>>>>>> text by the vcs\n"
22478                    "  otherparameter);\n"));
22479 
22480   // Perforce markers.
22481   EXPECT_EQ("void f() {\n"
22482             "  function(\n"
22483             ">>>> text by the vcs\n"
22484             "      parameter,\n"
22485             "==== text by the vcs\n"
22486             "      parameter,\n"
22487             "==== text by the vcs\n"
22488             "      parameter,\n"
22489             "<<<< text by the vcs\n"
22490             "      parameter);\n",
22491             format("void f() {\n"
22492                    "  function(\n"
22493                    ">>>> text by the vcs\n"
22494                    "  parameter,\n"
22495                    "==== text by the vcs\n"
22496                    "  parameter,\n"
22497                    "==== text by the vcs\n"
22498                    "  parameter,\n"
22499                    "<<<< text by the vcs\n"
22500                    "  parameter);\n"));
22501 
22502   EXPECT_EQ("<<<<<<<\n"
22503             "|||||||\n"
22504             "=======\n"
22505             ">>>>>>>",
22506             format("<<<<<<<\n"
22507                    "|||||||\n"
22508                    "=======\n"
22509                    ">>>>>>>"));
22510 
22511   EXPECT_EQ("<<<<<<<\n"
22512             "|||||||\n"
22513             "int i;\n"
22514             "=======\n"
22515             ">>>>>>>",
22516             format("<<<<<<<\n"
22517                    "|||||||\n"
22518                    "int i;\n"
22519                    "=======\n"
22520                    ">>>>>>>"));
22521 
22522   // FIXME: Handle parsing of macros around conflict markers correctly:
22523   EXPECT_EQ("#define Macro \\\n"
22524             "<<<<<<<\n"
22525             "Something \\\n"
22526             "|||||||\n"
22527             "Else \\\n"
22528             "=======\n"
22529             "Other \\\n"
22530             ">>>>>>>\n"
22531             "    End int i;\n",
22532             format("#define Macro \\\n"
22533                    "<<<<<<<\n"
22534                    "  Something \\\n"
22535                    "|||||||\n"
22536                    "  Else \\\n"
22537                    "=======\n"
22538                    "  Other \\\n"
22539                    ">>>>>>>\n"
22540                    "  End\n"
22541                    "int i;\n"));
22542 
22543   verifyFormat(R"(====
22544 #ifdef A
22545 a
22546 #else
22547 b
22548 #endif
22549 )");
22550 }
22551 
22552 TEST_F(FormatTest, DisableRegions) {
22553   EXPECT_EQ("int i;\n"
22554             "// clang-format off\n"
22555             "  int j;\n"
22556             "// clang-format on\n"
22557             "int k;",
22558             format(" int  i;\n"
22559                    "   // clang-format off\n"
22560                    "  int j;\n"
22561                    " // clang-format on\n"
22562                    "   int   k;"));
22563   EXPECT_EQ("int i;\n"
22564             "/* clang-format off */\n"
22565             "  int j;\n"
22566             "/* clang-format on */\n"
22567             "int k;",
22568             format(" int  i;\n"
22569                    "   /* clang-format off */\n"
22570                    "  int j;\n"
22571                    " /* clang-format on */\n"
22572                    "   int   k;"));
22573 
22574   // Don't reflow comments within disabled regions.
22575   EXPECT_EQ("// clang-format off\n"
22576             "// long long long long long long line\n"
22577             "/* clang-format on */\n"
22578             "/* long long long\n"
22579             " * long long long\n"
22580             " * line */\n"
22581             "int i;\n"
22582             "/* clang-format off */\n"
22583             "/* long long long long long long line */\n",
22584             format("// clang-format off\n"
22585                    "// long long long long long long line\n"
22586                    "/* clang-format on */\n"
22587                    "/* long long long long long long line */\n"
22588                    "int i;\n"
22589                    "/* clang-format off */\n"
22590                    "/* long long long long long long line */\n",
22591                    getLLVMStyleWithColumns(20)));
22592 }
22593 
22594 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22595   format("? ) =");
22596   verifyNoCrash("#define a\\\n /**/}");
22597 }
22598 
22599 TEST_F(FormatTest, FormatsTableGenCode) {
22600   FormatStyle Style = getLLVMStyle();
22601   Style.Language = FormatStyle::LK_TableGen;
22602   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22603 }
22604 
22605 TEST_F(FormatTest, ArrayOfTemplates) {
22606   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22607             format("auto a = new unique_ptr<int > [ 10];"));
22608 
22609   FormatStyle Spaces = getLLVMStyle();
22610   Spaces.SpacesInSquareBrackets = true;
22611   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22612             format("auto a = new unique_ptr<int > [10];", Spaces));
22613 }
22614 
22615 TEST_F(FormatTest, ArrayAsTemplateType) {
22616   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22617             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22618 
22619   FormatStyle Spaces = getLLVMStyle();
22620   Spaces.SpacesInSquareBrackets = true;
22621   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22622             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22623 }
22624 
22625 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22626 
22627 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22628   llvm::vfs::InMemoryFileSystem FS;
22629   auto Style1 = getStyle("file", "", "Google", "", &FS);
22630   ASSERT_TRUE((bool)Style1);
22631   ASSERT_EQ(*Style1, getGoogleStyle());
22632 }
22633 
22634 TEST(FormatStyle, GetStyleOfFile) {
22635   llvm::vfs::InMemoryFileSystem FS;
22636   // Test 1: format file in the same directory.
22637   ASSERT_TRUE(
22638       FS.addFile("/a/.clang-format", 0,
22639                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22640   ASSERT_TRUE(
22641       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22642   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22643   ASSERT_TRUE((bool)Style1);
22644   ASSERT_EQ(*Style1, getLLVMStyle());
22645 
22646   // Test 2.1: fallback to default.
22647   ASSERT_TRUE(
22648       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22649   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22650   ASSERT_TRUE((bool)Style2);
22651   ASSERT_EQ(*Style2, getMozillaStyle());
22652 
22653   // Test 2.2: no format on 'none' fallback style.
22654   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22655   ASSERT_TRUE((bool)Style2);
22656   ASSERT_EQ(*Style2, getNoStyle());
22657 
22658   // Test 2.3: format if config is found with no based style while fallback is
22659   // 'none'.
22660   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22661                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22662   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22663   ASSERT_TRUE((bool)Style2);
22664   ASSERT_EQ(*Style2, getLLVMStyle());
22665 
22666   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22667   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22668   ASSERT_TRUE((bool)Style2);
22669   ASSERT_EQ(*Style2, getLLVMStyle());
22670 
22671   // Test 3: format file in parent directory.
22672   ASSERT_TRUE(
22673       FS.addFile("/c/.clang-format", 0,
22674                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22675   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22676                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22677   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22678   ASSERT_TRUE((bool)Style3);
22679   ASSERT_EQ(*Style3, getGoogleStyle());
22680 
22681   // Test 4: error on invalid fallback style
22682   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22683   ASSERT_FALSE((bool)Style4);
22684   llvm::consumeError(Style4.takeError());
22685 
22686   // Test 5: error on invalid yaml on command line
22687   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22688   ASSERT_FALSE((bool)Style5);
22689   llvm::consumeError(Style5.takeError());
22690 
22691   // Test 6: error on invalid style
22692   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22693   ASSERT_FALSE((bool)Style6);
22694   llvm::consumeError(Style6.takeError());
22695 
22696   // Test 7: found config file, error on parsing it
22697   ASSERT_TRUE(
22698       FS.addFile("/d/.clang-format", 0,
22699                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22700                                                   "InvalidKey: InvalidValue")));
22701   ASSERT_TRUE(
22702       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22703   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22704   ASSERT_FALSE((bool)Style7a);
22705   llvm::consumeError(Style7a.takeError());
22706 
22707   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22708   ASSERT_TRUE((bool)Style7b);
22709 
22710   // Test 8: inferred per-language defaults apply.
22711   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22712   ASSERT_TRUE((bool)StyleTd);
22713   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22714 
22715   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22716   // fallback style.
22717   ASSERT_TRUE(FS.addFile(
22718       "/e/sub/.clang-format", 0,
22719       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22720                                        "ColumnLimit: 20")));
22721   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22722                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22723   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22724   ASSERT_TRUE(static_cast<bool>(Style9));
22725   ASSERT_EQ(*Style9, [] {
22726     auto Style = getNoStyle();
22727     Style.ColumnLimit = 20;
22728     return Style;
22729   }());
22730 
22731   // Test 9.1.2: propagate more than one level with no parent file.
22732   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22733                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22734   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22735                          llvm::MemoryBuffer::getMemBuffer(
22736                              "BasedOnStyle: InheritParentConfig\n"
22737                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22738   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22739 
22740   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22741   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22742   ASSERT_TRUE(static_cast<bool>(Style9));
22743   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22744     auto Style = getNoStyle();
22745     Style.ColumnLimit = 20;
22746     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22747     return Style;
22748   }());
22749 
22750   // Test 9.2: with LLVM fallback style
22751   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22752   ASSERT_TRUE(static_cast<bool>(Style9));
22753   ASSERT_EQ(*Style9, [] {
22754     auto Style = getLLVMStyle();
22755     Style.ColumnLimit = 20;
22756     return Style;
22757   }());
22758 
22759   // Test 9.3: with a parent file
22760   ASSERT_TRUE(
22761       FS.addFile("/e/.clang-format", 0,
22762                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
22763                                                   "UseTab: Always")));
22764   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22765   ASSERT_TRUE(static_cast<bool>(Style9));
22766   ASSERT_EQ(*Style9, [] {
22767     auto Style = getGoogleStyle();
22768     Style.ColumnLimit = 20;
22769     Style.UseTab = FormatStyle::UT_Always;
22770     return Style;
22771   }());
22772 
22773   // Test 9.4: propagate more than one level with a parent file.
22774   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
22775     auto Style = getGoogleStyle();
22776     Style.ColumnLimit = 20;
22777     Style.UseTab = FormatStyle::UT_Always;
22778     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22779     return Style;
22780   }();
22781 
22782   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22783   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22784   ASSERT_TRUE(static_cast<bool>(Style9));
22785   ASSERT_EQ(*Style9, SubSubStyle);
22786 
22787   // Test 9.5: use InheritParentConfig as style name
22788   Style9 =
22789       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
22790   ASSERT_TRUE(static_cast<bool>(Style9));
22791   ASSERT_EQ(*Style9, SubSubStyle);
22792 
22793   // Test 9.6: use command line style with inheritance
22794   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
22795                     "none", "", &FS);
22796   ASSERT_TRUE(static_cast<bool>(Style9));
22797   ASSERT_EQ(*Style9, SubSubStyle);
22798 
22799   // Test 9.7: use command line style with inheritance and own config
22800   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
22801                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
22802                     "/e/sub/code.cpp", "none", "", &FS);
22803   ASSERT_TRUE(static_cast<bool>(Style9));
22804   ASSERT_EQ(*Style9, SubSubStyle);
22805 
22806   // Test 9.8: use inheritance from a file without BasedOnStyle
22807   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
22808                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
22809   ASSERT_TRUE(
22810       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
22811                  llvm::MemoryBuffer::getMemBuffer(
22812                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
22813   // Make sure we do not use the fallback style
22814   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
22815   ASSERT_TRUE(static_cast<bool>(Style9));
22816   ASSERT_EQ(*Style9, [] {
22817     auto Style = getLLVMStyle();
22818     Style.ColumnLimit = 123;
22819     return Style;
22820   }());
22821 
22822   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
22823   ASSERT_TRUE(static_cast<bool>(Style9));
22824   ASSERT_EQ(*Style9, [] {
22825     auto Style = getLLVMStyle();
22826     Style.ColumnLimit = 123;
22827     Style.IndentWidth = 7;
22828     return Style;
22829   }());
22830 
22831   // Test 9.9: use inheritance from a specific config file.
22832   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
22833                     "none", "", &FS);
22834   ASSERT_TRUE(static_cast<bool>(Style9));
22835   ASSERT_EQ(*Style9, SubSubStyle);
22836 }
22837 
22838 TEST(FormatStyle, GetStyleOfSpecificFile) {
22839   llvm::vfs::InMemoryFileSystem FS;
22840   // Specify absolute path to a format file in a parent directory.
22841   ASSERT_TRUE(
22842       FS.addFile("/e/.clang-format", 0,
22843                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22844   ASSERT_TRUE(
22845       FS.addFile("/e/explicit.clang-format", 0,
22846                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22847   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
22848                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22849   auto Style = getStyle("file:/e/explicit.clang-format",
22850                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22851   ASSERT_TRUE(static_cast<bool>(Style));
22852   ASSERT_EQ(*Style, getGoogleStyle());
22853 
22854   // Specify relative path to a format file.
22855   ASSERT_TRUE(
22856       FS.addFile("../../e/explicit.clang-format", 0,
22857                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22858   Style = getStyle("file:../../e/explicit.clang-format",
22859                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22860   ASSERT_TRUE(static_cast<bool>(Style));
22861   ASSERT_EQ(*Style, getGoogleStyle());
22862 
22863   // Specify path to a format file that does not exist.
22864   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
22865                    "LLVM", "", &FS);
22866   ASSERT_FALSE(static_cast<bool>(Style));
22867   llvm::consumeError(Style.takeError());
22868 
22869   // Specify path to a file on the filesystem.
22870   SmallString<128> FormatFilePath;
22871   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
22872       "FormatFileTest", "tpl", FormatFilePath);
22873   EXPECT_FALSE((bool)ECF);
22874   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
22875   EXPECT_FALSE((bool)ECF);
22876   FormatFileTest << "BasedOnStyle: Google\n";
22877   FormatFileTest.close();
22878 
22879   SmallString<128> TestFilePath;
22880   std::error_code ECT =
22881       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
22882   EXPECT_FALSE((bool)ECT);
22883   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
22884   CodeFileTest << "int i;\n";
22885   CodeFileTest.close();
22886 
22887   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
22888   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
22889 
22890   llvm::sys::fs::remove(FormatFilePath.c_str());
22891   llvm::sys::fs::remove(TestFilePath.c_str());
22892   ASSERT_TRUE(static_cast<bool>(Style));
22893   ASSERT_EQ(*Style, getGoogleStyle());
22894 }
22895 
22896 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
22897   // Column limit is 20.
22898   std::string Code = "Type *a =\n"
22899                      "    new Type();\n"
22900                      "g(iiiii, 0, jjjjj,\n"
22901                      "  0, kkkkk, 0, mm);\n"
22902                      "int  bad     = format   ;";
22903   std::string Expected = "auto a = new Type();\n"
22904                          "g(iiiii, nullptr,\n"
22905                          "  jjjjj, nullptr,\n"
22906                          "  kkkkk, nullptr,\n"
22907                          "  mm);\n"
22908                          "int  bad     = format   ;";
22909   FileID ID = Context.createInMemoryFile("format.cpp", Code);
22910   tooling::Replacements Replaces = toReplacements(
22911       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
22912                             "auto "),
22913        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
22914                             "nullptr"),
22915        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
22916                             "nullptr"),
22917        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
22918                             "nullptr")});
22919 
22920   FormatStyle Style = getLLVMStyle();
22921   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
22922   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22923   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22924       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22925   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22926   EXPECT_TRUE(static_cast<bool>(Result));
22927   EXPECT_EQ(Expected, *Result);
22928 }
22929 
22930 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
22931   std::string Code = "#include \"a.h\"\n"
22932                      "#include \"c.h\"\n"
22933                      "\n"
22934                      "int main() {\n"
22935                      "  return 0;\n"
22936                      "}";
22937   std::string Expected = "#include \"a.h\"\n"
22938                          "#include \"b.h\"\n"
22939                          "#include \"c.h\"\n"
22940                          "\n"
22941                          "int main() {\n"
22942                          "  return 0;\n"
22943                          "}";
22944   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
22945   tooling::Replacements Replaces = toReplacements(
22946       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
22947                             "#include \"b.h\"\n")});
22948 
22949   FormatStyle Style = getLLVMStyle();
22950   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
22951   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22952   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22953       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22954   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22955   EXPECT_TRUE(static_cast<bool>(Result));
22956   EXPECT_EQ(Expected, *Result);
22957 }
22958 
22959 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
22960   EXPECT_EQ("using std::cin;\n"
22961             "using std::cout;",
22962             format("using std::cout;\n"
22963                    "using std::cin;",
22964                    getGoogleStyle()));
22965 }
22966 
22967 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
22968   FormatStyle Style = getLLVMStyle();
22969   Style.Standard = FormatStyle::LS_Cpp03;
22970   // cpp03 recognize this string as identifier u8 and literal character 'a'
22971   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
22972 }
22973 
22974 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
22975   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
22976   // all modes, including C++11, C++14 and C++17
22977   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
22978 }
22979 
22980 TEST_F(FormatTest, DoNotFormatLikelyXml) {
22981   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
22982   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
22983 }
22984 
22985 TEST_F(FormatTest, StructuredBindings) {
22986   // Structured bindings is a C++17 feature.
22987   // all modes, including C++11, C++14 and C++17
22988   verifyFormat("auto [a, b] = f();");
22989   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
22990   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
22991   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
22992   EXPECT_EQ("auto const volatile [a, b] = f();",
22993             format("auto  const   volatile[a, b] = f();"));
22994   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
22995   EXPECT_EQ("auto &[a, b, c] = f();",
22996             format("auto   &[  a  ,  b,c   ] = f();"));
22997   EXPECT_EQ("auto &&[a, b, c] = f();",
22998             format("auto   &&[  a  ,  b,c   ] = f();"));
22999   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
23000   EXPECT_EQ("auto const volatile &&[a, b] = f();",
23001             format("auto  const  volatile  &&[a, b] = f();"));
23002   EXPECT_EQ("auto const &&[a, b] = f();",
23003             format("auto  const   &&  [a, b] = f();"));
23004   EXPECT_EQ("const auto &[a, b] = f();",
23005             format("const  auto  &  [a, b] = f();"));
23006   EXPECT_EQ("const auto volatile &&[a, b] = f();",
23007             format("const  auto   volatile  &&[a, b] = f();"));
23008   EXPECT_EQ("volatile const auto &&[a, b] = f();",
23009             format("volatile  const  auto   &&[a, b] = f();"));
23010   EXPECT_EQ("const auto &&[a, b] = f();",
23011             format("const  auto  &&  [a, b] = f();"));
23012 
23013   // Make sure we don't mistake structured bindings for lambdas.
23014   FormatStyle PointerMiddle = getLLVMStyle();
23015   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
23016   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
23017   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
23018   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
23019   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
23020   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
23021   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
23022   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
23023   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
23024   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
23025   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
23026   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
23027   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
23028 
23029   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
23030             format("for (const auto   &&   [a, b] : some_range) {\n}"));
23031   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
23032             format("for (const auto   &   [a, b] : some_range) {\n}"));
23033   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
23034             format("for (const auto[a, b] : some_range) {\n}"));
23035   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
23036   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
23037   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
23038   EXPECT_EQ("auto const &[x, y](expr);",
23039             format("auto  const  &  [x,y]  (expr);"));
23040   EXPECT_EQ("auto const &&[x, y](expr);",
23041             format("auto  const  &&  [x,y]  (expr);"));
23042   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
23043   EXPECT_EQ("auto const &[x, y]{expr};",
23044             format("auto  const  &  [x,y]  {expr};"));
23045   EXPECT_EQ("auto const &&[x, y]{expr};",
23046             format("auto  const  &&  [x,y]  {expr};"));
23047 
23048   FormatStyle Spaces = getLLVMStyle();
23049   Spaces.SpacesInSquareBrackets = true;
23050   verifyFormat("auto [ a, b ] = f();", Spaces);
23051   verifyFormat("auto &&[ a, b ] = f();", Spaces);
23052   verifyFormat("auto &[ a, b ] = f();", Spaces);
23053   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
23054   verifyFormat("auto const &[ a, b ] = f();", Spaces);
23055 }
23056 
23057 TEST_F(FormatTest, FileAndCode) {
23058   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
23059   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
23060   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
23061   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
23062   EXPECT_EQ(FormatStyle::LK_ObjC,
23063             guessLanguage("foo.h", "@interface Foo\n@end\n"));
23064   EXPECT_EQ(
23065       FormatStyle::LK_ObjC,
23066       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
23067   EXPECT_EQ(FormatStyle::LK_ObjC,
23068             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
23069   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
23070   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
23071   EXPECT_EQ(FormatStyle::LK_ObjC,
23072             guessLanguage("foo", "@interface Foo\n@end\n"));
23073   EXPECT_EQ(FormatStyle::LK_ObjC,
23074             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
23075   EXPECT_EQ(
23076       FormatStyle::LK_ObjC,
23077       guessLanguage("foo.h",
23078                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
23079   EXPECT_EQ(
23080       FormatStyle::LK_Cpp,
23081       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
23082   // Only one of the two preprocessor regions has ObjC-like code.
23083   EXPECT_EQ(FormatStyle::LK_ObjC,
23084             guessLanguage("foo.h", "#if A\n"
23085                                    "#define B() C\n"
23086                                    "#else\n"
23087                                    "#define B() [NSString a:@\"\"]\n"
23088                                    "#endif\n"));
23089 }
23090 
23091 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
23092   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
23093   EXPECT_EQ(FormatStyle::LK_ObjC,
23094             guessLanguage("foo.h", "array[[calculator getIndex]];"));
23095   EXPECT_EQ(FormatStyle::LK_Cpp,
23096             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
23097   EXPECT_EQ(
23098       FormatStyle::LK_Cpp,
23099       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
23100   EXPECT_EQ(FormatStyle::LK_ObjC,
23101             guessLanguage("foo.h", "[[noreturn foo] bar];"));
23102   EXPECT_EQ(FormatStyle::LK_Cpp,
23103             guessLanguage("foo.h", "[[clang::fallthrough]];"));
23104   EXPECT_EQ(FormatStyle::LK_ObjC,
23105             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
23106   EXPECT_EQ(FormatStyle::LK_Cpp,
23107             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
23108   EXPECT_EQ(FormatStyle::LK_Cpp,
23109             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
23110   EXPECT_EQ(FormatStyle::LK_ObjC,
23111             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
23112   EXPECT_EQ(FormatStyle::LK_Cpp,
23113             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
23114   EXPECT_EQ(
23115       FormatStyle::LK_Cpp,
23116       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
23117   EXPECT_EQ(
23118       FormatStyle::LK_Cpp,
23119       guessLanguage("foo.h",
23120                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
23121   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
23122 }
23123 
23124 TEST_F(FormatTest, GuessLanguageWithCaret) {
23125   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
23126   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
23127   EXPECT_EQ(FormatStyle::LK_ObjC,
23128             guessLanguage("foo.h", "int(^)(char, float);"));
23129   EXPECT_EQ(FormatStyle::LK_ObjC,
23130             guessLanguage("foo.h", "int(^foo)(char, float);"));
23131   EXPECT_EQ(FormatStyle::LK_ObjC,
23132             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
23133   EXPECT_EQ(FormatStyle::LK_ObjC,
23134             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
23135   EXPECT_EQ(
23136       FormatStyle::LK_ObjC,
23137       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
23138 }
23139 
23140 TEST_F(FormatTest, GuessLanguageWithPragmas) {
23141   EXPECT_EQ(FormatStyle::LK_Cpp,
23142             guessLanguage("foo.h", "__pragma(warning(disable:))"));
23143   EXPECT_EQ(FormatStyle::LK_Cpp,
23144             guessLanguage("foo.h", "#pragma(warning(disable:))"));
23145   EXPECT_EQ(FormatStyle::LK_Cpp,
23146             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
23147 }
23148 
23149 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
23150   // ASM symbolic names are identifiers that must be surrounded by [] without
23151   // space in between:
23152   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
23153 
23154   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
23155   verifyFormat(R"(//
23156 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
23157 )");
23158 
23159   // A list of several ASM symbolic names.
23160   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
23161 
23162   // ASM symbolic names in inline ASM with inputs and outputs.
23163   verifyFormat(R"(//
23164 asm("cmoveq %1, %2, %[result]"
23165     : [result] "=r"(result)
23166     : "r"(test), "r"(new), "[result]"(old));
23167 )");
23168 
23169   // ASM symbolic names in inline ASM with no outputs.
23170   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
23171 }
23172 
23173 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
23174   EXPECT_EQ(FormatStyle::LK_Cpp,
23175             guessLanguage("foo.h", "void f() {\n"
23176                                    "  asm (\"mov %[e], %[d]\"\n"
23177                                    "     : [d] \"=rm\" (d)\n"
23178                                    "       [e] \"rm\" (*e));\n"
23179                                    "}"));
23180   EXPECT_EQ(FormatStyle::LK_Cpp,
23181             guessLanguage("foo.h", "void f() {\n"
23182                                    "  _asm (\"mov %[e], %[d]\"\n"
23183                                    "     : [d] \"=rm\" (d)\n"
23184                                    "       [e] \"rm\" (*e));\n"
23185                                    "}"));
23186   EXPECT_EQ(FormatStyle::LK_Cpp,
23187             guessLanguage("foo.h", "void f() {\n"
23188                                    "  __asm (\"mov %[e], %[d]\"\n"
23189                                    "     : [d] \"=rm\" (d)\n"
23190                                    "       [e] \"rm\" (*e));\n"
23191                                    "}"));
23192   EXPECT_EQ(FormatStyle::LK_Cpp,
23193             guessLanguage("foo.h", "void f() {\n"
23194                                    "  __asm__ (\"mov %[e], %[d]\"\n"
23195                                    "     : [d] \"=rm\" (d)\n"
23196                                    "       [e] \"rm\" (*e));\n"
23197                                    "}"));
23198   EXPECT_EQ(FormatStyle::LK_Cpp,
23199             guessLanguage("foo.h", "void f() {\n"
23200                                    "  asm (\"mov %[e], %[d]\"\n"
23201                                    "     : [d] \"=rm\" (d),\n"
23202                                    "       [e] \"rm\" (*e));\n"
23203                                    "}"));
23204   EXPECT_EQ(FormatStyle::LK_Cpp,
23205             guessLanguage("foo.h", "void f() {\n"
23206                                    "  asm volatile (\"mov %[e], %[d]\"\n"
23207                                    "     : [d] \"=rm\" (d)\n"
23208                                    "       [e] \"rm\" (*e));\n"
23209                                    "}"));
23210 }
23211 
23212 TEST_F(FormatTest, GuessLanguageWithChildLines) {
23213   EXPECT_EQ(FormatStyle::LK_Cpp,
23214             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
23215   EXPECT_EQ(FormatStyle::LK_ObjC,
23216             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
23217   EXPECT_EQ(
23218       FormatStyle::LK_Cpp,
23219       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
23220   EXPECT_EQ(
23221       FormatStyle::LK_ObjC,
23222       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
23223 }
23224 
23225 TEST_F(FormatTest, TypenameMacros) {
23226   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
23227 
23228   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
23229   FormatStyle Google = getGoogleStyleWithColumns(0);
23230   Google.TypenameMacros = TypenameMacros;
23231   verifyFormat("struct foo {\n"
23232                "  int bar;\n"
23233                "  TAILQ_ENTRY(a) bleh;\n"
23234                "};",
23235                Google);
23236 
23237   FormatStyle Macros = getLLVMStyle();
23238   Macros.TypenameMacros = TypenameMacros;
23239 
23240   verifyFormat("STACK_OF(int) a;", Macros);
23241   verifyFormat("STACK_OF(int) *a;", Macros);
23242   verifyFormat("STACK_OF(int const *) *a;", Macros);
23243   verifyFormat("STACK_OF(int *const) *a;", Macros);
23244   verifyFormat("STACK_OF(int, string) a;", Macros);
23245   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
23246   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
23247   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
23248   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
23249   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
23250   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
23251 
23252   Macros.PointerAlignment = FormatStyle::PAS_Left;
23253   verifyFormat("STACK_OF(int)* a;", Macros);
23254   verifyFormat("STACK_OF(int*)* a;", Macros);
23255   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
23256   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
23257   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
23258 }
23259 
23260 TEST_F(FormatTest, AtomicQualifier) {
23261   // Check that we treate _Atomic as a type and not a function call
23262   FormatStyle Google = getGoogleStyleWithColumns(0);
23263   verifyFormat("struct foo {\n"
23264                "  int a1;\n"
23265                "  _Atomic(a) a2;\n"
23266                "  _Atomic(_Atomic(int) *const) a3;\n"
23267                "};",
23268                Google);
23269   verifyFormat("_Atomic(uint64_t) a;");
23270   verifyFormat("_Atomic(uint64_t) *a;");
23271   verifyFormat("_Atomic(uint64_t const *) *a;");
23272   verifyFormat("_Atomic(uint64_t *const) *a;");
23273   verifyFormat("_Atomic(const uint64_t *) *a;");
23274   verifyFormat("_Atomic(uint64_t) a;");
23275   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
23276   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
23277   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
23278   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
23279 
23280   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
23281   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
23282   FormatStyle Style = getLLVMStyle();
23283   Style.PointerAlignment = FormatStyle::PAS_Left;
23284   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
23285   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
23286   verifyFormat("_Atomic(int)* a;", Style);
23287   verifyFormat("_Atomic(int*)* a;", Style);
23288   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
23289 
23290   Style.SpacesInCStyleCastParentheses = true;
23291   Style.SpacesInParentheses = false;
23292   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
23293   Style.SpacesInCStyleCastParentheses = false;
23294   Style.SpacesInParentheses = true;
23295   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
23296   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
23297 }
23298 
23299 TEST_F(FormatTest, AmbersandInLamda) {
23300   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
23301   FormatStyle AlignStyle = getLLVMStyle();
23302   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
23303   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23304   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
23305   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23306 }
23307 
23308 TEST_F(FormatTest, SpacesInConditionalStatement) {
23309   FormatStyle Spaces = getLLVMStyle();
23310   Spaces.IfMacros.clear();
23311   Spaces.IfMacros.push_back("MYIF");
23312   Spaces.SpacesInConditionalStatement = true;
23313   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
23314   verifyFormat("if ( !a )\n  return;", Spaces);
23315   verifyFormat("if ( a )\n  return;", Spaces);
23316   verifyFormat("if constexpr ( a )\n  return;", Spaces);
23317   verifyFormat("MYIF ( a )\n  return;", Spaces);
23318   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
23319   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
23320   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
23321   verifyFormat("while ( a )\n  return;", Spaces);
23322   verifyFormat("while ( (a && b) )\n  return;", Spaces);
23323   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
23324   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
23325   // Check that space on the left of "::" is inserted as expected at beginning
23326   // of condition.
23327   verifyFormat("while ( ::func() )\n  return;", Spaces);
23328 
23329   // Check impact of ControlStatementsExceptControlMacros is honored.
23330   Spaces.SpaceBeforeParens =
23331       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
23332   verifyFormat("MYIF( a )\n  return;", Spaces);
23333   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
23334   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
23335 }
23336 
23337 TEST_F(FormatTest, AlternativeOperators) {
23338   // Test case for ensuring alternate operators are not
23339   // combined with their right most neighbour.
23340   verifyFormat("int a and b;");
23341   verifyFormat("int a and_eq b;");
23342   verifyFormat("int a bitand b;");
23343   verifyFormat("int a bitor b;");
23344   verifyFormat("int a compl b;");
23345   verifyFormat("int a not b;");
23346   verifyFormat("int a not_eq b;");
23347   verifyFormat("int a or b;");
23348   verifyFormat("int a xor b;");
23349   verifyFormat("int a xor_eq b;");
23350   verifyFormat("return this not_eq bitand other;");
23351   verifyFormat("bool operator not_eq(const X bitand other)");
23352 
23353   verifyFormat("int a and 5;");
23354   verifyFormat("int a and_eq 5;");
23355   verifyFormat("int a bitand 5;");
23356   verifyFormat("int a bitor 5;");
23357   verifyFormat("int a compl 5;");
23358   verifyFormat("int a not 5;");
23359   verifyFormat("int a not_eq 5;");
23360   verifyFormat("int a or 5;");
23361   verifyFormat("int a xor 5;");
23362   verifyFormat("int a xor_eq 5;");
23363 
23364   verifyFormat("int a compl(5);");
23365   verifyFormat("int a not(5);");
23366 
23367   /* FIXME handle alternate tokens
23368    * https://en.cppreference.com/w/cpp/language/operator_alternative
23369   // alternative tokens
23370   verifyFormat("compl foo();");     //  ~foo();
23371   verifyFormat("foo() <%%>;");      // foo();
23372   verifyFormat("void foo() <%%>;"); // void foo(){}
23373   verifyFormat("int a <:1:>;");     // int a[1];[
23374   verifyFormat("%:define ABC abc"); // #define ABC abc
23375   verifyFormat("%:%:");             // ##
23376   */
23377 }
23378 
23379 TEST_F(FormatTest, STLWhileNotDefineChed) {
23380   verifyFormat("#if defined(while)\n"
23381                "#define while EMIT WARNING C4005\n"
23382                "#endif // while");
23383 }
23384 
23385 TEST_F(FormatTest, OperatorSpacing) {
23386   FormatStyle Style = getLLVMStyle();
23387   Style.PointerAlignment = FormatStyle::PAS_Right;
23388   verifyFormat("Foo::operator*();", Style);
23389   verifyFormat("Foo::operator void *();", Style);
23390   verifyFormat("Foo::operator void **();", Style);
23391   verifyFormat("Foo::operator void *&();", Style);
23392   verifyFormat("Foo::operator void *&&();", Style);
23393   verifyFormat("Foo::operator void const *();", Style);
23394   verifyFormat("Foo::operator void const **();", Style);
23395   verifyFormat("Foo::operator void const *&();", Style);
23396   verifyFormat("Foo::operator void const *&&();", Style);
23397   verifyFormat("Foo::operator()(void *);", Style);
23398   verifyFormat("Foo::operator*(void *);", Style);
23399   verifyFormat("Foo::operator*();", Style);
23400   verifyFormat("Foo::operator**();", Style);
23401   verifyFormat("Foo::operator&();", Style);
23402   verifyFormat("Foo::operator<int> *();", Style);
23403   verifyFormat("Foo::operator<Foo> *();", Style);
23404   verifyFormat("Foo::operator<int> **();", Style);
23405   verifyFormat("Foo::operator<Foo> **();", Style);
23406   verifyFormat("Foo::operator<int> &();", Style);
23407   verifyFormat("Foo::operator<Foo> &();", Style);
23408   verifyFormat("Foo::operator<int> &&();", Style);
23409   verifyFormat("Foo::operator<Foo> &&();", Style);
23410   verifyFormat("Foo::operator<int> *&();", Style);
23411   verifyFormat("Foo::operator<Foo> *&();", Style);
23412   verifyFormat("Foo::operator<int> *&&();", Style);
23413   verifyFormat("Foo::operator<Foo> *&&();", Style);
23414   verifyFormat("operator*(int (*)(), class Foo);", Style);
23415 
23416   verifyFormat("Foo::operator&();", Style);
23417   verifyFormat("Foo::operator void &();", Style);
23418   verifyFormat("Foo::operator void const &();", Style);
23419   verifyFormat("Foo::operator()(void &);", Style);
23420   verifyFormat("Foo::operator&(void &);", Style);
23421   verifyFormat("Foo::operator&();", Style);
23422   verifyFormat("operator&(int (&)(), class Foo);", Style);
23423   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23424 
23425   verifyFormat("Foo::operator&&();", Style);
23426   verifyFormat("Foo::operator**();", Style);
23427   verifyFormat("Foo::operator void &&();", Style);
23428   verifyFormat("Foo::operator void const &&();", Style);
23429   verifyFormat("Foo::operator()(void &&);", Style);
23430   verifyFormat("Foo::operator&&(void &&);", Style);
23431   verifyFormat("Foo::operator&&();", Style);
23432   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23433   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23434   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23435                Style);
23436   verifyFormat("operator void **()", Style);
23437   verifyFormat("operator const FooRight<Object> &()", Style);
23438   verifyFormat("operator const FooRight<Object> *()", Style);
23439   verifyFormat("operator const FooRight<Object> **()", Style);
23440   verifyFormat("operator const FooRight<Object> *&()", Style);
23441   verifyFormat("operator const FooRight<Object> *&&()", Style);
23442 
23443   Style.PointerAlignment = FormatStyle::PAS_Left;
23444   verifyFormat("Foo::operator*();", Style);
23445   verifyFormat("Foo::operator**();", Style);
23446   verifyFormat("Foo::operator void*();", Style);
23447   verifyFormat("Foo::operator void**();", Style);
23448   verifyFormat("Foo::operator void*&();", Style);
23449   verifyFormat("Foo::operator void*&&();", Style);
23450   verifyFormat("Foo::operator void const*();", Style);
23451   verifyFormat("Foo::operator void const**();", Style);
23452   verifyFormat("Foo::operator void const*&();", Style);
23453   verifyFormat("Foo::operator void const*&&();", Style);
23454   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23455   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23456   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23457   verifyFormat("Foo::operator()(void*);", Style);
23458   verifyFormat("Foo::operator*(void*);", Style);
23459   verifyFormat("Foo::operator*();", Style);
23460   verifyFormat("Foo::operator<int>*();", Style);
23461   verifyFormat("Foo::operator<Foo>*();", Style);
23462   verifyFormat("Foo::operator<int>**();", Style);
23463   verifyFormat("Foo::operator<Foo>**();", Style);
23464   verifyFormat("Foo::operator<Foo>*&();", Style);
23465   verifyFormat("Foo::operator<int>&();", Style);
23466   verifyFormat("Foo::operator<Foo>&();", Style);
23467   verifyFormat("Foo::operator<int>&&();", Style);
23468   verifyFormat("Foo::operator<Foo>&&();", Style);
23469   verifyFormat("Foo::operator<int>*&();", Style);
23470   verifyFormat("Foo::operator<Foo>*&();", Style);
23471   verifyFormat("operator*(int (*)(), class Foo);", Style);
23472 
23473   verifyFormat("Foo::operator&();", Style);
23474   verifyFormat("Foo::operator void&();", Style);
23475   verifyFormat("Foo::operator void const&();", Style);
23476   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23477   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23478   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
23479   verifyFormat("Foo::operator()(void&);", Style);
23480   verifyFormat("Foo::operator&(void&);", Style);
23481   verifyFormat("Foo::operator&();", Style);
23482   verifyFormat("operator&(int (&)(), class Foo);", Style);
23483   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23484   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23485 
23486   verifyFormat("Foo::operator&&();", Style);
23487   verifyFormat("Foo::operator void&&();", Style);
23488   verifyFormat("Foo::operator void const&&();", Style);
23489   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23490   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23491   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23492   verifyFormat("Foo::operator()(void&&);", Style);
23493   verifyFormat("Foo::operator&&(void&&);", Style);
23494   verifyFormat("Foo::operator&&();", Style);
23495   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23496   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23497   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23498                Style);
23499   verifyFormat("operator void**()", Style);
23500   verifyFormat("operator const FooLeft<Object>&()", Style);
23501   verifyFormat("operator const FooLeft<Object>*()", Style);
23502   verifyFormat("operator const FooLeft<Object>**()", Style);
23503   verifyFormat("operator const FooLeft<Object>*&()", Style);
23504   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23505 
23506   // PR45107
23507   verifyFormat("operator Vector<String>&();", Style);
23508   verifyFormat("operator const Vector<String>&();", Style);
23509   verifyFormat("operator foo::Bar*();", Style);
23510   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23511   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23512                Style);
23513 
23514   Style.PointerAlignment = FormatStyle::PAS_Middle;
23515   verifyFormat("Foo::operator*();", Style);
23516   verifyFormat("Foo::operator void *();", Style);
23517   verifyFormat("Foo::operator()(void *);", Style);
23518   verifyFormat("Foo::operator*(void *);", Style);
23519   verifyFormat("Foo::operator*();", Style);
23520   verifyFormat("operator*(int (*)(), class Foo);", Style);
23521 
23522   verifyFormat("Foo::operator&();", Style);
23523   verifyFormat("Foo::operator void &();", Style);
23524   verifyFormat("Foo::operator void const &();", Style);
23525   verifyFormat("Foo::operator()(void &);", Style);
23526   verifyFormat("Foo::operator&(void &);", Style);
23527   verifyFormat("Foo::operator&();", Style);
23528   verifyFormat("operator&(int (&)(), class Foo);", Style);
23529 
23530   verifyFormat("Foo::operator&&();", Style);
23531   verifyFormat("Foo::operator void &&();", Style);
23532   verifyFormat("Foo::operator void const &&();", Style);
23533   verifyFormat("Foo::operator()(void &&);", Style);
23534   verifyFormat("Foo::operator&&(void &&);", Style);
23535   verifyFormat("Foo::operator&&();", Style);
23536   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23537 }
23538 
23539 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23540   FormatStyle Style = getLLVMStyle();
23541   // PR46157
23542   verifyFormat("foo(operator+, -42);", Style);
23543   verifyFormat("foo(operator++, -42);", Style);
23544   verifyFormat("foo(operator--, -42);", Style);
23545   verifyFormat("foo(-42, operator--);", Style);
23546   verifyFormat("foo(-42, operator, );", Style);
23547   verifyFormat("foo(operator, , -42);", Style);
23548 }
23549 
23550 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23551   FormatStyle Style = getLLVMStyle();
23552   Style.WhitespaceSensitiveMacros.push_back("FOO");
23553 
23554   // Don't use the helpers here, since 'mess up' will change the whitespace
23555   // and these are all whitespace sensitive by definition
23556   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23557             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23558   EXPECT_EQ(
23559       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23560       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23561   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23562             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23563   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23564             "       Still=Intentional);",
23565             format("FOO(String-ized&Messy+But,: :\n"
23566                    "       Still=Intentional);",
23567                    Style));
23568   Style.AlignConsecutiveAssignments.Enabled = true;
23569   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
23570             "       Still=Intentional);",
23571             format("FOO(String-ized=&Messy+But,: :\n"
23572                    "       Still=Intentional);",
23573                    Style));
23574 
23575   Style.ColumnLimit = 21;
23576   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23577             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23578 }
23579 
23580 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23581   // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
23582   // test its interaction with line wrapping
23583   FormatStyle Style = getLLVMStyleWithColumns(80);
23584   verifyFormat("namespace {\n"
23585                "int i;\n"
23586                "int j;\n"
23587                "} // namespace",
23588                Style);
23589 
23590   verifyFormat("namespace AAA {\n"
23591                "int i;\n"
23592                "int j;\n"
23593                "} // namespace AAA",
23594                Style);
23595 
23596   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23597             "int i;\n"
23598             "int j;\n"
23599             "} // namespace Averyveryveryverylongnamespace",
23600             format("namespace Averyveryveryverylongnamespace {\n"
23601                    "int i;\n"
23602                    "int j;\n"
23603                    "}",
23604                    Style));
23605 
23606   EXPECT_EQ(
23607       "namespace "
23608       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23609       "    went::mad::now {\n"
23610       "int i;\n"
23611       "int j;\n"
23612       "} // namespace\n"
23613       "  // "
23614       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23615       "went::mad::now",
23616       format("namespace "
23617              "would::it::save::you::a::lot::of::time::if_::i::"
23618              "just::gave::up::and_::went::mad::now {\n"
23619              "int i;\n"
23620              "int j;\n"
23621              "}",
23622              Style));
23623 
23624   // This used to duplicate the comment again and again on subsequent runs
23625   EXPECT_EQ(
23626       "namespace "
23627       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23628       "    went::mad::now {\n"
23629       "int i;\n"
23630       "int j;\n"
23631       "} // namespace\n"
23632       "  // "
23633       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23634       "went::mad::now",
23635       format("namespace "
23636              "would::it::save::you::a::lot::of::time::if_::i::"
23637              "just::gave::up::and_::went::mad::now {\n"
23638              "int i;\n"
23639              "int j;\n"
23640              "} // namespace\n"
23641              "  // "
23642              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23643              "and_::went::mad::now",
23644              Style));
23645 }
23646 
23647 TEST_F(FormatTest, LikelyUnlikely) {
23648   FormatStyle Style = getLLVMStyle();
23649 
23650   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23651                "  return 29;\n"
23652                "}",
23653                Style);
23654 
23655   verifyFormat("if (argc > 5) [[likely]] {\n"
23656                "  return 29;\n"
23657                "}",
23658                Style);
23659 
23660   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23661                "  return 29;\n"
23662                "} else [[likely]] {\n"
23663                "  return 42;\n"
23664                "}\n",
23665                Style);
23666 
23667   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23668                "  return 29;\n"
23669                "} else if (argc > 10) [[likely]] {\n"
23670                "  return 99;\n"
23671                "} else {\n"
23672                "  return 42;\n"
23673                "}\n",
23674                Style);
23675 
23676   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23677                "  return 29;\n"
23678                "}",
23679                Style);
23680 
23681   verifyFormat("if (argc > 5) [[unlikely]]\n"
23682                "  return 29;\n",
23683                Style);
23684   verifyFormat("if (argc > 5) [[likely]]\n"
23685                "  return 29;\n",
23686                Style);
23687 
23688   Style.AttributeMacros.push_back("UNLIKELY");
23689   Style.AttributeMacros.push_back("LIKELY");
23690   verifyFormat("if (argc > 5) UNLIKELY\n"
23691                "  return 29;\n",
23692                Style);
23693 
23694   verifyFormat("if (argc > 5) UNLIKELY {\n"
23695                "  return 29;\n"
23696                "}",
23697                Style);
23698   verifyFormat("if (argc > 5) UNLIKELY {\n"
23699                "  return 29;\n"
23700                "} else [[likely]] {\n"
23701                "  return 42;\n"
23702                "}\n",
23703                Style);
23704   verifyFormat("if (argc > 5) UNLIKELY {\n"
23705                "  return 29;\n"
23706                "} else LIKELY {\n"
23707                "  return 42;\n"
23708                "}\n",
23709                Style);
23710   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23711                "  return 29;\n"
23712                "} else LIKELY {\n"
23713                "  return 42;\n"
23714                "}\n",
23715                Style);
23716 }
23717 
23718 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23719   verifyFormat("Constructor()\n"
23720                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23721                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
23722                "aaaaaaaaaaaaaaaaaat))");
23723   verifyFormat("Constructor()\n"
23724                "    : aaaaaaaaaaaaa(aaaaaa), "
23725                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
23726 
23727   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
23728   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
23729   verifyFormat("Constructor()\n"
23730                "    : aaaaaa(aaaaaa),\n"
23731                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23732                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
23733                StyleWithWhitespacePenalty);
23734   verifyFormat("Constructor()\n"
23735                "    : aaaaaaaaaaaaa(aaaaaa), "
23736                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
23737                StyleWithWhitespacePenalty);
23738 }
23739 
23740 TEST_F(FormatTest, LLVMDefaultStyle) {
23741   FormatStyle Style = getLLVMStyle();
23742   verifyFormat("extern \"C\" {\n"
23743                "int foo();\n"
23744                "}",
23745                Style);
23746 }
23747 TEST_F(FormatTest, GNUDefaultStyle) {
23748   FormatStyle Style = getGNUStyle();
23749   verifyFormat("extern \"C\"\n"
23750                "{\n"
23751                "  int foo ();\n"
23752                "}",
23753                Style);
23754 }
23755 TEST_F(FormatTest, MozillaDefaultStyle) {
23756   FormatStyle Style = getMozillaStyle();
23757   verifyFormat("extern \"C\"\n"
23758                "{\n"
23759                "  int foo();\n"
23760                "}",
23761                Style);
23762 }
23763 TEST_F(FormatTest, GoogleDefaultStyle) {
23764   FormatStyle Style = getGoogleStyle();
23765   verifyFormat("extern \"C\" {\n"
23766                "int foo();\n"
23767                "}",
23768                Style);
23769 }
23770 TEST_F(FormatTest, ChromiumDefaultStyle) {
23771   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
23772   verifyFormat("extern \"C\" {\n"
23773                "int foo();\n"
23774                "}",
23775                Style);
23776 }
23777 TEST_F(FormatTest, MicrosoftDefaultStyle) {
23778   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
23779   verifyFormat("extern \"C\"\n"
23780                "{\n"
23781                "    int foo();\n"
23782                "}",
23783                Style);
23784 }
23785 TEST_F(FormatTest, WebKitDefaultStyle) {
23786   FormatStyle Style = getWebKitStyle();
23787   verifyFormat("extern \"C\" {\n"
23788                "int foo();\n"
23789                "}",
23790                Style);
23791 }
23792 
23793 TEST_F(FormatTest, Concepts) {
23794   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
23795             FormatStyle::BBCDS_Always);
23796   verifyFormat("template <typename T>\n"
23797                "concept True = true;");
23798 
23799   verifyFormat("template <typename T>\n"
23800                "concept C = ((false || foo()) && C2<T>) ||\n"
23801                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
23802                getLLVMStyleWithColumns(60));
23803 
23804   verifyFormat("template <typename T>\n"
23805                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
23806                "sizeof(T) <= 8;");
23807 
23808   verifyFormat("template <typename T>\n"
23809                "concept DelayedCheck = true && requires(T t) {\n"
23810                "                                 t.bar();\n"
23811                "                                 t.baz();\n"
23812                "                               } && sizeof(T) <= 8;");
23813 
23814   verifyFormat("template <typename T>\n"
23815                "concept DelayedCheck = true && requires(T t) { // Comment\n"
23816                "                                 t.bar();\n"
23817                "                                 t.baz();\n"
23818                "                               } && sizeof(T) <= 8;");
23819 
23820   verifyFormat("template <typename T>\n"
23821                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
23822                "sizeof(T) <= 8;");
23823 
23824   verifyFormat("template <typename T>\n"
23825                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
23826                "&& sizeof(T) <= 8;");
23827 
23828   verifyFormat(
23829       "template <typename T>\n"
23830       "concept DelayedCheck = static_cast<bool>(0) ||\n"
23831       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23832 
23833   verifyFormat("template <typename T>\n"
23834                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
23835                "&& sizeof(T) <= 8;");
23836 
23837   verifyFormat(
23838       "template <typename T>\n"
23839       "concept DelayedCheck = (bool)(0) ||\n"
23840       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23841 
23842   verifyFormat("template <typename T>\n"
23843                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
23844                "&& sizeof(T) <= 8;");
23845 
23846   verifyFormat("template <typename T>\n"
23847                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
23848                "sizeof(T) <= 8;");
23849 
23850   verifyFormat("template <typename T>\n"
23851                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
23852                "               requires(T t) {\n"
23853                "                 t.bar();\n"
23854                "                 t.baz();\n"
23855                "               } && sizeof(T) <= 8 && !(4 < 3);",
23856                getLLVMStyleWithColumns(60));
23857 
23858   verifyFormat("template <typename T>\n"
23859                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
23860 
23861   verifyFormat("template <typename T>\n"
23862                "concept C = foo();");
23863 
23864   verifyFormat("template <typename T>\n"
23865                "concept C = foo(T());");
23866 
23867   verifyFormat("template <typename T>\n"
23868                "concept C = foo(T{});");
23869 
23870   verifyFormat("template <typename T>\n"
23871                "concept Size = V<sizeof(T)>::Value > 5;");
23872 
23873   verifyFormat("template <typename T>\n"
23874                "concept True = S<T>::Value;");
23875 
23876   verifyFormat(
23877       "template <typename T>\n"
23878       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
23879       "            sizeof(T) <= 8;");
23880 
23881   // FIXME: This is misformatted because the fake l paren starts at bool, not at
23882   // the lambda l square.
23883   verifyFormat("template <typename T>\n"
23884                "concept C = [] -> bool { return true; }() && requires(T t) { "
23885                "t.bar(); } &&\n"
23886                "                      sizeof(T) <= 8;");
23887 
23888   verifyFormat(
23889       "template <typename T>\n"
23890       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
23891       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23892 
23893   verifyFormat("template <typename T>\n"
23894                "concept C = decltype([]() { return std::true_type{}; "
23895                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
23896                getLLVMStyleWithColumns(120));
23897 
23898   verifyFormat("template <typename T>\n"
23899                "concept C = decltype([]() -> std::true_type { return {}; "
23900                "}())::value &&\n"
23901                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23902 
23903   verifyFormat("template <typename T>\n"
23904                "concept C = true;\n"
23905                "Foo Bar;");
23906 
23907   verifyFormat("template <typename T>\n"
23908                "concept Hashable = requires(T a) {\n"
23909                "                     { std::hash<T>{}(a) } -> "
23910                "std::convertible_to<std::size_t>;\n"
23911                "                   };");
23912 
23913   verifyFormat(
23914       "template <typename T>\n"
23915       "concept EqualityComparable = requires(T a, T b) {\n"
23916       "                               { a == b } -> std::same_as<bool>;\n"
23917       "                             };");
23918 
23919   verifyFormat(
23920       "template <typename T>\n"
23921       "concept EqualityComparable = requires(T a, T b) {\n"
23922       "                               { a == b } -> std::same_as<bool>;\n"
23923       "                               { a != b } -> std::same_as<bool>;\n"
23924       "                             };");
23925 
23926   verifyFormat("template <typename T>\n"
23927                "concept WeakEqualityComparable = requires(T a, T b) {\n"
23928                "                                   { a == b };\n"
23929                "                                   { a != b };\n"
23930                "                                 };");
23931 
23932   verifyFormat("template <typename T>\n"
23933                "concept HasSizeT = requires { typename T::size_t; };");
23934 
23935   verifyFormat("template <typename T>\n"
23936                "concept Semiregular =\n"
23937                "    DefaultConstructible<T> && CopyConstructible<T> && "
23938                "CopyAssignable<T> &&\n"
23939                "    requires(T a, std::size_t n) {\n"
23940                "      requires Same<T *, decltype(&a)>;\n"
23941                "      { a.~T() } noexcept;\n"
23942                "      requires Same<T *, decltype(new T)>;\n"
23943                "      requires Same<T *, decltype(new T[n])>;\n"
23944                "      { delete new T; };\n"
23945                "      { delete new T[n]; };\n"
23946                "    };");
23947 
23948   verifyFormat("template <typename T>\n"
23949                "concept Semiregular =\n"
23950                "    requires(T a, std::size_t n) {\n"
23951                "      requires Same<T *, decltype(&a)>;\n"
23952                "      { a.~T() } noexcept;\n"
23953                "      requires Same<T *, decltype(new T)>;\n"
23954                "      requires Same<T *, decltype(new T[n])>;\n"
23955                "      { delete new T; };\n"
23956                "      { delete new T[n]; };\n"
23957                "      { new T } -> std::same_as<T *>;\n"
23958                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
23959                "CopyAssignable<T>;");
23960 
23961   verifyFormat(
23962       "template <typename T>\n"
23963       "concept Semiregular =\n"
23964       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
23965       "                                 requires Same<T *, decltype(&a)>;\n"
23966       "                                 { a.~T() } noexcept;\n"
23967       "                                 requires Same<T *, decltype(new T)>;\n"
23968       "                                 requires Same<T *, decltype(new "
23969       "T[n])>;\n"
23970       "                                 { delete new T; };\n"
23971       "                                 { delete new T[n]; };\n"
23972       "                               } && CopyConstructible<T> && "
23973       "CopyAssignable<T>;");
23974 
23975   verifyFormat("template <typename T>\n"
23976                "concept Two = requires(T t) {\n"
23977                "                { t.foo() } -> std::same_as<Bar>;\n"
23978                "              } && requires(T &&t) {\n"
23979                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
23980                "                   };");
23981 
23982   verifyFormat(
23983       "template <typename T>\n"
23984       "concept C = requires(T x) {\n"
23985       "              { *x } -> std::convertible_to<typename T::inner>;\n"
23986       "              { x + 1 } noexcept -> std::same_as<int>;\n"
23987       "              { x * 1 } -> std::convertible_to<T>;\n"
23988       "            };");
23989 
23990   verifyFormat(
23991       "template <typename T, typename U = T>\n"
23992       "concept Swappable = requires(T &&t, U &&u) {\n"
23993       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
23994       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
23995       "                    };");
23996 
23997   verifyFormat("template <typename T, typename U>\n"
23998                "concept Common = requires(T &&t, U &&u) {\n"
23999                "                   typename CommonType<T, U>;\n"
24000                "                   { CommonType<T, U>(std::forward<T>(t)) };\n"
24001                "                 };");
24002 
24003   verifyFormat("template <typename T, typename U>\n"
24004                "concept Common = requires(T &&t, U &&u) {\n"
24005                "                   typename CommonType<T, U>;\n"
24006                "                   { CommonType<T, U>{std::forward<T>(t)} };\n"
24007                "                 };");
24008 
24009   verifyFormat(
24010       "template <typename T>\n"
24011       "concept C = requires(T t) {\n"
24012       "              requires Bar<T> && Foo<T>;\n"
24013       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24014       "            };");
24015 
24016   verifyFormat("template <typename T>\n"
24017                "concept HasFoo = requires(T t) {\n"
24018                "                   { t.foo() };\n"
24019                "                   t.foo();\n"
24020                "                 };\n"
24021                "template <typename T>\n"
24022                "concept HasBar = requires(T t) {\n"
24023                "                   { t.bar() };\n"
24024                "                   t.bar();\n"
24025                "                 };");
24026 
24027   verifyFormat("template <typename T>\n"
24028                "concept Large = sizeof(T) > 10;");
24029 
24030   verifyFormat("template <typename T, typename U>\n"
24031                "concept FooableWith = requires(T t, U u) {\n"
24032                "                        typename T::foo_type;\n"
24033                "                        { t.foo(u) } -> typename T::foo_type;\n"
24034                "                        t++;\n"
24035                "                      };\n"
24036                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
24037 
24038   verifyFormat("template <typename T>\n"
24039                "concept Context = is_specialization_of_v<context, T>;");
24040 
24041   verifyFormat("template <typename T>\n"
24042                "concept Node = std::is_object_v<T>;");
24043 
24044   verifyFormat("template <class T>\n"
24045                "concept integral = __is_integral(T);");
24046 
24047   verifyFormat("template <class T>\n"
24048                "concept is2D = __array_extent(T, 1) == 2;");
24049 
24050   verifyFormat("template <class T>\n"
24051                "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
24052 
24053   verifyFormat("template <class T, class T2>\n"
24054                "concept Same = __is_same_as<T, T2>;");
24055 
24056   auto Style = getLLVMStyle();
24057   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
24058 
24059   verifyFormat(
24060       "template <typename T>\n"
24061       "concept C = requires(T t) {\n"
24062       "              requires Bar<T> && Foo<T>;\n"
24063       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24064       "            };",
24065       Style);
24066 
24067   verifyFormat("template <typename T>\n"
24068                "concept HasFoo = requires(T t) {\n"
24069                "                   { t.foo() };\n"
24070                "                   t.foo();\n"
24071                "                 };\n"
24072                "template <typename T>\n"
24073                "concept HasBar = requires(T t) {\n"
24074                "                   { t.bar() };\n"
24075                "                   t.bar();\n"
24076                "                 };",
24077                Style);
24078 
24079   verifyFormat("template <typename T> concept True = true;", Style);
24080 
24081   verifyFormat("template <typename T>\n"
24082                "concept C = decltype([]() -> std::true_type { return {}; "
24083                "}())::value &&\n"
24084                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24085                Style);
24086 
24087   verifyFormat("template <typename T>\n"
24088                "concept Semiregular =\n"
24089                "    DefaultConstructible<T> && CopyConstructible<T> && "
24090                "CopyAssignable<T> &&\n"
24091                "    requires(T a, std::size_t n) {\n"
24092                "      requires Same<T *, decltype(&a)>;\n"
24093                "      { a.~T() } noexcept;\n"
24094                "      requires Same<T *, decltype(new T)>;\n"
24095                "      requires Same<T *, decltype(new T[n])>;\n"
24096                "      { delete new T; };\n"
24097                "      { delete new T[n]; };\n"
24098                "    };",
24099                Style);
24100 
24101   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
24102 
24103   verifyFormat("template <typename T> concept C =\n"
24104                "    requires(T t) {\n"
24105                "      requires Bar<T> && Foo<T>;\n"
24106                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24107                "    };",
24108                Style);
24109 
24110   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
24111                "                                         { t.foo() };\n"
24112                "                                         t.foo();\n"
24113                "                                       };\n"
24114                "template <typename T> concept HasBar = requires(T t) {\n"
24115                "                                         { t.bar() };\n"
24116                "                                         t.bar();\n"
24117                "                                       };",
24118                Style);
24119 
24120   verifyFormat("template <typename T> concept True = true;", Style);
24121 
24122   verifyFormat(
24123       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
24124       "                                    return {};\n"
24125       "                                  }())::value &&\n"
24126       "                                  requires(T t) { t.bar(); } && "
24127       "sizeof(T) <= 8;",
24128       Style);
24129 
24130   verifyFormat("template <typename T> concept Semiregular =\n"
24131                "    DefaultConstructible<T> && CopyConstructible<T> && "
24132                "CopyAssignable<T> &&\n"
24133                "    requires(T a, std::size_t n) {\n"
24134                "      requires Same<T *, decltype(&a)>;\n"
24135                "      { a.~T() } noexcept;\n"
24136                "      requires Same<T *, decltype(new T)>;\n"
24137                "      requires Same<T *, decltype(new T[n])>;\n"
24138                "      { delete new T; };\n"
24139                "      { delete new T[n]; };\n"
24140                "    };",
24141                Style);
24142 
24143   // The following tests are invalid C++, we just want to make sure we don't
24144   // assert.
24145   verifyFormat("template <typename T>\n"
24146                "concept C = requires C2<T>;");
24147 
24148   verifyFormat("template <typename T>\n"
24149                "concept C = 5 + 4;");
24150 
24151   verifyFormat("template <typename T>\n"
24152                "concept C =\n"
24153                "class X;");
24154 
24155   verifyFormat("template <typename T>\n"
24156                "concept C = [] && true;");
24157 
24158   verifyFormat("template <typename T>\n"
24159                "concept C = [] && requires(T t) { typename T::size_type; };");
24160 }
24161 
24162 TEST_F(FormatTest, RequiresClausesPositions) {
24163   auto Style = getLLVMStyle();
24164   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
24165   EXPECT_EQ(Style.IndentRequiresClause, true);
24166 
24167   verifyFormat("template <typename T>\n"
24168                "  requires(Foo<T> && std::trait<T>)\n"
24169                "struct Bar;",
24170                Style);
24171 
24172   verifyFormat("template <typename T>\n"
24173                "  requires(Foo<T> && std::trait<T>)\n"
24174                "class Bar {\n"
24175                "public:\n"
24176                "  Bar(T t);\n"
24177                "  bool baz();\n"
24178                "};",
24179                Style);
24180 
24181   verifyFormat(
24182       "template <typename T>\n"
24183       "  requires requires(T &&t) {\n"
24184       "             typename T::I;\n"
24185       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
24186       "           }\n"
24187       "Bar(T) -> Bar<typename T::I>;",
24188       Style);
24189 
24190   verifyFormat("template <typename T>\n"
24191                "  requires(Foo<T> && std::trait<T>)\n"
24192                "constexpr T MyGlobal;",
24193                Style);
24194 
24195   verifyFormat("template <typename T>\n"
24196                "  requires Foo<T> && requires(T t) {\n"
24197                "                       { t.baz() } -> std::same_as<bool>;\n"
24198                "                       requires std::same_as<T::Factor, int>;\n"
24199                "                     }\n"
24200                "inline int bar(T t) {\n"
24201                "  return t.baz() ? T::Factor : 5;\n"
24202                "}",
24203                Style);
24204 
24205   verifyFormat("template <typename T>\n"
24206                "inline int bar(T t)\n"
24207                "  requires Foo<T> && requires(T t) {\n"
24208                "                       { t.baz() } -> std::same_as<bool>;\n"
24209                "                       requires std::same_as<T::Factor, int>;\n"
24210                "                     }\n"
24211                "{\n"
24212                "  return t.baz() ? T::Factor : 5;\n"
24213                "}",
24214                Style);
24215 
24216   verifyFormat("template <typename T>\n"
24217                "  requires F<T>\n"
24218                "int bar(T t) {\n"
24219                "  return 5;\n"
24220                "}",
24221                Style);
24222 
24223   verifyFormat("template <typename T>\n"
24224                "int bar(T t)\n"
24225                "  requires F<T>\n"
24226                "{\n"
24227                "  return 5;\n"
24228                "}",
24229                Style);
24230 
24231   verifyFormat("template <typename T>\n"
24232                "int bar(T t)\n"
24233                "  requires F<T>;",
24234                Style);
24235 
24236   Style.IndentRequiresClause = false;
24237   verifyFormat("template <typename T>\n"
24238                "requires F<T>\n"
24239                "int bar(T t) {\n"
24240                "  return 5;\n"
24241                "}",
24242                Style);
24243 
24244   verifyFormat("template <typename T>\n"
24245                "int bar(T t)\n"
24246                "requires F<T>\n"
24247                "{\n"
24248                "  return 5;\n"
24249                "}",
24250                Style);
24251 
24252   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
24253   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
24254                "template <typename T> requires Foo<T> void bar() {}\n"
24255                "template <typename T> void bar() requires Foo<T> {}\n"
24256                "template <typename T> void bar() requires Foo<T>;\n"
24257                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
24258                Style);
24259 
24260   auto ColumnStyle = Style;
24261   ColumnStyle.ColumnLimit = 40;
24262   verifyFormat("template <typename AAAAAAA>\n"
24263                "requires Foo<T> struct Bar {};\n"
24264                "template <typename AAAAAAA>\n"
24265                "requires Foo<T> void bar() {}\n"
24266                "template <typename AAAAAAA>\n"
24267                "void bar() requires Foo<T> {}\n"
24268                "template <typename AAAAAAA>\n"
24269                "requires Foo<T> Baz(T) -> Baz<T>;",
24270                ColumnStyle);
24271 
24272   verifyFormat("template <typename T>\n"
24273                "requires Foo<AAAAAAA> struct Bar {};\n"
24274                "template <typename T>\n"
24275                "requires Foo<AAAAAAA> void bar() {}\n"
24276                "template <typename T>\n"
24277                "void bar() requires Foo<AAAAAAA> {}\n"
24278                "template <typename T>\n"
24279                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
24280                ColumnStyle);
24281 
24282   verifyFormat("template <typename AAAAAAA>\n"
24283                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24284                "struct Bar {};\n"
24285                "template <typename AAAAAAA>\n"
24286                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24287                "void bar() {}\n"
24288                "template <typename AAAAAAA>\n"
24289                "void bar()\n"
24290                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24291                "template <typename AAAAAAA>\n"
24292                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24293                "template <typename AAAAAAA>\n"
24294                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24295                "Bar(T) -> Bar<T>;",
24296                ColumnStyle);
24297 
24298   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24299   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24300 
24301   verifyFormat("template <typename T>\n"
24302                "requires Foo<T> struct Bar {};\n"
24303                "template <typename T>\n"
24304                "requires Foo<T> void bar() {}\n"
24305                "template <typename T>\n"
24306                "void bar()\n"
24307                "requires Foo<T> {}\n"
24308                "template <typename T>\n"
24309                "void bar()\n"
24310                "requires Foo<T>;\n"
24311                "template <typename T>\n"
24312                "requires Foo<T> Bar(T) -> Bar<T>;",
24313                Style);
24314 
24315   verifyFormat("template <typename AAAAAAA>\n"
24316                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24317                "struct Bar {};\n"
24318                "template <typename AAAAAAA>\n"
24319                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24320                "void bar() {}\n"
24321                "template <typename AAAAAAA>\n"
24322                "void bar()\n"
24323                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24324                "template <typename AAAAAAA>\n"
24325                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24326                "template <typename AAAAAAA>\n"
24327                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24328                "Bar(T) -> Bar<T>;",
24329                ColumnStyle);
24330 
24331   Style.IndentRequiresClause = true;
24332   ColumnStyle.IndentRequiresClause = true;
24333 
24334   verifyFormat("template <typename T>\n"
24335                "  requires Foo<T> struct Bar {};\n"
24336                "template <typename T>\n"
24337                "  requires Foo<T> void bar() {}\n"
24338                "template <typename T>\n"
24339                "void bar()\n"
24340                "  requires Foo<T> {}\n"
24341                "template <typename T>\n"
24342                "  requires Foo<T> Bar(T) -> Bar<T>;",
24343                Style);
24344 
24345   verifyFormat("template <typename AAAAAAA>\n"
24346                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24347                "struct Bar {};\n"
24348                "template <typename AAAAAAA>\n"
24349                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24350                "void bar() {}\n"
24351                "template <typename AAAAAAA>\n"
24352                "void bar()\n"
24353                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24354                "template <typename AAAAAAA>\n"
24355                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
24356                "template <typename AAAAAAA>\n"
24357                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24358                "Bar(T) -> Bar<T>;",
24359                ColumnStyle);
24360 
24361   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24362   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24363 
24364   verifyFormat("template <typename T> requires Foo<T>\n"
24365                "struct Bar {};\n"
24366                "template <typename T> requires Foo<T>\n"
24367                "void bar() {}\n"
24368                "template <typename T>\n"
24369                "void bar() requires Foo<T>\n"
24370                "{}\n"
24371                "template <typename T> void bar() requires Foo<T>;\n"
24372                "template <typename T> requires Foo<T>\n"
24373                "Bar(T) -> Bar<T>;",
24374                Style);
24375 
24376   verifyFormat("template <typename AAAAAAA>\n"
24377                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24378                "struct Bar {};\n"
24379                "template <typename AAAAAAA>\n"
24380                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24381                "void bar() {}\n"
24382                "template <typename AAAAAAA>\n"
24383                "void bar()\n"
24384                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24385                "{}\n"
24386                "template <typename AAAAAAA>\n"
24387                "requires Foo<AAAAAAAA>\n"
24388                "Bar(T) -> Bar<T>;\n"
24389                "template <typename AAAAAAA>\n"
24390                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24391                "Bar(T) -> Bar<T>;",
24392                ColumnStyle);
24393 }
24394 
24395 TEST_F(FormatTest, RequiresClauses) {
24396   verifyFormat("struct [[nodiscard]] zero_t {\n"
24397                "  template <class T>\n"
24398                "    requires requires { number_zero_v<T>; }\n"
24399                "  [[nodiscard]] constexpr operator T() const {\n"
24400                "    return number_zero_v<T>;\n"
24401                "  }\n"
24402                "};");
24403 
24404   auto Style = getLLVMStyle();
24405 
24406   verifyFormat(
24407       "template <typename T>\n"
24408       "  requires is_default_constructible_v<hash<T>> and\n"
24409       "           is_copy_constructible_v<hash<T>> and\n"
24410       "           is_move_constructible_v<hash<T>> and\n"
24411       "           is_copy_assignable_v<hash<T>> and "
24412       "is_move_assignable_v<hash<T>> and\n"
24413       "           is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
24414       "           is_callable_v<hash<T>(T)> and\n"
24415       "           is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n"
24416       "           is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n"
24417       "           is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
24418       "struct S {};",
24419       Style);
24420 
24421   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
24422   verifyFormat(
24423       "template <typename T>\n"
24424       "  requires is_default_constructible_v<hash<T>>\n"
24425       "           and is_copy_constructible_v<hash<T>>\n"
24426       "           and is_move_constructible_v<hash<T>>\n"
24427       "           and is_copy_assignable_v<hash<T>> and "
24428       "is_move_assignable_v<hash<T>>\n"
24429       "           and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
24430       "           and is_callable_v<hash<T>(T)>\n"
24431       "           and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n"
24432       "           and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n"
24433       "           and is_same_v<size_t, decltype(hash<T>(declval<const T "
24434       "&>()))>\n"
24435       "struct S {};",
24436       Style);
24437 
24438   // Not a clause, but we once hit an assert.
24439   verifyFormat("#if 0\n"
24440                "#else\n"
24441                "foo();\n"
24442                "#endif\n"
24443                "bar(requires);");
24444 }
24445 
24446 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24447   FormatStyle Style = getLLVMStyle();
24448   StringRef Source = "void Foo::slot() {\n"
24449                      "  unsigned char MyChar = 'x';\n"
24450                      "  emit signal(MyChar);\n"
24451                      "  Q_EMIT signal(MyChar);\n"
24452                      "}";
24453 
24454   EXPECT_EQ(Source, format(Source, Style));
24455 
24456   Style.AlignConsecutiveDeclarations.Enabled = true;
24457   EXPECT_EQ("void Foo::slot() {\n"
24458             "  unsigned char MyChar = 'x';\n"
24459             "  emit          signal(MyChar);\n"
24460             "  Q_EMIT signal(MyChar);\n"
24461             "}",
24462             format(Source, Style));
24463 
24464   Style.StatementAttributeLikeMacros.push_back("emit");
24465   EXPECT_EQ(Source, format(Source, Style));
24466 
24467   Style.StatementAttributeLikeMacros = {};
24468   EXPECT_EQ("void Foo::slot() {\n"
24469             "  unsigned char MyChar = 'x';\n"
24470             "  emit          signal(MyChar);\n"
24471             "  Q_EMIT        signal(MyChar);\n"
24472             "}",
24473             format(Source, Style));
24474 }
24475 
24476 TEST_F(FormatTest, IndentAccessModifiers) {
24477   FormatStyle Style = getLLVMStyle();
24478   Style.IndentAccessModifiers = true;
24479   // Members are *two* levels below the record;
24480   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24481   verifyFormat("class C {\n"
24482                "    int i;\n"
24483                "};\n",
24484                Style);
24485   verifyFormat("union C {\n"
24486                "    int i;\n"
24487                "    unsigned u;\n"
24488                "};\n",
24489                Style);
24490   // Access modifiers should be indented one level below the record.
24491   verifyFormat("class C {\n"
24492                "  public:\n"
24493                "    int i;\n"
24494                "};\n",
24495                Style);
24496   verifyFormat("struct S {\n"
24497                "  private:\n"
24498                "    class C {\n"
24499                "        int j;\n"
24500                "\n"
24501                "      public:\n"
24502                "        C();\n"
24503                "    };\n"
24504                "\n"
24505                "  public:\n"
24506                "    int i;\n"
24507                "};\n",
24508                Style);
24509   // Enumerations are not records and should be unaffected.
24510   Style.AllowShortEnumsOnASingleLine = false;
24511   verifyFormat("enum class E {\n"
24512                "  A,\n"
24513                "  B\n"
24514                "};\n",
24515                Style);
24516   // Test with a different indentation width;
24517   // also proves that the result is Style.AccessModifierOffset agnostic.
24518   Style.IndentWidth = 3;
24519   verifyFormat("class C {\n"
24520                "   public:\n"
24521                "      int i;\n"
24522                "};\n",
24523                Style);
24524 }
24525 
24526 TEST_F(FormatTest, LimitlessStringsAndComments) {
24527   auto Style = getLLVMStyleWithColumns(0);
24528   constexpr StringRef Code =
24529       "/**\n"
24530       " * This is a multiline comment with quite some long lines, at least for "
24531       "the LLVM Style.\n"
24532       " * We will redo this with strings and line comments. Just to  check if "
24533       "everything is working.\n"
24534       " */\n"
24535       "bool foo() {\n"
24536       "  /* Single line multi line comment. */\n"
24537       "  const std::string String = \"This is a multiline string with quite "
24538       "some long lines, at least for the LLVM Style.\"\n"
24539       "                             \"We already did it with multi line "
24540       "comments, and we will do it with line comments. Just to check if "
24541       "everything is working.\";\n"
24542       "  // This is a line comment (block) with quite some long lines, at "
24543       "least for the LLVM Style.\n"
24544       "  // We already did this with multi line comments and strings. Just to "
24545       "check if everything is working.\n"
24546       "  const std::string SmallString = \"Hello World\";\n"
24547       "  // Small line comment\n"
24548       "  return String.size() > SmallString.size();\n"
24549       "}";
24550   EXPECT_EQ(Code, format(Code, Style));
24551 }
24552 
24553 TEST_F(FormatTest, FormatDecayCopy) {
24554   // error cases from unit tests
24555   verifyFormat("foo(auto())");
24556   verifyFormat("foo(auto{})");
24557   verifyFormat("foo(auto({}))");
24558   verifyFormat("foo(auto{{}})");
24559 
24560   verifyFormat("foo(auto(1))");
24561   verifyFormat("foo(auto{1})");
24562   verifyFormat("foo(new auto(1))");
24563   verifyFormat("foo(new auto{1})");
24564   verifyFormat("decltype(auto(1)) x;");
24565   verifyFormat("decltype(auto{1}) x;");
24566   verifyFormat("auto(x);");
24567   verifyFormat("auto{x};");
24568   verifyFormat("new auto{x};");
24569   verifyFormat("auto{x} = y;");
24570   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24571                                 // the user's own fault
24572   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24573                                          // clearly the user's own fault
24574   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24575 }
24576 
24577 TEST_F(FormatTest, Cpp20ModulesSupport) {
24578   FormatStyle Style = getLLVMStyle();
24579   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24580   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24581 
24582   verifyFormat("export import foo;", Style);
24583   verifyFormat("export import foo:bar;", Style);
24584   verifyFormat("export import foo.bar;", Style);
24585   verifyFormat("export import foo.bar:baz;", Style);
24586   verifyFormat("export import :bar;", Style);
24587   verifyFormat("export module foo:bar;", Style);
24588   verifyFormat("export module foo;", Style);
24589   verifyFormat("export module foo.bar;", Style);
24590   verifyFormat("export module foo.bar:baz;", Style);
24591   verifyFormat("export import <string_view>;", Style);
24592 
24593   verifyFormat("export type_name var;", Style);
24594   verifyFormat("template <class T> export using A = B<T>;", Style);
24595   verifyFormat("export using A = B;", Style);
24596   verifyFormat("export int func() {\n"
24597                "  foo();\n"
24598                "}",
24599                Style);
24600   verifyFormat("export struct {\n"
24601                "  int foo;\n"
24602                "};",
24603                Style);
24604   verifyFormat("export {\n"
24605                "  int foo;\n"
24606                "};",
24607                Style);
24608   verifyFormat("export export char const *hello() { return \"hello\"; }");
24609 
24610   verifyFormat("import bar;", Style);
24611   verifyFormat("import foo.bar;", Style);
24612   verifyFormat("import foo:bar;", Style);
24613   verifyFormat("import :bar;", Style);
24614   verifyFormat("import <ctime>;", Style);
24615   verifyFormat("import \"header\";", Style);
24616 
24617   verifyFormat("module foo;", Style);
24618   verifyFormat("module foo:bar;", Style);
24619   verifyFormat("module foo.bar;", Style);
24620   verifyFormat("module;", Style);
24621 
24622   verifyFormat("export namespace hi {\n"
24623                "const char *sayhi();\n"
24624                "}",
24625                Style);
24626 
24627   verifyFormat("module :private;", Style);
24628   verifyFormat("import <foo/bar.h>;", Style);
24629   verifyFormat("import foo...bar;", Style);
24630   verifyFormat("import ..........;", Style);
24631   verifyFormat("module foo:private;", Style);
24632   verifyFormat("import a", Style);
24633   verifyFormat("module a", Style);
24634   verifyFormat("export import a", Style);
24635   verifyFormat("export module a", Style);
24636 
24637   verifyFormat("import", Style);
24638   verifyFormat("module", Style);
24639   verifyFormat("export", Style);
24640 }
24641 
24642 TEST_F(FormatTest, CoroutineForCoawait) {
24643   FormatStyle Style = getLLVMStyle();
24644   verifyFormat("for co_await (auto x : range())\n  ;");
24645   verifyFormat("for (auto i : arr) {\n"
24646                "}",
24647                Style);
24648   verifyFormat("for co_await (auto i : arr) {\n"
24649                "}",
24650                Style);
24651   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24652                "}",
24653                Style);
24654 }
24655 
24656 TEST_F(FormatTest, CoroutineCoAwait) {
24657   verifyFormat("int x = co_await foo();");
24658   verifyFormat("int x = (co_await foo());");
24659   verifyFormat("co_await (42);");
24660   verifyFormat("void operator co_await(int);");
24661   verifyFormat("void operator co_await(a);");
24662   verifyFormat("co_await a;");
24663   verifyFormat("co_await missing_await_resume{};");
24664   verifyFormat("co_await a; // comment");
24665   verifyFormat("void test0() { co_await a; }");
24666   verifyFormat("co_await co_await co_await foo();");
24667   verifyFormat("co_await foo().bar();");
24668   verifyFormat("co_await [this]() -> Task { co_return x; }");
24669   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24670                "foo(); }(x, y);");
24671 
24672   FormatStyle Style = getLLVMStyleWithColumns(40);
24673   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24674                "  co_return co_await foo();\n"
24675                "}(x, y);",
24676                Style);
24677   verifyFormat("co_await;");
24678 }
24679 
24680 TEST_F(FormatTest, CoroutineCoYield) {
24681   verifyFormat("int x = co_yield foo();");
24682   verifyFormat("int x = (co_yield foo());");
24683   verifyFormat("co_yield (42);");
24684   verifyFormat("co_yield {42};");
24685   verifyFormat("co_yield 42;");
24686   verifyFormat("co_yield n++;");
24687   verifyFormat("co_yield ++n;");
24688   verifyFormat("co_yield;");
24689 }
24690 
24691 TEST_F(FormatTest, CoroutineCoReturn) {
24692   verifyFormat("co_return (42);");
24693   verifyFormat("co_return;");
24694   verifyFormat("co_return {};");
24695   verifyFormat("co_return x;");
24696   verifyFormat("co_return co_await foo();");
24697   verifyFormat("co_return co_yield foo();");
24698 }
24699 
24700 TEST_F(FormatTest, EmptyShortBlock) {
24701   auto Style = getLLVMStyle();
24702   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24703 
24704   verifyFormat("try {\n"
24705                "  doA();\n"
24706                "} catch (Exception &e) {\n"
24707                "  e.printStackTrace();\n"
24708                "}\n",
24709                Style);
24710 
24711   verifyFormat("try {\n"
24712                "  doA();\n"
24713                "} catch (Exception &e) {}\n",
24714                Style);
24715 }
24716 
24717 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
24718   auto Style = getLLVMStyle();
24719 
24720   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
24721   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
24722   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
24723   verifyFormat("struct Y<[] { return 0; }> {};", Style);
24724 
24725   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
24726   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
24727 }
24728 
24729 TEST_F(FormatTest, InsertBraces) {
24730   FormatStyle Style = getLLVMStyle();
24731   Style.InsertBraces = true;
24732 
24733   verifyFormat("// clang-format off\n"
24734                "// comment\n"
24735                "if (a) f();\n"
24736                "// clang-format on\n"
24737                "if (b) {\n"
24738                "  g();\n"
24739                "}",
24740                "// clang-format off\n"
24741                "// comment\n"
24742                "if (a) f();\n"
24743                "// clang-format on\n"
24744                "if (b) g();",
24745                Style);
24746 
24747   verifyFormat("if (a) {\n"
24748                "  switch (b) {\n"
24749                "  case 1:\n"
24750                "    c = 0;\n"
24751                "    break;\n"
24752                "  default:\n"
24753                "    c = 1;\n"
24754                "  }\n"
24755                "}",
24756                "if (a)\n"
24757                "  switch (b) {\n"
24758                "  case 1:\n"
24759                "    c = 0;\n"
24760                "    break;\n"
24761                "  default:\n"
24762                "    c = 1;\n"
24763                "  }",
24764                Style);
24765 
24766   verifyFormat("for (auto node : nodes) {\n"
24767                "  if (node) {\n"
24768                "    break;\n"
24769                "  }\n"
24770                "}",
24771                "for (auto node : nodes)\n"
24772                "  if (node)\n"
24773                "    break;",
24774                Style);
24775 
24776   verifyFormat("for (auto node : nodes) {\n"
24777                "  if (node)\n"
24778                "}",
24779                "for (auto node : nodes)\n"
24780                "  if (node)",
24781                Style);
24782 
24783   verifyFormat("do {\n"
24784                "  --a;\n"
24785                "} while (a);",
24786                "do\n"
24787                "  --a;\n"
24788                "while (a);",
24789                Style);
24790 
24791   verifyFormat("if (i) {\n"
24792                "  ++i;\n"
24793                "} else {\n"
24794                "  --i;\n"
24795                "}",
24796                "if (i)\n"
24797                "  ++i;\n"
24798                "else {\n"
24799                "  --i;\n"
24800                "}",
24801                Style);
24802 
24803   verifyFormat("void f() {\n"
24804                "  while (j--) {\n"
24805                "    while (i) {\n"
24806                "      --i;\n"
24807                "    }\n"
24808                "  }\n"
24809                "}",
24810                "void f() {\n"
24811                "  while (j--)\n"
24812                "    while (i)\n"
24813                "      --i;\n"
24814                "}",
24815                Style);
24816 
24817   verifyFormat("f({\n"
24818                "  if (a) {\n"
24819                "    g();\n"
24820                "  }\n"
24821                "});",
24822                "f({\n"
24823                "  if (a)\n"
24824                "    g();\n"
24825                "});",
24826                Style);
24827 
24828   verifyFormat("if (a) {\n"
24829                "  f();\n"
24830                "} else if (b) {\n"
24831                "  g();\n"
24832                "} else {\n"
24833                "  h();\n"
24834                "}",
24835                "if (a)\n"
24836                "  f();\n"
24837                "else if (b)\n"
24838                "  g();\n"
24839                "else\n"
24840                "  h();",
24841                Style);
24842 
24843   verifyFormat("if (a) {\n"
24844                "  f();\n"
24845                "}\n"
24846                "// comment\n"
24847                "/* comment */",
24848                "if (a)\n"
24849                "  f();\n"
24850                "// comment\n"
24851                "/* comment */",
24852                Style);
24853 
24854   verifyFormat("if (a) {\n"
24855                "  // foo\n"
24856                "  // bar\n"
24857                "  f();\n"
24858                "}",
24859                "if (a)\n"
24860                "  // foo\n"
24861                "  // bar\n"
24862                "  f();",
24863                Style);
24864 
24865   verifyFormat("if (a) { // comment\n"
24866                "  // comment\n"
24867                "  f();\n"
24868                "}",
24869                "if (a) // comment\n"
24870                "  // comment\n"
24871                "  f();",
24872                Style);
24873 
24874   verifyFormat("if (a) {\n"
24875                "  f(); // comment\n"
24876                "}",
24877                "if (a)\n"
24878                "  f(); // comment",
24879                Style);
24880 
24881   verifyFormat("if (a) {\n"
24882                "  f();\n"
24883                "}\n"
24884                "#undef A\n"
24885                "#undef B",
24886                "if (a)\n"
24887                "  f();\n"
24888                "#undef A\n"
24889                "#undef B",
24890                Style);
24891 
24892   verifyFormat("if (a)\n"
24893                "#ifdef A\n"
24894                "  f();\n"
24895                "#else\n"
24896                "  g();\n"
24897                "#endif",
24898                Style);
24899 
24900   verifyFormat("#if 0\n"
24901                "#elif 1\n"
24902                "#endif\n"
24903                "void f() {\n"
24904                "  if (a) {\n"
24905                "    g();\n"
24906                "  }\n"
24907                "}",
24908                "#if 0\n"
24909                "#elif 1\n"
24910                "#endif\n"
24911                "void f() {\n"
24912                "  if (a) g();\n"
24913                "}",
24914                Style);
24915 
24916   Style.ColumnLimit = 15;
24917 
24918   verifyFormat("#define A     \\\n"
24919                "  if (a)      \\\n"
24920                "    f();",
24921                Style);
24922 
24923   verifyFormat("if (a + b >\n"
24924                "    c) {\n"
24925                "  f();\n"
24926                "}",
24927                "if (a + b > c)\n"
24928                "  f();",
24929                Style);
24930 }
24931 
24932 TEST_F(FormatTest, RemoveBraces) {
24933   FormatStyle Style = getLLVMStyle();
24934   Style.RemoveBracesLLVM = true;
24935 
24936   // The following eight test cases are fully-braced versions of the examples at
24937   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
24938   // statement-bodies-of-if-else-loop-statements".
24939 
24940   // 1. Omit the braces, since the body is simple and clearly associated with
24941   // the if.
24942   verifyFormat("if (isa<FunctionDecl>(D))\n"
24943                "  handleFunctionDecl(D);\n"
24944                "else if (isa<VarDecl>(D))\n"
24945                "  handleVarDecl(D);",
24946                "if (isa<FunctionDecl>(D)) {\n"
24947                "  handleFunctionDecl(D);\n"
24948                "} else if (isa<VarDecl>(D)) {\n"
24949                "  handleVarDecl(D);\n"
24950                "}",
24951                Style);
24952 
24953   // 2. Here we document the condition itself and not the body.
24954   verifyFormat("if (isa<VarDecl>(D)) {\n"
24955                "  // It is necessary that we explain the situation with this\n"
24956                "  // surprisingly long comment, so it would be unclear\n"
24957                "  // without the braces whether the following statement is in\n"
24958                "  // the scope of the `if`.\n"
24959                "  // Because the condition is documented, we can't really\n"
24960                "  // hoist this comment that applies to the body above the\n"
24961                "  // if.\n"
24962                "  handleOtherDecl(D);\n"
24963                "}",
24964                Style);
24965 
24966   // 3. Use braces on the outer `if` to avoid a potential dangling else
24967   // situation.
24968   verifyFormat("if (isa<VarDecl>(D)) {\n"
24969                "  for (auto *A : D.attrs())\n"
24970                "    if (shouldProcessAttr(A))\n"
24971                "      handleAttr(A);\n"
24972                "}",
24973                "if (isa<VarDecl>(D)) {\n"
24974                "  for (auto *A : D.attrs()) {\n"
24975                "    if (shouldProcessAttr(A)) {\n"
24976                "      handleAttr(A);\n"
24977                "    }\n"
24978                "  }\n"
24979                "}",
24980                Style);
24981 
24982   // 4. Use braces for the `if` block to keep it uniform with the else block.
24983   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24984                "  handleFunctionDecl(D);\n"
24985                "} else {\n"
24986                "  // In this else case, it is necessary that we explain the\n"
24987                "  // situation with this surprisingly long comment, so it\n"
24988                "  // would be unclear without the braces whether the\n"
24989                "  // following statement is in the scope of the `if`.\n"
24990                "  handleOtherDecl(D);\n"
24991                "}",
24992                Style);
24993 
24994   // 5. This should also omit braces.  The `for` loop contains only a single
24995   // statement, so it shouldn't have braces.  The `if` also only contains a
24996   // single simple statement (the for loop), so it also should omit braces.
24997   verifyFormat("if (isa<FunctionDecl>(D))\n"
24998                "  for (auto *A : D.attrs())\n"
24999                "    handleAttr(A);",
25000                "if (isa<FunctionDecl>(D)) {\n"
25001                "  for (auto *A : D.attrs()) {\n"
25002                "    handleAttr(A);\n"
25003                "  }\n"
25004                "}",
25005                Style);
25006 
25007   // 6. Use braces for the outer `if` since the nested `for` is braced.
25008   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25009                "  for (auto *A : D.attrs()) {\n"
25010                "    // In this for loop body, it is necessary that we explain\n"
25011                "    // the situation with this surprisingly long comment,\n"
25012                "    // forcing braces on the `for` block.\n"
25013                "    handleAttr(A);\n"
25014                "  }\n"
25015                "}",
25016                Style);
25017 
25018   // 7. Use braces on the outer block because there are more than two levels of
25019   // nesting.
25020   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25021                "  for (auto *A : D.attrs())\n"
25022                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
25023                "      handleAttrOnDecl(D, A, i);\n"
25024                "}",
25025                "if (isa<FunctionDecl>(D)) {\n"
25026                "  for (auto *A : D.attrs()) {\n"
25027                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
25028                "      handleAttrOnDecl(D, A, i);\n"
25029                "    }\n"
25030                "  }\n"
25031                "}",
25032                Style);
25033 
25034   // 8. Use braces on the outer block because of a nested `if`, otherwise the
25035   // compiler would warn: `add explicit braces to avoid dangling else`
25036   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25037                "  if (shouldProcess(D))\n"
25038                "    handleVarDecl(D);\n"
25039                "  else\n"
25040                "    markAsIgnored(D);\n"
25041                "}",
25042                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25043                "  if (shouldProcess(D)) {\n"
25044                "    handleVarDecl(D);\n"
25045                "  } else {\n"
25046                "    markAsIgnored(D);\n"
25047                "  }\n"
25048                "}",
25049                Style);
25050 
25051   verifyFormat("// clang-format off\n"
25052                "// comment\n"
25053                "while (i > 0) { --i; }\n"
25054                "// clang-format on\n"
25055                "while (j < 0)\n"
25056                "  ++j;",
25057                "// clang-format off\n"
25058                "// comment\n"
25059                "while (i > 0) { --i; }\n"
25060                "// clang-format on\n"
25061                "while (j < 0) { ++j; }",
25062                Style);
25063 
25064   verifyFormat("if (a)\n"
25065                "  b; // comment\n"
25066                "else if (c)\n"
25067                "  d; /* comment */\n"
25068                "else\n"
25069                "  e;",
25070                "if (a) {\n"
25071                "  b; // comment\n"
25072                "} else if (c) {\n"
25073                "  d; /* comment */\n"
25074                "} else {\n"
25075                "  e;\n"
25076                "}",
25077                Style);
25078 
25079   verifyFormat("if (a) {\n"
25080                "  b;\n"
25081                "  c;\n"
25082                "} else if (d) {\n"
25083                "  e;\n"
25084                "}",
25085                Style);
25086 
25087   verifyFormat("if (a) {\n"
25088                "#undef NDEBUG\n"
25089                "  b;\n"
25090                "} else {\n"
25091                "  c;\n"
25092                "}",
25093                Style);
25094 
25095   verifyFormat("if (a) {\n"
25096                "  // comment\n"
25097                "} else if (b) {\n"
25098                "  c;\n"
25099                "}",
25100                Style);
25101 
25102   verifyFormat("if (a) {\n"
25103                "  b;\n"
25104                "} else {\n"
25105                "  { c; }\n"
25106                "}",
25107                Style);
25108 
25109   verifyFormat("if (a) {\n"
25110                "  if (b) // comment\n"
25111                "    c;\n"
25112                "} else if (d) {\n"
25113                "  e;\n"
25114                "}",
25115                "if (a) {\n"
25116                "  if (b) { // comment\n"
25117                "    c;\n"
25118                "  }\n"
25119                "} else if (d) {\n"
25120                "  e;\n"
25121                "}",
25122                Style);
25123 
25124   verifyFormat("if (a) {\n"
25125                "  if (b) {\n"
25126                "    c;\n"
25127                "    // comment\n"
25128                "  } else if (d) {\n"
25129                "    e;\n"
25130                "  }\n"
25131                "}",
25132                Style);
25133 
25134   verifyFormat("if (a) {\n"
25135                "  if (b)\n"
25136                "    c;\n"
25137                "}",
25138                "if (a) {\n"
25139                "  if (b) {\n"
25140                "    c;\n"
25141                "  }\n"
25142                "}",
25143                Style);
25144 
25145   verifyFormat("if (a)\n"
25146                "  if (b)\n"
25147                "    c;\n"
25148                "  else\n"
25149                "    d;\n"
25150                "else\n"
25151                "  e;",
25152                "if (a) {\n"
25153                "  if (b) {\n"
25154                "    c;\n"
25155                "  } else {\n"
25156                "    d;\n"
25157                "  }\n"
25158                "} else {\n"
25159                "  e;\n"
25160                "}",
25161                Style);
25162 
25163   verifyFormat("if (a) {\n"
25164                "  // comment\n"
25165                "  if (b)\n"
25166                "    c;\n"
25167                "  else if (d)\n"
25168                "    e;\n"
25169                "} else {\n"
25170                "  g;\n"
25171                "}",
25172                "if (a) {\n"
25173                "  // comment\n"
25174                "  if (b) {\n"
25175                "    c;\n"
25176                "  } else if (d) {\n"
25177                "    e;\n"
25178                "  }\n"
25179                "} else {\n"
25180                "  g;\n"
25181                "}",
25182                Style);
25183 
25184   verifyFormat("if (a)\n"
25185                "  b;\n"
25186                "else if (c)\n"
25187                "  d;\n"
25188                "else\n"
25189                "  e;",
25190                "if (a) {\n"
25191                "  b;\n"
25192                "} else {\n"
25193                "  if (c) {\n"
25194                "    d;\n"
25195                "  } else {\n"
25196                "    e;\n"
25197                "  }\n"
25198                "}",
25199                Style);
25200 
25201   verifyFormat("if (a) {\n"
25202                "  if (b)\n"
25203                "    c;\n"
25204                "  else if (d)\n"
25205                "    e;\n"
25206                "} else {\n"
25207                "  g;\n"
25208                "}",
25209                "if (a) {\n"
25210                "  if (b)\n"
25211                "    c;\n"
25212                "  else {\n"
25213                "    if (d)\n"
25214                "      e;\n"
25215                "  }\n"
25216                "} else {\n"
25217                "  g;\n"
25218                "}",
25219                Style);
25220 
25221   verifyFormat("if (a)\n"
25222                "  b;\n"
25223                "else if (c)\n"
25224                "  while (d)\n"
25225                "    e;\n"
25226                "// comment",
25227                "if (a)\n"
25228                "{\n"
25229                "  b;\n"
25230                "} else if (c) {\n"
25231                "  while (d) {\n"
25232                "    e;\n"
25233                "  }\n"
25234                "}\n"
25235                "// comment",
25236                Style);
25237 
25238   verifyFormat("if (a) {\n"
25239                "  b;\n"
25240                "} else if (c) {\n"
25241                "  d;\n"
25242                "} else {\n"
25243                "  e;\n"
25244                "  g;\n"
25245                "}",
25246                Style);
25247 
25248   verifyFormat("if (a) {\n"
25249                "  b;\n"
25250                "} else if (c) {\n"
25251                "  d;\n"
25252                "} else {\n"
25253                "  e;\n"
25254                "} // comment",
25255                Style);
25256 
25257   verifyFormat("int abs = [](int i) {\n"
25258                "  if (i >= 0)\n"
25259                "    return i;\n"
25260                "  return -i;\n"
25261                "};",
25262                "int abs = [](int i) {\n"
25263                "  if (i >= 0) {\n"
25264                "    return i;\n"
25265                "  }\n"
25266                "  return -i;\n"
25267                "};",
25268                Style);
25269 
25270   verifyFormat("if (a)\n"
25271                "  foo();\n"
25272                "else\n"
25273                "  bar();",
25274                "if (a)\n"
25275                "{\n"
25276                "  foo();\n"
25277                "}\n"
25278                "else\n"
25279                "{\n"
25280                "  bar();\n"
25281                "}",
25282                Style);
25283 
25284   verifyFormat("if (a) {\n"
25285                "Label:\n"
25286                "}",
25287                Style);
25288 
25289   verifyFormat("if (a) {\n"
25290                "Label:\n"
25291                "  f();\n"
25292                "}",
25293                Style);
25294 
25295   verifyFormat("if (a) {\n"
25296                "  f();\n"
25297                "Label:\n"
25298                "}",
25299                Style);
25300 
25301   // FIXME: See https://github.com/llvm/llvm-project/issues/53543.
25302 #if 0
25303   Style.ColumnLimit = 65;
25304 
25305   verifyFormat("if (condition) {\n"
25306                "  ff(Indices,\n"
25307                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25308                "} else {\n"
25309                "  ff(Indices,\n"
25310                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25311                "}",
25312                Style);
25313 
25314   Style.ColumnLimit = 20;
25315 
25316   verifyFormat("if (a) {\n"
25317                "  b = c + // 1 -\n"
25318                "      d;\n"
25319                "}",
25320                Style);
25321 
25322   verifyFormat("if (a) {\n"
25323                "  b = c >= 0 ? d\n"
25324                "             : e;\n"
25325                "}",
25326                "if (a) {\n"
25327                "  b = c >= 0 ? d : e;\n"
25328                "}",
25329                Style);
25330 #endif
25331 
25332   Style.ColumnLimit = 20;
25333 
25334   verifyFormat("if (a)\n"
25335                "  b = c > 0 ? d : e;",
25336                "if (a) {\n"
25337                "  b = c > 0 ? d : e;\n"
25338                "}",
25339                Style);
25340 
25341   Style.ColumnLimit = 0;
25342 
25343   verifyFormat("if (a)\n"
25344                "  b234567890223456789032345678904234567890 = "
25345                "c234567890223456789032345678904234567890;",
25346                "if (a) {\n"
25347                "  b234567890223456789032345678904234567890 = "
25348                "c234567890223456789032345678904234567890;\n"
25349                "}",
25350                Style);
25351 }
25352 
25353 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
25354   auto Style = getLLVMStyle();
25355 
25356   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
25357                     "void functionDecl(int a, int b, int c);";
25358 
25359   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25360                      "paramF, paramG, paramH, paramI);\n"
25361                      "void functionDecl(int argumentA, int argumentB, int "
25362                      "argumentC, int argumentD, int argumentE);";
25363 
25364   verifyFormat(Short, Style);
25365 
25366   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25367                       "paramF, paramG, paramH,\n"
25368                       "             paramI);\n"
25369                       "void functionDecl(int argumentA, int argumentB, int "
25370                       "argumentC, int argumentD,\n"
25371                       "                  int argumentE);";
25372 
25373   verifyFormat(NoBreak, Medium, Style);
25374   verifyFormat(NoBreak,
25375                "functionCall(\n"
25376                "    paramA,\n"
25377                "    paramB,\n"
25378                "    paramC,\n"
25379                "    paramD,\n"
25380                "    paramE,\n"
25381                "    paramF,\n"
25382                "    paramG,\n"
25383                "    paramH,\n"
25384                "    paramI\n"
25385                ");\n"
25386                "void functionDecl(\n"
25387                "    int argumentA,\n"
25388                "    int argumentB,\n"
25389                "    int argumentC,\n"
25390                "    int argumentD,\n"
25391                "    int argumentE\n"
25392                ");",
25393                Style);
25394 
25395   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
25396                "                  nestedLongFunctionCall(argument1, "
25397                "argument2, argument3,\n"
25398                "                                         argument4, "
25399                "argument5));",
25400                Style);
25401 
25402   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25403 
25404   verifyFormat(Short, Style);
25405   verifyFormat(
25406       "functionCall(\n"
25407       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25408       "paramI\n"
25409       ");\n"
25410       "void functionDecl(\n"
25411       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25412       "argumentE\n"
25413       ");",
25414       Medium, Style);
25415 
25416   Style.AllowAllArgumentsOnNextLine = false;
25417   Style.AllowAllParametersOfDeclarationOnNextLine = false;
25418 
25419   verifyFormat(Short, Style);
25420   verifyFormat(
25421       "functionCall(\n"
25422       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25423       "paramI\n"
25424       ");\n"
25425       "void functionDecl(\n"
25426       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25427       "argumentE\n"
25428       ");",
25429       Medium, Style);
25430 
25431   Style.BinPackArguments = false;
25432   Style.BinPackParameters = false;
25433 
25434   verifyFormat(Short, Style);
25435 
25436   verifyFormat("functionCall(\n"
25437                "    paramA,\n"
25438                "    paramB,\n"
25439                "    paramC,\n"
25440                "    paramD,\n"
25441                "    paramE,\n"
25442                "    paramF,\n"
25443                "    paramG,\n"
25444                "    paramH,\n"
25445                "    paramI\n"
25446                ");\n"
25447                "void functionDecl(\n"
25448                "    int argumentA,\n"
25449                "    int argumentB,\n"
25450                "    int argumentC,\n"
25451                "    int argumentD,\n"
25452                "    int argumentE\n"
25453                ");",
25454                Medium, Style);
25455 
25456   verifyFormat("outerFunctionCall(\n"
25457                "    nestedFunctionCall(argument1),\n"
25458                "    nestedLongFunctionCall(\n"
25459                "        argument1,\n"
25460                "        argument2,\n"
25461                "        argument3,\n"
25462                "        argument4,\n"
25463                "        argument5\n"
25464                "    )\n"
25465                ");",
25466                Style);
25467 
25468   verifyFormat("int a = (int)b;", Style);
25469   verifyFormat("int a = (int)b;",
25470                "int a = (\n"
25471                "    int\n"
25472                ") b;",
25473                Style);
25474 
25475   verifyFormat("return (true);", Style);
25476   verifyFormat("return (true);",
25477                "return (\n"
25478                "    true\n"
25479                ");",
25480                Style);
25481 
25482   verifyFormat("void foo();", Style);
25483   verifyFormat("void foo();",
25484                "void foo(\n"
25485                ");",
25486                Style);
25487 
25488   verifyFormat("void foo() {}", Style);
25489   verifyFormat("void foo() {}",
25490                "void foo(\n"
25491                ") {\n"
25492                "}",
25493                Style);
25494 
25495   verifyFormat("auto string = std::string();", Style);
25496   verifyFormat("auto string = std::string();",
25497                "auto string = std::string(\n"
25498                ");",
25499                Style);
25500 
25501   verifyFormat("void (*functionPointer)() = nullptr;", Style);
25502   verifyFormat("void (*functionPointer)() = nullptr;",
25503                "void (\n"
25504                "    *functionPointer\n"
25505                ")\n"
25506                "(\n"
25507                ") = nullptr;",
25508                Style);
25509 }
25510 
25511 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
25512   auto Style = getLLVMStyle();
25513 
25514   verifyFormat("if (foo()) {\n"
25515                "  return;\n"
25516                "}",
25517                Style);
25518 
25519   verifyFormat("if (quitelongarg !=\n"
25520                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25521                "comment\n"
25522                "  return;\n"
25523                "}",
25524                Style);
25525 
25526   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25527 
25528   verifyFormat("if (foo()) {\n"
25529                "  return;\n"
25530                "}",
25531                Style);
25532 
25533   verifyFormat("if (quitelongarg !=\n"
25534                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25535                "comment\n"
25536                "  return;\n"
25537                "}",
25538                Style);
25539 }
25540 
25541 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
25542   auto Style = getLLVMStyle();
25543 
25544   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25545                "  doSomething();\n"
25546                "}",
25547                Style);
25548 
25549   verifyFormat("for (int myReallyLongCountVariable = 0; "
25550                "myReallyLongCountVariable < count;\n"
25551                "     myReallyLongCountVariable++) {\n"
25552                "  doSomething();\n"
25553                "}",
25554                Style);
25555 
25556   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25557 
25558   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25559                "  doSomething();\n"
25560                "}",
25561                Style);
25562 
25563   verifyFormat("for (int myReallyLongCountVariable = 0; "
25564                "myReallyLongCountVariable < count;\n"
25565                "     myReallyLongCountVariable++) {\n"
25566                "  doSomething();\n"
25567                "}",
25568                Style);
25569 }
25570 
25571 TEST_F(FormatTest, UnderstandsDigraphs) {
25572   verifyFormat("int arr<:5:> = {};");
25573   verifyFormat("int arr[5] = <%%>;");
25574   verifyFormat("int arr<:::qualified_variable:> = {};");
25575   verifyFormat("int arr[::qualified_variable] = <%%>;");
25576   verifyFormat("%:include <header>");
25577   verifyFormat("%:define A x##y");
25578   verifyFormat("#define A x%:%:y");
25579 }
25580 
25581 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
25582   auto Style = getLLVMStyle();
25583   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
25584   Style.AlignConsecutiveAssignments.Enabled = true;
25585   Style.AlignConsecutiveDeclarations.Enabled = true;
25586 
25587   // The AlignArray code is incorrect for non square Arrays and can cause
25588   // crashes, these tests assert that the array is not changed but will
25589   // also act as regression tests for when it is properly fixed
25590   verifyFormat("struct test demo[] = {\n"
25591                "    {1, 2},\n"
25592                "    {3, 4, 5},\n"
25593                "    {6, 7, 8}\n"
25594                "};",
25595                Style);
25596   verifyFormat("struct test demo[] = {\n"
25597                "    {1, 2, 3, 4, 5},\n"
25598                "    {3, 4, 5},\n"
25599                "    {6, 7, 8}\n"
25600                "};",
25601                Style);
25602   verifyFormat("struct test demo[] = {\n"
25603                "    {1, 2, 3, 4, 5},\n"
25604                "    {3, 4, 5},\n"
25605                "    {6, 7, 8, 9, 10, 11, 12}\n"
25606                "};",
25607                Style);
25608   verifyFormat("struct test demo[] = {\n"
25609                "    {1, 2, 3},\n"
25610                "    {3, 4, 5},\n"
25611                "    {6, 7, 8, 9, 10, 11, 12}\n"
25612                "};",
25613                Style);
25614 
25615   verifyFormat("S{\n"
25616                "    {},\n"
25617                "    {},\n"
25618                "    {a, b}\n"
25619                "};",
25620                Style);
25621   verifyFormat("S{\n"
25622                "    {},\n"
25623                "    {},\n"
25624                "    {a, b},\n"
25625                "};",
25626                Style);
25627   verifyFormat("void foo() {\n"
25628                "  auto thing = test{\n"
25629                "      {\n"
25630                "       {13}, {something}, // A\n"
25631                "      }\n"
25632                "  };\n"
25633                "}",
25634                "void foo() {\n"
25635                "  auto thing = test{\n"
25636                "      {\n"
25637                "       {13},\n"
25638                "       {something}, // A\n"
25639                "      }\n"
25640                "  };\n"
25641                "}",
25642                Style);
25643 }
25644 
25645 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
25646   auto Style = getLLVMStyle();
25647   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
25648   Style.AlignConsecutiveAssignments.Enabled = true;
25649   Style.AlignConsecutiveDeclarations.Enabled = true;
25650 
25651   // The AlignArray code is incorrect for non square Arrays and can cause
25652   // crashes, these tests assert that the array is not changed but will
25653   // also act as regression tests for when it is properly fixed
25654   verifyFormat("struct test demo[] = {\n"
25655                "    {1, 2},\n"
25656                "    {3, 4, 5},\n"
25657                "    {6, 7, 8}\n"
25658                "};",
25659                Style);
25660   verifyFormat("struct test demo[] = {\n"
25661                "    {1, 2, 3, 4, 5},\n"
25662                "    {3, 4, 5},\n"
25663                "    {6, 7, 8}\n"
25664                "};",
25665                Style);
25666   verifyFormat("struct test demo[] = {\n"
25667                "    {1, 2, 3, 4, 5},\n"
25668                "    {3, 4, 5},\n"
25669                "    {6, 7, 8, 9, 10, 11, 12}\n"
25670                "};",
25671                Style);
25672   verifyFormat("struct test demo[] = {\n"
25673                "    {1, 2, 3},\n"
25674                "    {3, 4, 5},\n"
25675                "    {6, 7, 8, 9, 10, 11, 12}\n"
25676                "};",
25677                Style);
25678 
25679   verifyFormat("S{\n"
25680                "    {},\n"
25681                "    {},\n"
25682                "    {a, b}\n"
25683                "};",
25684                Style);
25685   verifyFormat("S{\n"
25686                "    {},\n"
25687                "    {},\n"
25688                "    {a, b},\n"
25689                "};",
25690                Style);
25691   verifyFormat("void foo() {\n"
25692                "  auto thing = test{\n"
25693                "      {\n"
25694                "       {13}, {something}, // A\n"
25695                "      }\n"
25696                "  };\n"
25697                "}",
25698                "void foo() {\n"
25699                "  auto thing = test{\n"
25700                "      {\n"
25701                "       {13},\n"
25702                "       {something}, // A\n"
25703                "      }\n"
25704                "  };\n"
25705                "}",
25706                Style);
25707 }
25708 
25709 TEST_F(FormatTest, FormatsVariableTemplates) {
25710   verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
25711   verifyFormat("template <typename T> "
25712                "inline bool var = is_integral_v<T> && is_signed_v<T>;");
25713 }
25714 
25715 } // namespace
25716 } // namespace format
25717 } // namespace clang
25718